mbox series

[v19,0/8] mm: introduce memfd_secret system call to create "secret" memory areas

Message ID 20210513184734.29317-1-rppt@kernel.org
Headers show
Series mm: introduce memfd_secret system call to create "secret" memory areas | expand

Message

Mike Rapoport May 13, 2021, 6:47 p.m. UTC
From: Mike Rapoport <rppt@linux.ibm.com>

Hi,

@Andrew, this is based on v5.13-rc1, I can rebase whatever way you prefer.

This is an implementation of "secret" mappings backed by a file descriptor.

The file descriptor backing secret memory mappings is created using a
dedicated memfd_secret system call The desired protection mode for the
memory is configured using flags parameter of the system call. The mmap()
of the file descriptor created with memfd_secret() will create a "secret"
memory mapping. The pages in that mapping will be marked as not present in
the direct map and will be present only in the page table of the owning mm.

Although normally Linux userspace mappings are protected from other users,
such secret mappings are useful for environments where a hostile tenant is
trying to trick the kernel into giving them access to other tenants
mappings.

It's designed to provide the following protections:

* Enhanced protection (in conjunction with all the other in-kernel
attack prevention systems) against ROP attacks. Seceretmem makes "simple"
ROP insufficient to perform exfiltration, which increases the required
complexity of the attack. Along with other protections like the kernel
stack size limit and address space layout randomization which make finding
gadgets is really hard, absence of any in-kernel primitive for accessing
secret memory means the one gadget ROP attack can't work. Since the only
way to access secret memory is to reconstruct the missing mapping entry,
the attacker has to recover the physical page and insert a PTE pointing to
it in the kernel and then retrieve the contents.  That takes at least three
gadgets which is a level of difficulty beyond most standard attacks.

* Prevent cross-process secret userspace memory exposures. Once the secret
memory is allocated, the user can't accidentally pass it into the kernel to
be transmitted somewhere. The secreremem pages cannot be accessed via the
direct map and they are disallowed in GUP.

* Harden against exploited kernel flaws. In order to access secretmem, a
kernel-side attack would need to either walk the page tables and create new
ones, or spawn a new privileged uiserspace process to perform secrets
exfiltration using ptrace.

In the future the secret mappings may be used as a mean to protect guest memory
in a virtual machine host.

For demonstration of secret memory usage we've created a userspace library

https://git.kernel.org/pub/scm/linux/kernel/git/jejb/secret-memory-preloader.git

that does two things: the first is act as a preloader for openssl to
redirect all the OPENSSL_malloc calls to secret memory meaning any secret
keys get automatically protected this way and the other thing it does is
expose the API to the user who needs it. We anticipate that a lot of the
use cases would be like the openssl one: many toolkits that deal with
secret keys already have special handling for the memory to try to give
them greater protection, so this would simply be pluggable into the
toolkits without any need for user application modification.

Hiding secret memory mappings behind an anonymous file allows usage of
the page cache for tracking pages allocated for the "secret" mappings as
well as using address_space_operations for e.g. page migration callbacks.

The anonymous file may be also used implicitly, like hugetlb files, to
implement mmap(MAP_SECRET) and use the secret memory areas with "native" mm
ABIs in the future.

Removing of the pages from the direct map may cause its fragmentation on
architectures that use large pages to map the physical memory which affects
the system performance. However, the original Kconfig text for
CONFIG_DIRECT_GBPAGES said that gigabyte pages in the direct map "... can
improve the kernel's performance a tiny bit ..." (commit 00d1c5e05736
("x86: add gbpages switches")) and the recent report [1] showed that "...
although 1G mappings are a good default choice, there is no compelling
evidence that it must be the only choice". Hence, it is sufficient to have
secretmem disabled by default with the ability of a system administrator to
enable it at boot time.

In addition, there is also a long term goal to improve management of the
direct map.

[1] https://lore.kernel.org/linux-mm/213b4567-46ce-f116-9cdf-bbd0c884eb3c@linux.intel.com/

v19:
* block /dev/mem mmap access, per David
* disallow mmap/mprotect with PROT_EXEC, per Kees
* simplify return in page_is_secretmem(), per Matthew
* use unsigned int for syscall falgs, per Yury

v18: https://lore.kernel.org/lkml/20210303162209.8609-1-rppt@kernel.org
* rebase on v5.12-rc1
* merge kfence fix into the original patch
* massage commit message of the patch introducing the memfd_secret syscall

v17: https://lore.kernel.org/lkml/20210208084920.2884-1-rppt@kernel.org
* Remove pool of large pages backing secretmem allocations, per Michal Hocko
* Add secretmem pages to unevictable LRU, per Michal Hocko
* Use GFP_HIGHUSER as secretmem mapping mask, per Michal Hocko
* Make secretmem an opt-in feature that is disabled by default
 
v16: https://lore.kernel.org/lkml/20210121122723.3446-1-rppt@kernel.org
* Fix memory leak intorduced in v15
* Clean the data left from previous page user before handing the page to
  the userspace

v15: https://lore.kernel.org/lkml/20210120180612.1058-1-rppt@kernel.org
* Add riscv/Kconfig update to disable set_memory operations for nommu
  builds (patch 3)
* Update the code around add_to_page_cache() per Matthew's comments
  (patches 6,7)
* Add fixups for build/checkpatch errors discovered by CI systems

Older history:
v14: https://lore.kernel.org/lkml/20201203062949.5484-1-rppt@kernel.org
v13: https://lore.kernel.org/lkml/20201201074559.27742-1-rppt@kernel.org
v12: https://lore.kernel.org/lkml/20201125092208.12544-1-rppt@kernel.org
v11: https://lore.kernel.org/lkml/20201124092556.12009-1-rppt@kernel.org
v10: https://lore.kernel.org/lkml/20201123095432.5860-1-rppt@kernel.org
v9: https://lore.kernel.org/lkml/20201117162932.13649-1-rppt@kernel.org
v8: https://lore.kernel.org/lkml/20201110151444.20662-1-rppt@kernel.org
v7: https://lore.kernel.org/lkml/20201026083752.13267-1-rppt@kernel.org
v6: https://lore.kernel.org/lkml/20200924132904.1391-1-rppt@kernel.org
v5: https://lore.kernel.org/lkml/20200916073539.3552-1-rppt@kernel.org
v4: https://lore.kernel.org/lkml/20200818141554.13945-1-rppt@kernel.org
v3: https://lore.kernel.org/lkml/20200804095035.18778-1-rppt@kernel.org
v2: https://lore.kernel.org/lkml/20200727162935.31714-1-rppt@kernel.org
v1: https://lore.kernel.org/lkml/20200720092435.17469-1-rppt@kernel.org
rfc-v2: https://lore.kernel.org/lkml/20200706172051.19465-1-rppt@kernel.org/
rfc-v1: https://lore.kernel.org/lkml/20200130162340.GA14232@rapoport-lnx/
rfc-v0: https://lore.kernel.org/lkml/1572171452-7958-1-git-send-email-rppt@kernel.org/

Mike Rapoport (8):
  mmap: make mlock_future_check() global
  riscv/Kconfig: make direct map manipulation options depend on MMU
  set_memory: allow set_direct_map_*_noflush() for multiple pages
  set_memory: allow querying whether set_direct_map_*() is actually enabled
  mm: introduce memfd_secret system call to create "secret" memory areas
  PM: hibernate: disable when there are active secretmem users
  arch, mm: wire up memfd_secret system call where relevant
  secretmem: test: add basic selftest for memfd_secret(2)

 arch/arm64/include/asm/Kbuild             |   1 -
 arch/arm64/include/asm/cacheflush.h       |   6 -
 arch/arm64/include/asm/kfence.h           |   2 +-
 arch/arm64/include/asm/set_memory.h       |  17 ++
 arch/arm64/include/uapi/asm/unistd.h      |   1 +
 arch/arm64/kernel/machine_kexec.c         |   1 +
 arch/arm64/mm/mmu.c                       |   6 +-
 arch/arm64/mm/pageattr.c                  |  23 +-
 arch/riscv/Kconfig                        |   4 +-
 arch/riscv/include/asm/set_memory.h       |   4 +-
 arch/riscv/include/asm/unistd.h           |   1 +
 arch/riscv/mm/pageattr.c                  |   8 +-
 arch/x86/entry/syscalls/syscall_32.tbl    |   1 +
 arch/x86/entry/syscalls/syscall_64.tbl    |   1 +
 arch/x86/include/asm/set_memory.h         |   4 +-
 arch/x86/mm/pat/set_memory.c              |   8 +-
 drivers/char/mem.c                        |   4 +
 include/linux/secretmem.h                 |  54 ++++
 include/linux/set_memory.h                |  16 +-
 include/linux/syscalls.h                  |   1 +
 include/uapi/asm-generic/unistd.h         |   7 +-
 include/uapi/linux/magic.h                |   1 +
 kernel/power/hibernate.c                  |   5 +-
 kernel/power/snapshot.c                   |   4 +-
 kernel/sys_ni.c                           |   2 +
 mm/Kconfig                                |   4 +
 mm/Makefile                               |   1 +
 mm/gup.c                                  |  12 +
 mm/internal.h                             |   3 +
 mm/mlock.c                                |   3 +-
 mm/mmap.c                                 |   5 +-
 mm/secretmem.c                            | 254 +++++++++++++++++++
 mm/vmalloc.c                              |   5 +-
 scripts/checksyscalls.sh                  |   4 +
 tools/testing/selftests/vm/.gitignore     |   1 +
 tools/testing/selftests/vm/Makefile       |   3 +-
 tools/testing/selftests/vm/memfd_secret.c | 296 ++++++++++++++++++++++
 tools/testing/selftests/vm/run_vmtests.sh |  17 ++
 38 files changed, 744 insertions(+), 46 deletions(-)
 create mode 100644 arch/arm64/include/asm/set_memory.h
 create mode 100644 include/linux/secretmem.h
 create mode 100644 mm/secretmem.c
 create mode 100644 tools/testing/selftests/vm/memfd_secret.c


