Re: [PATCH v2] rapidio: fix possible UAF when kfifo_alloc() fails

From: wangweiyang
Date: Mon Nov 21 2022 - 22:45:57 EST


Hi Andrew,

on 2022/11/22 6:04, Andrew Morton wrote:
> On Sat, 19 Nov 2022 12:03:35 +0800 Wang Weiyang <wangweiyang2@xxxxxxxxxx> wrote:
>
>> If kfifo_alloc() fails in mport_cdev_open(), goto err_fifo and just free
>> priv. But priv is still in the chdev->file_list, then list traversal
>> may cause UAF. This fixes the following smatch warning:
>>
>> drivers/rapidio/devices/rio_mport_cdev.c:1930 mport_cdev_open() warn: '&priv->list' not removed from list
>>
>> ...
>>
>> Changes in v2:
>> - Avoid adding the new instance onto the list until the new instance
>> has been fully initialized.
>
> But it still isn't fully initialized.

Yes, I ignored that the initialization is still going on.

>
>> drivers/rapidio/devices/rio_mport_cdev.c | 7 +++----
>> 1 file changed, 3 insertions(+), 4 deletions(-)
>>
>> diff --git a/drivers/rapidio/devices/rio_mport_cdev.c b/drivers/rapidio/devices/rio_mport_cdev.c
>> index 3cc83997a1f8..86b28c4cd906 100644
>> --- a/drivers/rapidio/devices/rio_mport_cdev.c
>> +++ b/drivers/rapidio/devices/rio_mport_cdev.c
>> @@ -1904,10 +1904,6 @@ static int mport_cdev_open(struct inode *inode, struct file *filp)
>>
>> priv->md = chdev;
>>
>> - mutex_lock(&chdev->file_mutex);
>> - list_add_tail(&priv->list, &chdev->file_list);
>> - mutex_unlock(&chdev->file_mutex);
>> -
>> INIT_LIST_HEAD(&priv->db_filters);
>> INIT_LIST_HEAD(&priv->pw_filters);
>> spin_lock_init(&priv->fifo_lock);
>> @@ -1920,6 +1916,9 @@ static int mport_cdev_open(struct inode *inode, struct file *filp)
>> ret = -ENOMEM;
>> goto err_fifo;
>> }
>> + mutex_lock(&chdev->file_mutex);
>> + list_add_tail(&priv->list, &chdev->file_list);
>> + mutex_unlock(&chdev->file_mutex);
>>
>> #ifdef CONFIG_RAPIDIO_DMA_ENGINE
>> INIT_LIST_HEAD(&priv->async_list);
>
> Here we're still setting up state at *priv. I'm thinking the list
> addition shouldn't occur until after the
>
> filp->private_data = priv;
>
> Or just prior to it. I'm not sure what the atomicity rules are for
> file.private versus mport_dev.file_list.

I prefer to put the list addition just prior to the

filp->private_data = priv;

to keep mport_cdev_release() in reverse order of init. If it's ok with
you, I'll send a new patch later.

> .
>