On Sun, Dec 08, 2019 at 07:49:07PM +0000, Al Viro wrote: > On Mon, Nov 25, 2019 at 01:53:42PM +0100, Vladis Dronov wrote: > > In a case when a chardev file (like /dev/ptp0) is open but an underlying > > device is removed, closing this file leads to a use-after-free. This > > reproduces easily in a KVM virtual machine: > > > > # cat openptp0.c > > int main() { ... fp = fopen("/dev/ptp0", "r"); ... sleep(10); } > > > static void __fput(struct file *file) > > { ... > > if (file->f_op->release) > > file->f_op->release(inode, file); <<< cdev is kfree'd here > > > if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL && > > !(mode & FMODE_PATH))) { > > cdev_put(inode->i_cdev); <<< cdev fields are accessed here > > > > because of: > > > > __fput() > > posix_clock_release() > > kref_put(&clk->kref, delete_clock) <<< the last reference > > delete_clock() > > delete_ptp_clock() > > kfree(ptp) <<< cdev is embedded in ptp > > cdev_put > > module_put(p->owner) <<< *p is kfree'd > > > > The fix is to call cdev_put() before file->f_op->release(). This fix the > > class of bugs when a chardev device is removed when its file is open, for > > example: > > And what's to prevent rmmod coming and freeing ->release code right as you > are executing it? FWIW, the bug here seems to be that the lifetime rules of cdev are fucked - if it can get freed while its ->kobj is still alive, we have something very wrong there. IOW, you have ptp lifetime controlled by *TWO* refcounts - that of clk and that of of cdev->kobj. That's doesn't work. Replace that kfree() with dropping a kobject reference, perhaps, so that freeing would've been done by its release callback?