Re: [PATCH] Input: psmouse - fix use-after-free bugs due to rescheduled delayed works

From: Dmitry Torokhov

Date: Sat Nov 08 2025 - 01:27:54 EST


On Sat, Nov 08, 2025 at 02:22:10PM +0800, duoming@xxxxxxxxxx wrote:
> On Fri, 7 Nov 2025 21:43:37 -0800, Dmitry Torokhov wrote:
> > > The flush_workqueue() in psmouse_disconnect() only blocks and waits for
> > > work items that were already queued to the workqueue prior to its
> > > invocation. Any work items submitted after flush_workqueue() is called
> > > are not included in the set of tasks that the flush operation awaits.
> > > This means that after flush_workqueue() has finished executing, the
> > > resync_work and dev3_register_work could be rescheduled again, resulting
> > > in the following two use-after-free scenarios:
> > >
> > > 1. The psmouse structure is deallocated in psmouse_disconnect(), while
> > > resync_work remains active and attempts to dereference the already
> > > freed psmouse in psmouse_resync().
> > >
> > > CPU 0 | CPU 1
> > > psmouse_disconnect() | psmouse_receive_byte()
> > > | if(psmouse->state == ...)
> > > psmouse_set_state() |
> > > flush_workqueue() |
> > > | psmouse_queue_work() //reschedule
> > > kfree(psmouse); //FREE|
> > > | psmouse_resync()
> > > | psmouse = container_of(); //USE
> > > | psmouse-> //USE
> >
> > Before flushing the workqueue we set psmouse state to PSMOUSE_CMD_MODE,
> > but psmouse_queue_work() is only called from psmouse_receive_byte() if
> > the mouse is PSMOUSE_ACTIVE. Therefore there is no chance that work will
> > be scheduled while psmouse instance is being freed.
>
> I believe a potential race condition still exists between 
> psmouse_receive_byte() and psmouse_disconnect(). Specifically,
> if the condition check 'if (psmouse->state == PSMOUSE_ACTIVATED)' 
> has already been passed, and then we set the psmouse state to 
> PSMOUSE_CMD_MODE and flush the workqueue, it is still possible
> for psmouse_queue_work() to be scheduled after flush_workqueue().

Setting psmouse state can not race with psmouse_receive_byte() because
we take the serio->lock and disable interrupts.

Thanks.

--
Dmitry