From b6093c47fe2ac9ec4dbbed37d98db4a04f7244f7 Mon Sep 17 00:00:00 2001 From: Jann Horn Date: Fri, 21 Jul 2023 05:46:43 +0200 Subject: [PATCH] BACKPORT: mm: lock VMA in dup_anon_vma() before setting ->anon_vma When VMAs are merged, dup_anon_vma() is called with `dst` pointing to the VMA that is being expanded to cover the area previously occupied by another VMA. This currently happens while `dst` is not write-locked. This means that, in the `src->anon_vma && !dst->anon_vma` case, as soon as the assignment `dst->anon_vma = src->anon_vma` has happened, concurrent page faults can happen on `dst` under the per-VMA lock. This is already icky in itself, since such page faults can now install pages into `dst` that are attached to an `anon_vma` that is not yet tied back to the `anon_vma` with an `anon_vma_chain`. But if `anon_vma_clone()` fails due to an out-of-memory error, things get much worse: `anon_vma_clone()` then reverts `dst->anon_vma` back to NULL, and `dst` remains completely unconnected to the `anon_vma`, even though we can have pages in the area covered by `dst` that point to the `anon_vma`. This means the `anon_vma` of such pages can be freed while the pages are still mapped into userspace, which leads to UAF when a helper like folio_lock_anon_vma_read() tries to look up the anon_vma of such a page. This theoretically is a security bug, but I believe it is really hard to actually trigger as an unprivileged user because it requires that you can make an order-0 GFP_KERNEL allocation fail, and the page allocator tries pretty hard to prevent that. I think doing the vma_start_write() call inside dup_anon_vma() is the most straightforward fix for now. For a kernel-assisted reproducer, see the notes section of the patch mail. Link: https://lkml.kernel.org/r/20230721034643.616851-1-jannh@google.com Fixes: 5e31275cc997 ("mm: add per-VMA lock and helper functions to control it") Signed-off-by: Jann Horn Reviewed-by: Suren Baghdasaryan Cc: Signed-off-by: Andrew Morton (cherry picked from commit d8ab9f7b644a2c9b64de405c1953c905ff219dc9) [surenb: since dup_anon_vma() is missing, add vma_start_write() directly before anon_vma is assigned] Bug: 293665307 Change-Id: I1b44e6278e464157e666cc5dbdb0fcc29bcf665e Signed-off-by: Suren Baghdasaryan --- mm/mmap.c | 1 + 1 file changed, 1 insertion(+) diff --git a/mm/mmap.c b/mm/mmap.c index 2a8e7396413a..5d7129b3f03f 100644 --- a/mm/mmap.c +++ b/mm/mmap.c @@ -537,6 +537,7 @@ inline int vma_expand(struct ma_state *mas, struct vm_area_struct *vma, int error; anon_vma = next->anon_vma; + vma_start_write(vma); vma->anon_vma = anon_vma; error = anon_vma_clone(vma, next); if (error)