base-commit: 6efb943b8616ec53a5e444193dccf1af9ad627b5

Comments

James Bottomley May 13, 2021, 7:08 p.m. UTC | #1
On Thu, 2021-05-13 at 21:47 +0300, Mike Rapoport wrote:
> From: Mike Rapoport <rppt@linux.ibm.com>
> 
> Hi,
> 
> @Andrew, this is based on v5.13-rc1, I can rebase whatever way you
> prefer.
> 
> This is an implementation of "secret" mappings backed by a file
> descriptor.
> 
> The file descriptor backing secret memory mappings is created using a
> dedicated memfd_secret system call The desired protection mode for
> the
> memory is configured using flags parameter of the system call. The
> mmap()
> of the file descriptor created with memfd_secret() will create a
> "secret"
> memory mapping. The pages in that mapping will be marked as not
> present in
> the direct map and will be present only in the page table of the
> owning mm.
> 
> Although normally Linux userspace mappings are protected from other
> users,
> such secret mappings are useful for environments where a hostile
> tenant is
> trying to trick the kernel into giving them access to other tenants
> mappings.
> 
> It's designed to provide the following protections:
> 
> * Enhanced protection (in conjunction with all the other in-kernel
> attack prevention systems) against ROP attacks. Seceretmem makes
> "simple"
> ROP insufficient to perform exfiltration, which increases the
> required
> complexity of the attack. Along with other protections like the
> kernel
> stack size limit and address space layout randomization which make
> finding
> gadgets is really hard, absence of any in-kernel primitive for
> accessing
> secret memory means the one gadget ROP attack can't work. Since the
> only
> way to access secret memory is to reconstruct the missing mapping
> entry,
> the attacker has to recover the physical page and insert a PTE
> pointing to
> it in the kernel and then retrieve the contents.  That takes at least
> three
> gadgets which is a level of difficulty beyond most standard attacks.
> 
> * Prevent cross-process secret userspace memory exposures. Once the
> secret
> memory is allocated, the user can't accidentally pass it into the
> kernel to
> be transmitted somewhere. The secreremem pages cannot be accessed via
> the
> direct map and they are disallowed in GUP.
> 
> * Harden against exploited kernel flaws. In order to access
> secretmem, a
> kernel-side attack would need to either walk the page tables and
> create new
> ones, or spawn a new privileged uiserspace process to perform secrets
> exfiltration using ptrace.
> 
> In the future the secret mappings may be used as a mean to protect
> guest memory
> in a virtual machine host.
> 
> For demonstration of secret memory usage we've created a userspace
> library
> 
> https://git.kernel.org/pub/scm/linux/kernel/git/jejb/secret-memory-preloader.git
> 
> that does two things: the first is act as a preloader for openssl to
> redirect all the OPENSSL_malloc calls to secret memory meaning any
> secret
> keys get automatically protected this way and the other thing it does
> is
> expose the API to the user who needs it. We anticipate that a lot of
> the
> use cases would be like the openssl one: many toolkits that deal with
> secret keys already have special handling for the memory to try to
> give
> them greater protection, so this would simply be pluggable into the
> toolkits without any need for user application modification.
> 
> Hiding secret memory mappings behind an anonymous file allows usage
> of
> the page cache for tracking pages allocated for the "secret" mappings
> as
> well as using address_space_operations for e.g. page migration
> callbacks.
> 
> The anonymous file may be also used implicitly, like hugetlb files,
> to
> implement mmap(MAP_SECRET) and use the secret memory areas with
> "native" mm
> ABIs in the future.
> 
> Removing of the pages from the direct map may cause its fragmentation
> on
> architectures that use large pages to map the physical memory which
> affects
> the system performance. However, the original Kconfig text for
> CONFIG_DIRECT_GBPAGES said that gigabyte pages in the direct map "...
> can
> improve the kernel's performance a tiny bit ..." (commit 00d1c5e05736
> ("x86: add gbpages switches")) and the recent report [1] showed that
> "...
> although 1G mappings are a good default choice, there is no
> compelling
> evidence that it must be the only choice". Hence, it is sufficient to
> have
> secretmem disabled by default with the ability of a system
> administrator to
> enable it at boot time.
> 
> In addition, there is also a long term goal to improve management of
> the
> direct map.
> 
> [1] 
> https://lore.kernel.org/linux-mm/213b4567-46ce-f116-9cdf-bbd0c884eb3c@linux.intel.com/
> 
> v19:
> * block /dev/mem mmap access, per David
> * disallow mmap/mprotect with PROT_EXEC, per Kees
> * simplify return in page_is_secretmem(), per Matthew
> * use unsigned int for syscall falgs, per Yury
> 
> v18: 
> https://lore.kernel.org/lkml/20210303162209.8609-1-rppt@kernel.org
> * rebase on v5.12-rc1
> * merge kfence fix into the original patch
> * massage commit message of the patch introducing the memfd_secret
> syscall
> 
> v17: 
> https://lore.kernel.org/lkml/20210208084920.2884-1-rppt@kernel.org
> * Remove pool of large pages backing secretmem allocations, per
> Michal Hocko
> * Add secretmem pages to unevictable LRU, per Michal Hocko
> * Use GFP_HIGHUSER as secretmem mapping mask, per Michal Hocko
> * Make secretmem an opt-in feature that is disabled by default
>  
> v16: 
> https://lore.kernel.org/lkml/20210121122723.3446-1-rppt@kernel.org
> * Fix memory leak intorduced in v15
> * Clean the data left from previous page user before handing the page
> to
>   the userspace
> 
> v15: 
> https://lore.kernel.org/lkml/20210120180612.1058-1-rppt@kernel.org
> * Add riscv/Kconfig update to disable set_memory operations for nommu
>   builds (patch 3)
> * Update the code around add_to_page_cache() per Matthew's comments
>   (patches 6,7)
> * Add fixups for build/checkpatch errors discovered by CI systems
> 
> Older history:
> v14: 
> https://lore.kernel.org/lkml/20201203062949.5484-1-rppt@kernel.org
> v13: 
> https://lore.kernel.org/lkml/20201201074559.27742-1-rppt@kernel.org
> v12: 
> https://lore.kernel.org/lkml/20201125092208.12544-1-rppt@kernel.org
> v11: 
> https://lore.kernel.org/lkml/20201124092556.12009-1-rppt@kernel.org
> v10: 
> https://lore.kernel.org/lkml/20201123095432.5860-1-rppt@kernel.org
> v9: 
> https://lore.kernel.org/lkml/20201117162932.13649-1-rppt@kernel.org
> v8: 
> https://lore.kernel.org/lkml/20201110151444.20662-1-rppt@kernel.org
> v7: 
> https://lore.kernel.org/lkml/20201026083752.13267-1-rppt@kernel.org
> v6: 
> https://lore.kernel.org/lkml/20200924132904.1391-1-rppt@kernel.org
> v5: 
> https://lore.kernel.org/lkml/20200916073539.3552-1-rppt@kernel.org
> v4: 
> https://lore.kernel.org/lkml/20200818141554.13945-1-rppt@kernel.org
> v3: 
> https://lore.kernel.org/lkml/20200804095035.18778-1-rppt@kernel.org
> v2: 
> https://lore.kernel.org/lkml/20200727162935.31714-1-rppt@kernel.org
> v1: 
> https://lore.kernel.org/lkml/20200720092435.17469-1-rppt@kernel.org
> rfc-v2: 
> https://lore.kernel.org/lkml/20200706172051.19465-1-rppt@kernel.org/
> rfc-v1: 
> https://lore.kernel.org/lkml/20200130162340.GA14232@rapoport-lnx/
> rfc-v0: 
> https://lore.kernel.org/lkml/1572171452-7958-1-git-send-email-rppt@kernel.org/
> 
> Mike Rapoport (8):
>   mmap: make mlock_future_check() global
>   riscv/Kconfig: make direct map manipulation options depend on MMU
>   set_memory: allow set_direct_map_*_noflush() for multiple pages
>   set_memory: allow querying whether set_direct_map_*() is actually
> enabled
>   mm: introduce memfd_secret system call to create "secret" memory
> areas
>   PM: hibernate: disable when there are active secretmem users
>   arch, mm: wire up memfd_secret system call where relevant
>   secretmem: test: add basic selftest for memfd_secret(2)
> 
>  arch/arm64/include/asm/Kbuild             |   1 -
>  arch/arm64/include/asm/cacheflush.h       |   6 -
>  arch/arm64/include/asm/kfence.h           |   2 +-
>  arch/arm64/include/asm/set_memory.h       |  17 ++
>  arch/arm64/include/uapi/asm/unistd.h      |   1 +
>  arch/arm64/kernel/machine_kexec.c         |   1 +
>  arch/arm64/mm/mmu.c                       |   6 +-
>  arch/arm64/mm/pageattr.c                  |  23 +-
>  arch/riscv/Kconfig                        |   4 +-
>  arch/riscv/include/asm/set_memory.h       |   4 +-
>  arch/riscv/include/asm/unistd.h           |   1 +
>  arch/riscv/mm/pageattr.c                  |   8 +-
>  arch/x86/entry/syscalls/syscall_32.tbl    |   1 +
>  arch/x86/entry/syscalls/syscall_64.tbl    |   1 +
>  arch/x86/include/asm/set_memory.h         |   4 +-
>  arch/x86/mm/pat/set_memory.c              |   8 +-
>  drivers/char/mem.c                        |   4 +
>  include/linux/secretmem.h                 |  54 ++++
>  include/linux/set_memory.h                |  16 +-
>  include/linux/syscalls.h                  |   1 +
>  include/uapi/asm-generic/unistd.h         |   7 +-
>  include/uapi/linux/magic.h                |   1 +
>  kernel/power/hibernate.c                  |   5 +-
>  kernel/power/snapshot.c                   |   4 +-
>  kernel/sys_ni.c                           |   2 +
>  mm/Kconfig                                |   4 +
>  mm/Makefile                               |   1 +
>  mm/gup.c                                  |  12 +
>  mm/internal.h                             |   3 +
>  mm/mlock.c                                |   3 +-
>  mm/mmap.c                                 |   5 +-
>  mm/secretmem.c                            | 254 +++++++++++++++++++
>  mm/vmalloc.c                              |   5 +-
>  scripts/checksyscalls.sh                  |   4 +
>  tools/testing/selftests/vm/.gitignore     |   1 +
>  tools/testing/selftests/vm/Makefile       |   3 +-
>  tools/testing/selftests/vm/memfd_secret.c | 296
> ++++++++++++++++++++++
>  tools/testing/selftests/vm/run_vmtests.sh |  17 ++
>  38 files changed, 744 insertions(+), 46 deletions(-)
>  create mode 100644 arch/arm64/include/asm/set_memory.h
>  create mode 100644 include/linux/secretmem.h
>  create mode 100644 mm/secretmem.c
>  create mode 100644 tools/testing/selftests/vm/memfd_secret.c
> 
> 
> base-commit: 6efb943b8616ec53a5e444193dccf1af9ad627b5

