Re: [PATCH] kernfs: fix use-after-free in __kernfs_remove

From: Christian A. Ehrhardt
Date: Thu Sep 08 2022 - 18:25:45 EST



Hello Tejun,

On Thu, Sep 08, 2022 at 07:14:43AM -1000, Tejun Heo wrote:
> Hello, Christian.
>
> On Wed, Sep 07, 2022 at 10:08:11PM +0200, Christian A. Ehrhardt wrote:
> > Concurrent calls to __kernfs_remove can race on the removal
> > of the root node: The race occurs if the root node(kn) is freed
> > during kernfs_drain. The child node(pos) is explicitly protected
> > with an additional ref count. Do the same for the root node.
>
> I don't think this is right. We don't support parallel invocations of
> __kernfs_remove() this way. If @kn can be freed during kernfs_drain(), it
> also means that it can be freed before kernfs_rwsem is grabbed in
> kernfs_remove().

Point taken. However, the syzkaller reproducer reliably triggers
the bug without the patch and the bug is gone with the patch.

> The caller must be responsible for ensuring that @kn
> remains allocated. Otherwise, it can't be made reliable.

In this case the caller of __kernfs_remove is not kernfs_remove but
kernfs_remove_by_name_ns and it fails to take a reference for the
node that it looks up and deletes. Thus a second call to
kernfs_remove_by_name_ns can remove the node while kernfs_drain
drops the semaphore.

I'll post an updated patch tomorrow.

regards Christian