media: rc: Fix use-after-free bugs caused by ene_tx_irqsim()
authorDuoming Zhou <duoming@zju.edu.cn>
Tue, 24 Jan 2023 07:55:33 +0000 (08:55 +0100)
committerMauro Carvalho Chehab <mchehab@kernel.org>
Wed, 8 Feb 2023 06:49:22 +0000 (07:49 +0100)
When the ene device is detaching, function ene_remove() will
be called. But there is no function to cancel tx_sim_timer
in ene_remove(), the timer handler ene_tx_irqsim() could race
with ene_remove(). As a result, the UAF bugs could happen,
the process is shown below.

    (cleanup routine)          |        (timer routine)
                               | mod_timer(&dev->tx_sim_timer, ..)
ene_remove()                   | (wait a time)
                               | ene_tx_irqsim()
                               |   dev->hw_lock //USE
                               |   ene_tx_sample(dev) //USE

Fix by adding del_timer_sync(&dev->tx_sim_timer) in ene_remove(),
The tx_sim_timer could stop before ene device is deallocated.

What's more, The rc_unregister_device() and del_timer_sync()
should be called first in ene_remove() and the deallocated
functions such as free_irq(), release_region() and so on
should be called behind them. Because the rc_unregister_device()
is well synchronized. Otherwise, race conditions may happen. The
situations that may lead to race conditions are shown below.

Firstly, the rx receiver is disabled with ene_rx_disable()
before rc_unregister_device() in ene_remove(), which means it
can be enabled again if a process opens /dev/lirc0 between
ene_rx_disable() and rc_unregister_device().

Secondly, the irqaction descriptor is freed by free_irq()
before the rc device is unregistered, which means irqaction
descriptor may be accessed again after it is deallocated.

Thirdly, the timer can call ene_tx_sample() that can write
to the io ports, which means the io ports could be accessed
again after they are deallocated by release_region().

Therefore, the rc_unregister_device() and del_timer_sync()
should be called first in ene_remove().

Suggested by: Sean Young <sean@mess.org>

Fixes: 9ea53b74df9c ("V4L/DVB: STAGING: remove lirc_ene0100 driver")
Signed-off-by: Duoming Zhou <duoming@zju.edu.cn>
Signed-off-by: Sean Young <sean@mess.org>
Signed-off-by: Mauro Carvalho Chehab <mchehab@kernel.org>
drivers/media/rc/ene_ir.c

index e09270916fbca340048242c87724c7418ec763cd..11ee21a7db8f00e56ac1b4b123fba91b6d2988c5 100644 (file)
@@ -1106,6 +1106,8 @@ static void ene_remove(struct pnp_dev *pnp_dev)
        struct ene_device *dev = pnp_get_drvdata(pnp_dev);
        unsigned long flags;
 
+       rc_unregister_device(dev->rdev);
+       del_timer_sync(&dev->tx_sim_timer);
        spin_lock_irqsave(&dev->hw_lock, flags);
        ene_rx_disable(dev);
        ene_rx_restore_hw_buffer(dev);
@@ -1113,7 +1115,6 @@ static void ene_remove(struct pnp_dev *pnp_dev)
 
        free_irq(dev->irq, dev);
        release_region(dev->hw_io, ENE_IO_SIZE);
-       rc_unregister_device(dev->rdev);
        kfree(dev);
 }