[PATCH] drm/gem: Avoid use-after-free on drm_gem_mmap_obj() failure

From: Shigeru Yoshida
Date: Tue Sep 20 2022 - 03:24:42 EST


syzbot reported use-after-free for drm_gem_object [1]. This causes
the call trace like below:

[ 75.327400][ T5723] Call Trace:
[ 75.327611][ T5723] <TASK>
[ 75.327803][ T5723] drm_gem_object_handle_put_unlocked+0x11e/0x1a0
[ 75.328209][ T5723] drm_gem_object_release_handle+0x5d/0x70
[ 75.328568][ T5723] ? drm_gem_object_handle_put_unlocked+0x1a0/0x1a0
[ 75.328965][ T5723] idr_for_each+0x99/0x160
[ 75.329253][ T5723] drm_gem_release+0x20/0x30
[ 75.329544][ T5723] drm_file_free.part.0+0x269/0x310
[ 75.329867][ T5723] drm_close_helper.isra.0+0x88/0xa0
[ 75.330305][ T5723] drm_release+0x8e/0x1a0
[ 75.330674][ T5723] ? drm_release_noglobal+0xc0/0xc0
[ 75.331138][ T5723] __fput+0x10e/0x440
[ 75.331503][ T5723] task_work_run+0x73/0xd0
[ 75.331895][ T5723] do_exit+0x535/0x1200
[ 75.332280][ T5723] ? ktime_get_coarse_real_ts64+0x13b/0x170
[ 75.332810][ T5723] do_group_exit+0x51/0x100
[ 75.333215][ T5723] __x64_sys_exit_group+0x18/0x20
[ 75.333654][ T5723] do_syscall_64+0x37/0x90
[ 75.334058][ T5723] entry_SYSCALL_64_after_hwframe+0x63/0xcd

If drm_gem_mmap_obj() failed, it drops the reference count by calling
drm_gem_object_put(). However, drm_gem_mmap() drops the reference
count after calling drm_gem_mmap_obj() even if it failed, so it breaks
the balance of the reference count.

This patch fixes this issue by calling drm_gem_object_put() only if
drm_gem_mmap_obj() succeeds, and returns immediately if
drm_gem_mmap_obj() failed without calling drm_gem_object_put().

Link: https://syzkaller.appspot.com/bug?id=c42a72b0b3bcedd95e5f132a4ccd7cd550334160 [1]
Reported-by: syzbot+c512687fff9d22327436@xxxxxxxxxxxxxxxxxxxxxxxxx
Signed-off-by: Shigeru Yoshida <syoshida@xxxxxxxxxx>
---
drivers/gpu/drm/drm_gem.c | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/drivers/gpu/drm/drm_gem.c b/drivers/gpu/drm/drm_gem.c
index ad068865ba20..f345d38df50a 100644
--- a/drivers/gpu/drm/drm_gem.c
+++ b/drivers/gpu/drm/drm_gem.c
@@ -1115,10 +1115,12 @@ int drm_gem_mmap(struct file *filp, struct vm_area_struct *vma)

ret = drm_gem_mmap_obj(obj, drm_vma_node_size(node) << PAGE_SHIFT,
vma);
+ if (ret)
+ return ret;

drm_gem_object_put(obj);

- return ret;
+ return 0;
}
EXPORT_SYMBOL(drm_gem_mmap);

--
2.37.3