For the series:

Acked-by: James Bottomley <James.Bottomley@HansenPartnership.com>

James
David Hildenbrand May 14, 2021, 8:27 a.m. UTC | #2
On 13.05.21 20:47, Mike Rapoport wrote:
> From: Mike Rapoport <rppt@linux.ibm.com>

> 

> It will be used by the upcoming secret memory implementation.

> 

> Signed-off-by: Mike Rapoport <rppt@linux.ibm.com>

> Cc: Alexander Viro <viro@zeniv.linux.org.uk>

> Cc: Andy Lutomirski <luto@kernel.org>

> Cc: Arnd Bergmann <arnd@arndb.de>

> Cc: Borislav Petkov <bp@alien8.de>

> Cc: Catalin Marinas <catalin.marinas@arm.com>

> Cc: Christopher Lameter <cl@linux.com>

> Cc: Dan Williams <dan.j.williams@intel.com>

> Cc: Dave Hansen <dave.hansen@linux.intel.com>

> Cc: David Hildenbrand <david@redhat.com>

> Cc: Elena Reshetova <elena.reshetova@intel.com>

> Cc: Hagen Paul Pfeifer <hagen@jauu.net>

> Cc: "H. Peter Anvin" <hpa@zytor.com>

> Cc: Ingo Molnar <mingo@redhat.com>

> Cc: James Bottomley <jejb@linux.ibm.com>

> Cc: "Kirill A. Shutemov" <kirill@shutemov.name>

> Cc: Mark Rutland <mark.rutland@arm.com>

> Cc: Matthew Wilcox <willy@infradead.org>

> Cc: Michael Kerrisk <mtk.manpages@gmail.com>

> Cc: Palmer Dabbelt <palmer@dabbelt.com>

> Cc: Palmer Dabbelt <palmerdabbelt@google.com>

> Cc: Paul Walmsley <paul.walmsley@sifive.com>

> Cc: Peter Zijlstra <peterz@infradead.org>

> Cc: Rick Edgecombe <rick.p.edgecombe@intel.com>

> Cc: Roman Gushchin <guro@fb.com>

> Cc: Shakeel Butt <shakeelb@google.com>

> Cc: Shuah Khan <shuah@kernel.org>

> Cc: Thomas Gleixner <tglx@linutronix.de>

> Cc: Tycho Andersen <tycho@tycho.ws>

> Cc: Will Deacon <will@kernel.org>

> ---

>   mm/internal.h | 3 +++

>   mm/mmap.c     | 5 ++---

>   2 files changed, 5 insertions(+), 3 deletions(-)

> 

> diff --git a/mm/internal.h b/mm/internal.h

> index 54bd0dc2c23c..46eb82eaa195 100644

> --- a/mm/internal.h

> +++ b/mm/internal.h

> @@ -373,6 +373,9 @@ static inline void munlock_vma_pages_all(struct vm_area_struct *vma)

>   extern void mlock_vma_page(struct page *page);

>   extern unsigned int munlock_vma_page(struct page *page);

>   

> +extern int mlock_future_check(struct mm_struct *mm, unsigned long flags,

> +			      unsigned long len);

> +

