Forwarded: [PATCH] mm/userfaultfd: validate dst_addr after re-acquiring VMA lock in mfill_copy_folio_retry

syzbot posted 1 patch 3 weeks ago
mm/userfaultfd.c | 10 ++++++++++
1 file changed, 10 insertions(+)
Forwarded: [PATCH] mm/userfaultfd: validate dst_addr after re-acquiring VMA lock in mfill_copy_folio_retry
Posted by syzbot 3 weeks ago
For archival purposes, forwarding an incoming command email to
linux-kernel@vger.kernel.org, syzkaller-bugs@googlegroups.com.

***

Subject: [PATCH] mm/userfaultfd: validate dst_addr after re-acquiring VMA lock in mfill_copy_folio_retry
Author: kartikey406@gmail.com

#syz test: git://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git master


mfill_copy_folio_retry() drops the VMA lock to perform
copy_from_user() without holding it, then reacquires it
via mfill_get_vma(). However, mfill_get_vma() only validates
that dst_start is within the VMA bounds, not dst_addr (the
current page being processed).

A concurrent UFFDIO_UNREGISTER can split the VMA during the
window where the lock is dropped, shrinking vma->vm_end. When
mfill_get_vma() reacquires the lock, it finds the VMA using
dst_start which may still be valid, but dst_addr may now fall
outside the split VMA's bounds.

This causes folio_add_new_anon_rmap() to trigger its sanity
check:

  address < vma->vm_start || address + (nr << 12) > vma->vm_end
  WARNING: mm/rmap.c:1682 folio_add_new_anon_rmap+0x5fe/0x14b0

Fix this by validating dst_addr against the reacquired VMA
bounds after mfill_get_vma() returns in mfill_copy_folio_retry().

Reported-by: syzbot+e24a2e34fad0efbac047@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=e24a2e34fad0efbac047
Signed-off-by: Deepanshu Kartikey <Kartikey406@gmail.com>
---
 mm/userfaultfd.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c
index 9ffc80d0a51b..dbf16c9bcf6f 100644
--- a/mm/userfaultfd.c
+++ b/mm/userfaultfd.c
@@ -467,6 +467,16 @@ static int mfill_copy_folio_retry(struct mfill_state *state, struct folio *folio
 	if (err)
 		return err;
 
+        /*
+         * VMA may have been split while the lock was dropped for
+         * copy_from_user(). mfill_get_vma() only validates dst_start
+         * but not dst_addr (current page). Re-validate dst_addr against
+         * the reacquired VMA bounds before installing the PTE.
+         */
+	if (state->dst_addr < state->vma->vm_start ||
+	    state->dst_addr >= state->vma->vm_end)
+		return -EFAULT;
+
 	err = mfill_get_pmd(state);
 	if (err)
 		return err;
-- 
2.43.0