[Bug 272585] calling mprotect in an mmap-ed stack can affect non-target pages

From: <bugzilla-noreply_at_freebsd.org>
Date: Wed, 19 Jul 2023 00:40:13 UTC
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=272585

            Bug ID: 272585
           Summary: calling mprotect in an mmap-ed stack can affect
                    non-target pages
           Product: Base System
           Version: CURRENT
          Hardware: Any
                OS: Any
            Status: New
          Severity: Affects Only Me
          Priority: ---
         Component: kern
          Assignee: bugs@FreeBSD.org
          Reporter: jfc@mit.edu
 Attachment #243475 text/plain
         mime type:

Created attachment 243475
  --> https://bugs.freebsd.org/bugzilla/attachment.cgi?id=243475&action=edit
mmap-ed stack with an inaccessible gap

If I call mmap with MAP_GROWSDOWN|MAP_STACK and use mprotect to mark the 32nd
page from the top inaccessible (PROT_NONE), lower addresses in the region also
become inaccessible.  This is an odd thing to do, I agree, but it happened in a
real program.

Put another way: I call mmap with stack hints and get pages 0-255.  Before
touching the memory I call mprotect(PROT_NONE) on page 224.  Now pages 1-223
are also inaccessible.

The target of mprotect has to be 32 pages down, not 31 or 33, at least with my
system's configuration.  Perhaps 32 pages is the initial mapped size of a stack
region and when the stack grows it clones the page attributes of the lowest
address.

I attached an example that crashes reading an address that should be valid.  It
works on Mac OS (without the unsupported MAP_GROWSDOWN|MAP_STACK flags) and
Linux.

(This is simplified from a larger program that allocates a highly aligned 1 MB
stack by mapping a larger region and using mprotect to install guard pages. It
is not the "right" way to do it when MAP_ALIGNED is available.  The program was
written first on Linux which doesn't have that option.)

Reproduced on 13.2-STABLE/amd64, 13.2-STABLE/aarch64, 14-CURRENT/amd64.

-- 
You are receiving this mail because:
You are the assignee for the bug.