>   /*

>    * Clear the page's PageMlocked().  This can be useful in a situation where

>    * we want to unconditionally remove a page from the pagecache -- e.g.,

> diff --git a/mm/mmap.c b/mm/mmap.c

> index 0584e540246e..81f5595a8490 100644

> --- a/mm/mmap.c

> +++ b/mm/mmap.c

> @@ -1352,9 +1352,8 @@ static inline unsigned long round_hint_to_min(unsigned long hint)

>   	return hint;

>   }

>   

> -static inline int mlock_future_check(struct mm_struct *mm,

> -				     unsigned long flags,

> -				     unsigned long len)

> +int mlock_future_check(struct mm_struct *mm, unsigned long flags,

> +		       unsigned long len)

>   {

>   	unsigned long locked, lock_limit;

>   

> 


Reviewed-by: David Hildenbrand <david@redhat.com>


-- 
Thanks,

David / dhildenb
David Hildenbrand May 14, 2021, 8:43 a.m. UTC | #3
On 13.05.21 20:47, Mike Rapoport wrote:
> From: Mike Rapoport <rppt@linux.ibm.com>

> 

> The underlying implementations of set_direct_map_invalid_noflush() and

> set_direct_map_default_noflush() allow updating multiple contiguous pages

> at once.

> 

> Add numpages parameter to set_direct_map_*_noflush() to expose this

> ability with these APIs.

> 


[...]

Finally doing some in-depth review, sorry for not having a detailed look 
earlier.


>   

> -int set_direct_map_invalid_noflush(struct page *page)

> +int set_direct_map_invalid_noflush(struct page *page, int numpages)

>   {

>   	struct page_change_data data = {

>   		.set_mask = __pgprot(0),

>   		.clear_mask = __pgprot(PTE_VALID),

>   	};

> +	unsigned long size = PAGE_SIZE * numpages;

>   


Nit: I'd have made this const and added an early exit for !numpages. But 
whatever you prefer.

>   	if (!debug_pagealloc_enabled() && !rodata_full)

>   		return 0;

>   

>   	return apply_to_page_range(&init_mm,

>   				   (unsigned long)page_address(page),

> -				   PAGE_SIZE, change_page_range, &data);

> +				   size, change_page_range, &data);

>   }

>   

> -int set_direct_map_default_noflush(struct page *page)

> +int set_direct_map_default_noflush(struct page *page, int numpages)

>   {

>   	struct page_change_data data = {

>   		.set_mask = __pgprot(PTE_VALID | PTE_WRITE),

>   		.clear_mask = __pgprot(PTE_RDONLY),

>   	};

> +	unsigned long size = PAGE_SIZE * numpages;

>   


Nit: dito

>   	if (!debug_pagealloc_enabled() && !rodata_full)

>   		return 0;

>   

>   	return apply_to_page_range(&init_mm,

>   				   (unsigned long)page_address(page),

> -				   PAGE_SIZE, change_page_range, &data);

> +				   size, change_page_range, &data);

>   }

>   



[...]

>   extern int kernel_set_to_readonly;

> diff --git a/arch/x86/mm/pat/set_memory.c b/arch/x86/mm/pat/set_memory.c

> index 156cd235659f..15a55d6e9cec 100644

> --- a/arch/x86/mm/pat/set_memory.c

> +++ b/arch/x86/mm/pat/set_memory.c

> @@ -2192,14 +2192,14 @@ static int __set_pages_np(struct page *page, int numpages)

>   	return __change_page_attr_set_clr(&cpa, 0);

>   }

>   

> -int set_direct_map_invalid_noflush(struct page *page)

> +int set_direct_map_invalid_noflush(struct page *page, int numpages)

>   {

> -	return __set_pages_np(page, 1);

> +	return __set_pages_np(page, numpages);

>   }

>   

> -int set_direct_map_default_noflush(struct page *page)

> +int set_direct_map_default_noflush(struct page *page, int numpages)

>   {

> -	return __set_pages_p(page, 1);

> +	return __set_pages_p(page, numpages);

>   }

>   


So, what happens if we succeeded setting 
set_direct_map_invalid_noflush() for some pages but fail when having to 
split a large mapping?

Did I miss something or would the current code not undo what it 
partially did? Or do we simply not care?

I guess to handle this cleanly we would either have to catch all error 
cases first (esp. splitting large mappings) before actually performing 
the set to invalid, or have some recovery code in place if possible.


AFAIKs, your patch #5 right now only calls it with 1 page, do we need 
this change at all? Feels like a leftover from older versions to me 
where we could have had more than a single page.

-- 
Thanks,

David / dhildenb
David Hildenbrand May 14, 2021, 8:50 a.m. UTC | #4
On 13.05.21 20:47, Mike Rapoport wrote:
> From: Mike Rapoport <rppt@linux.ibm.com>

> 

> Introduce "memfd_secret" system call with the ability to create

> memory areas visible only in the context of the owning process and

> not mapped not only to other processes but in the kernel page tables

> as well.

> 

> The secretmem feature is off by default and the user must explicitly

> enable it at the boot time.

> 

> Once secretmem is enabled, the user will be able to create a file 

> descriptor using the memfd_secret() system call. The memory areas

> created by mmap() calls from this file descriptor will be unmapped

> from the kernel direct map and they will be only mapped in the page

> table of the processes that have access to the file descriptor.

> 

> The file descriptor based memory has several advantages over the 

> "traditional" mm interfaces, such as mlock(), mprotect(), madvise().

> File descriptor approach allows explict and controlled sharing of the

> memory


s/explict/explicit/

> areas, it allows to seal the operations. Besides, file descriptor

> based memory paves the way for VMMs to remove the secret memory range

> from the userpace hipervisor process, for instance QEMU. Andy

> Lutomirski says:


s/userpace hipervisor/userspace hypervisor/

> 

> "Getting fd-backed memory into a guest will take some possibly major

> work in the kernel, but getting vma-backed memory into a guest

> without mapping it in the host user address space seems much, much

> worse."

> 

> memfd_secret() is made a dedicated system call rather than an

> extention to


s/extention/extension/

> memfd_create() because it's purpose is to allow the user to create

> more secure memory mappings rather than to simply allow file based

> access to the memory. Nowadays a new system call cost is negligible

> while it is way simpler for userspace to deal with a clear-cut system

> calls than with a multiplexer or an overloaded syscall. Moreover, the

> initial implementation of memfd_secret() is completely distinct from

> memfd_create() so there is no much sense in overloading

> memfd_create() to begin with. If there will be a need for code

> sharing between these implementation it can be easily achieved

> without a need to adjust user visible APIs.

> 

> The secret memory remains accessible in the process context using

> uaccess primitives, but it is not exposed to the kernel otherwise;

> secret memory areas are removed from the direct map and functions in

> the follow_page()/get_user_page() family will refuse to return a page

> that belongs to the secret memory area.

> 

> Once there will be a use case that will require exposing secretmem to

> the kernel it will be an opt-in request in the system call flags so

> that user would have to decide what data can be exposed to the

> kernel.


Maybe spell out an example: like page migration.

> 

> Removing of the pages from the direct map may cause its fragmentation

> on architectures that use large pages to map the physical memory

> which affects the system performance. However, the original Kconfig

> text for CONFIG_DIRECT_GBPAGES said that gigabyte pages in the direct

> map "... can improve the kernel's performance a tiny bit ..." (commit

> 00d1c5e05736 ("x86: add gbpages switches")) and the recent report [1]

> showed that "... although 1G mappings are a good default choice,

> there is no compelling evidence that it must be the only choice".

> Hence, it is sufficient to have secretmem disabled by default with

> the ability of a system administrator to enable it at boot time.


Maybe add a link to the Intel performance evaluation.

> 

> Pages in the secretmem regions are unevictable and unmovable to

> avoid accidental exposure of the sensitive data via swap or during

> page migration.

> 

> Since the secretmem mappings are locked in memory they cannot exceed 

> RLIMIT_MEMLOCK. Since these mappings are already locked independently

> from mlock(), an attempt to mlock()/munlock() secretmem range would

> fail and mlockall()/munlockall() will ignore secretmem mappings.


Maybe add something like "similar to pages pinned by VFIO".

> 

> However, unlike mlock()ed memory, secretmem currently behaves more

> like long-term GUP: secretmem mappings are unmovable mappings

> directly consumed by user space. With default limits, there is no

> excessive use of secretmem and it poses no real problem in

> combination with ZONE_MOVABLE/CMA, but in the future this should be

> addressed to allow balanced use of large amounts of secretmem along

> with ZONE_MOVABLE/CMA.

> 

> A page that was a part of the secret memory area is cleared when it

> is freed to ensure the data is not exposed to the next user of that

> page.


You could skip that with init_on_free (and eventually also with 
init_on_alloc) set to avoid double clearing.

> 

> The following example demonstrates creation of a secret mapping

> (error handling is omitted):

> 

> fd = memfd_secret(0); ftruncate(fd, MAP_SIZE); ptr = mmap(NULL,

> MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

> 

> [1]

> https://lore.kernel.org/linux-mm/213b4567-46ce-f116-9cdf-bbd0c884eb3c@linux.intel.com/


[my mail client messed up the remainder of the mail for whatever reason, 
will comment in a separate mail if there is anything to comment :) ]

-- 
Thanks,

David / dhildenb
David Hildenbrand May 14, 2021, 9:25 a.m. UTC | #5
>   #ifdef CONFIG_IA64

>   # include <linux/efi.h>

> @@ -64,6 +65,9 @@ static inline int valid_mmap_phys_addr_range(unsigned long pfn, size_t size)

>   #ifdef CONFIG_STRICT_DEVMEM

>   static inline int page_is_allowed(unsigned long pfn)

>   {

> +	if (pfn_valid(pfn) && page_is_secretmem(pfn_to_page(pfn)))

> +		return 0;

> +


1. The memmap might be garbage. You should use pfn_to_online_page() instead.

page = pfn_to_online_page(pfn);
if (page && page_is_secretmem(page))
	return 0;

2. What about !CONFIG_STRICT_DEVMEM?

3. Someone could map physical memory before a secretmem page gets 
allocated and read the content after it got allocated and gets used. If 
someone would gain root privileges and would wait for the target 
application to (re)start, that could be problematic.


I do wonder if enforcing CONFIG_STRICT_DEVMEM would be cleaner. 
devmem_is_allowed() should disallow access to any system ram, and 
thereby, any possible secretmem pages, avoiding this check completely.


[...]

>   

> diff --git a/mm/secretmem.c b/mm/secretmem.c

> new file mode 100644

> index 000000000000..1ae50089adf1

> --- /dev/null

> +++ b/mm/secretmem.c

> @@ -0,0 +1,239 @@

> +// SPDX-License-Identifier: GPL-2.0

> +/*

> + * Copyright IBM Corporation, 2021

> + *

> + * Author: Mike Rapoport <rppt@linux.ibm.com>

> + */

> +

> +#include <linux/mm.h>

> +#include <linux/fs.h>

> +#include <linux/swap.h>

> +#include <linux/mount.h>

> +#include <linux/memfd.h>

> +#include <linux/bitops.h>

> +#include <linux/printk.h>

> +#include <linux/pagemap.h>

> +#include <linux/syscalls.h>

> +#include <linux/pseudo_fs.h>

> +#include <linux/secretmem.h>

> +#include <linux/set_memory.h>

> +#include <linux/sched/signal.h>

> +

> +#include <uapi/linux/magic.h>

> +

> +#include <asm/tlbflush.h>

> +

> +#include "internal.h"

> +

> +#undef pr_fmt

> +#define pr_fmt(fmt) "secretmem: " fmt

> +

> +/*

> + * Define mode and flag masks to allow validation of the system call

> + * parameters.

> + */

> +#define SECRETMEM_MODE_MASK	(0x0)

> +#define SECRETMEM_FLAGS_MASK	SECRETMEM_MODE_MASK

> +

> +static bool secretmem_enable __ro_after_init;

> +module_param_named(enable, secretmem_enable, bool, 0400);

> +MODULE_PARM_DESC(secretmem_enable,

> +		 "Enable secretmem and memfd_secret(2) system call");

> +

> +static vm_fault_t secretmem_fault(struct vm_fault *vmf)

> +{

> +	struct address_space *mapping = vmf->vma->vm_file->f_mapping;

> +	struct inode *inode = file_inode(vmf->vma->vm_file);

> +	pgoff_t offset = vmf->pgoff;

> +	gfp_t gfp = vmf->gfp_mask;

> +	unsigned long addr;

> +	struct page *page;

> +	int err;

> +

> +	if (((loff_t)vmf->pgoff << PAGE_SHIFT) >= i_size_read(inode))

> +		return vmf_error(-EINVAL);

> +

> +retry:

> +	page = find_lock_page(mapping, offset);

> +	if (!page) {

> +		page = alloc_page(gfp | __GFP_ZERO);


We'll end up here with gfp == GFP_HIGHUSER (via the mapping below), correct?

> +		if (!page)

> +			return VM_FAULT_OOM;

> +

> +		err = set_direct_map_invalid_noflush(page, 1);

> +		if (err) {

> +			put_page(page);

> +			return vmf_error(err);


Would we want to translate that to a proper VM_FAULT_..., which would 
most probably be VM_FAULT_OOM when we fail to allocate a pagetable?

> +		}

> +

> +		__SetPageUptodate(page);

> +		err = add_to_page_cache_lru(page, mapping, offset, gfp);

> +		if (unlikely(err)) {

> +			put_page(page);

> +			/*

> +			 * If a split of large page was required, it

> +			 * already happened when we marked the page invalid

> +			 * which guarantees that this call won't fail

> +			 */

> +			set_direct_map_default_noflush(page, 1);

> +			if (err == -EEXIST)

> +				goto retry;

> +

> +			return vmf_error(err);

> +		}

> +

> +		addr = (unsigned long)page_address(page);

> +		flush_tlb_kernel_range(addr, addr + PAGE_SIZE);


Hmm, to me it feels like something like that belongs into the 
set_direct_map_invalid_*() calls? Otherwise it's just very easy to mess 
up ...


I'm certainly not a filesystem guy. Nothing else jumped at me.


To me, the overall approach makes sense and I consider it an improved 
mlock() mechanism for storing secrets, although I'd love to have some 
more information in the log regarding access via root, namely that there 
are still fancy ways to read secretmem memory once root via

1. warm reboot attacks especially in VMs (e.g., modifying the cmdline)
2. kexec-style reboot attacks (e.g., modifying the cmdline)
3. kdump attacks
4. kdb most probably
5. "letting the process read the memory for us" via Kees if that still
    applies
6. ... most probably something else

Just to make people aware that there are still some things to be sorted 
out when we fully want to protect against privilege escalations.

(maybe this information is buried in the cover letter already, where it 
usually gets lost)

-- 
Thanks,

David / dhildenb
David Hildenbrand May 14, 2021, 9:27 a.m. UTC | #6
On 13.05.21 20:47, Mike Rapoport wrote:
> From: Mike Rapoport <rppt@linux.ibm.com>

> 

> Wire up memfd_secret system call on architectures that define

> ARCH_HAS_SET_DIRECT_MAP, namely arm64, risc-v and x86.

> 

> Signed-off-by: Mike Rapoport <rppt@linux.ibm.com>

> Acked-by: Palmer Dabbelt <palmerdabbelt@google.com>

> Acked-by: Arnd Bergmann <arnd@arndb.de>

> Acked-by: Catalin Marinas <catalin.marinas@arm.com>

> Cc: Alexander Viro <viro@zeniv.linux.org.uk>

> Cc: Andy Lutomirski <luto@kernel.org>

> Cc: Borislav Petkov <bp@alien8.de>

> Cc: Christopher Lameter <cl@linux.com>

> Cc: Dan Williams <dan.j.williams@intel.com>

> Cc: Dave Hansen <dave.hansen@linux.intel.com>

> Cc: David Hildenbrand <david@redhat.com>

> Cc: Elena Reshetova <elena.reshetova@intel.com>

> Cc: Hagen Paul Pfeifer <hagen@jauu.net>

> Cc: "H. Peter Anvin" <hpa@zytor.com>

> Cc: Ingo Molnar <mingo@redhat.com>

> Cc: James Bottomley <jejb@linux.ibm.com>

> Cc: "Kirill A. Shutemov" <kirill@shutemov.name>

> Cc: Mark Rutland <mark.rutland@arm.com>

> Cc: Matthew Wilcox <willy@infradead.org>

> Cc: Michael Kerrisk <mtk.manpages@gmail.com>

> Cc: Palmer Dabbelt <palmer@dabbelt.com>

> Cc: Paul Walmsley <paul.walmsley@sifive.com>

> Cc: Peter Zijlstra <peterz@infradead.org>

> Cc: Rick Edgecombe <rick.p.edgecombe@intel.com>

> Cc: Roman Gushchin <guro@fb.com>

> Cc: Shakeel Butt <shakeelb@google.com>

> Cc: Shuah Khan <shuah@kernel.org>

> Cc: Thomas Gleixner <tglx@linutronix.de>

> Cc: Tycho Andersen <tycho@tycho.ws>

> Cc: Will Deacon <will@kernel.org>

> ---

>   arch/arm64/include/uapi/asm/unistd.h   | 1 +

>   arch/riscv/include/asm/unistd.h        | 1 +

>   arch/x86/entry/syscalls/syscall_32.tbl | 1 +

>   arch/x86/entry/syscalls/syscall_64.tbl | 1 +

>   include/linux/syscalls.h               | 1 +

>   include/uapi/asm-generic/unistd.h      | 7 ++++++-

>   scripts/checksyscalls.sh               | 4 ++++

>   7 files changed, 15 insertions(+), 1 deletion(-)

> 

> diff --git a/arch/arm64/include/uapi/asm/unistd.h b/arch/arm64/include/uapi/asm/unistd.h

> index f83a70e07df8..ce2ee8f1e361 100644

> --- a/arch/arm64/include/uapi/asm/unistd.h

> +++ b/arch/arm64/include/uapi/asm/unistd.h

> @@ -20,5 +20,6 @@

>   #define __ARCH_WANT_SET_GET_RLIMIT

>   #define __ARCH_WANT_TIME32_SYSCALLS

>   #define __ARCH_WANT_SYS_CLONE3

> +#define __ARCH_WANT_MEMFD_SECRET

>   

>   #include <asm-generic/unistd.h>

> diff --git a/arch/riscv/include/asm/unistd.h b/arch/riscv/include/asm/unistd.h

> index 977ee6181dab..6c316093a1e5 100644

> --- a/arch/riscv/include/asm/unistd.h

> +++ b/arch/riscv/include/asm/unistd.h

> @@ -9,6 +9,7 @@

>    */

>   

>   #define __ARCH_WANT_SYS_CLONE

> +#define __ARCH_WANT_MEMFD_SECRET

>   

>   #include <uapi/asm/unistd.h>

>   

> diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl

> index 28a1423ce32e..e44519020a43 100644

> --- a/arch/x86/entry/syscalls/syscall_32.tbl

> +++ b/arch/x86/entry/syscalls/syscall_32.tbl

> @@ -451,3 +451,4 @@

>   444	i386	landlock_create_ruleset	sys_landlock_create_ruleset

>   445	i386	landlock_add_rule	sys_landlock_add_rule

>   446	i386	landlock_restrict_self	sys_landlock_restrict_self

> +447	i386	memfd_secret		sys_memfd_secret

> diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl

> index ecd551b08d05..a06f16106f24 100644

> --- a/arch/x86/entry/syscalls/syscall_64.tbl

> +++ b/arch/x86/entry/syscalls/syscall_64.tbl

> @@ -368,6 +368,7 @@

>   444	common	landlock_create_ruleset	sys_landlock_create_ruleset

>   445	common	landlock_add_rule	sys_landlock_add_rule

>   446	common	landlock_restrict_self	sys_landlock_restrict_self

> +447	common	memfd_secret		sys_memfd_secret

>   

>   #

>   # Due to a historical design error, certain syscalls are numbered differently

> diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h

> index 050511e8f1f8..1a1b5d724497 100644

> --- a/include/linux/syscalls.h

> +++ b/include/linux/syscalls.h

> @@ -1050,6 +1050,7 @@ asmlinkage long sys_landlock_create_ruleset(const struct landlock_ruleset_attr _

>   asmlinkage long sys_landlock_add_rule(int ruleset_fd, enum landlock_rule_type rule_type,

>   		const void __user *rule_attr, __u32 flags);

>   asmlinkage long sys_landlock_restrict_self(int ruleset_fd, __u32 flags);

> +asmlinkage long sys_memfd_secret(unsigned int flags);

>   

>   /*

>    * Architecture-specific system calls

> diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h

> index 6de5a7fc066b..28b388368cf6 100644

> --- a/include/uapi/asm-generic/unistd.h

> +++ b/include/uapi/asm-generic/unistd.h

> @@ -873,8 +873,13 @@ __SYSCALL(__NR_landlock_add_rule, sys_landlock_add_rule)

>   #define __NR_landlock_restrict_self 446

>   __SYSCALL(__NR_landlock_restrict_self, sys_landlock_restrict_self)

>   

> +#ifdef __ARCH_WANT_MEMFD_SECRET

> +#define __NR_memfd_secret 447

> +__SYSCALL(__NR_memfd_secret, sys_memfd_secret)

> +#endif

> +

>   #undef __NR_syscalls

> -#define __NR_syscalls 447

> +#define __NR_syscalls 448

>   

>   /*

>    * 32 bit systems traditionally used different

> diff --git a/scripts/checksyscalls.sh b/scripts/checksyscalls.sh

> index a18b47695f55..b7609958ee36 100755

> --- a/scripts/checksyscalls.sh

> +++ b/scripts/checksyscalls.sh

> @@ -40,6 +40,10 @@ cat << EOF

>   #define __IGNORE_setrlimit	/* setrlimit */

>   #endif

>   

> +#ifndef __ARCH_WANT_MEMFD_SECRET

> +#define __IGNORE_memfd_secret

> +#endif

> +

>   /* Missing flags argument */

>   #define __IGNORE_renameat	/* renameat2 */

>   

> 


Acked-by: David Hildenbrand <david@redhat.com>


-- 
Thanks,

David / dhildenb
Mike Rapoport May 16, 2021, 7:13 a.m. UTC | #7
On Fri, May 14, 2021 at 10:43:29AM +0200, David Hildenbrand wrote:
> On 13.05.21 20:47, Mike Rapoport wrote:

> > From: Mike Rapoport <rppt@linux.ibm.com>

> > 

> > The underlying implementations of set_direct_map_invalid_noflush() and

> > set_direct_map_default_noflush() allow updating multiple contiguous pages

> > at once.

> > 

> > Add numpages parameter to set_direct_map_*_noflush() to expose this

> > ability with these APIs.

> 

> AFAIKs, your patch #5 right now only calls it with 1 page, do we need this

> change at all? Feels like a leftover from older versions to me where we

> could have had more than a single page.


Right, will drop it. 

-- 
Sincerely yours,
Mike.
Mike Rapoport May 16, 2021, 7:29 a.m. UTC | #8
On Fri, May 14, 2021 at 11:25:43AM +0200, David Hildenbrand wrote:
> >   #ifdef CONFIG_IA64

> >   # include <linux/efi.h>

> > @@ -64,6 +65,9 @@ static inline int valid_mmap_phys_addr_range(unsigned long pfn, size_t size)

> >   #ifdef CONFIG_STRICT_DEVMEM

> >   static inline int page_is_allowed(unsigned long pfn)

> >   {

> > +	if (pfn_valid(pfn) && page_is_secretmem(pfn_to_page(pfn)))

> > +		return 0;

> > +

> 

> 1. The memmap might be garbage. You should use pfn_to_online_page() instead.

> 

> page = pfn_to_online_page(pfn);

> if (page && page_is_secretmem(page))

> 	return 0;

> 

> 2. What about !CONFIG_STRICT_DEVMEM?

> 

> 3. Someone could map physical memory before a secretmem page gets allocated

> and read the content after it got allocated and gets used. If someone would

> gain root privileges and would wait for the target application to (re)start,

> that could be problematic.

> 

> 

> I do wonder if enforcing CONFIG_STRICT_DEVMEM would be cleaner.

> devmem_is_allowed() should disallow access to any system ram, and thereby,

> any possible secretmem pages, avoiding this check completely.


I've been thinking a bit more about the /dev/mem case, it seems I was to
fast on the trigger with adding that test for page_is_secretmem().

When CONFIG_STRICT_DEVMEM=y the access to RAM is anyway forbidden and if
the user built a kernel with CONFIG_STRICT_DEVMEM=n all the physical memory
is accessible by root anyway.

We might want to default STRICT_DEVMEM to "y" for all architectures and not
only arm64, ppc and x86, but this is not strictly related to this series.
 
> [...]

> 

> > diff --git a/mm/secretmem.c b/mm/secretmem.c

> > new file mode 100644

> > index 000000000000..1ae50089adf1

> > --- /dev/null

> > +++ b/mm/secretmem.c

> > @@ -0,0 +1,239 @@

> > +// SPDX-License-Identifier: GPL-2.0

> > +/*

> > + * Copyright IBM Corporation, 2021

> > + *

> > + * Author: Mike Rapoport <rppt@linux.ibm.com>

> > + */

> > +

> > +#include <linux/mm.h>

> > +#include <linux/fs.h>

> > +#include <linux/swap.h>

> > +#include <linux/mount.h>

> > +#include <linux/memfd.h>

> > +#include <linux/bitops.h>

> > +#include <linux/printk.h>

> > +#include <linux/pagemap.h>

> > +#include <linux/syscalls.h>

> > +#include <linux/pseudo_fs.h>

> > +#include <linux/secretmem.h>

> > +#include <linux/set_memory.h>

> > +#include <linux/sched/signal.h>

> > +

> > +#include <uapi/linux/magic.h>

> > +

> > +#include <asm/tlbflush.h>

> > +

> > +#include "internal.h"

> > +

> > +#undef pr_fmt

> > +#define pr_fmt(fmt) "secretmem: " fmt

> > +

> > +/*

> > + * Define mode and flag masks to allow validation of the system call

> > + * parameters.

> > + */

> > +#define SECRETMEM_MODE_MASK	(0x0)

> > +#define SECRETMEM_FLAGS_MASK	SECRETMEM_MODE_MASK

> > +

> > +static bool secretmem_enable __ro_after_init;

> > +module_param_named(enable, secretmem_enable, bool, 0400);

> > +MODULE_PARM_DESC(secretmem_enable,

> > +		 "Enable secretmem and memfd_secret(2) system call");

> > +

> > +static vm_fault_t secretmem_fault(struct vm_fault *vmf)

> > +{

> > +	struct address_space *mapping = vmf->vma->vm_file->f_mapping;

> > +	struct inode *inode = file_inode(vmf->vma->vm_file);

> > +	pgoff_t offset = vmf->pgoff;

> > +	gfp_t gfp = vmf->gfp_mask;

> > +	unsigned long addr;

> > +	struct page *page;

> > +	int err;

> > +

> > +	if (((loff_t)vmf->pgoff << PAGE_SHIFT) >= i_size_read(inode))

> > +		return vmf_error(-EINVAL);

> > +

> > +retry:

> > +	page = find_lock_page(mapping, offset);

> > +	if (!page) {

> > +		page = alloc_page(gfp | __GFP_ZERO);

> 

> We'll end up here with gfp == GFP_HIGHUSER (via the mapping below), correct?


Yes
 
> > +		if (!page)

> > +			return VM_FAULT_OOM;

> > +

> > +		err = set_direct_map_invalid_noflush(page, 1);

> > +		if (err) {

> > +			put_page(page);

> > +			return vmf_error(err);

> 

> Would we want to translate that to a proper VM_FAULT_..., which would most

> probably be VM_FAULT_OOM when we fail to allocate a pagetable?


That's what vmf_error does, it translates -ESOMETHING to VM_FAULT_XYZ.

> > +		}

> > +

> > +		__SetPageUptodate(page);

> > +		err = add_to_page_cache_lru(page, mapping, offset, gfp);

> > +		if (unlikely(err)) {

> > +			put_page(page);

> > +			/*

> > +			 * If a split of large page was required, it

> > +			 * already happened when we marked the page invalid

> > +			 * which guarantees that this call won't fail

> > +			 */

> > +			set_direct_map_default_noflush(page, 1);

> > +			if (err == -EEXIST)

> > +				goto retry;

> > +

> > +			return vmf_error(err);

> > +		}

> > +

> > +		addr = (unsigned long)page_address(page);

> > +		flush_tlb_kernel_range(addr, addr + PAGE_SIZE);

> 

> Hmm, to me it feels like something like that belongs into the

> set_direct_map_invalid_*() calls? Otherwise it's just very easy to mess up

> ...


AFAIU set_direct_map() deliberately do not flush TLB and leave it to the
caller to allow gathering multiple updates of the direct map and doing a
single TLB flush afterwards.

> I'm certainly not a filesystem guy. Nothing else jumped at me.

> 

> 

> To me, the overall approach makes sense and I consider it an improved

> mlock() mechanism for storing secrets, although I'd love to have some more

> information in the log regarding access via root, namely that there are

> still fancy ways to read secretmem memory once root via

> 

> 1. warm reboot attacks especially in VMs (e.g., modifying the cmdline)

> 2. kexec-style reboot attacks (e.g., modifying the cmdline)

> 3. kdump attacks

> 4. kdb most probably

> 5. "letting the process read the memory for us" via Kees if that still

>    applies

> 6. ... most probably something else

> 

> Just to make people aware that there are still some things to be sorted out

> when we fully want to protect against privilege escalations.

> 

> (maybe this information is buried in the cover letter already, where it

> usually gets lost)


I believe that it belongs more to the man page than to changelog so that
the *users* are aware of secretmem limitations.
 
-- 
Sincerely yours,
Mike.
Mike Rapoport May 17, 2021, 7:23 a.m. UTC | #9
On Fri, May 14, 2021 at 10:50:55AM +0200, David Hildenbrand wrote:
> On 13.05.21 20:47, Mike Rapoport wrote:

> > From: Mike Rapoport <rppt@linux.ibm.com>

> > 

> > Removing of the pages from the direct map may cause its fragmentation

> > on architectures that use large pages to map the physical memory

> > which affects the system performance. However, the original Kconfig

> > text for CONFIG_DIRECT_GBPAGES said that gigabyte pages in the direct

> > map "... can improve the kernel's performance a tiny bit ..." (commit

> > 00d1c5e05736 ("x86: add gbpages switches")) and the recent report [1]

> > showed that "... although 1G mappings are a good default choice,

> > there is no compelling evidence that it must be the only choice".

> > Hence, it is sufficient to have secretmem disabled by default with

> > the ability of a system administrator to enable it at boot time.

> 

> Maybe add a link to the Intel performance evaluation.

 
" ... the recent report [1]" and the link below.
 
> > Pages in the secretmem regions are unevictable and unmovable to

> > avoid accidental exposure of the sensitive data via swap or during

> > page migration.

 
...

> > A page that was a part of the secret memory area is cleared when it

> > is freed to ensure the data is not exposed to the next user of that

> > page.

> 

> You could skip that with init_on_free (and eventually also with

> init_on_alloc) set to avoid double clearing.


Right, but for now I'd prefer to keep this explicit in the secretmem
implementation. We may add the check for init_on_free/init_on_alloc later
on.


> > [1]

> > https://lore.kernel.org/linux-mm/213b4567-46ce-f116-9cdf-bbd0c884eb3c@linux.intel.com/

> 


-- 
Sincerely yours,
Mike.
Michal Hocko May 18, 2021, 9:59 a.m. UTC | #10
On Sun 16-05-21 10:29:24, Mike Rapoport wrote:
> On Fri, May 14, 2021 at 11:25:43AM +0200, David Hildenbrand wrote:

[...]
> > > +		if (!page)

> > > +			return VM_FAULT_OOM;

> > > +

> > > +		err = set_direct_map_invalid_noflush(page, 1);

> > > +		if (err) {

> > > +			put_page(page);

> > > +			return vmf_error(err);

> > 

> > Would we want to translate that to a proper VM_FAULT_..., which would most

> > probably be VM_FAULT_OOM when we fail to allocate a pagetable?

> 

> That's what vmf_error does, it translates -ESOMETHING to VM_FAULT_XYZ.


I haven't read through the rest but this has just caught my attention.
Is it really reasonable to trigger the oom killer when you cannot
invalidate the direct mapping. From a quick look at the code it is quite
unlikely to se ENOMEM from that path (it allocates small pages) but this
can become quite sublte over time. Shouldn't this simply SIGBUS if it
cannot manipulate the direct mapping regardless of the underlying reason
for that?
-- 
Michal Hocko
SUSE Labs
David Hildenbrand May 18, 2021, 10:06 a.m. UTC | #11
On 18.05.21 11:59, Michal Hocko wrote:
> On Sun 16-05-21 10:29:24, Mike Rapoport wrote:

>> On Fri, May 14, 2021 at 11:25:43AM +0200, David Hildenbrand wrote:

> [...]

>>>> +		if (!page)

>>>> +			return VM_FAULT_OOM;

>>>> +

>>>> +		err = set_direct_map_invalid_noflush(page, 1);

>>>> +		if (err) {

>>>> +			put_page(page);

>>>> +			return vmf_error(err);

>>>

>>> Would we want to translate that to a proper VM_FAULT_..., which would most

>>> probably be VM_FAULT_OOM when we fail to allocate a pagetable?

>>

>> That's what vmf_error does, it translates -ESOMETHING to VM_FAULT_XYZ.

> 

> I haven't read through the rest but this has just caught my attention.

> Is it really reasonable to trigger the oom killer when you cannot

> invalidate the direct mapping. From a quick look at the code it is quite

> unlikely to se ENOMEM from that path (it allocates small pages) but this

> can become quite sublte over time. Shouldn't this simply SIGBUS if it

> cannot manipulate the direct mapping regardless of the underlying reason

> for that?

> 


OTOH, it means our kernel zones are depleted, so we'd better reclaim 
somehow ...

-- 
Thanks,

David / dhildenb
Michal Hocko May 18, 2021, 10:31 a.m. UTC | #12
On Tue 18-05-21 12:06:42, David Hildenbrand wrote:
> On 18.05.21 11:59, Michal Hocko wrote:

> > On Sun 16-05-21 10:29:24, Mike Rapoport wrote:

> > > On Fri, May 14, 2021 at 11:25:43AM +0200, David Hildenbrand wrote:

> > [...]

> > > > > +		if (!page)

> > > > > +			return VM_FAULT_OOM;

> > > > > +

> > > > > +		err = set_direct_map_invalid_noflush(page, 1);

> > > > > +		if (err) {

> > > > > +			put_page(page);

> > > > > +			return vmf_error(err);

> > > > 

> > > > Would we want to translate that to a proper VM_FAULT_..., which would most

> > > > probably be VM_FAULT_OOM when we fail to allocate a pagetable?

> > > 

> > > That's what vmf_error does, it translates -ESOMETHING to VM_FAULT_XYZ.

> > 

> > I haven't read through the rest but this has just caught my attention.

> > Is it really reasonable to trigger the oom killer when you cannot

> > invalidate the direct mapping. From a quick look at the code it is quite

> > unlikely to se ENOMEM from that path (it allocates small pages) but this

> > can become quite sublte over time. Shouldn't this simply SIGBUS if it

> > cannot manipulate the direct mapping regardless of the underlying reason

> > for that?

> > 

> 

> OTOH, it means our kernel zones are depleted, so we'd better reclaim somehow

> ...


Killing a userspace seems to be just a bad way around that.

Although I have to say openly that I am not a great fan of VM_FAULT_OOM
in general. It is usually a a wrong way to tell the handle the failure
because it happens outside of the allocation context so you lose all the
details (e.g. allocation constrains, numa policy etc.). Also whenever
there is ENOMEM then the allocation itself has already made sure that
all the reclaim attempts have been already depleted. Just consider an
allocation with GFP_NOWAIT/NO_RETRY or similar to fail and propagate
ENOMEM up the call stack. Turning that into the OOM killer sounds like a
bad idea to me.  But that is a more general topic. I have tried to bring
this up in the past but there was not much of an interest to fix it as
it was not a pressing problem...
-- 
Michal Hocko
SUSE Labs
David Hildenbrand May 18, 2021, 10:35 a.m. UTC | #13
On 18.05.21 12:31, Michal Hocko wrote:
> On Tue 18-05-21 12:06:42, David Hildenbrand wrote:

>> On 18.05.21 11:59, Michal Hocko wrote:

>>> On Sun 16-05-21 10:29:24, Mike Rapoport wrote:

>>>> On Fri, May 14, 2021 at 11:25:43AM +0200, David Hildenbrand wrote:

>>> [...]

>>>>>> +		if (!page)

>>>>>> +			return VM_FAULT_OOM;

>>>>>> +

>>>>>> +		err = set_direct_map_invalid_noflush(page, 1);

>>>>>> +		if (err) {

>>>>>> +			put_page(page);

>>>>>> +			return vmf_error(err);

>>>>>

>>>>> Would we want to translate that to a proper VM_FAULT_..., which would most

>>>>> probably be VM_FAULT_OOM when we fail to allocate a pagetable?

>>>>

>>>> That's what vmf_error does, it translates -ESOMETHING to VM_FAULT_XYZ.

>>>

>>> I haven't read through the rest but this has just caught my attention.

>>> Is it really reasonable to trigger the oom killer when you cannot

>>> invalidate the direct mapping. From a quick look at the code it is quite

>>> unlikely to se ENOMEM from that path (it allocates small pages) but this

>>> can become quite sublte over time. Shouldn't this simply SIGBUS if it

>>> cannot manipulate the direct mapping regardless of the underlying reason

>>> for that?

>>>

>>

>> OTOH, it means our kernel zones are depleted, so we'd better reclaim somehow

>> ...

> 

> Killing a userspace seems to be just a bad way around that.

> 

> Although I have to say openly that I am not a great fan of VM_FAULT_OOM

> in general. It is usually a a wrong way to tell the handle the failure

> because it happens outside of the allocation context so you lose all the

> details (e.g. allocation constrains, numa policy etc.). Also whenever

> there is ENOMEM then the allocation itself has already made sure that

> all the reclaim attempts have been already depleted. Just consider an

> allocation with GFP_NOWAIT/NO_RETRY or similar to fail and propagate

> ENOMEM up the call stack. Turning that into the OOM killer sounds like a

> bad idea to me.  But that is a more general topic. I have tried to bring

> this up in the past but there was not much of an interest to fix it as

> it was not a pressing problem...

> 


I'm certainly interested; it would mean that we actually want to try 
recovering from VM_FAULT_OOM in various cases, and as you state, we 
might have to supply more information to make that work reliably.

Having that said, I guess what we have here is just the same as when our 
process fails to allocate a generic page table in __handle_mm_fault(), 
when we fail p4d_alloc() and friends ...

-- 
Thanks,

David / dhildenb
Michal Hocko May 18, 2021, 11:08 a.m. UTC | #14
On Tue 18-05-21 12:35:36, David Hildenbrand wrote:
> On 18.05.21 12:31, Michal Hocko wrote:

> > On Tue 18-05-21 12:06:42, David Hildenbrand wrote:

> > > On 18.05.21 11:59, Michal Hocko wrote:

> > > > On Sun 16-05-21 10:29:24, Mike Rapoport wrote:

> > > > > On Fri, May 14, 2021 at 11:25:43AM +0200, David Hildenbrand wrote:

> > > > [...]

> > > > > > > +		if (!page)

> > > > > > > +			return VM_FAULT_OOM;

> > > > > > > +

> > > > > > > +		err = set_direct_map_invalid_noflush(page, 1);

> > > > > > > +		if (err) {

> > > > > > > +			put_page(page);

> > > > > > > +			return vmf_error(err);

> > > > > > 

> > > > > > Would we want to translate that to a proper VM_FAULT_..., which would most

> > > > > > probably be VM_FAULT_OOM when we fail to allocate a pagetable?

> > > > > 

> > > > > That's what vmf_error does, it translates -ESOMETHING to VM_FAULT_XYZ.

> > > > 

> > > > I haven't read through the rest but this has just caught my attention.

> > > > Is it really reasonable to trigger the oom killer when you cannot

> > > > invalidate the direct mapping. From a quick look at the code it is quite

> > > > unlikely to se ENOMEM from that path (it allocates small pages) but this

> > > > can become quite sublte over time. Shouldn't this simply SIGBUS if it

> > > > cannot manipulate the direct mapping regardless of the underlying reason

> > > > for that?

> > > > 

> > > 

> > > OTOH, it means our kernel zones are depleted, so we'd better reclaim somehow

> > > ...

> > 

> > Killing a userspace seems to be just a bad way around that.

> > 

> > Although I have to say openly that I am not a great fan of VM_FAULT_OOM

> > in general. It is usually a a wrong way to tell the handle the failure

> > because it happens outside of the allocation context so you lose all the

> > details (e.g. allocation constrains, numa policy etc.). Also whenever

> > there is ENOMEM then the allocation itself has already made sure that

> > all the reclaim attempts have been already depleted. Just consider an

> > allocation with GFP_NOWAIT/NO_RETRY or similar to fail and propagate

> > ENOMEM up the call stack. Turning that into the OOM killer sounds like a

> > bad idea to me.  But that is a more general topic. I have tried to bring

> > this up in the past but there was not much of an interest to fix it as

> > it was not a pressing problem...

> > 

> 

> I'm certainly interested; it would mean that we actually want to try

> recovering from VM_FAULT_OOM in various cases, and as you state, we might

> have to supply more information to make that work reliably.


Or maybe we want to get rid of VM_FAULT_OOM altogether... But this is
really tangent to this discussion. The only relation is that this would
be another place to check when somebody wants to go that direction.

> Having that said, I guess what we have here is just the same as when our

> process fails to allocate a generic page table in __handle_mm_fault(), when

> we fail p4d_alloc() and friends ...


From a quick look it is really similar in a sense that it effectively never
happens and if it does then it certainly does the wrong thing. The point
I was trying to make is that there is likely no need to go that way.
Fundamentally, not being able to handle direct map for the page fault
sounds like what SIGBUS should be used for. From my POV it is similar to
ENOSPC when FS cannot allocate metadata on the storage.
-- 
Michal Hocko
SUSE Labs
Mike Rapoport May 19, 2021, 7:13 a.m. UTC | #15
On Tue, May 18, 2021 at 01:08:27PM +0200, Michal Hocko wrote:
> On Tue 18-05-21 12:35:36, David Hildenbrand wrote:

> > On 18.05.21 12:31, Michal Hocko wrote:

> > >

> > > Although I have to say openly that I am not a great fan of VM_FAULT_OOM

> > > in general. It is usually a a wrong way to tell the handle the failure

> > > because it happens outside of the allocation context so you lose all the

> > > details (e.g. allocation constrains, numa policy etc.). Also whenever

> > > there is ENOMEM then the allocation itself has already made sure that

> > > all the reclaim attempts have been already depleted. Just consider an

> > > allocation with GFP_NOWAIT/NO_RETRY or similar to fail and propagate

> > > ENOMEM up the call stack. Turning that into the OOM killer sounds like a

> > > bad idea to me.  But that is a more general topic. I have tried to bring

> > > this up in the past but there was not much of an interest to fix it as

> > > it was not a pressing problem...

> > > 

> > 

> > I'm certainly interested; it would mean that we actually want to try

> > recovering from VM_FAULT_OOM in various cases, and as you state, we might

> > have to supply more information to make that work reliably.

> 

> Or maybe we want to get rid of VM_FAULT_OOM altogether... But this is

> really tangent to this discussion. The only relation is that this would

> be another place to check when somebody wants to go that direction.


If we are to get rid of VM_FAULT_OOM, vmf_error() would be updated and this
place will get the update automagically.

> > Having that said, I guess what we have here is just the same as when our

> > process fails to allocate a generic page table in __handle_mm_fault(), when

> > we fail p4d_alloc() and friends ...

> 

> From a quick look it is really similar in a sense that it effectively never

> happens and if it does then it certainly does the wrong thing. The point

> I was trying to make is that there is likely no need to go that way.


As David pointed out, failure to handle direct map in secretmem_fault() is
like any allocation failure in page fault handling and most of them result
in VM_FAULT_OOM, so I think that having vmf_error() in secretmem_fault() is
more consistent with the rest of the code than using VM_FAULT_SIGBUS.

Besides if the direct map manipulation failures would result in errors
other than -ENOMEM, having vmf_error() may prove useful.

-- 
Sincerely yours,
Mike.