Linux Sound subsystem development
 help / color / mirror / Atom feed
* 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) 徐晗翔
                     ` (12 subsequent siblings)
  13 siblings, 1 reply; 16+ 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] 16+ 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-13 12:04   ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
                     ` (11 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-13 12:06   ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (UAF) 徐晗翔
                     ` (10 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-13 12:15   ` ALSA: pcm: link-group walk in timer callback can use a closed substream's freed runtime (UAF) 徐晗翔
                     ` (9 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-13 12:28   ` ALSA: usb-audio: us144mkii: PCM close frees runtime while playback/feedback URB completion and capture work still use it (UAF) 徐晗翔
                     ` (8 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-13 12:29   ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
                     ` (7 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-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) 徐晗翔
                     ` (6 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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
  0 siblings, 0 replies; 16+ 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] 16+ 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) 徐晗翔
                     ` (5 subsequent siblings)
  13 siblings, 1 reply; 16+ 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] 16+ 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-22  7:50   ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
                     ` (4 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-22  7:52   ` sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF) 徐晗翔
                     ` (3 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-22  7:55   ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
                     ` (2 subsequent siblings)
  13 siblings, 0 replies; 16+ 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] 16+ 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-22  7:56   ` sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod 徐晗翔
  2026-11-22  7:57   ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
  13 siblings, 0 replies; 16+ 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] 16+ 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-22  7:57   ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔
  13 siblings, 0 replies; 16+ 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] 16+ 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   ` 徐晗翔
  13 siblings, 0 replies; 16+ 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] 16+ 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
  0 siblings, 0 replies; 16+ 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] 16+ messages in thread

end of thread, other threads:[~2026-11-22  8:07 UTC | newest]

Thread overview: 16+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
     [not found] <4c7f9772.192e1.1a17d5c2ed5.Coremail.xuhx@hust.edu.cn>
     [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 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) 徐晗翔
2026-11-13 12:04   ` ALSA: asihpi: free IRQ before snd_card_free()/HPI delete on HPI6205 removal (UAF) 徐晗翔
2026-11-13 12:06   ` ALSA: asihpi: quiesce PCM timer and IRQ before freeing dpcm on close (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-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   ` ALSA: usb-audio: us144mkii: queued stop_pcm_work calls snd_pcm_stop() after PCM close and dereferences NULL runtime 徐晗翔
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-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   ` sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF) 徐晗翔
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   ` sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk) 徐晗翔
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   ` sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer 徐晗翔

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox