Skip to contentSkip to conversation

Shadow stacks for userspace

PATCH Superseded Rick Edgecombe 6 participants 107 messages Dec 3, 2022 – Jan 5, 2023

Subsystems (23)

v4 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#0 lore raw

v4 cover Shadow stacks for userspace

Hi,

This series implements Shadow Stacks for userspace using x86's Control-flow Enforcement Technology (CET). CET consists of two related security features:
Shadow Stacks and Indirect Branch Tracking. This series implements just the Shadow Stack part of this feature, and just for userspace.

The main use case for shadow stack is providing protection against return oriented programming attacks. It works by maintaining a secondary (shadow) stack using a special memory type that has protections against modification. When executing a CALL instruction, the processor pushes the return address to both the normal stack and to the special permissioned shadow stack. Upon RET, the processor pops the shadow stack copy and compares it to the normal stack copy. For more details, see the coverletter from v1 [0].

I humbly think this is looking decent at this point, please consider applying.

Again there were some smaller changes (logged in the patches). The more noteworthy changes were:
- Separate Shadow stack from IBT in kernel APIs. This involves renaming the arch_prctl()s. And changing the ptrace cet regset interface to only expose the SSP, and not any IBT bits.
- Handle 32 bit case more completely. (see commit log of “x86: Prevent 32 bit operations for 64 bit shstk tasks” for the details)
- Drop elf header bit filtering compatibility patch for now, per Linus. [1]
- Break apart _PAGE_COW patch for bisectability reasons.

I left the Tested-by tags that were already in place, testers please re-test.

Previous version [2].

Thanks,

Rick

[0] https://lore.kernel.org/lkml/[email protected]/
[1] https://lore.kernel.org/lkml/CAHk-=wgP5mk3poVeejw16Asbid0ghDt4okHnWaWKLBkRhQntRA@mail.gmail.com/
[2] https://lore.kernel.org/lkml/[email protected]/

Kirill A. Shutemov (1):
x86: Introduce userspace API for shadow stack

Mike Rapoport (1):
x86/shstk: Add ARCH_SHSTK_UNLOCK

Rick Edgecombe (13):
x86/fpu: Add helper for modifying xstate x86/mm: Introduce _PAGE_COW
x86/mm: Start actually marking _PAGE_COW
mm: Don't allow write GUPs to shadow stack memory
mm: Warn on shadow stack memory in wrong vma x86/shstk: Introduce map_shadow_stack syscall x86/shstk: Support wrss for userspace
x86: Expose thread features in /proc/$PID/status
x86: Prevent 32 bit operations for 64 bit shstk tasks x86/shstk: Wire in shadow stack interface selftests/x86: Add shadow stack test x86/fpu: Add helper for initing features x86/shstk: Add ARCH_SHSTK_STATUS

Yu-cheng Yu (24):
Documentation/x86: Add CET shadow stack description x86/shstk: Add Kconfig option for Shadow Stack x86/cpufeatures: Add CPU feature flags for shadow stacks x86/cpufeatures: Enable CET CR4 bit for shadow stack x86/fpu/xstate: Introduce CET MSR and XSAVES supervisor states
x86: Add user control-protection fault handler x86/mm: Remove _PAGE_DIRTY from kernel RO pages x86/mm: Move pmd_write(), pud_write() up in the file x86/mm: Update pte_modify for _PAGE_COW
x86/mm: Update ptep_set_wrprotect() and pmdp_set_wrprotect() for
transition from _PAGE_DIRTY to _PAGE_COW
mm: Move VM_UFFD_MINOR_BIT from 37 to 38
mm: Introduce VM_SHADOW_STACK for shadow stack memory x86/mm: Check Shadow Stack page fault errors
x86/mm: Update maybe_mkwrite() for shadow stack
mm: Fixup places that call pte_mkwrite() directly
mm: Add guard pages around a shadow stack.
mm/mmap: Add shadow stack pages to memory accounting mm/mprotect: Exclude shadow stack from preserve_write
mm: Re-introduce vm_flags to do_mmap()
x86/shstk: Add user-mode shadow stack support x86/shstk: Handle thread shadow stack
x86/shstk: Introduce routines modifying shstk x86/shstk: Handle signals for shadow stack
x86: Add PTRACE interface for shadow stack

 Documentation/filesystems/proc.rst            |   1 +
 Documentation/x86/index.rst                   |   1 +
 Documentation/x86/shstk.rst                   | 172 +++++
 arch/arm/kernel/signal.c                      |   2 +-
 arch/arm64/kernel/signal.c                    |   2 +-
 arch/arm64/kernel/signal32.c                  |   2 +-
 arch/sparc/kernel/signal32.c                  |   2 +-
 arch/sparc/kernel/signal_64.c                 |   2 +-
 arch/x86/Kconfig                              |  24 +
 arch/x86/Kconfig.assembler                    |   5 +
 arch/x86/entry/syscalls/syscall_64.tbl        |   1 +
 arch/x86/include/asm/cpufeatures.h            |   2 +
 arch/x86/include/asm/disabled-features.h      |  16 +-
 arch/x86/include/asm/fpu/api.h                |   9 +
 arch/x86/include/asm/fpu/regset.h             |   7 +-
 arch/x86/include/asm/fpu/sched.h              |   3 +-
 arch/x86/include/asm/fpu/types.h              |  14 +-
 arch/x86/include/asm/fpu/xstate.h             |   6 +-
 arch/x86/include/asm/idtentry.h               |   2 +-
 arch/x86/include/asm/mmu_context.h            |   2 +
 arch/x86/include/asm/msr.h                    |  11 +
 arch/x86/include/asm/pgtable.h                | 320 +++++++-
 arch/x86/include/asm/pgtable_types.h          |  65 +-
 arch/x86/include/asm/processor.h              |   8 +
 arch/x86/include/asm/shstk.h                  |  52 ++
 arch/x86/include/asm/sighandling.h            |   1 +
 arch/x86/include/asm/special_insns.h          |  13 +
 arch/x86/include/asm/tlbflush.h               |   3 +-
 arch/x86/include/asm/trap_pf.h                |   2 +
 arch/x86/include/uapi/asm/mman.h              |   3 +
 arch/x86/include/uapi/asm/prctl.h             |  12 +
 arch/x86/kernel/Makefile                      |   2 +
 arch/x86/kernel/cpu/common.c                  |  37 +-
 arch/x86/kernel/cpu/cpuid-deps.c              |   1 +
 arch/x86/kernel/cpu/proc.c                    |  23 +
 arch/x86/kernel/fpu/core.c                    |  60 +-
 arch/x86/kernel/fpu/regset.c                  |  87 +++
 arch/x86/kernel/fpu/xstate.c                  | 148 ++--
 arch/x86/kernel/fpu/xstate.h                  |   6 +
 arch/x86/kernel/idt.c                         |   2 +-
 arch/x86/kernel/process.c                     |  18 +-
 arch/x86/kernel/process_64.c                  |   8 +
 arch/x86/kernel/ptrace.c                      |  12 +
 arch/x86/kernel/shstk.c                       | 495 +++++++++++++
 arch/x86/kernel/signal.c                      |  21 +
 arch/x86/kernel/signal_64.c                   |   6 +
 arch/x86/kernel/signal_compat.c               |   7 +-
 arch/x86/kernel/traps.c                       | 107 ++-
 arch/x86/mm/fault.c                           |  38 +
 arch/x86/mm/pat/set_memory.c                  |   2 +-
 arch/x86/mm/pgtable.c                         |   6 +
 arch/x86/xen/enlighten_pv.c                   |   2 +-
 arch/x86/xen/xen-asm.S                        |   2 +-
 fs/aio.c                                      |   2 +-
 fs/proc/array.c                               |   6 +
 fs/proc/task_mmu.c                            |   3 +
 include/linux/mm.h                            |  57 +-
 include/linux/pgtable.h                       |  35 +
 include/linux/proc_fs.h                       |   2 +
 include/linux/ptrace.h                        |   1 +
 include/linux/syscalls.h                      |   1 +
 include/uapi/asm-generic/siginfo.h            |   3 +-
 include/uapi/asm-generic/unistd.h             |   2 +-
 include/uapi/linux/elf.h                      |   2 +
 ipc/shm.c                                     |   2 +-
 kernel/signal.c                               |   8 +
 kernel/sys_ni.c                               |   1 +
 mm/gup.c                                      |   2 +-
 mm/huge_memory.c                              |  20 +-
 mm/memory.c                                   |   7 +-
 mm/migrate_device.c                           |   4 +-
 mm/mmap.c                                     |  12 +-
 mm/mprotect.c                                 |   8 +
 mm/nommu.c                                    |   4 +-
 mm/userfaultfd.c                              |  10 +-
 mm/util.c                                     |   2 +-
 tools/testing/selftests/x86/Makefile          |   4 +-
 .../testing/selftests/x86/test_shadow_stack.c | 685 ++++++++++++++++++
 78 files changed, 2560 insertions(+), 178 deletions(-)
 create mode 100644 Documentation/x86/shstk.rst
 create mode 100644 arch/x86/include/asm/shstk.h
 create mode 100644 arch/x86/kernel/shstk.c
 create mode 100644 tools/testing/selftests/x86/test_shadow_stack.c
Signature · 1 line
2.17.1
#1 lore raw

PATCH v4 1/39 Documentation/x86: Add CET shadow stack description

From: Yu-cheng Yu <[email protected]>

Introduce a new document on Control-flow Enforcement Technology (CET).

---

v4:
- Drop clearcpuid piece (Boris)
- Add some info about 32 bit

v3:
- Clarify kernel IBT is supported by the kernel. (Kees, Andrew Cooper)
- Clarify which arch_prctl's can take multiple bits. (Kees)
- Describe ASLR characteristics of thread shadow stacks. (Kees)
- Add exec section. (Andrew Cooper)
- Fix some capitalization (Bagas Sanjaya)
- Update new location of enablement status proc.
- Add info about new user_shstk software capability.
- Add more info about what the kernel pushes to the shadow stack on signal.

v2:
- Updated to new arch_prctl() API
- Add bit about new proc status

v1:
- Update and clarify the docs.
- Moved kernel parameters documentation to other patch.

 Documentation/x86/index.rst |   1 +
 Documentation/x86/shstk.rst | 162 ++++++++++++++++++++++++++++++++++++
 2 files changed, 163 insertions(+)
 create mode 100644 Documentation/x86/shstk.rst
Documentation/x86/index.rst +1 -0
index c73d133fd37c..8ac64d7de4dc 100644
@@ -22,6 +22,7 @@ x86-specific Documentation
    mtrr
    pat
    intel-hfi
+   shstk
    iommu
    intel_txt
    amd-memory-encryption
Documentation/x86/shstk.rst new file +162 -0

162 lines not on this page · raw message

Signature · 1 line
2.17.1
Reviewed-by on v4 1/39
#3 lore raw

Re: [PATCH v4 01/39] Documentation/x86: Add CET shadow stack description

In reply to Rick Edgecombe

Documentation/x86/shstk.rst line 49

Quoted 5 lines · Rick Edgecombe
Documentation/x86/shstk.rst new file +5 -0
+An application's CET capability is marked in its ELF note and can be verified
+from readelf/llvm-readelf output:
+
+    readelf -n <application> | grep -a SHSTK
+        properties: x86 feature: SHSTK

Shell commands should be inside literal code block (try double colon). Above is rendered as definition lists instead.

Documentation/x86/shstk.rst line 77

Quoted 2 lines
Documentation/x86/shstk.rst new file +2 -0
+The return values are as following:
+    On success, return 0. On error, errno can be::

Drop indentation on the second line, or better yet, continue the line, like "... as following. On success, ..."

Otherwise LGTM, thanks for review.

In any case,

Signature · 1 line
An old man doll... just what I always wanted! - Clara
#4 lore raw

Re: [PATCH v4 01/39] Documentation/x86: Add CET shadow stack description

Quoted 19 lines · Bagas Sanjaya
Quoted 1 line · Rick Edgecombe

+An application's CET capability is marked in its ELF note and can

be verified

Documentation/x86/shstk.rst line 49

Quoted 4 lines
Documentation/x86/shstk.rst new file +4 -0
+from readelf/llvm-readelf output:
+
+    readelf -n <application> | grep -a SHSTK
+        properties: x86 feature: SHSTK

Shell commands should be inside literal code block (try double colon).
Above is rendered as definition lists instead.

Documentation/x86/shstk.rst line 77

Quoted 2 lines
Documentation/x86/shstk.rst new file +2 -0
+The return values are as following:
+    On success, return 0. On error, errno can be::

Drop indentation on the second line, or better yet, continue the line,
like "... as following. On success, ..."

Quoted 5 lines

Otherwise LGTM, thanks for review.

In any case,

Sure on both, and thanks for the review.

#5 lore raw

PATCH v4 2/39 x86/shstk: Add Kconfig option for Shadow Stack

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Shadow Stack provides protection for applications against function return address corruption. It is active when the processor supports it, the kernel has CONFIG_X86_SHADOW_STACK enabled, and the application is built for the feature. This is only implemented for the 64-bit kernel. When it is enabled, legacy non-Shadow Stack applications continue to work, but without protection.

Since there is another feature that utilizes CET (Kernel IBT) that will share implementation with Shadow Stacks, create CONFIG_CET to signify that at least one CET feature is configured.

---

v3:
- Add X86_CET (Kees)
- Add back WRUSS dependency (Kees)
- Fix verbiage (Dave)
- Change from promt to bool (Kirill)
- Add more to commit log

v2:
- Remove already wrong kernel size increase info (tlgx)
- Change prompt to remove "Intel" (tglx)
- Update line about what CPUs are supported (Dave)

Yu-cheng v25:
- Remove X86_CET and use X86_SHADOW_STACK directly.

Yu-cheng v24:
- Update for the splitting X86_CET to X86_SHADOW_STACK and X86_IBT.

 arch/x86/Kconfig           | 24 ++++++++++++++++++++++++
 arch/x86/Kconfig.assembler |  5 +++++
 2 files changed, 29 insertions(+)
arch/x86/Kconfig +24 -0
index ae36661cfd81..3c4a8e47cf19 100644
@@ -1853,6 +1853,11 @@ config CC_HAS_IBT
 		  (CC_IS_CLANG && CLANG_VERSION >= 140000)) && \
 		  $(as-instr,endbr64)
 
+config X86_CET
+	def_bool n
+	help
+	  CET features configured (Shadow Stack or IBT)
+
 config X86_KERNEL_IBT
 	prompt "Indirect Branch Tracking"
 	def_bool y
@@ -1860,6 +1865,7 @@ config X86_KERNEL_IBT
 	# https://github.com/llvm/llvm-project/commit/9d7001eba9c4cb311e03cd8cdc231f9e579f2d0f
 	depends on !LD_IS_LLD || LLD_VERSION >= 140000
 	select OBJTOOL
+	select X86_CET
 	help
 	  Build the kernel with support for Indirect Branch Tracking, a
 	  hardware support course-grain forward-edge Control Flow Integrity
@@ -1954,6 +1960,24 @@ config X86_SGX
 
 	  If unsure, say N.
 
+config X86_USER_SHADOW_STACK
+	bool "X86 Userspace Shadow Stack"
+	depends on AS_WRUSS
+	depends on X86_64
+	select ARCH_USES_HIGH_VMA_FLAGS
+	select X86_CET
+	help
+	  Shadow Stack protection is a hardware feature that detects function
+	  return address corruption.  This helps mitigate ROP attacks.
+	  Applications must be enabled to use it, and old userspace does not
+	  get protection "for free".
+
+	  CPUs supporting shadow stacks were first released in 2020.
+
+	  See Documentation/x86/cet.rst for more information.
+
+	  If unsure, say N.
+
 config EFI
 	bool "EFI runtime service support"
 	depends on ACPI
arch/x86/Kconfig.assembler +5 -0
index 26b8c08e2fc4..00c79dd93651 100644
@@ -19,3 +19,8 @@ config AS_TPAUSE
 	def_bool $(as-instr,tpause %ecx)
 	help
 	  Supported by binutils >= 2.31.1 and LLVM integrated assembler >= V7
+
+config AS_WRUSS
+	def_bool $(as-instr,wrussq %rax$(comma)(%rbx))
+	help
+	  Supported by binutils >= 2.31 and LLVM integrated assembler
Signature · 1 line
2.17.1
Reviewed-by on v4 2/39
#6 lore raw

Re: [PATCH v4 02/39] x86/shstk: Add Kconfig option for Shadow Stack

Quoted 9 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Shadow Stack provides protection for applications against function return address corruption. It is active when the processor supports it, the kernel has CONFIG_X86_SHADOW_STACK enabled, and the application is built for the feature. This is only implemented for the 64-bit kernel. When it is enabled, legacy non-Shadow Stack applications continue to work, but without protection.

Quoted 7 lines

Since there is another feature that utilizes CET (Kernel IBT) that will share implementation with Shadow Stacks, create CONFIG_CET to signify that at least one CET feature is configured.

Signature · 1 line
Kees Cook
#7 lore raw

PATCH v4 3/39 x86/cpufeatures: Add CPU feature flags for shadow stacks

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The Control-Flow Enforcement Technology contains two related features, one of which is Shadow Stacks. Future patches will utilize this feature for shadow stack support in KVM, so add a CPU feature flags for Shadow Stacks (CPUID.(EAX=7,ECX=0):ECX[bit 7]).

To protect shadow stack state from malicious modification, the registers are only accessible in supervisor mode. This implementation context-switches the registers with XSAVES. Make X86_FEATURE_SHSTK depend on XSAVES.

The shadow stack feature, enumerated by the CPUID bit described above, encompasses both supervisor and userspace support for shadow stack. In near future patches, only userspace shadow stack will be enabled. In expectation of future supervisor shadow stack support, create a software CPU capability to enumerate kernel utilization of userspace shadow stack support. This will also allow for userspace shadow stack to be disabled, while leaving the shadow stack hardware capability exposed in the cpuinfo proc. This user shadow stack bit should depend on the HW "shstk" capability and that logic will be implemented in future patches.

---

v3:
- Add user specific shadow stack cpu cap (Andrew Cooper)
- Drop reviewed-bys from Boris and Kees due to the above change.

v2:
- Remove IBT reference in commit log (Kees)
- Describe xsaves dependency using text from (Dave)

v1:
- Remove IBT, can be added in a follow on IBT series.

Yu-cheng v25:
- Make X86_FEATURE_IBT depend on X86_FEATURE_SHSTK.

 arch/x86/include/asm/cpufeatures.h       | 2 ++
 arch/x86/include/asm/disabled-features.h | 8 +++++++-
 arch/x86/kernel/cpu/cpuid-deps.c         | 1 +
 3 files changed, 10 insertions(+), 1 deletion(-)
arch/x86/include/asm/cpufeatures.h +2 -0
index 11a0e06362e4..aab7fa4104d7 100644
@@ -307,6 +307,7 @@
 #define X86_FEATURE_SGX_EDECCSSA	(11*32+18) /* "" SGX EDECCSSA user leaf function */
 #define X86_FEATURE_CALL_DEPTH		(11*32+19) /* "" Call depth tracking for RSB stuffing */
 #define X86_FEATURE_MSR_TSX_CTRL	(11*32+20) /* "" MSR IA32_TSX_CTRL (Intel) implemented */
+#define X86_FEATURE_USER_SHSTK		(11*32+21) /* Shadow stack support for user mode applications */
 
 /* Intel-defined CPU features, CPUID level 0x00000007:1 (EAX), word 12 */
 #define X86_FEATURE_AVX_VNNI		(12*32+ 4) /* AVX VNNI instructions */
@@ -369,6 +370,7 @@
 #define X86_FEATURE_OSPKE		(16*32+ 4) /* OS Protection Keys Enable */
 #define X86_FEATURE_WAITPKG		(16*32+ 5) /* UMONITOR/UMWAIT/TPAUSE Instructions */
 #define X86_FEATURE_AVX512_VBMI2	(16*32+ 6) /* Additional AVX512 Vector Bit Manipulation Instructions */
+#define X86_FEATURE_SHSTK		(16*32+ 7) /* Shadow Stack */
 #define X86_FEATURE_GFNI		(16*32+ 8) /* Galois Field New Instructions */
 #define X86_FEATURE_VAES		(16*32+ 9) /* Vector AES */
 #define X86_FEATURE_VPCLMULQDQ		(16*32+10) /* Carry-Less Multiplication Double Quadword */
arch/x86/include/asm/disabled-features.h +7 -1
index c44b56f7ffba..7a2954a16cb7 100644
@@ -99,6 +99,12 @@
 # define DISABLE_TDX_GUEST	(1 << (X86_FEATURE_TDX_GUEST & 31))
 #endif
 
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+#define DISABLE_USER_SHSTK	0
+#else
+#define DISABLE_USER_SHSTK	(1 << (X86_FEATURE_USER_SHSTK & 31))
+#endif
+
 /*
  * Make sure to add features to the correct mask
  */
@@ -114,7 +120,7 @@
 #define DISABLED_MASK9	(DISABLE_SGX)
 #define DISABLED_MASK10	0
 #define DISABLED_MASK11	(DISABLE_RETPOLINE|DISABLE_RETHUNK|DISABLE_UNRET| \
-			 DISABLE_CALL_DEPTH_TRACKING)
+			 DISABLE_CALL_DEPTH_TRACKING|DISABLE_USER_SHSTK)
 #define DISABLED_MASK12	0
 #define DISABLED_MASK13	0
 #define DISABLED_MASK14	0
arch/x86/kernel/cpu/cpuid-deps.c +1 -0
index d95221117129..c3e4e5246df9 100644
@@ -79,6 +79,7 @@ static const struct cpuid_dep cpuid_deps[] = {
 	{ X86_FEATURE_XFD,			X86_FEATURE_XSAVES    },
 	{ X86_FEATURE_XFD,			X86_FEATURE_XGETBV1   },
 	{ X86_FEATURE_AMX_TILE,			X86_FEATURE_XFD       },
+	{ X86_FEATURE_SHSTK,			X86_FEATURE_XSAVES    },
 	{}
 };
 
Signature · 1 line
2.17.1
Reviewed-by on v4 3/39
#8 lore raw

Re: [PATCH v4 03/39] x86/cpufeatures: Add CPU feature flags for shadow stacks

Quoted 22 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The Control-Flow Enforcement Technology contains two related features, one of which is Shadow Stacks. Future patches will utilize this feature for shadow stack support in KVM, so add a CPU feature flags for Shadow Stacks (CPUID.(EAX=7,ECX=0):ECX[bit 7]).

To protect shadow stack state from malicious modification, the registers are only accessible in supervisor mode. This implementation context-switches the registers with XSAVES. Make X86_FEATURE_SHSTK depend on XSAVES.

The shadow stack feature, enumerated by the CPUID bit described above, encompasses both supervisor and userspace support for shadow stack. In near future patches, only userspace shadow stack will be enabled. In expectation of future supervisor shadow stack support, create a software CPU capability to enumerate kernel utilization of userspace shadow stack support. This will also allow for userspace shadow stack to be disabled, while leaving the shadow stack hardware capability exposed in the cpuinfo proc. This user shadow stack bit should depend on the HW "shstk" capability and that logic will be implemented in future patches.

Quoted 3 lines
Signature · 1 line
Kees Cook
maintainer
#9 lore raw

Re: [PATCH v4 03/39] x86/cpufeatures: Add CPU feature flags for shadow stacks

In reply to Rick Edgecombe
Quoted 13 lines · Rick Edgecombe
arch/x86/include/asm/cpufeatures.h +1 -0
index 11a0e06362e4..aab7fa4104d7 100644
@@ -307,6 +307,7 @@
 #define X86_FEATURE_SGX_EDECCSSA	(11*32+18) /* "" SGX EDECCSSA user leaf function */
 #define X86_FEATURE_CALL_DEPTH		(11*32+19) /* "" Call depth tracking for RSB stuffing */
 #define X86_FEATURE_MSR_TSX_CTRL	(11*32+20) /* "" MSR IA32_TSX_CTRL (Intel) implemented */
+#define X86_FEATURE_USER_SHSTK		(11*32+21) /* Shadow stack support for user mode applications */
 
 /* Intel-defined CPU features, CPUID level 0x00000007:1 (EAX), word 12 */
 #define X86_FEATURE_AVX_VNNI		(12*32+ 4) /* AVX VNNI instructions */

arch/x86/include/asm/cpufeatures.h line 376

Quoted 7 lines
arch/x86/include/asm/cpufeatures.h +1 -0
@@ -369,6 +370,7 @@
 #define X86_FEATURE_OSPKE		(16*32+ 4) /* OS Protection Keys Enable */
 #define X86_FEATURE_WAITPKG		(16*32+ 5) /* UMONITOR/UMWAIT/TPAUSE Instructions */
 #define X86_FEATURE_AVX512_VBMI2	(16*32+ 6) /* Additional AVX512 Vector Bit Manipulation Instructions */
+#define X86_FEATURE_SHSTK		(16*32+ 7) /* Shadow Stack */
 #define X86_FEATURE_GFNI		(16*32+ 8) /* Galois Field New Instructions */
 #define X86_FEATURE_VAES		(16*32+ 9) /* Vector AES */
 #define X86_FEATURE_VPCLMULQDQ		(16*32+10) /* Carry-Less Multiplication Double Quadword */

What is the end goal here?

To have X86_FEATURE_KERNEL_SHSTK or so someday too?

If so, then the hardware bit X86_FEATURE_SHSTK should be hidden in /proc/cpuinfo, i.e.,

#define X86_FEATURE_SHSTK (16*32+ 7) /* "" Shadow Stack hardware support */

note the "", otherwise you'll have people go:

"hey, I have "shstk" in /proc/cpuinfo on my machine. Why doesn't it do anything?"

Or am I misreading where this is headed?

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#10 lore raw

Re: [PATCH v4 03/39] x86/cpufeatures: Add CPU feature flags for shadow stacks

Quoted 44 lines · Borislav Petkov
Quoted 24 lines · Rick Edgecombe
arch/x86/include/asm/cpufeatures.h +0 -0
index 11a0e06362e4..aab7fa4104d7 100644
@@ -307,6 +307,7 @@
  #define X86_FEATURE_SGX_EDECCSSA     (11*32+18) /* "" SGX

EDECCSSA user leaf function */
#define X86_FEATURE_CALL_DEPTH (11*32+19) /* ""
Call depth tracking for RSB stuffing */
#define X86_FEATURE_MSR_TSX_CTRL (11*32+20) /* "" MSR
IA32_TSX_CTRL (Intel) implemented */
+#define X86_FEATURE_USER_SHSTK (11*32+21) /* Shadow
stack support for user mode applications */

/* Intel-defined CPU features, CPUID level 0x00000007:1 (EAX),
word 12 */
#define X86_FEATURE_AVX_VNNI (12*32+ 4) /* AVX VNNI
instructions */

arch/x86/include/asm/cpufeatures.h +0 -0
@@ -369,6 +370,7 @@
  #define X86_FEATURE_OSPKE            (16*32+ 4) /* OS Protection

Keys Enable */
#define X86_FEATURE_WAITPKG (16*32+ 5) /*
UMONITOR/UMWAIT/TPAUSE Instructions */

Quoted 8 lines

#define X86_FEATURE_AVX512_VBMI2 (16*32+ 6) /* Additional
AVX512 Vector Bit Manipulation Instructions */
+#define X86_FEATURE_SHSTK (16*32+ 7) /* Shadow Stack */
#define X86_FEATURE_GFNI (16*32+ 8) /* Galois Field
New Instructions */
#define X86_FEATURE_VAES (16*32+ 9) /* Vector AES */
#define X86_FEATURE_VPCLMULQDQ (16*32+10) /* Carry-
Less Multiplication Double Quadword */

What is the end goal here?

To have X86_FEATURE_KERNEL_SHSTK or so someday too?

If so, then the hardware bit X86_FEATURE_SHSTK should be hidden in /proc/cpuinfo, i.e.,

#define X86_FEATURE_SHSTK (16*32+ 7) /* "" Shadow Stack
hardware support */

Quoted 7 lines

note the "", otherwise you'll have people go:

"hey, I have "shstk" in /proc/cpuinfo on my machine. Why doesn't it do
anything?"

Or am I misreading where this is headed?

Yes, the suggestion was to have one for kernel and one for user. But I was also thinking about how KVM could hypothetically support shadow stack in guests in the non !CONFIG_X86_USER_SHADOW_STACK case (it only needs CET_U xsave support). So that configuration wouldn't expose user_shstk and since KVM's guest feature support is retrieved programmatically, it could be nice to have some hint for KVM users that they could try. Maybe it's simpler to just tie KVM and host support together though. I'll remove "shstk".

maintainer
#11 lore raw

Re: [PATCH v4 03/39] x86/cpufeatures: Add CPU feature flags for shadow stacks

Quoted 8 lines · Rick P

Yes, the suggestion was to have one for kernel and one for user. But I was also thinking about how KVM could hypothetically support shadow stack in guests in the non !CONFIG_X86_USER_SHADOW_STACK case (it only needs CET_U xsave support). So that configuration wouldn't expose user_shstk and since KVM's guest feature support is retrieved programmatically, it could be nice to have some hint for KVM users that they could try. Maybe it's simpler to just tie KVM and host support together though. I'll remove "shstk".

Hmm, I don't have a clear idea how guest shstk support should do so maybe this is all way off but yeah, if the host supports CET - the *hardware* feature - then you can use the same logic to support that in a VM.

I.e., if the guest sees CET - i.e., HV has advertized it - then guest kernel behaves exactly the same as on the host.

But it is likely I'm missing something more involved...

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#12 lore raw

PATCH v4 4/39 x86/cpufeatures: Enable CET CR4 bit for shadow stack

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Setting CR4.CET is a prerequisite for utilizing any CET features, most of which also require setting MSRs.

Kernel IBT already enables the CET CR4 bit when it detects IBT HW support and is configured with kernel IBT. However, future patches that enable userspace shadow stack support will need the bit set as well. So change the logic to enable it in either case.

Clear MSR_IA32_U_CET in cet_disable() so that it can't live to see userspace in a new kexec-ed kernel that has CR4.CET set from kernel IBT.

---

v4:
- Add back dedicated command line disable: "nousershtk" (Boris)

v3:
- Remove stay new line (Boris)
- Simplify commit log (Andrew Cooper)

v2:
- In the shadow stack case, go back to only setting CR4.CET if the kernel is compiled with user shadow stack support.
- Clear MSR_IA32_U_CET as well. (PeterZ)

KVM refresh:
- Set CR4.CET if SHSTK or IBT are supported by HW, so that KVM can support CET even if IBT is disabled.
- Drop no_user_shstk (Dave Hansen)
- Elaborate on what the CR4 bit does in the commit log
- Integrate with Kernel IBT logic

 arch/x86/kernel/cpu/common.c | 37 ++++++++++++++++++++++++++++++------
 1 file changed, 31 insertions(+), 6 deletions(-)
arch/x86/kernel/cpu/common.c +31 -6
index 73cc546e024d..579f10222432 100644
@@ -597,29 +597,51 @@ __noendbr void ibt_restore(u64 save)
 
 #endif
 
+#ifdef CONFIG_X86_CET
 static __always_inline void setup_cet(struct cpuinfo_x86 *c)
 {
-	u64 msr = CET_ENDBR_EN;
+	bool kernel_ibt = HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT);
+	bool user_shstk;
+	u64 msr = 0;
+
+	/*
+	 * Enable user shadow stack only if the Linux defined user shadow stack
+	 * cap was not cleared by command line.
+	 */
+	user_shstk = cpu_feature_enabled(X86_FEATURE_SHSTK) &&
+		     IS_ENABLED(CONFIG_X86_USER_SHADOW_STACK);
 
-	if (!HAS_KERNEL_IBT ||
-	    !cpu_feature_enabled(X86_FEATURE_IBT))
+	if (!kernel_ibt && !user_shstk)
 		return;
 
+	if (user_shstk)
+		set_cpu_cap(c, X86_FEATURE_USER_SHSTK);
+
+	if (kernel_ibt)
+		msr = CET_ENDBR_EN;
+
 	wrmsrl(MSR_IA32_S_CET, msr);
 	cr4_set_bits(X86_CR4_CET);
 
-	if (!ibt_selftest()) {
+	if (kernel_ibt && !ibt_selftest()) {
 		pr_err("IBT selftest: Failed!\n");
 		wrmsrl(MSR_IA32_S_CET, 0);
 		setup_clear_cpu_cap(X86_FEATURE_IBT);
 		return;
 	}
 }
+#else /* CONFIG_X86_CET */
+static inline void setup_cet(struct cpuinfo_x86 *c) {}
+#endif
 
 __noendbr void cet_disable(void)
 {
-	if (cpu_feature_enabled(X86_FEATURE_IBT))
-		wrmsrl(MSR_IA32_S_CET, 0);
+	if (!(cpu_feature_enabled(X86_FEATURE_IBT) ||
+	      cpu_feature_enabled(X86_FEATURE_SHSTK)))
+		return;
+
+	wrmsrl(MSR_IA32_S_CET, 0);
+	wrmsrl(MSR_IA32_U_CET, 0);
 }
 
 /*
@@ -1470,6 +1492,9 @@ static void __init cpu_parse_early_param(void)
 	if (cmdline_find_option_bool(boot_command_line, "noxsaves"))
 		setup_clear_cpu_cap(X86_FEATURE_XSAVES);
 
+	if (cmdline_find_option_bool(boot_command_line, "nousershstk"))
+		setup_clear_cpu_cap(X86_FEATURE_USER_SHSTK);
+
 	arglen = cmdline_find_option(boot_command_line, "clearcpuid", arg, sizeof(arg));
 	if (arglen <= 0)
 		return;
Signature · 1 line
2.17.1
Reviewed-by on v4 4/39
#13 lore raw

Re: [PATCH v4 04/39] x86/cpufeatures: Enable CET CR4 bit for shadow stack

Quoted 10 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Setting CR4.CET is a prerequisite for utilizing any CET features, most of which also require setting MSRs.

Kernel IBT already enables the CET CR4 bit when it detects IBT HW support and is configured with kernel IBT. However, future patches that enable userspace shadow stack support will need the bit set as well. So change the logic to enable it in either case.

Quoted 6 lines

Clear MSR_IA32_U_CET in cet_disable() so that it can't live to see userspace in a new kexec-ed kernel that has CR4.CET set from kernel IBT.

Signature · 1 line
Kees Cook
maintainer
#14 lore raw

Re: [PATCH v4 04/39] x86/cpufeatures: Enable CET CR4 bit for shadow stack

In reply to Rick Edgecombe
Quoted 4 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Setting CR4.CET is a prerequisite for utilizing any CET features, most of which also require setting MSRs.

...

Quoted 2 lines
 arch/x86/kernel/cpu/common.c | 37 ++++++++++++++++++++++++++++++------
 1 file changed, 31 insertions(+), 6 deletions(-)

Looks better.

Let's get rid of the ifdeffery and simplify it even more. Diff ontop:

---

arch/x86/kernel/cpu/common.c +9 -10
index 579f10222432..c364f3067121 100644
@@ -597,12 +597,14 @@ __noendbr void ibt_restore(u64 save)
 
 #endif
 
-#ifdef CONFIG_X86_CET
 static __always_inline void setup_cet(struct cpuinfo_x86 *c)
 {
-	bool kernel_ibt = HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT);
-	bool user_shstk;
-	u64 msr = 0;
+	bool kernel_ibt, user_shstk;
+
+	if (!IS_ENABLED(CONFIG_X86_CET))
+		return;
+
+	kernel_ibt = HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT);
 
 	/*
 	 * Enable user shadow stack only if the Linux defined user shadow stack
@@ -618,21 +620,18 @@ static __always_inline void setup_cet(struct cpuinfo_x86 *c)
 		set_cpu_cap(c, X86_FEATURE_USER_SHSTK);
 
 	if (kernel_ibt)
-		msr = CET_ENDBR_EN;
+		wrmsrl(MSR_IA32_S_CET, CET_ENDBR_EN);
+	else
+		wrmsrl(MSR_IA32_S_CET, 0);
 
-	wrmsrl(MSR_IA32_S_CET, msr);
 	cr4_set_bits(X86_CR4_CET);
 
 	if (kernel_ibt && !ibt_selftest()) {
 		pr_err("IBT selftest: Failed!\n");
 		wrmsrl(MSR_IA32_S_CET, 0);
 		setup_clear_cpu_cap(X86_FEATURE_IBT);
-		return;
 	}
 }
-#else /* CONFIG_X86_CET */
-static inline void setup_cet(struct cpuinfo_x86 *c) {}
-#endif
 
 __noendbr void cet_disable(void)
 {
Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#15 lore raw

Re: [PATCH v4 04/39] x86/cpufeatures: Enable CET CR4 bit for shadow stack

Quoted 9 lines · Borislav Petkov
Quoted 5 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Setting CR4.CET is a prerequisite for utilizing any CET features, most of
which also require setting MSRs.

...

Quoted 7 lines
Quoted 3 lines
  arch/x86/kernel/cpu/common.c | 37 ++++++++++++++++++++++++++++++-
-----
  1 file changed, 31 insertions(+), 6 deletions(-)

Looks better.

Let's get rid of the ifdeffery and simplify it even more. Diff ontop:

Sure, thanks!

#16 lore raw

PATCH v4 5/39 x86/fpu/xstate: Introduce CET MSR and XSAVES supervisor states

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Shadow stack register state can be managed with XSAVE. The registers can logically be separated into two groups:
* Registers controlling user-mode operation
* Registers controlling kernel-mode operation

The architecture has two new XSAVE state components: one for each group of those groups of registers. This lets an OS manage them separately if it chooses. Future patches for host userspace and KVM guests will only utilize the user-mode registers, so only configure XSAVE to save user-mode registers. This state will add 16 bytes to the xsave buffer size.

Future patches will use the user-mode XSAVE area to save guest user-mode CET state. However, VMCS includes new fields for guest CET supervisor states. KVM can use these to save and restore guest supervisor state, so host supervisor XSAVE support is not required.

Adding this exacerbates the already unwieldy if statement in check_xstate_against_struct() that handles warning about un-implemented xfeatures. So refactor these check's by having XCHECK_SZ() set a bool when it actually check's the xfeature. This ends up exceeding 80 chars, but was better on balance than other options explored. Pass the bool as pointer to make it clear that XCHECK_SZ() can change the variable.

While configuring user-mode XSAVE, clarify kernel-mode registers are not managed by XSAVE by defining the xfeature in XFEATURE_MASK_SUPERVISOR_UNSUPPORTED, like is done for XFEATURE_MASK_PT. This serves more of a documentation as code purpose, and functionally, only enables a few safety checks.

Both XSAVE state components are supervisor states, even the state controlling user-mode operation. This is a departure from earlier features like protection keys where the PKRU state is a normal user (non-supervisor) state. Having the user state be supervisor-managed ensures there is no direct, unprivileged access to it, making it harder for an attacker to subvert CET.

To facilitate this privileged access, define the two user-mode CET MSRs, and the bits defined in those MSRs relevant to future shadow stack enablement patches.

---

v3:
- Add missing "is" in commit log (Boris)
- Change to case statement for struct size checking (Boris)
- Adjust commas on xfeature_names (Kees, Boris)

v2:
- Change name to XFEATURE_CET_KERNEL_UNUSED (peterz)

KVM refresh:
- Reword commit log using some verbiage posted by Dave Hansen
- Remove unlikely to be used supervisor cet xsave struct
- Clarify that supervisor cet state is not saved by xsave
- Remove unused supervisor MSRs

v1:
- Remove outdated reference to sigreturn checks on msr's.

 arch/x86/include/asm/fpu/types.h  | 14 ++++-
 arch/x86/include/asm/fpu/xstate.h |  6 ++-
 arch/x86/kernel/fpu/xstate.c      | 90 +++++++++++++++----------------
 3 files changed, 59 insertions(+), 51 deletions(-)
arch/x86/include/asm/fpu/types.h +12 -2
index eb7cd1139d97..344baad02b97 100644
@@ -115,8 +115,8 @@ enum xfeature {
 	XFEATURE_PT_UNIMPLEMENTED_SO_FAR,
 	XFEATURE_PKRU,
 	XFEATURE_PASID,
-	XFEATURE_RSRVD_COMP_11,
-	XFEATURE_RSRVD_COMP_12,
+	XFEATURE_CET_USER,
+	XFEATURE_CET_KERNEL_UNUSED,
 	XFEATURE_RSRVD_COMP_13,
 	XFEATURE_RSRVD_COMP_14,
 	XFEATURE_LBR,
@@ -138,6 +138,8 @@ enum xfeature {
 #define XFEATURE_MASK_PT		(1 << XFEATURE_PT_UNIMPLEMENTED_SO_FAR)
 #define XFEATURE_MASK_PKRU		(1 << XFEATURE_PKRU)
 #define XFEATURE_MASK_PASID		(1 << XFEATURE_PASID)
+#define XFEATURE_MASK_CET_USER		(1 << XFEATURE_CET_USER)
+#define XFEATURE_MASK_CET_KERNEL	(1 << XFEATURE_CET_KERNEL_UNUSED)
 #define XFEATURE_MASK_LBR		(1 << XFEATURE_LBR)
 #define XFEATURE_MASK_XTILE_CFG		(1 << XFEATURE_XTILE_CFG)
 #define XFEATURE_MASK_XTILE_DATA	(1 << XFEATURE_XTILE_DATA)
@@ -252,6 +254,14 @@ struct pkru_state {
 	u32				pad;
 } __packed;
 
+/*
+ * State component 11 is Control-flow Enforcement user states
+ */
+struct cet_user_state {
+	u64 user_cet;			/* user control-flow settings */
+	u64 user_ssp;			/* user shadow stack pointer */
+};
+
 /*
  * State component 15: Architectural LBR configuration state.
  * The size of Arch LBR state depends on the number of LBRs (lbr_depth).
arch/x86/include/asm/fpu/xstate.h +4 -2
index cd3dd170e23a..d4427b88ee12 100644
@@ -50,7 +50,8 @@
 #define XFEATURE_MASK_USER_DYNAMIC	XFEATURE_MASK_XTILE_DATA
 
 /* All currently supported supervisor features */
-#define XFEATURE_MASK_SUPERVISOR_SUPPORTED (XFEATURE_MASK_PASID)
+#define XFEATURE_MASK_SUPERVISOR_SUPPORTED (XFEATURE_MASK_PASID | \
+					    XFEATURE_MASK_CET_USER)
 
 /*
  * A supervisor state component may not always contain valuable information,
@@ -77,7 +78,8 @@
  * Unsupported supervisor features. When a supervisor feature in this mask is
  * supported in the future, move it to the supported supervisor feature mask.
  */
-#define XFEATURE_MASK_SUPERVISOR_UNSUPPORTED (XFEATURE_MASK_PT)
+#define XFEATURE_MASK_SUPERVISOR_UNSUPPORTED (XFEATURE_MASK_PT | \
+					      XFEATURE_MASK_CET_KERNEL)
 
 /* All supervisor states including supported and unsupported states. */
 #define XFEATURE_MASK_SUPERVISOR_ALL (XFEATURE_MASK_SUPERVISOR_SUPPORTED | \
arch/x86/kernel/fpu/xstate.c +43 -47

137 lines not on this page · raw message

Signature · 1 line
2.17.1
Reviewed-by on v4 5/39
#17 lore raw

Re: [PATCH v4 05/39] x86/fpu/xstate: Introduce CET MSR and XSAVES supervisor states

Quoted 39 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Shadow stack register state can be managed with XSAVE. The registers can logically be separated into two groups:
* Registers controlling user-mode operation
* Registers controlling kernel-mode operation

The architecture has two new XSAVE state components: one for each group of those groups of registers. This lets an OS manage them separately if it chooses. Future patches for host userspace and KVM guests will only utilize the user-mode registers, so only configure XSAVE to save user-mode registers. This state will add 16 bytes to the xsave buffer size.

Future patches will use the user-mode XSAVE area to save guest user-mode CET state. However, VMCS includes new fields for guest CET supervisor states. KVM can use these to save and restore guest supervisor state, so host supervisor XSAVE support is not required.

Adding this exacerbates the already unwieldy if statement in check_xstate_against_struct() that handles warning about un-implemented xfeatures. So refactor these check's by having XCHECK_SZ() set a bool when it actually check's the xfeature. This ends up exceeding 80 chars, but was better on balance than other options explored. Pass the bool as pointer to make it clear that XCHECK_SZ() can change the variable.

While configuring user-mode XSAVE, clarify kernel-mode registers are not managed by XSAVE by defining the xfeature in XFEATURE_MASK_SUPERVISOR_UNSUPPORTED, like is done for XFEATURE_MASK_PT. This serves more of a documentation as code purpose, and functionally, only enables a few safety checks.

Both XSAVE state components are supervisor states, even the state controlling user-mode operation. This is a departure from earlier features like protection keys where the PKRU state is a normal user (non-supervisor) state. Having the user state be supervisor-managed ensures there is no direct, unprivileged access to it, making it harder for an attacker to subvert CET.

Quoted 7 lines

To facilitate this privileged access, define the two user-mode CET MSRs, and the bits defined in those MSRs relevant to future shadow stack enablement patches.

Signature · 1 line
Kees Cook
maintainer
#18 lore raw

Re: [PATCH v4 05/39] x86/fpu/xstate: Introduce CET MSR and XSAVES supervisor states

In reply to Rick Edgecombe

arch/x86/include/asm/fpu/types.h struct pkru_state { · line 262

Quoted 10 lines · Rick Edgecombe
arch/x86/include/asm/fpu/types.h +6 -0
@@ -252,6 +254,14 @@ struct pkru_state {
 	u32				pad;
 } __packed;
 
+/*
+ * State component 11 is Control-flow Enforcement user states
+ */
+struct cet_user_state {
+	u64 user_cet;			/* user control-flow settings */
+	u64 user_ssp;			/* user shadow stack pointer */

Please put those side comments over the members, like struct fpstate does it in that same file.

Rest looks good.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#19 lore raw

Re: [PATCH v4 05/39] x86/fpu/xstate: Introduce CET MSR and XSAVES supervisor states

Quoted 16 lines · Borislav Petkov
Quoted 9 lines · Rick Edgecombe
arch/x86/include/asm/fpu/types.h +0 -0
@@ -252,6 +254,14 @@ struct pkru_state {
         u32                             pad;
   } __packed;

arch/x86/include/asm/fpu/types.h +5 -0
+/*
+ * State component 11 is Control-flow Enforcement user states
+ */
+struct cet_user_state {
+       u64 user_cet;                   /* user control-flow
Quoted 3 lines

settings */
+       u64 user_ssp;                   /* user shadow stack pointer */

Please put those side comments over the members, like struct fpstate does it in that same file.

Sure, thanks.

#20 lore raw

PATCH v4 6/39 x86/fpu: Add helper for modifying xstate

In reply to Rick Edgecombe

Just like user xfeatures, supervisor xfeatures can be active in the registers or present in the task FPU buffer. If the registers are active, the registers can be modified directly. If the registers are not active, the modification must be performed on the task FPU buffer.

When the state is not active, the kernel could perform modifications directly to the buffer. But in order for it to do that, it needs to know where in the buffer the specific state it wants to modify is located. Doing this is not robust against optimizations that compact the FPU buffer, as each access would require computing where in the buffer it is.

The easiest way to modify supervisor xfeature data is to force restore the registers and write directly to the MSRs. Often times this is just fine anyway as the registers need to be restored before returning to userspace. Do this for now, leaving buffer writing optimizations for the future.

Add a new function fpregs_lock_and_load() that can simultaneously call fpregs_lock() and do this restore. Also perform some extra sanity checks in this function since this will be used in non-fpu focused code.

---

v3:
- Rename to fpregs_lock_and_load() to match the unlocking fpregs_unlock(). (Kees)
- Elaborate in comment about helper. (Dave)

v2:
- Drop optimization of writing directly the buffer, and change API accordingly.
- fpregs_lock_and_load() suggested by tglx
- Some commit log verbiage from dhansen

v1:
- New patch.

 arch/x86/include/asm/fpu/api.h |  9 +++++++++
 arch/x86/kernel/fpu/core.c     | 19 +++++++++++++++++++
 2 files changed, 28 insertions(+)
arch/x86/include/asm/fpu/api.h +9 -0
index 503a577814b2..aadc6893dcaa 100644
@@ -82,6 +82,15 @@ static inline void fpregs_unlock(void)
 		preempt_enable();
 }
 
+/*
+ * FPU state gets lazily restored before returning to userspace. So when in the
+ * kernel, the valid FPU state may be kept in the buffer. This function will force
+ * restore all the fpu state to the registers early if needed, and lock them from
+ * being automatically saved/restored. Then FPU state can be modified safely in the
+ * registers, before unlocking with fpregs_unlock().
+ */
+void fpregs_lock_and_load(void);
+
 #ifdef CONFIG_X86_DEBUG_FPU
 extern void fpregs_assert_state_consistent(void);
 #else
arch/x86/kernel/fpu/core.c +19 -0
index 9baa89a8877d..9af78e9d92a0 100644
@@ -753,6 +753,25 @@ void switch_fpu_return(void)
 }
 EXPORT_SYMBOL_GPL(switch_fpu_return);
 
+void fpregs_lock_and_load(void)
+{
+	/*
+	 * fpregs_lock() only disables preemption (mostly). So modifing state
+	 * in an interrupt could screw up some in progress fpregs operation,
+	 * but appear to work. Warn about it.
+	 */
+	WARN_ON_ONCE(!irq_fpu_usable());
+	WARN_ON_ONCE(current->flags & PF_KTHREAD);
+
+	fpregs_lock();
+
+	fpregs_assert_state_consistent();
+
+	if (test_thread_flag(TIF_NEED_FPU_LOAD))
+		fpregs_restore_userregs();
+}
+EXPORT_SYMBOL_GPL(fpregs_lock_and_load);
+
 #ifdef CONFIG_X86_DEBUG_FPU
 /*
  * If current FPU state according to its tracking (loaded FPU context on this
Signature · 1 line
2.17.1
Reviewed-by on v4 6/39
#21 lore raw

Re: [PATCH v4 06/39] x86/fpu: Add helper for modifying xstate

Quoted 17 lines · Rick Edgecombe

Just like user xfeatures, supervisor xfeatures can be active in the registers or present in the task FPU buffer. If the registers are active, the registers can be modified directly. If the registers are not active, the modification must be performed on the task FPU buffer.

When the state is not active, the kernel could perform modifications directly to the buffer. But in order for it to do that, it needs to know where in the buffer the specific state it wants to modify is located. Doing this is not robust against optimizations that compact the FPU buffer, as each access would require computing where in the buffer it is.

The easiest way to modify supervisor xfeature data is to force restore the registers and write directly to the MSRs. Often times this is just fine anyway as the registers need to be restored before returning to userspace. Do this for now, leaving buffer writing optimizations for the future.

Quoted 8 lines

Add a new function fpregs_lock_and_load() that can simultaneously call fpregs_lock() and do this restore. Also perform some extra sanity checks in this function since this will be used in non-fpu focused code.

Signature · 1 line
Kees Cook
maintainer
#22 lore raw

Re: [PATCH v4 06/39] x86/fpu: Add helper for modifying xstate

In reply to Rick Edgecombe
Quoted 1 line · Rick Edgecombe

+void fpregs_lock_and_load(void)

Fun naming :)

arch/x86/kernel/fpu/core.c void switch_fpu_return(void) · line 759

Quoted 3 lines
arch/x86/kernel/fpu/core.c +3 -0
+{
+	/*
+	 * fpregs_lock() only disables preemption (mostly). So modifing state

Unknown word [modifing] in comment.
Suggestions: ['modifying',...

arch/x86/kernel/fpu/core.c void switch_fpu_return(void) · line 766

Quoted 7 lines
arch/x86/kernel/fpu/core.c +7 -0
+	 * in an interrupt could screw up some in progress fpregs operation,
+	 * but appear to work. Warn about it.
+	 */
+	WARN_ON_ONCE(!irq_fpu_usable());
+	WARN_ON_ONCE(current->flags & PF_KTHREAD);
+
+	fpregs_lock();

So it locks them here...

/me goes further into the patchset

aha, and the counterpart of this function is fpregs_unlock() so everything gets sandwitched between the two.

Ok, I guess.

Quoted 1 line

+EXPORT_SYMBOL_GPL(fpregs_lock_and_load);

Exported for KVM?

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#23 lore raw

Re: [PATCH v4 06/39] x86/fpu: Add helper for modifying xstate

Quoted 4 lines · Borislav Petkov
Quoted 1 line · Rick Edgecombe

+void fpregs_lock_and_load(void)

Fun naming :)

Yea. Suggested by Thomas.

Quoted 8 lines
Quoted 5 lines

+{
+       /*
+        * fpregs_lock() only disables preemption (mostly). So modifing state

Unknown word [modifing] in comment.
Suggestions: ['modifying',...

Sorry about this and the others. I get spelling errors in checkpatch, so I must have dictionary issues or something.

Quoted 16 lines
Quoted 9 lines

+        * in an interrupt could screw up some in progress fpregs operation,
+        * but appear to work. Warn about it.
+        */
+       WARN_ON_ONCE(!irq_fpu_usable());
+       WARN_ON_ONCE(current->flags & PF_KTHREAD);
+
+       fpregs_lock();

So it locks them here...

/me goes further into the patchset
aha, and the counterpart of this function is fpregs_unlock() so everything gets sandwitched between the two.

Quoted 6 lines

Ok, I guess.

Quoted 1 line

+EXPORT_SYMBOL_GPL(fpregs_lock_and_load);

Exported for KVM?

Yes, the KVM series needed it. Part of the reasoning here was to provide some helpers to avoid mistakes in modifying xstate, so the general idea was that it should be available. I suppose that series could add the export though?

maintainer
#24 lore raw

Re: [PATCH v4 06/39] x86/fpu: Add helper for modifying xstate

Quoted 2 lines · Rick P

Sorry about this and the others. I get spelling errors in checkpatch, so I must have dictionary issues or something.

No worries, happens to everyone.

Quoted 4 lines

Yes, the KVM series needed it. Part of the reasoning here was to provide some helpers to avoid mistakes in modifying xstate, so the general idea was that it should be available. I suppose that series could add the export though?

Yeah, you do have a point. Preemptive exposure of functionality is not really needed, so yeah, let's add it when actually really needed.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#25 lore raw

PATCH v4 7/39 x86: Add user control-protection fault handler

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

A control-protection fault is triggered when a control-flow transfer attempt violates Shadow Stack or Indirect Branch Tracking constraints. For example, the return address for a RET instruction differs from the copy on the shadow stack.

There already exists a control-protection fault handler for handling kernel IBT. Refactor this fault handler into sparate user and kernel handlers, like the page fault handler. Add a control-protection handler for usermode.

Keep the same behavior for the kernel side of the fault handler, except for converting a BUG to a WARN in the case of a #CP happening when !cpu_feature_enabled(). This unifies the behavior with the new shadow stack code, and also prevents the kernel from crashing under this situation which is potentially recoverable.

The control-protection fault handler works in a similar way as the general protection fault handler. It provides the si_code SEGV_CPERR to the signal handler.

---

v3:
- Shorten user/kernel #CP handler function names (peterz)
- Restore CP_ENDBR check to kernel handler (peterz)
- Utilize CONFIG_X86_CET (Kees)
- Unify "unexpected" warnings (Andrew Cooper)
- Use 2d array for error code chars (Andrew Cooper)
- Add comment about why to read SSP MSR before enabling interrupts

v2:
- Integrate with kernel IBT fault handler
- Update printed messages. (Dave)
- Remove array_index_nospec() usage. (Dave)
- Remove IBT messages. (Dave)
- Add enclave error code bit processing it case it can get triggered somehow.
- Add extra "unknown" in control_protection_err.

v1:
- Update static asserts for NSIGSEGV

Yu-cheng v29:
- Remove pr_emerg() since it is followed by die().
- Change boot_cpu_has() to cpu_feature_enabled().

 arch/arm/kernel/signal.c                 |   2 +-
 arch/arm64/kernel/signal.c               |   2 +-
 arch/arm64/kernel/signal32.c             |   2 +-
 arch/sparc/kernel/signal32.c             |   2 +-
 arch/sparc/kernel/signal_64.c            |   2 +-
 arch/x86/include/asm/disabled-features.h |   8 +-
 arch/x86/include/asm/idtentry.h          |   2 +-
 arch/x86/kernel/idt.c                    |   2 +-
 arch/x86/kernel/signal_compat.c          |   2 +-
 arch/x86/kernel/traps.c                  | 107 ++++++++++++++++++++---
 arch/x86/xen/enlighten_pv.c              |   2 +-
 arch/x86/xen/xen-asm.S                   |   2 +-
 include/uapi/asm-generic/siginfo.h       |   3 +-
 13 files changed, 114 insertions(+), 24 deletions(-)
arch/arm/kernel/signal.c +1 -1
index e07f359254c3..9a3c9de5ac5e 100644
@@ -681,7 +681,7 @@ asmlinkage void do_rseq_syscall(struct pt_regs *regs)
  */
 static_assert(NSIGILL	== 11);
 static_assert(NSIGFPE	== 15);
-static_assert(NSIGSEGV	== 9);
+static_assert(NSIGSEGV	== 10);
 static_assert(NSIGBUS	== 5);
 static_assert(NSIGTRAP	== 6);
 static_assert(NSIGCHLD	== 6);
arch/arm64/kernel/signal.c +1 -1
index 9ad911f1647c..81b13a21046e 100644
@@ -1166,7 +1166,7 @@ void __init minsigstksz_setup(void)
  */
 static_assert(NSIGILL	== 11);
 static_assert(NSIGFPE	== 15);
-static_assert(NSIGSEGV	== 9);
+static_assert(NSIGSEGV	== 10);
 static_assert(NSIGBUS	== 5);
 static_assert(NSIGTRAP	== 6);
 static_assert(NSIGCHLD	== 6);
arch/arm64/kernel/signal32.c +1 -1
index 4700f8522d27..bbd542704730 100644
@@ -460,7 +460,7 @@ void compat_setup_restart_syscall(struct pt_regs *regs)
  */
 static_assert(NSIGILL	== 11);
 static_assert(NSIGFPE	== 15);
-static_assert(NSIGSEGV	== 9);
+static_assert(NSIGSEGV	== 10);
 static_assert(NSIGBUS	== 5);
 static_assert(NSIGTRAP	== 6);
 static_assert(NSIGCHLD	== 6);
arch/sparc/kernel/signal32.c +1 -1
index dad38960d1a8..82da8a2d769d 100644
@@ -751,7 +751,7 @@ asmlinkage int do_sys32_sigstack(u32 u_ssptr, u32 u_ossptr, unsigned long sp)
  */
 static_assert(NSIGILL	== 11);
 static_assert(NSIGFPE	== 15);
-static_assert(NSIGSEGV	== 9);
+static_assert(NSIGSEGV	== 10);
 static_assert(NSIGBUS	== 5);
 static_assert(NSIGTRAP	== 6);
 static_assert(NSIGCHLD	== 6);
arch/sparc/kernel/signal_64.c +1 -1
index 570e43e6fda5..b4e410976e0d 100644
@@ -562,7 +562,7 @@ void do_notify_resume(struct pt_regs *regs, unsigned long orig_i0, unsigned long
  */
 static_assert(NSIGILL	== 11);
 static_assert(NSIGFPE	== 15);
-static_assert(NSIGSEGV	== 9);
+static_assert(NSIGSEGV	== 10);
 static_assert(NSIGBUS	== 5);
 static_assert(NSIGTRAP	== 6);
 static_assert(NSIGCHLD	== 6);
arch/x86/include/asm/disabled-features.h +7 -1
index 7a2954a16cb7..b7646b471537 100644
@@ -105,6 +105,12 @@
 #define DISABLE_USER_SHSTK	(1 << (X86_FEATURE_USER_SHSTK & 31))
 #endif
 
+#ifdef CONFIG_X86_KERNEL_IBT
+#define DISABLE_IBT	0
+#else
+#define DISABLE_IBT	(1 << (X86_FEATURE_IBT & 31))
+#endif
+
 /*
  * Make sure to add features to the correct mask
  */
@@ -128,7 +134,7 @@
 #define DISABLED_MASK16	(DISABLE_PKU|DISABLE_OSPKE|DISABLE_LA57|DISABLE_UMIP| \
 			 DISABLE_ENQCMD)
 #define DISABLED_MASK17	0
-#define DISABLED_MASK18	0
+#define DISABLED_MASK18	(DISABLE_IBT)
 #define DISABLED_MASK19	0
 #define DISABLED_MASK_CHECK BUILD_BUG_ON_ZERO(NCAPINTS != 20)
 
arch/x86/include/asm/idtentry.h +1 -1
index 72184b0b2219..69e26f48d027 100644
@@ -618,7 +618,7 @@ DECLARE_IDTENTRY_RAW_ERRORCODE(X86_TRAP_DF,	xenpv_exc_double_fault);
 #endif
 
 /* #CP */
-#ifdef CONFIG_X86_KERNEL_IBT
+#ifdef CONFIG_X86_CET
 DECLARE_IDTENTRY_ERRORCODE(X86_TRAP_CP,	exc_control_protection);
 #endif
 
arch/x86/kernel/idt.c +1 -1
index a58c6bc1cd68..5074b8420359 100644
@@ -107,7 +107,7 @@ static const __initconst struct idt_data def_idts[] = {
 	ISTG(X86_TRAP_MC,		asm_exc_machine_check, IST_INDEX_MCE),
 #endif
 
-#ifdef CONFIG_X86_KERNEL_IBT
+#ifdef CONFIG_X86_CET
 	INTG(X86_TRAP_CP,		asm_exc_control_protection),
 #endif
 
arch/x86/kernel/signal_compat.c +1 -1
index 879ef8c72f5c..d441804443d5 100644
@@ -27,7 +27,7 @@ static inline void signal_compat_build_tests(void)
 	 */
 	BUILD_BUG_ON(NSIGILL  != 11);
 	BUILD_BUG_ON(NSIGFPE  != 15);
-	BUILD_BUG_ON(NSIGSEGV != 9);
+	BUILD_BUG_ON(NSIGSEGV != 10);
 	BUILD_BUG_ON(NSIGBUS  != 5);
 	BUILD_BUG_ON(NSIGTRAP != 6);
 	BUILD_BUG_ON(NSIGCHLD != 6);
arch/x86/kernel/traps.c +95 -12

131 lines not on this page · raw message

arch/x86/xen/enlighten_pv.c +1 -1
index a7d83c7800e4..e58d6cd30853 100644
@@ -639,7 +639,7 @@ static struct trap_array_entry trap_array[] = {
 	TRAP_ENTRY(exc_coprocessor_error,		false ),
 	TRAP_ENTRY(exc_alignment_check,			false ),
 	TRAP_ENTRY(exc_simd_coprocessor_error,		false ),
-#ifdef CONFIG_X86_KERNEL_IBT
+#ifdef CONFIG_X86_CET
 	TRAP_ENTRY(exc_control_protection,		false ),
 #endif
 };
arch/x86/xen/xen-asm.S +1 -1
index 4a184f6e4e4d..7cdcb4ce6976 100644
@@ -148,7 +148,7 @@ xen_pv_trap asm_exc_page_fault
 xen_pv_trap asm_exc_spurious_interrupt_bug
 xen_pv_trap asm_exc_coprocessor_error
 xen_pv_trap asm_exc_alignment_check
-#ifdef CONFIG_X86_KERNEL_IBT
+#ifdef CONFIG_X86_CET
 xen_pv_trap asm_exc_control_protection
 #endif
 #ifdef CONFIG_X86_MCE
include/uapi/asm-generic/siginfo.h +2 -1
index ffbe4cec9f32..0f52d0ac47c5 100644
@@ -242,7 +242,8 @@ typedef struct siginfo {
 #define SEGV_ADIPERR	7	/* Precise MCD exception */
 #define SEGV_MTEAERR	8	/* Asynchronous ARM MTE error */
 #define SEGV_MTESERR	9	/* Synchronous ARM MTE exception */
-#define NSIGSEGV	9
+#define SEGV_CPERR	10	/* Control protection fault */
+#define NSIGSEGV	10
 
 /*
  * SIGBUS si_codes
Signature · 1 line
2.17.1
Reviewed-by on v4 7/39
#26 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

Quoted 21 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

A control-protection fault is triggered when a control-flow transfer attempt violates Shadow Stack or Indirect Branch Tracking constraints. For example, the return address for a RET instruction differs from the copy on the shadow stack.

There already exists a control-protection fault handler for handling kernel IBT. Refactor this fault handler into sparate user and kernel handlers, like the page fault handler. Add a control-protection handler for usermode.

Keep the same behavior for the kernel side of the fault handler, except for converting a BUG to a WARN in the case of a #CP happening when !cpu_feature_enabled(). This unifies the behavior with the new shadow stack code, and also prevents the kernel from crashing under this situation which is potentially recoverable.

The control-protection fault handler works in a similar way as the general protection fault handler. It provides the si_code SEGV_CPERR to the signal handler.

Quoted 5 lines

This looks nice cleaner to me. Thanks!

Signature · 1 line
Kees Cook
maintainer
#27 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

In reply to Rick Edgecombe
Quoted 9 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

A control-protection fault is triggered when a control-flow transfer attempt violates Shadow Stack or Indirect Branch Tracking constraints. For example, the return address for a RET instruction differs from the copy on the shadow stack.

There already exists a control-protection fault handler for handling kernel IBT. Refactor this fault handler into sparate user and kernel handlers,

Unknown word [sparate] in commit message.
Suggestions: ['separate',

You could use a spellchecker with your commit messages so that it catches all those typos.

...

Quoted 19 lines
arch/x86/kernel/traps.c +1 -6
index 8b83d8fbce71..e35c70dc1afb 100644
@@ -213,12 +213,7 @@ DEFINE_IDTENTRY(exc_overflow)
 	do_error_trap(regs, 0, "overflow", X86_TRAP_OF, SIGSEGV, 0, NULL);
 }
 
-#ifdef CONFIG_X86_KERNEL_IBT
-
-static __ro_after_init bool ibt_fatal = true;
-
-extern void ibt_selftest_ip(void); /* code label defined in asm below */
-
+#ifdef CONFIG_X86_CET
 enum cp_error_code {
 	CP_EC        = (1 << 15) - 1,
 

arch/x86/kernel/traps.c enum cp_error_code { · line 229

Quoted 5 lines
arch/x86/kernel/traps.c +1 -1
@@ -231,15 +226,87 @@ enum cp_error_code {
 	CP_ENCL	     = 1 << 15,
 };
 
-DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)
+static const char control_protection_err[][10] = {

You already use the "cp_" prefix for the other things, might as well use it here too.

Quoted 16 lines
arch/x86/kernel/traps.c +16 -0
+	[0] = "unknown",
+	[1] = "near ret",
+	[2] = "far/iret",
+	[3] = "endbranch",
+	[4] = "rstorssp",
+	[5] = "setssbsy",
+};
+
+static const char *cp_err_string(unsigned long error_code)
+{
+	unsigned int cpec = error_code & CP_EC;
+
+	if (cpec >= ARRAY_SIZE(control_protection_err))
+		cpec = 0;
+	return control_protection_err[cpec];
+}

arch/x86/kernel/traps.c enum cp_error_code { · line 255

Quoted 10 lines
arch/x86/kernel/traps.c +10 -0
+
+static void do_unexpected_cp(struct pt_regs *regs, unsigned long error_code)
+{
+	WARN_ONCE(1, "Unexpected %s #CP, error_code: %s\n",
+		     user_mode(regs) ? "user mode" : "kernel mode",
+		     cp_err_string(error_code));
+}
+#endif /* CONFIG_X86_CET */
+
+void do_user_cp_fault(struct pt_regs *regs, unsigned long error_code);

What's that forward declaration for?

In any case, push it into traps.h pls.

I gotta say, I'm not a big fan of that ifdeffery here. Do we really really need it?

Quoted 40 lines
arch/x86/kernel/traps.c +33 -4
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+static DEFINE_RATELIMIT_STATE(cpf_rate, DEFAULT_RATELIMIT_INTERVAL,
+			      DEFAULT_RATELIMIT_BURST);
+
+void do_user_cp_fault(struct pt_regs *regs, unsigned long error_code)
 {
-	if (!cpu_feature_enabled(X86_FEATURE_IBT)) {
-		pr_err("Unexpected #CP\n");
-		BUG();
+	struct task_struct *tsk;
+	unsigned long ssp;
+
+	/*
+	 * An exception was just taken from userspace. Since interrupts are disabled
+	 * here, no scheduling should have messed with the registers yet and they
+	 * will be whatever is live in userspace. So read the SSP before enabling
+	 * interrupts so locking the fpregs to do it later is not required.
+	 */
+	rdmsrl(MSR_IA32_PL3_SSP, ssp);
+
+	cond_local_irq_enable(regs);
+
+	tsk = current;
+	tsk->thread.error_code = error_code;
+	tsk->thread.trap_nr = X86_TRAP_CP;
+
+	/* Ratelimit to prevent log spamming. */
+	if (show_unhandled_signals && unhandled_signal(tsk, SIGSEGV) &&
+	    __ratelimit(&cpf_rate)) {
+		pr_emerg("%s[%d] control protection ip:%lx sp:%lx ssp:%lx error:%lx(%s)%s",
+			 tsk->comm, task_pid_nr(tsk),
+			 regs->ip, regs->sp, ssp, error_code,
+			 cp_err_string(error_code),
+			 error_code & CP_ENCL ? " in enclave" : "");
+		print_vma_addr(KERN_CONT " in ", regs->ip);
+		pr_cont("\n");
 	}
 
-	if (WARN_ON_ONCE(user_mode(regs) || (error_code & CP_EC) != CP_ENDBR))
+	force_sig_fault(SIGSEGV, SEGV_CPERR, (void __user *)0);

arch/x86/kernel/traps.c enum cp_error_code { · line 302

Quoted 10 lines
arch/x86/kernel/traps.c +10 -0
+	cond_local_irq_disable(regs);
+}
+#endif
+
+void do_kernel_cp_fault(struct pt_regs *regs, unsigned long error_code);
+
+#ifdef CONFIG_X86_KERNEL_IBT
+static __ro_after_init bool ibt_fatal = true;
+
+extern void ibt_selftest_ip(void); /* code label defined in asm below */

Yeah, pls put that comment above the function. Side comments are nasty.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#28 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

Quoted 16 lines · Borislav Petkov
Quoted 10 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

A control-protection fault is triggered when a control-flow transfer
attempt violates Shadow Stack or Indirect Branch Tracking constraints.
For example, the return address for a RET instruction differs from the copy
on the shadow stack.

Quoted 4 lines

There already exists a control-protection fault handler for handling kernel
IBT. Refactor this fault handler into separate user and kernel handlers,

Quoted 5 lines

Unknown word [separate] in commit message.
Suggestions: ['separate',

You could use a spellchecker with your commit messages so that it catches all those typos.

Argh, sorry. I'll upgrade my tools.

Quoted 25 lines

...

Quoted 22 lines
arch/x86/kernel/traps.c +0 -0
index 8b83d8fbce71..e35c70dc1afb 100644
@@ -213,12 +213,7 @@ DEFINE_IDTENTRY(exc_overflow)
         do_error_trap(regs, 0, "overflow", X86_TRAP_OF, SIGSEGV, 0,
 NULL);
  }

arch/x86/kernel/traps.c +0 -5
-#ifdef CONFIG_X86_KERNEL_IBT
-
-static __ro_after_init bool ibt_fatal = true;
-
-extern void ibt_selftest_ip(void); /* code label defined in asm

below */

arch/x86/kernel/traps.c +1 -1
-
+#ifdef CONFIG_X86_CET

 enum cp_error_code {
        CP_EC        = (1 << 15) - 1,

arch/x86/kernel/traps.c +0 -0
@@ -231,15 +226,87 @@ enum cp_error_code {
         CP_ENCL      = 1 << 15,
Quoted 8 lines

arch/x86/kernel/traps.c enum cp_error_code { · line 229

Quoted 4 lines
arch/x86/kernel/traps.c +0 -0
  };

arch/x86/kernel/traps.c +1 -1
-DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)
+static const char control_protection_err[][10] = {

You already use the "cp_" prefix for the other things, might as well use
it here too.

Sure.

Quoted 23 lines
Quoted 23 lines

+       [0] = "unknown",
+       [1] = "near ret",
+       [2] = "far/iret",
+       [3] = "endbranch",
+       [4] = "rstorssp",
+       [5] = "setssbsy",

arch/x86/kernel/traps.c +12 -0
+};
+
+static const char *cp_err_string(unsigned long error_code)
+{
+       unsigned int cpec = error_code & CP_EC;
+
+       if (cpec >= ARRAY_SIZE(control_protection_err))
+               cpec = 0;
+       return control_protection_err[cpec];
+}
+
+static void do_unexpected_cp(struct pt_regs *regs, unsigned long

error_code)
+{
+       WARN_ONCE(1, "Unexpected %s #CP, error_code: %s\n", +                    user_mode(regs) ? "user mode" : "kernel mode",

Quoted 8 lines
Quoted 6 lines

+                    cp_err_string(error_code));

arch/x86/kernel/traps.c +4 -0
+}
+#endif /* CONFIG_X86_CET */
+
+void do_user_cp_fault(struct pt_regs *regs, unsigned long

error_code);

What's that forward declaration for?

The reason is cpu_feature_enabled(X86_FEATURE_USER_SHSTK) will compile- time evaluate to false when user shadow stack is not configured, so a do_user_cp_fault() implementation is not needed in that case. The reference in exec_control_protection will get optimized out, but it still needs to be defined.

Otherwise it could have a stub implementation in an #else block, but this seemed cleaner.

Quoted 2 lines

In any case, push it into traps.h pls.

It's not really supposed to be called from outside traps.c. The only reason it is not static it because it doesn't work with these IS_ENABLED()-style solutions for compiling out code. Now I'm wondering if these are not preferred...

Quoted 3 lines

I gotta say, I'm not a big fan of that ifdeffery here. Do we really really need it?

You mean having separate paths for kernel IBT and user shadow stack that compile out? I guess it could just all be in place if CONFIG_X86_CET is in place.

I don't know, I thought it was relatively clean, but I can remove it.

Quoted 67 lines
Quoted 62 lines
arch/x86/kernel/traps.c +2 -0
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+static DEFINE_RATELIMIT_STATE(cpf_rate,

DEFAULT_RATELIMIT_INTERVAL,
+                             DEFAULT_RATELIMIT_BURST);

arch/x86/kernel/traps.c +2 -0
+
+void do_user_cp_fault(struct pt_regs *regs, unsigned long

error_code)
 {
-       if (!cpu_feature_enabled(X86_FEATURE_IBT)) {
-               pr_err("Unexpected #CP\n");
-               BUG();
+       struct task_struct *tsk;
+       unsigned long ssp;
+
+       /*
+        * An exception was just taken from userspace. Since interrupts are disabled
+        * here, no scheduling should have messed with the registers yet and they
+        * will be whatever is live in userspace. So read the SSP before enabling
+        * interrupts so locking the fpregs to do it later is not required.
+        */
+       rdmsrl(MSR_IA32_PL3_SSP, ssp);

arch/x86/kernel/traps.c +9 -0
+
+       cond_local_irq_enable(regs);
+
+       tsk = current;
+       tsk->thread.error_code = error_code;
+       tsk->thread.trap_nr = X86_TRAP_CP;
+
+       /* Ratelimit to prevent log spamming. */
+       if (show_unhandled_signals && unhandled_signal(tsk,

SIGSEGV) &&
+           __ratelimit(&cpf_rate)) {
+               pr_emerg("%s[%d] control protection ip:%lx sp:%lx ssp:%lx error:%lx(%s)%s",
+                        tsk->comm, task_pid_nr(tsk),
+                        regs->ip, regs->sp, ssp, error_code, +                        cp_err_string(error_code),
+                        error_code & CP_ENCL ? " in enclave" :
"");
+               print_vma_addr(KERN_CONT " in ", regs->ip); +               pr_cont("\n");
        }

-       if (WARN_ON_ONCE(user_mode(regs) || (error_code & CP_EC) != CP_ENDBR))
+       force_sig_fault(SIGSEGV, SEGV_CPERR, (void __user *)0); +       cond_local_irq_disable(regs);

arch/x86/kernel/traps.c +4 -0
+}
+#endif
+
+void do_kernel_cp_fault(struct pt_regs *regs, unsigned long

error_code);

arch/x86/kernel/traps.c +5 -0
+
+#ifdef CONFIG_X86_KERNEL_IBT
+static __ro_after_init bool ibt_fatal = true;
+
+extern void ibt_selftest_ip(void); /* code label defined in asm
Quoted 1 line

below */

Yeah, pls put that comment above the function. Side comments are nasty.

Quoted 2 lines

Thx.

Sure. Thanks.

maintainer
#29 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

Quoted 5 lines · Rick P

You mean having separate paths for kernel IBT and user shadow stack that compile out? I guess it could just all be in place if CONFIG_X86_CET is in place.

I don't know, I thought it was relatively clean, but I can remove it.

Yeah, I'm wondering if we really need the ifdeffery. I always question ifdeffery because it is a) ugly, b) a mess to deal with and having it is not really worth it. Yeah, we save a couple of KBs, big deal.

What would practically happen is, shadow stack will be default-enabled on the majority of kernels out there - distro ones - so it will be enabled practically everywhere.

And it'll be off only in some self-built kernels which are the very small minority.

And how much are the space savings with the whole set applied, with and without the Kconfig item enabled? Probably only a couple of KBs.

And if so, I'm thinking we could at least make the traps.c stuff unconditional - it'll be there but won't run. Unless we get some weird #CP but it'll be caught by do_unexpected_cp().

And you have feature tests everywhere so it's not like it'll get "misused".

And when you do that, you'll have everything a lot simpler, a lot less Kconfig items to build-test and all good.

Right?

Or am I completely way off into the weeds here and am missing an important aspect...?

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#30 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

Quoted 19 lines · Borislav Petkov
Quoted 6 lines · Rick P

You mean having separate paths for kernel IBT and user shadow stack that compile out? I guess it could just all be in place if CONFIG_X86_CET is in place.

I don't know, I thought it was relatively clean, but I can remove it.

Yeah, I'm wondering if we really need the ifdeffery. I always question
ifdeffery because it is a) ugly, b) a mess to deal with and having it is
not really worth it. Yeah, we save a couple of KBs, big deal.

What would practically happen is, shadow stack will be default- enabled
on the majority of kernels out there - distro ones - so it will be enabled practically everywhere.

Quoted 6 lines

And it'll be off only in some self-built kernels which are the very small minority.

And how much are the space savings with the whole set applied, with and
without the Kconfig item enabled? Probably only a couple of KBs.

Oh, you mean the whole Kconfig thing. Yea, I mean I see the point about typical configs. But at least CONFIG_X86_CET seems consistent with CONFIG_INTEL_TDX_GUEST, CONFIG_IOMMU_SVA, etc.

What about moving it out of traps.c to a cet.c, like exc_vmm_communication for CONFIG_AMD_MEM_ENCRT? Then the inclusion logic lives in the build files, instead of an ifdef.

Quoted 9 lines

And if so, I'm thinking we could at least make the traps.c stuff unconditional - it'll be there but won't run. Unless we get some weird
#CP but it'll be caught by do_unexpected_cp().

And you have feature tests everywhere so it's not like it'll get "misused".

Quoted 9 lines

And when you do that, you'll have everything a lot simpler, a lot less
Kconfig items to build-test and all good.

Right?

Or am I completely way off into the weeds here and am missing an important aspect...?

One aspect that has come up a couple of times, is how closely related all these CET features are (or aren't). Shadow stack and IBT are mostly separate, but do share an xfeature and an exception type. Similarly for supervisor and user mode support for either of the CET features. So maybe that is what is unusual here. There are some aspects that make them look like separate features, which leads people to think they should be separate in the code. But actually separating them leads to excess ifdefery.

To me, putting the whole handler in even if there are no CET features seems like too much. Leaving it in unconditionally is apparently also inconsistent with some of the previous traps.c decisions. So I'd leave CONFIG_X86_CET at least and it can help anyone building super stripped down kernels. But I'm ok with whatever people think.

maintainer
#31 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

Quoted 7 lines · Rick P

Oh, you mean the whole Kconfig thing. Yea, I mean I see the point about typical configs. But at least CONFIG_X86_CET seems consistent with CONFIG_INTEL_TDX_GUEST, CONFIG_IOMMU_SVA, etc.

What about moving it out of traps.c to a cet.c, like exc_vmm_communication for CONFIG_AMD_MEM_ENCRT? Then the inclusion logic lives in the build files, instead of an ifdef.

Yeah, that definitely sounds cleaner. Another example would be the #MC handler being in mce code and not in traps.c.

So yeah, the reason why I'm even mentioning this is that I get an allergic reaction when I see unwieldy ifdeffery in one screen worth of code. But this is just me. :)

Quoted 8 lines

One aspect that has come up a couple of times, is how closely related all these CET features are (or aren't). Shadow stack and IBT are mostly separate, but do share an xfeature and an exception type. Similarly for supervisor and user mode support for either of the CET features. So maybe that is what is unusual here. There are some aspects that make them look like separate features, which leads people to think they should be separate in the code. But actually separating them leads to excess ifdefery.

Yeah, I think you solved that correctly by having the common X86_CET symbol selected by the two.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
maintainer
#32 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

In reply to Rick Edgecombe
Quoted 3 lines · Rick Edgecombe

Keep the same behavior for the kernel side of the fault handler, except for converting a BUG to a WARN in the case of a #CP happening when !cpu_feature_enabled().

^^^^^^^^^^^^^^^^^^^^^^^^^

Yeah, let's stick to plain english in the commit message pls, instead of pseudo code.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#33 lore raw

Re: [PATCH v4 07/39] x86: Add user control-protection fault handler

Quoted 10 lines · Borislav Petkov
Quoted 4 lines · Rick Edgecombe

Keep the same behavior for the kernel side of the fault handler, except for
converting a BUG to a WARN in the case of a #CP happening when !cpu_feature_enabled().

^^^^^^^^^^^^^^^^^^^^^^^^^

Yeah, let's stick to plain english in the commit message pls, instead of
pseudo code.

Sure, I'll change it. Thanks.

#34 lore raw

PATCH v4 8/39 x86/mm: Remove _PAGE_DIRTY from kernel RO pages

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

New processors that support Shadow Stack regard Write=0,Dirty=1 PTEs as shadow stack pages.

In normal cases, it can be helpful to create Write=1 PTEs as also Dirty=1 if HW dirty tracking is not needed, because if the Dirty bit is not already set the CPU has to set Dirty=1 when it the memory gets written to. This creates addiontal work for the CPU. So tradional wisdom was to simply set the Dirty bit whenever you didn't care about it. However, it was never really very helpful for read only kernel memory.

When CR4.CET=1 and IA32_S_CET.SH_STK_EN=1, some instructions can write to such supervisor memory. The kernel does not set IA32_S_CET.SH_STK_EN, so avoiding kernel Write=0,Dirty=1 memory is not strictly needed for any functional reason. But having Write=0,Dirty=1 kernel memory doesn't have any functional benefit either, so to reduce ambiguity between shadow stack and regular Write=0 pages, removed Dirty=1 from any kernel Write=0 PTEs.

Cc "H. Peter Anvin" <[email protected]>
Cc Kees Cook <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Christoph Hellwig <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Borislav Petkov <[email protected]>
Cc Peter Zijlstra <[email protected]>

---

v3:
- Update commit log (Andrew Cooper, Peterz)

v2:
- Normalize PTE bit descriptions between patches

 arch/x86/include/asm/pgtable_types.h | 6 +++---
 arch/x86/mm/pat/set_memory.c         | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)
arch/x86/include/asm/pgtable_types.h +3 -3
index 447d4bee25c4..0646ad00178b 100644
@@ -192,10 +192,10 @@ enum page_cache_mode {
 #define _KERNPG_TABLE		 (__PP|__RW|   0|___A|   0|___D|   0|   0| _ENC)
 #define _PAGE_TABLE_NOENC	 (__PP|__RW|_USR|___A|   0|___D|   0|   0)
 #define _PAGE_TABLE		 (__PP|__RW|_USR|___A|   0|___D|   0|   0| _ENC)
-#define __PAGE_KERNEL_RO	 (__PP|   0|   0|___A|__NX|___D|   0|___G)
-#define __PAGE_KERNEL_ROX	 (__PP|   0|   0|___A|   0|___D|   0|___G)
+#define __PAGE_KERNEL_RO	 (__PP|   0|   0|___A|__NX|   0|   0|___G)
+#define __PAGE_KERNEL_ROX	 (__PP|   0|   0|___A|   0|   0|   0|___G)
 #define __PAGE_KERNEL_NOCACHE	 (__PP|__RW|   0|___A|__NX|___D|   0|___G| __NC)
-#define __PAGE_KERNEL_VVAR	 (__PP|   0|_USR|___A|__NX|___D|   0|___G)
+#define __PAGE_KERNEL_VVAR	 (__PP|   0|_USR|___A|__NX|   0|   0|___G)
 #define __PAGE_KERNEL_LARGE	 (__PP|__RW|   0|___A|__NX|___D|_PSE|___G)
 #define __PAGE_KERNEL_LARGE_EXEC (__PP|__RW|   0|___A|   0|___D|_PSE|___G)
 #define __PAGE_KERNEL_WP	 (__PP|__RW|   0|___A|__NX|___D|   0|___G| __WP)
arch/x86/mm/pat/set_memory.c +1 -1
index 0db69514fe29..50e07e8493e0 100644
@@ -2055,7 +2055,7 @@ int set_memory_nx(unsigned long addr, int numpages)
 
 int set_memory_ro(unsigned long addr, int numpages)
 {
-	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_RW), 0);
+	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_RW | _PAGE_DIRTY), 0);
 }
 
 int set_memory_rox(unsigned long addr, int numpages)
Signature · 1 line
2.17.1
Reviewed-by on v4 8/39
#35 lore raw

Re: [PATCH v4 08/39] x86/mm: Remove _PAGE_DIRTY from kernel RO pages

Quoted 19 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

New processors that support Shadow Stack regard Write=0,Dirty=1 PTEs as shadow stack pages.

In normal cases, it can be helpful to create Write=1 PTEs as also Dirty=1 if HW dirty tracking is not needed, because if the Dirty bit is not already set the CPU has to set Dirty=1 when it the memory gets written to. This creates addiontal work for the CPU. So tradional wisdom was to simply set the Dirty bit whenever you didn't care about it. However, it was never really very helpful for read only kernel memory.

When CR4.CET=1 and IA32_S_CET.SH_STK_EN=1, some instructions can write to such supervisor memory. The kernel does not set IA32_S_CET.SH_STK_EN, so avoiding kernel Write=0,Dirty=1 memory is not strictly needed for any functional reason. But having Write=0,Dirty=1 kernel memory doesn't have any functional benefit either, so to reduce ambiguity between shadow stack and regular Write=0 pages, removed Dirty=1 from any kernel Write=0 PTEs.

Quoted 3 lines
Signature · 1 line
Kees Cook
maintainer
#36 lore raw

Re: [PATCH v4 08/39] x86/mm: Remove _PAGE_DIRTY from kernel RO pages

In reply to Rick Edgecombe

Just typos and spelling fixes:

Quoted 8 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

New processors that support Shadow Stack regard Write=0,Dirty=1 PTEs as shadow stack pages.

In normal cases, it can be helpful to create Write=1 PTEs as also Dirty=1 if HW dirty tracking is not needed, because if the Dirty bit is not already set the CPU has to set Dirty=1 when it the memory gets written to. This

s/it //

Quoted 1 line

creates addiontal work for the CPU.

"additional"

Quoted 1 line

So tradional wisdom was to simply set

Unknown word [tradional] in commit message.
Suggestions: ['traditional', ...

Quoted 2 lines

the Dirty bit whenever you didn't care about it. However, it was never really very helpful for read only kernel memory.

read-only

Quoted 6 lines

When CR4.CET=1 and IA32_S_CET.SH_STK_EN=1, some instructions can write to such supervisor memory. The kernel does not set IA32_S_CET.SH_STK_EN, so avoiding kernel Write=0,Dirty=1 memory is not strictly needed for any functional reason. But having Write=0,Dirty=1 kernel memory doesn't have any functional benefit either, so to reduce ambiguity between shadow stack and regular Write=0 pages, removed Dirty=1 from any kernel Write=0 PTEs.

s/removed/remove/

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#37 lore raw

PATCH v4 9/39 x86/mm: Move pmd_write(), pud_write() up in the file

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

To prepare the introduction of _PAGE_COW, move pmd_write() and pud_write() up in the file, so that they can be used by other helpers below. No functional changes.

---
 arch/x86/include/asm/pgtable.h | 24 ++++++++++++------------
 1 file changed, 12 insertions(+), 12 deletions(-)
arch/x86/include/asm/pgtable.h +12 -12
index 5059799bebe3..a1d6f121ee35 100644
@@ -159,6 +159,18 @@ static inline int pte_write(pte_t pte)
 	return pte_flags(pte) & _PAGE_RW;
 }
 
+#define pmd_write pmd_write
+static inline int pmd_write(pmd_t pmd)
+{
+	return pmd_flags(pmd) & _PAGE_RW;
+}
+
+#define pud_write pud_write
+static inline int pud_write(pud_t pud)
+{
+	return pud_flags(pud) & _PAGE_RW;
+}
+
 static inline int pte_huge(pte_t pte)
 {
 	return pte_flags(pte) & _PAGE_PSE;
@@ -1103,12 +1115,6 @@ extern int pmdp_clear_flush_young(struct vm_area_struct *vma,
 				  unsigned long address, pmd_t *pmdp);
 
 
-#define pmd_write pmd_write
-static inline int pmd_write(pmd_t pmd)
-{
-	return pmd_flags(pmd) & _PAGE_RW;
-}
-
 #define __HAVE_ARCH_PMDP_HUGE_GET_AND_CLEAR
 static inline pmd_t pmdp_huge_get_and_clear(struct mm_struct *mm, unsigned long addr,
 				       pmd_t *pmdp)
@@ -1138,12 +1144,6 @@ static inline void pmdp_set_wrprotect(struct mm_struct *mm,
 	clear_bit(_PAGE_BIT_RW, (unsigned long *)pmdp);
 }
 
-#define pud_write pud_write
-static inline int pud_write(pud_t pud)
-{
-	return pud_flags(pud) & _PAGE_RW;
-}
-
 #ifndef pmdp_establish
 #define pmdp_establish pmdp_establish
 static inline pmd_t pmdp_establish(struct vm_area_struct *vma,
Signature · 1 line
2.17.1
#38 lore raw

PATCH v4 10/39 x86/mm: Introduce _PAGE_COW

In reply to Rick Edgecombe

Some OSes have a greater dependence on software available bits in PTEs than Linux. That left the hardware architects looking for a way to represent a new memory type (shadow stack) within the existing bits. They chose to repurpose a lightly-used state: Write=0,Dirty=1. So in order to support shadow stack memory, Linux should avoid creating memory with this PTE bit combination unless it intends for it to be shadow stack.

The reason it's lightly used is that Dirty=1 is normally set by HW _before_ a write. A write with a Write=0 PTE would typically only generate a fault, not set Dirty=1. Hardware can (rarely) both set Dirty=1 *and* generate the fault, resulting in a Write=0,Dirty=1 PTE. Hardware which supports shadow stacks will no longer exhibit this oddity.

So that leaves Write=0,Dirty=1 PTEs created in software. To achieve this, in places where Linux normally creates Write=0,Dirty=1, it can use the software-defined _PAGE_COW in place of the hardware _PAGE_DIRTY. In other words, whenever Linux needs to create Write=0,Dirty=1, it instead creates Write=0,Cow=1 except for shadow stack, which is Write=0,Dirty=1. Further differentiated by VMA flags, these PTE bit combinations would be set as follows for various types of memory:

(Write=0,Cow=1,Dirty=0):
- A modified, copy-on-write (COW) page. Previously when a typical anonymous writable mapping was made COW via fork(), the kernel would mark it Write=0,Dirty=1. Now it will instead use the Cow bit. This happens in copy_present_pte().
- A R/O page that has been COW'ed. The user page is in a R/O VMA, and get_user_pages(FOLL_FORCE) needs a writable copy. The page fault handler creates a copy of the page and sets the new copy's PTE as Write=0 and Cow=1.
- A shared shadow stack PTE. When a shadow stack page is being shared among processes (this happens at fork()), its PTE is made Dirty=0, so the next shadow stack access causes a fault, and the page is duplicated and Dirty=1 is set again. This is the COW equivalent for shadow stack pages, even though it's copy-on-access rather than copy-on-write.

(Write=0,Cow=0,Dirty=1):
- A shadow stack PTE.
- A Cow PTE created when a processor without shadow stack support set Dirty=1.

There are six bits left available to software in the 64-bit PTE after consuming a bit for _PAGE_COW. No space is consumed in 32-bit kernels because shadow stacks are not enabled there.

This is a prepratory patch. Changes to actually start marking _PAGE_COW will follow once other pieces are in place.

---

v4:
- Teach pte_flags_need_flush() about _PAGE_COW bit
- Break apart patch for better bisectability

v3:
- Add comment around _PAGE_TABLE in response to comment from (Andrew Cooper)
- Check for PSE in pmd_shstk (Andrew Cooper)
- Get to the point quicker in commit log (Andrew Cooper)
- Clarify and reorder commit log for why the PTE bit examples have multiple entries. Apply same changes for comment. (peterz)
- Fix comment that implied dirty bit for COW was a specific x86 thing (peterz)
- Fix swapping of Write/Dirty (PeterZ)

v2:
- Update commit log with comments (Dave Hansen)
- Add comments in code to explain pte modification code better (Dave)
- Clarify info on the meaning of various Write,Cow,Dirty combinations

 arch/x86/include/asm/pgtable.h       | 78 ++++++++++++++++++++++++++++
 arch/x86/include/asm/pgtable_types.h | 59 +++++++++++++++++++--
 arch/x86/include/asm/tlbflush.h      |  3 +-
 3 files changed, 134 insertions(+), 6 deletions(-)
arch/x86/include/asm/pgtable.h +78 -0
index a1d6f121ee35..ee5fbdc2615f 100644
@@ -300,6 +300,44 @@ static inline pte_t pte_clear_flags(pte_t pte, pteval_t clear)
 	return native_make_pte(v & ~clear);
 }
 
+/*
+ * Normally COW memory can result in Dirty=1,Write=0 PTs. But in the case
+ * of X86_FEATURE_USER_SHSTK, the software COW bit is used, since the
+ * Dirty=1,Write=0 will result in the memory being treated as shaodw stack
+ * by the HW. So when creating COW memory, a software bit is used
+ * _PAGE_BIT_COW. The following functions pte_mkcow() and pte_clear_cow()
+ * take a PTE marked conventially COW (Dirty=1) and transition it to the
+ * shadow stack compatible version of COW (Cow=1).
+ */
+
+static inline pte_t pte_mkcow(pte_t pte)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pte;
+
+	pte = pte_clear_flags(pte, _PAGE_DIRTY);
+	return pte_set_flags(pte, _PAGE_COW);
+}
+
+static inline pte_t pte_clear_cow(pte_t pte)
+{
+	/*
+	 * _PAGE_COW is unnecessary on !X86_FEATURE_USER_SHSTK kernels.
+	 * See the _PAGE_COW definition for more details.
+	 */
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pte;
+
+	/*
+	 * PTE is getting copied-on-write, so it will be dirtied
+	 * if writable, or made shadow stack if shadow stack and
+	 * being copied on access. Set they dirty bit for both
+	 * cases.
+	 */
+	pte = pte_set_flags(pte, _PAGE_DIRTY);
+	return pte_clear_flags(pte, _PAGE_COW);
+}
+
 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_WP
 static inline int pte_uffd_wp(pte_t pte)
 {
@@ -396,6 +434,26 @@ static inline pmd_t pmd_clear_flags(pmd_t pmd, pmdval_t clear)
 	return native_make_pmd(v & ~clear);
 }
 
+/* See comments above pte_mkcow() */
+static inline pmd_t pmd_mkcow(pmd_t pmd)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pmd;
+
+	pmd = pmd_clear_flags(pmd, _PAGE_DIRTY);
+	return pmd_set_flags(pmd, _PAGE_COW);
+}
+
+/* See comments above pte_mkcow() */
+static inline pmd_t pmd_clear_cow(pmd_t pmd)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pmd;
+
+	pmd = pmd_set_flags(pmd, _PAGE_DIRTY);
+	return pmd_clear_flags(pmd, _PAGE_COW);
+}
+
 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_WP
 static inline int pmd_uffd_wp(pmd_t pmd)
 {
@@ -467,6 +525,26 @@ static inline pud_t pud_clear_flags(pud_t pud, pudval_t clear)
 	return native_make_pud(v & ~clear);
 }
 
+/* See comments above pte_mkcow() */
+static inline pud_t pud_mkcow(pud_t pud)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pud;
+
+	pud = pud_clear_flags(pud, _PAGE_DIRTY);
+	return pud_set_flags(pud, _PAGE_COW);
+}
+
+/* See comments above pte_mkcow() */
+static inline pud_t pud_clear_cow(pud_t pud)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pud;
+
+	pud = pud_set_flags(pud, _PAGE_DIRTY);
+	return pud_clear_flags(pud, _PAGE_COW);
+}
+
 static inline pud_t pud_mkold(pud_t pud)
 {
 	return pud_clear_flags(pud, _PAGE_ACCESSED);
arch/x86/include/asm/pgtable_types.h +54 -5

85 lines not on this page · raw message

arch/x86/include/asm/tlbflush.h +2 -1
index 662598dea937..08d9b5fce4fd 100644
@@ -283,7 +283,8 @@ static inline bool pte_flags_need_flush(unsigned long oldflags,
 	const pteval_t flush_on_clear = _PAGE_DIRTY | _PAGE_PRESENT |
 					_PAGE_ACCESSED;
 	const pteval_t software_flags = _PAGE_SOFTW1 | _PAGE_SOFTW2 |
-					_PAGE_SOFTW3 | _PAGE_SOFTW4;
+					_PAGE_SOFTW3 | _PAGE_SOFTW4 |
+					_PAGE_COW;
 	const pteval_t flush_on_change = _PAGE_RW | _PAGE_USER | _PAGE_PWT |
 			  _PAGE_PCD | _PAGE_PSE | _PAGE_GLOBAL | _PAGE_PAT |
 			  _PAGE_PAT_LARGE | _PAGE_PKEY_BIT0 | _PAGE_PKEY_BIT1 |
Signature · 1 line
2.17.1
Reviewed-by on v4 10/39
#39 lore raw

Re: [PATCH v4 10/39] x86/mm: Introduce _PAGE_COW

Quoted 46 lines · Rick Edgecombe

Some OSes have a greater dependence on software available bits in PTEs than Linux. That left the hardware architects looking for a way to represent a new memory type (shadow stack) within the existing bits. They chose to repurpose a lightly-used state: Write=0,Dirty=1. So in order to support shadow stack memory, Linux should avoid creating memory with this PTE bit combination unless it intends for it to be shadow stack.

The reason it's lightly used is that Dirty=1 is normally set by HW _before_ a write. A write with a Write=0 PTE would typically only generate a fault, not set Dirty=1. Hardware can (rarely) both set Dirty=1 *and* generate the fault, resulting in a Write=0,Dirty=1 PTE. Hardware which supports shadow stacks will no longer exhibit this oddity.

So that leaves Write=0,Dirty=1 PTEs created in software. To achieve this, in places where Linux normally creates Write=0,Dirty=1, it can use the software-defined _PAGE_COW in place of the hardware _PAGE_DIRTY. In other words, whenever Linux needs to create Write=0,Dirty=1, it instead creates Write=0,Cow=1 except for shadow stack, which is Write=0,Dirty=1. Further differentiated by VMA flags, these PTE bit combinations would be set as follows for various types of memory:

(Write=0,Cow=1,Dirty=0):
- A modified, copy-on-write (COW) page. Previously when a typical anonymous writable mapping was made COW via fork(), the kernel would mark it Write=0,Dirty=1. Now it will instead use the Cow bit. This happens in copy_present_pte().
- A R/O page that has been COW'ed. The user page is in a R/O VMA, and get_user_pages(FOLL_FORCE) needs a writable copy. The page fault handler creates a copy of the page and sets the new copy's PTE as Write=0 and Cow=1.
- A shared shadow stack PTE. When a shadow stack page is being shared among processes (this happens at fork()), its PTE is made Dirty=0, so the next shadow stack access causes a fault, and the page is duplicated and Dirty=1 is set again. This is the COW equivalent for shadow stack pages, even though it's copy-on-access rather than copy-on-write.

(Write=0,Cow=0,Dirty=1):
- A shadow stack PTE.
- A Cow PTE created when a processor without shadow stack support set Dirty=1.

There are six bits left available to software in the 64-bit PTE after consuming a bit for _PAGE_COW. No space is consumed in 32-bit kernels because shadow stacks are not enabled there.

Quoted 7 lines

This is a prepratory patch. Changes to actually start marking _PAGE_COW will follow once other pieces are in place.

Signature · 1 line
Kees Cook
maintainer
#40 lore raw

Re: [PATCH v4 10/39] x86/mm: Introduce _PAGE_COW

In reply to Rick Edgecombe
Quoted 5 lines · Rick Edgecombe

There are six bits left available to software in the 64-bit PTE after consuming a bit for _PAGE_COW. No space is consumed in 32-bit kernels because shadow stacks are not enabled there.

This is a prepratory patch. Changes to actually start marking _PAGE_COW

Unknown word [prepratory] in commit message.
Suggestions: ['preparatory',

Quoted 1 line

will follow once other pieces are in place.

And regardless, you don't really need this sentence at all, AFAICT.

...

Quoted 2 lines

+/*
+ * Normally COW memory can result in Dirty=1,Write=0 PTs. But in the case

							^^^

PTEs.

Quoted 5 lines

+ * of X86_FEATURE_USER_SHSTK, the software COW bit is used, since the
+ * Dirty=1,Write=0 will result in the memory being treated as shaodw stack
+ * by the HW. So when creating COW memory, a software bit is used
+ * _PAGE_BIT_COW. The following functions pte_mkcow() and pte_clear_cow()
+ * take a PTE marked conventially COW (Dirty=1) and transition it to the

Unknown word [conventially] in comment.
Suggestions: ['conventionally', ...

Quoted 3 lines

+ * shadow stack compatible version of COW (Cow=1).
+ */
+

^ Superfluous newline.

arch/x86/include/asm/pgtable.h static inline pte_t pte_clear_flags(pte_t pte, pteval_t clear) · line 325

Quoted 13 lines
arch/x86/include/asm/pgtable.h +13 -0
+static inline pte_t pte_mkcow(pte_t pte)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pte;
+
+	pte = pte_clear_flags(pte, _PAGE_DIRTY);
+	return pte_set_flags(pte, _PAGE_COW);
+}
+
+static inline pte_t pte_clear_cow(pte_t pte)
+{
+	/*
+	 * _PAGE_COW is unnecessary on !X86_FEATURE_USER_SHSTK kernels.

I'm guessing this "unnecessary" is supposed to mean that on kernels not supporting shadow stack, a COW page uses the old bit flags?

I.e., Dirty=1,Write=0?

Might as well write it this way to be perfectly clear.

arch/x86/include/asm/pgtable.h static inline pte_t pte_clear_flags(pte_t pte, pteval_t clear) · line 334

Quoted 9 lines
arch/x86/include/asm/pgtable.h +9 -0
+	 * See the _PAGE_COW definition for more details.
+	 */
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return pte;
+
+	/*
+	 * PTE is getting copied-on-write, so it will be dirtied
+	 * if writable, or made shadow stack if shadow stack and
+	 * being copied on access. Set they dirty bit for both

"Set the dirty bit.."

arch/x86/include/asm/pgtable.h static inline pte_t pte_clear_flags(pte_t pte, pteval_t clear) · line 339

Quoted 5 lines
arch/x86/include/asm/pgtable.h +5 -0
+	 * cases.
+	 */
+	pte = pte_set_flags(pte, _PAGE_DIRTY);
+	return pte_clear_flags(pte, _PAGE_COW);
+}

Rest looks ok.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#41 lore raw

Re: [PATCH v4 10/39] x86/mm: Introduce _PAGE_COW

Quoted 7 lines · Borislav Petkov
Quoted 6 lines · Rick Edgecombe

There are six bits left available to software in the 64-bit PTE after
consuming a bit for _PAGE_COW. No space is consumed in 32-bit kernels
because shadow stacks are not enabled there.

Quoted 5 lines
Quoted 2 lines

This is a prepratory patch. Changes to actually start marking _PAGE_COW

Unknown word [prepratory] in commit message.
Suggestions: ['preparatory',

Sorry about all these spelling errors.

Quoted 6 lines
Quoted 2 lines

will follow once other pieces are in place.

And regardless, you don't really need this sentence at all, AFAICT.

...

Ok.

Quoted 7 lines
Quoted 4 lines

+/*
+ * Normally COW memory can result in Dirty=1,Write=0 PTs. But in the case

                                                        ^^^

PTEs.

Thanks.

Quoted 11 lines
Quoted 10 lines

+ * of X86_FEATURE_USER_SHSTK, the software COW bit is used, since the
+ * Dirty=1,Write=0 will result in the memory being treated as shaodw stack
+ * by the HW. So when creating COW memory, a software bit is used
+ * _PAGE_BIT_COW. The following functions pte_mkcow() and pte_clear_cow()
+ * take a PTE marked conventially COW (Dirty=1) and transition it to the

Quoted 8 lines

Unknown word [conventially] in comment.
Suggestions: ['conventionally', ...

Quoted 3 lines

+ * shadow stack compatible version of COW (Cow=1).
+ */
+

^ Superfluous newline.

Thanks.

Quoted 20 lines
Quoted 14 lines
arch/x86/include/asm/pgtable.h +13 -0
+static inline pte_t pte_mkcow(pte_t pte)
+{
+       if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+               return pte;
+
+       pte = pte_clear_flags(pte, _PAGE_DIRTY);
+       return pte_set_flags(pte, _PAGE_COW);
+}
+
+static inline pte_t pte_clear_cow(pte_t pte)
+{
+       /*
+        * _PAGE_COW is unnecessary on !X86_FEATURE_USER_SHSTK
Quoted 1 line

kernels.

I'm guessing this "unnecessary" is supposed to mean that on kernels not
supporting shadow stack, a COW page uses the old bit flags?

Quoted 3 lines

I.e., Dirty=1,Write=0?

Might as well write it this way to be perfectly clear.

Right, I can clarify.

Quoted 11 lines
Quoted 10 lines

+        * See the _PAGE_COW definition for more details. +        */
+       if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK)) +               return pte;
+
+       /*
+        * PTE is getting copied-on-write, so it will be dirtied +        * if writable, or made shadow stack if shadow stack and +        * being copied on access. Set they dirty bit for both

Quoted 1 line

"Set the dirty bit.."

Oof.

Quoted 8 lines
Quoted 6 lines

+        * cases.
+        */
+       pte = pte_set_flags(pte, _PAGE_DIRTY);
+       return pte_clear_flags(pte, _PAGE_COW);
+}

Rest looks ok.

Thanks.

Quoted 3 lines

Thx.

#42 lore raw

PATCH v4 11/39 x86/mm: Update pte_modify for _PAGE_COW

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The Write=0,Dirty=1 PTE has been used to indicate copy-on-write pages. However, newer x86 processors also regard a Write=0,Dirty=1 PTE as a shadow stack page. In order to separate the two, the software-defined _PAGE_DIRTY is changed to _PAGE_COW for the copy-on-write case, and pte_*() are updated to do this.

pte_modify() takes a "raw" pgprot_t which was not necessarily created with any of the existing PTE bit helpers. That means that it can return a pte_t with Write=0,Dirty=1, a shadow stack PTE, when it did not intend to create one.

However pte_modify() changes a PTE to 'newprot', but it doesn't use the pte_*(). Modify it to also move _PAGE_DIRTY to _PAGE_COW. Apply the same changes to pmd_modify().

---

v4:
- Fix an issue in soft-dirty test, where pte_modify() would detect _PAGE_COW in pte_dirty() and set the soft dirty bit in pte_mkdirty().

v2:
- Update commit log with text and suggestions from (Dave Hansen)
- Drop fixup_dirty_pte() in favor of clearing the HW dirty bit along with the _PAGE_CHG_MASK masking, then calling pte_mkdirty() (Dave Hansen)

 arch/x86/include/asm/pgtable.h | 40 +++++++++++++++++++++++++++++-----
 1 file changed, 34 insertions(+), 6 deletions(-)
arch/x86/include/asm/pgtable.h +34 -6
index ee5fbdc2615f..67bd2627c293 100644
@@ -698,26 +698,54 @@ static inline u64 flip_protnone_guard(u64 oldval, u64 val, u64 mask);
 
 static inline pte_t pte_modify(pte_t pte, pgprot_t newprot)
 {
+	pteval_t _page_chg_mask_no_dirty = _PAGE_CHG_MASK & ~_PAGE_DIRTY;
 	pteval_t val = pte_val(pte), oldval = val;
+	pte_t pte_result;
 
 	/*
 	 * Chop off the NX bit (if present), and add the NX portion of
 	 * the newprot (if present):
 	 */
-	val &= _PAGE_CHG_MASK;
-	val |= check_pgprot(newprot) & ~_PAGE_CHG_MASK;
+	val &= _page_chg_mask_no_dirty;
+	val |= check_pgprot(newprot) & ~_page_chg_mask_no_dirty;
 	val = flip_protnone_guard(oldval, val, PTE_PFN_MASK);
-	return __pte(val);
+
+	pte_result = __pte(val);
+
+	/*
+	 * Dirty bit is not preserved above so it can be done
+	 * in a special way for the shadow stack case, where it
+	 * needs to set _PAGE_COW. pte_mkcow() will do this in
+	 * the case of shadow stack.
+	 */
+	if (pte_dirty(pte_result))
+		pte_result = pte_mkcow(pte_result);
+
+	return pte_result;
 }
 
 static inline pmd_t pmd_modify(pmd_t pmd, pgprot_t newprot)
 {
+	pteval_t _hpage_chg_mask_no_dirty = _HPAGE_CHG_MASK & ~_PAGE_DIRTY;
 	pmdval_t val = pmd_val(pmd), oldval = val;
+	pmd_t pmd_result;
 
-	val &= _HPAGE_CHG_MASK;
-	val |= check_pgprot(newprot) & ~_HPAGE_CHG_MASK;
+	val &= _hpage_chg_mask_no_dirty;
+	val |= check_pgprot(newprot) & ~_hpage_chg_mask_no_dirty;
 	val = flip_protnone_guard(oldval, val, PHYSICAL_PMD_PAGE_MASK);
-	return __pmd(val);
+
+	pmd_result = __pmd(val);
+
+	/*
+	 * Dirty bit is not preserved above so it can be done
+	 * in a special way for the shadow stack case, where it
+	 * needs to set _PAGE_COW. pmd_mkcow() will do this in
+	 * the case of shadow stack.
+	 */
+	if (pmd_dirty(pmd_result))
+		pmd_result = pmd_mkcow(pmd_result);
+
+	return pmd_result;
 }
 
 /*
Signature · 1 line
2.17.1
Reviewed-by on v4 11/39
#43 lore raw

Re: [PATCH v4 11/39] x86/mm: Update pte_modify for _PAGE_COW

Quoted 13 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The Write=0,Dirty=1 PTE has been used to indicate copy-on-write pages. However, newer x86 processors also regard a Write=0,Dirty=1 PTE as a shadow stack page. In order to separate the two, the software-defined _PAGE_DIRTY is changed to _PAGE_COW for the copy-on-write case, and pte_*() are updated to do this.

pte_modify() takes a "raw" pgprot_t which was not necessarily created with any of the existing PTE bit helpers. That means that it can return a pte_t with Write=0,Dirty=1, a shadow stack PTE, when it did not intend to create one.

Quoted 7 lines

However pte_modify() changes a PTE to 'newprot', but it doesn't use the pte_*(). Modify it to also move _PAGE_DIRTY to _PAGE_COW. Apply the same changes to pmd_modify().

Signature · 1 line
Kees Cook
maintainer
#44 lore raw

Re: [PATCH v4 11/39] x86/mm: Update pte_modify for _PAGE_COW

In reply to Rick Edgecombe
Quoted 11 lines · Rick Edgecombe

static inline pte_t pte_modify(pte_t pte, pgprot_t newprot) {

arch/x86/include/asm/pgtable.h +2 -1
+	pteval_t _page_chg_mask_no_dirty = _PAGE_CHG_MASK & ~_PAGE_DIRTY;
 	pteval_t val = pte_val(pte), oldval = val;
+	pte_t pte_result;
 
 	/*
 	 * Chop off the NX bit (if present), and add the NX portion of
 	 * the newprot (if present):
 	 */
-	val &= _PAGE_CHG_MASK;

arch/x86/include/asm/pgtable.h static inline u64 flip_protnone_guard(u64 oldval, u64 val, u64 mask); · line 716

Quoted 10 lines
arch/x86/include/asm/pgtable.h +7 -2
-	val |= check_pgprot(newprot) & ~_PAGE_CHG_MASK;
+	val &= _page_chg_mask_no_dirty;
+	val |= check_pgprot(newprot) & ~_page_chg_mask_no_dirty;
 	val = flip_protnone_guard(oldval, val, PTE_PFN_MASK);
-	return __pte(val);
+
+	pte_result = __pte(val);
+
+	/*
+	 * Dirty bit is not preserved above so it can be done

Just for my own understanding: are you saying here that flip_protnone_guard() might end up setting _PAGE_DIRTY in val...

arch/x86/include/asm/pgtable.h static inline u64 flip_protnone_guard(u64 oldval, u64 val, u64 mask); · line 722

Quoted 6 lines
arch/x86/include/asm/pgtable.h +6 -0
+	 * in a special way for the shadow stack case, where it
+	 * needs to set _PAGE_COW. pte_mkcow() will do this in
+	 * the case of shadow stack.
+	 */
+	if (pte_dirty(pte_result))
+		pte_result = pte_mkcow(pte_result);

... and in that case we need to turn it into a _PAGE_COW setting?

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#45 lore raw

Re: [PATCH v4 11/39] x86/mm: Update pte_modify for _PAGE_COW

Quoted 28 lines · Borislav Petkov
Quoted 18 lines · Rick Edgecombe

 static inline pte_t pte_modify(pte_t pte, pgprot_t newprot) {
+       pteval_t _page_chg_mask_no_dirty = _PAGE_CHG_MASK & ~_PAGE_DIRTY;
        pteval_t val = pte_val(pte), oldval = val;
+       pte_t pte_result;

        /*
         * Chop off the NX bit (if present), and add the NX portion of
         * the newprot (if present):
         */
-       val &= _PAGE_CHG_MASK;
-       val |= check_pgprot(newprot) & ~_PAGE_CHG_MASK; +       val &= _page_chg_mask_no_dirty;
+       val |= check_pgprot(newprot) & ~_page_chg_mask_no_dirty; val = flip_protnone_guard(oldval, val, PTE_PFN_MASK); -       return __pte(val);

arch/x86/include/asm/pgtable.h static inline u64 flip_protnone_guard(u64 oldval, u64 val, u64 mask); · line 716

Quoted 5 lines
arch/x86/include/asm/pgtable.h +5 -0
+
+       pte_result = __pte(val);
+
+       /*
+        * Dirty bit is not preserved above so it can be done

Just for my own understanding: are you saying here that flip_protnone_guard() might end up setting _PAGE_DIRTY in val...

Quoted 9 lines
Quoted 6 lines

+        * in a special way for the shadow stack case, where it +        * needs to set _PAGE_COW. pte_mkcow() will do this in +        * the case of shadow stack.
+        */
+       if (pte_dirty(pte_result))
+               pte_result = pte_mkcow(pte_result);

... and in that case we need to turn it into a _PAGE_COW setting?

The comment is referring to the dirty bits possibly coming from newprot, but looking at it now I think the code was broken trying to fix the recent soft dirty test breakage. Now it might lose pre-existing dirty bits in the pte unessarily... I think. I'm temporarily without access to my test equipment so will have to get back to you on this. Thanks for flagging that something looks off.

maintainer
#46 lore raw

Re: [PATCH v4 11/39] x86/mm: Update pte_modify for _PAGE_COW

Quoted 2 lines · Rick P

The comment is referring to the dirty bits possibly coming from newprot,

Ah right, ofc.

Quoted 3 lines

but looking at it now I think the code was broken trying to fix the recent soft dirty test breakage. Now it might lose pre-existing dirty bits in the pte unessarily... I think.

Right, does this code need to be simplified?

I.e., match the shadow stack PTE (Write=0,Dirty=1) and handle that in a separate helper?

So that the flows are separate. I'm not a mm guy but this function makes my head hurt - dunno about other folks. :)

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#47 lore raw

Re: [PATCH v4 11/39] x86/mm: Update pte_modify for _PAGE_COW

Quoted 13 lines · Borislav Petkov
Quoted 2 lines · Rick P

The comment is referring to the dirty bits possibly coming from newprot,

Ah right, ofc.

Quoted 4 lines

but looking at it now I think the code was broken trying to fix the recent soft dirty test breakage. Now it might lose pre- existing
dirty bits in the pte unessarily... I think.

Right, does this code need to be simplified?

Quoted 7 lines

I.e., match the shadow stack PTE (Write=0,Dirty=1) and handle that in a separate
helper?

So that the flows are separate. I'm not a mm guy but this function makes my head
hurt - dunno about other folks. :)

Yea, the whole Write=0,Dirty=1 thing has been a bit of a challenge to make clear in the MM code. Dave had suggested a sketch here for pte_modify():

https://lore.kernel.org/lkml/[email protected]/

The problem was that pte_mkdirty() also sets the soft dirty bit. So it did more than preserve the dirty bit - it also added on the soft dirty bit. I extracted a helper __pte_mkdirty() that can optionally not set the soft dirty bit. So then it looks pretty close to how Dave suggested:

static inline pte_t pte_modify(pte_t pte, pgprot_t newprot) {
pteval_t _page_chg_mask_no_dirty = _PAGE_CHG_MASK &

~_PAGE_DIRTY;
	pteval_t val = pte_val(pte), oldval = val;
	pte_t pte_result;

	/*
	 * Chop off the NX bit (if present), and add the NX portion of
	 * the newprot (if present):
	 */
	val &= _page_chg_mask_no_dirty;
	val |= check_pgprot(newprot) & ~_page_chg_mask_no_dirty;
	val = flip_protnone_guard(oldval, val, PTE_PFN_MASK);

	pte_result = __pte(val);

	/*
	 * Dirty bit is not preserved above so it can be done
	 * in a special way for the shadow stack case, where it
	 * may need to set _PAGE_COW. __pte_mkdirty() will do this in
	 * the case of shadow stack.
	 */
	if (pte_dirty(pte))
		pte_result = __pte_mkdirty(pte_result, false);

	return pte_result;
}
#48 lore raw

PATCH v4 12/39 x86/mm: Update ptep_set_wrprotect() and pmdp_set_wrprotect() for transition from _PAGE_DIRTY to _PAGE_COW

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When Shadow Stack is in use, Write=0,Dirty=1 PTE are reserved for shadow stack. Copy-on-write PTes then have Write=0,Cow=1.

When a PTE goes from Write=1,Dirty=1 to Write=0,Cow=1, it could become a transient shadow stack PTE in two cases:

The first case is that some processors can start a write but end up seeing a Write=0 PTE by the time they get to the Dirty bit, creating a transient shadow stack PTE. However, this will not occur on processors supporting Shadow Stack, and a TLB flush is not necessary.

The second case is that when _PAGE_DIRTY is replaced with _PAGE_COW non- atomically, a transient shadow stack PTE can be created as a result. Thus, prevent that with cmpxchg.

In the case of pmdp_set_wrprotect(), for nopmd configs the ->pmd operated on does not exist and the logic would need to be different. Although the extra functionality will normally be optimized out when user shadow stacks are not configured, also exclude it in the preprocessor stage so that it will still compile. User shadow stack is not supported there by Linux anyway. Leave the cpu_feature_enabled() check so that the functionality also disables based on runtime detection of the feature.

Dave Hansen, Jann Horn, Andy Lutomirski, and Peter Zijlstra provided many insights to the issue. Jann Horn provided the cmpxchg solution.

---

v3:
- Remove unnecessary #ifdef (Dave Hansen)

v2:
- Compile out some code due to clang build error
- Clarify commit log (dhansen)
- Normalize PTE bit descriptions between patches (dhansen)
- Update comment with text from (dhansen)

Yu-cheng v30:
- Replace (pmdval_t) cast with CONFIG_PGTABLE_LEVELES > 2 (Borislav Petkov).

 arch/x86/include/asm/pgtable.h | 35 ++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
arch/x86/include/asm/pgtable.h +35 -0
index 67bd2627c293..b68428099932 100644
@@ -1195,6 +1195,21 @@ static inline pte_t ptep_get_and_clear_full(struct mm_struct *mm,
 static inline void ptep_set_wrprotect(struct mm_struct *mm,
 				      unsigned long addr, pte_t *ptep)
 {
+	/*
+	 * Avoid accidentally creating shadow stack PTEs
+	 * (Write=0,Dirty=1).  Use cmpxchg() to prevent races with
+	 * the hardware setting Dirty=1.
+	 */
+	if (cpu_feature_enabled(X86_FEATURE_USER_SHSTK)) {
+		pte_t old_pte, new_pte;
+
+		old_pte = READ_ONCE(*ptep);
+		do {
+			new_pte = pte_wrprotect(old_pte);
+		} while (!try_cmpxchg(&ptep->pte, &old_pte.pte, new_pte.pte));
+
+		return;
+	}
 	clear_bit(_PAGE_BIT_RW, (unsigned long *)&ptep->pte);
 }
 
@@ -1247,6 +1262,26 @@ static inline pud_t pudp_huge_get_and_clear(struct mm_struct *mm,
 static inline void pmdp_set_wrprotect(struct mm_struct *mm,
 				      unsigned long addr, pmd_t *pmdp)
 {
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+	/*
+	 * If Shadow Stack is enabled, pmd_wrprotect() moves _PAGE_DIRTY
+	 * to _PAGE_COW (see comments at pmd_wrprotect()).
+	 * When a thread reads a RW=1, Dirty=0 PMD and before changing it
+	 * to RW=0, Dirty=0, another thread could have written to the page
+	 * and the PMD is RW=1, Dirty=1 now.
+	 */
+	if (cpu_feature_enabled(X86_FEATURE_USER_SHSTK)) {
+		pmd_t old_pmd, new_pmd;
+
+		old_pmd = READ_ONCE(*pmdp);
+		do {
+			new_pmd = pmd_wrprotect(old_pmd);
+		} while (!try_cmpxchg(&pmdp->pmd, &old_pmd.pmd, new_pmd.pmd));
+
+		return;
+	}
+#endif
+
 	clear_bit(_PAGE_BIT_RW, (unsigned long *)pmdp);
 }
 
Signature · 1 line
2.17.1
Reviewed-by on v4 12/39
#49 lore raw

Re: [PATCH v4 12/39] x86/mm: Update ptep_set_wrprotect() and pmdp_set_wrprotect() for transition from _PAGE_DIRTY to _PAGE_COW

Quoted 25 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When Shadow Stack is in use, Write=0,Dirty=1 PTE are reserved for shadow stack. Copy-on-write PTes then have Write=0,Cow=1.

When a PTE goes from Write=1,Dirty=1 to Write=0,Cow=1, it could become a transient shadow stack PTE in two cases:

The first case is that some processors can start a write but end up seeing a Write=0 PTE by the time they get to the Dirty bit, creating a transient shadow stack PTE. However, this will not occur on processors supporting Shadow Stack, and a TLB flush is not necessary.

The second case is that when _PAGE_DIRTY is replaced with _PAGE_COW non- atomically, a transient shadow stack PTE can be created as a result. Thus, prevent that with cmpxchg.

In the case of pmdp_set_wrprotect(), for nopmd configs the ->pmd operated on does not exist and the logic would need to be different. Although the extra functionality will normally be optimized out when user shadow stacks are not configured, also exclude it in the preprocessor stage so that it will still compile. User shadow stack is not supported there by Linux anyway. Leave the cpu_feature_enabled() check so that the functionality also disables based on runtime detection of the feature.

Quoted 6 lines

Dave Hansen, Jann Horn, Andy Lutomirski, and Peter Zijlstra provided many insights to the issue. Jann Horn provided the cmpxchg solution.

Signature · 1 line
Kees Cook
maintainer
#50 lore raw

Re: [PATCH v4 12/39] x86/mm: Update ptep_set_wrprotect() and pmdp_set_wrprotect() for transition from _PAGE_DIRTY to _PAGE_COW

In reply to Rick Edgecombe

Just textual improvements:

Quoted 3 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When Shadow Stack is in use, Write=0,Dirty=1 PTE are reserved for shadow

Pls, no caps.

Quoted 1 line

stack. Copy-on-write PTes then have Write=0,Cow=1.

"... are preserved for shadow stack pages."

Quoted 3 lines

When a PTE goes from Write=1,Dirty=1 to Write=0,Cow=1, it could become a transient shadow stack PTE in two cases:

1. Some processors ...

2. When _PAGE_DIRTY ...

Quoted 9 lines

The first case is that some processors can start a write but end up seeing a Write=0 PTE by the time they get to the Dirty bit, creating a transient shadow stack PTE. However, this will not occur on processors supporting Shadow Stack, and a TLB flush is not necessary.

The second case is that when _PAGE_DIRTY is replaced with _PAGE_COW non- atomically, a transient shadow stack PTE can be created as a result. Thus, prevent that with cmpxchg.

Quoted 7 lines

In the case of pmdp_set_wrprotect(), for nopmd configs the ->pmd operated on does not exist and the logic would need to be different. Although the extra functionality will normally be optimized out when user shadow stacks are not configured, also exclude it in the preprocessor stage so that it will still compile. User shadow stack is not supported there by Linux anyway. Leave the cpu_feature_enabled() check so that the functionality also disables based on runtime detection of the feature.

"... also gets disabled ..."

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#51 lore raw

Re: [PATCH v4 12/39] x86/mm: Update ptep_set_wrprotect() and pmdp_set_wrprotect() for transition from _PAGE_DIRTY to _PAGE_COW

Quoted 9 lines · Borislav Petkov

Just textual improvements:

Quoted 4 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When Shadow Stack is in use, Write=0,Dirty=1 PTE are reserved for shadow

Pls, no caps.

Sure on "Shadow Stack". For Write=0,Dirty=1 there was a previous suggestion to standardize on how these bits are referred to across the series in both the comments and commit logs. I think the capitalization helps differentiate between the concepts of write and dirty and the actual PTE bits with those names. Especially since shadow stack muddies the concepts of writable and dirty memory, I thought it was a helpful distinction. Is it ok?

The other suggestions seem good.

Thanks,

Rick

maintainer
#52 lore raw

Re: [PATCH v4 12/39] x86/mm: Update ptep_set_wrprotect() and pmdp_set_wrprotect() for transition from _PAGE_DIRTY to _PAGE_COW

Quoted 7 lines · Rick P

Sure on "Shadow Stack". For Write=0,Dirty=1 there was a previous suggestion to standardize on how these bits are referred to across the series in both the comments and commit logs. I think the capitalization helps differentiate between the concepts of write and dirty and the actual PTE bits with those names. Especially since shadow stack muddies the concepts of writable and dirty memory, I thought it was a helpful distinction. Is it ok?

Oh sorry, I meant only

s/Shadow Stack/shadow stack/

The page flags are fine.

Bottom line is: hw documents love to capitalize features and concepts and that's just unnecessary marketing bla.

Thx.

Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#53 lore raw

PATCH v4 13/39 x86/mm: Start actually marking _PAGE_COW

In reply to Rick Edgecombe

The recently introduced _PAGE_COW should be used instead of the HW Dirty bit whenever a PTE is Write=0, in order to not inadvertently create shadow stack PTEs. Update pte_mk*() helpers to do this, and apply the same changes to pmd and pud.

---

v4:
- Break part patch for better bisectability

 arch/x86/include/asm/pgtable.h | 133 ++++++++++++++++++++++++++++-----
 1 file changed, 113 insertions(+), 20 deletions(-)
arch/x86/include/asm/pgtable.h +113 -20
index b68428099932..4a149cec0c07 100644
@@ -124,9 +124,17 @@ extern pmdval_t early_pmd_flags;
  * The following only work if pte_present() is true.
  * Undefined behaviour if not..
  */
-static inline int pte_dirty(pte_t pte)
+static inline bool pte_dirty(pte_t pte)
 {
-	return pte_flags(pte) & _PAGE_DIRTY;
+	return pte_flags(pte) & _PAGE_DIRTY_BITS;
+}
+
+static inline bool pte_shstk(pte_t pte)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return false;
+
+	return (pte_flags(pte) & (_PAGE_RW | _PAGE_DIRTY)) == _PAGE_DIRTY;
 }
 
 static inline int pte_young(pte_t pte)
@@ -134,9 +142,18 @@ static inline int pte_young(pte_t pte)
 	return pte_flags(pte) & _PAGE_ACCESSED;
 }
 
-static inline int pmd_dirty(pmd_t pmd)
+static inline bool pmd_dirty(pmd_t pmd)
 {
-	return pmd_flags(pmd) & _PAGE_DIRTY;
+	return pmd_flags(pmd) & _PAGE_DIRTY_BITS;
+}
+
+static inline bool pmd_shstk(pmd_t pmd)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return false;
+
+	return (pmd_flags(pmd) & (_PAGE_RW | _PAGE_DIRTY | _PAGE_PSE)) ==
+	       (_PAGE_DIRTY | _PAGE_PSE);
 }
 
 static inline int pmd_young(pmd_t pmd)
@@ -144,9 +161,9 @@ static inline int pmd_young(pmd_t pmd)
 	return pmd_flags(pmd) & _PAGE_ACCESSED;
 }
 
-static inline int pud_dirty(pud_t pud)
+static inline bool pud_dirty(pud_t pud)
 {
-	return pud_flags(pud) & _PAGE_DIRTY;
+	return pud_flags(pud) & _PAGE_DIRTY_BITS;
 }
 
 static inline int pud_young(pud_t pud)
@@ -156,13 +173,21 @@ static inline int pud_young(pud_t pud)
 
 static inline int pte_write(pte_t pte)
 {
-	return pte_flags(pte) & _PAGE_RW;
+	/*
+	 * Shadow stack pages are logically writable, but do not have
+	 * _PAGE_RW.  Check for them separately from _PAGE_RW itself.
+	 */
+	return (pte_flags(pte) & _PAGE_RW) || pte_shstk(pte);
 }
 
 #define pmd_write pmd_write
 static inline int pmd_write(pmd_t pmd)
 {
-	return pmd_flags(pmd) & _PAGE_RW;
+	/*
+	 * Shadow stack pages are logically writable, but do not have
+	 * _PAGE_RW.  Check for them separately from _PAGE_RW itself.
+	 */
+	return (pmd_flags(pmd) & _PAGE_RW) || pmd_shstk(pmd);
 }
 
 #define pud_write pud_write
@@ -357,7 +382,7 @@ static inline pte_t pte_clear_uffd_wp(pte_t pte)
 
 static inline pte_t pte_mkclean(pte_t pte)
 {
-	return pte_clear_flags(pte, _PAGE_DIRTY);
+	return pte_clear_flags(pte, _PAGE_DIRTY_BITS);
 }
 
 static inline pte_t pte_mkold(pte_t pte)
@@ -367,7 +392,16 @@ static inline pte_t pte_mkold(pte_t pte)
 
 static inline pte_t pte_wrprotect(pte_t pte)
 {
-	return pte_clear_flags(pte, _PAGE_RW);
+	pte = pte_clear_flags(pte, _PAGE_RW);
+
+	/*
+	 * Blindly clearing _PAGE_RW might accidentally create
+	 * a shadow stack PTE (Write=0,Dirty=1). Move the hardware
+	 * dirty value to the software bit.
+	 */
+	if (pte_dirty(pte))
+		pte = pte_mkcow(pte);
+	return pte;
 }
 
 static inline pte_t pte_mkexec(pte_t pte)
@@ -377,7 +411,19 @@ static inline pte_t pte_mkexec(pte_t pte)
 
 static inline pte_t pte_mkdirty(pte_t pte)
 {
-	return pte_set_flags(pte, _PAGE_DIRTY | _PAGE_SOFT_DIRTY);
+	pteval_t dirty = _PAGE_DIRTY;
+
+	/* Avoid creating Dirty=1,Write=0 PTEs */
+	if (cpu_feature_enabled(X86_FEATURE_USER_SHSTK) && !pte_write(pte))
+		dirty = _PAGE_COW;
+
+	return pte_set_flags(pte, dirty | _PAGE_SOFT_DIRTY);
+}
+
+static inline pte_t pte_mkwrite_shstk(pte_t pte)
+{
+	/* pte_clear_cow() also sets Dirty=1 */
+	return pte_clear_cow(pte);
 }
 
 static inline pte_t pte_mkyoung(pte_t pte)
@@ -387,7 +433,12 @@ static inline pte_t pte_mkyoung(pte_t pte)
 
 static inline pte_t pte_mkwrite(pte_t pte)
 {
-	return pte_set_flags(pte, _PAGE_RW);
+	pte = pte_set_flags(pte, _PAGE_RW);
+
+	if (pte_dirty(pte))
+		pte = pte_clear_cow(pte);
+
+	return pte;
 }
 
 static inline pte_t pte_mkhuge(pte_t pte)
@@ -478,17 +529,36 @@ static inline pmd_t pmd_mkold(pmd_t pmd)
 
 static inline pmd_t pmd_mkclean(pmd_t pmd)
 {
-	return pmd_clear_flags(pmd, _PAGE_DIRTY);
+	return pmd_clear_flags(pmd, _PAGE_DIRTY_BITS);
 }
 
 static inline pmd_t pmd_wrprotect(pmd_t pmd)
 {
-	return pmd_clear_flags(pmd, _PAGE_RW);
+	pmd = pmd_clear_flags(pmd, _PAGE_RW);
+	/*
+	 * Blindly clearing _PAGE_RW might accidentally create
+	 * a shadow stack PMD (RW=0, Dirty=1). Move the hardware
+	 * dirty value to the software bit.
+	 */
+	if (pmd_dirty(pmd))
+		pmd = pmd_mkcow(pmd);
+	return pmd;
 }
 
 static inline pmd_t pmd_mkdirty(pmd_t pmd)
 {
-	return pmd_set_flags(pmd, _PAGE_DIRTY | _PAGE_SOFT_DIRTY);
+	pmdval_t dirty = _PAGE_DIRTY;
+
+	/* Avoid creating (HW)Dirty=1, Write=0 PMDs */
+	if (cpu_feature_enabled(X86_FEATURE_USER_SHSTK) && !pmd_write(pmd))
+		dirty = _PAGE_COW;
+
+	return pmd_set_flags(pmd, dirty | _PAGE_SOFT_DIRTY);
+}
+
+static inline pmd_t pmd_mkwrite_shstk(pmd_t pmd)
+{
+	return pmd_clear_cow(pmd);
 }
 
 static inline pmd_t pmd_mkdevmap(pmd_t pmd)
@@ -508,7 +578,11 @@ static inline pmd_t pmd_mkyoung(pmd_t pmd)
 
 static inline pmd_t pmd_mkwrite(pmd_t pmd)
 {
-	return pmd_set_flags(pmd, _PAGE_RW);
+	pmd = pmd_set_flags(pmd, _PAGE_RW);
+
+	if (pmd_dirty(pmd))
+		pmd = pmd_clear_cow(pmd);
+	return pmd;
 }
 
 static inline pud_t pud_set_flags(pud_t pud, pudval_t set)
@@ -552,17 +626,32 @@ static inline pud_t pud_mkold(pud_t pud)
 
 static inline pud_t pud_mkclean(pud_t pud)
 {
-	return pud_clear_flags(pud, _PAGE_DIRTY);
+	return pud_clear_flags(pud, _PAGE_DIRTY_BITS);
 }
 
 static inline pud_t pud_wrprotect(pud_t pud)
 {
-	return pud_clear_flags(pud, _PAGE_RW);
+	pud = pud_clear_flags(pud, _PAGE_RW);
+
+	/*
+	 * Blindly clearing _PAGE_RW might accidentally create
+	 * a shadow stack PUD (RW=0, Dirty=1). Move the hardware
+	 * dirty value to the software bit.
+	 */
+	if (pud_dirty(pud))
+		pud = pud_mkcow(pud);
+	return pud;
 }
 
 static inline pud_t pud_mkdirty(pud_t pud)
 {
-	return pud_set_flags(pud, _PAGE_DIRTY | _PAGE_SOFT_DIRTY);
+	pudval_t dirty = _PAGE_DIRTY;
+
+	/* Avoid creating (HW)Dirty=1, Write=0 PUDs */
+	if (cpu_feature_enabled(X86_FEATURE_USER_SHSTK) && !pud_write(pud))
+		dirty = _PAGE_COW;
+
+	return pud_set_flags(pud, dirty | _PAGE_SOFT_DIRTY);
 }
 
 static inline pud_t pud_mkdevmap(pud_t pud)
@@ -582,7 +671,11 @@ static inline pud_t pud_mkyoung(pud_t pud)
 
 static inline pud_t pud_mkwrite(pud_t pud)
 {
-	return pud_set_flags(pud, _PAGE_RW);
+	pud = pud_set_flags(pud, _PAGE_RW);
+
+	if (pud_dirty(pud))
+		pud = pud_clear_cow(pud);
+	return pud;
 }
 
 #ifdef CONFIG_HAVE_ARCH_SOFT_DIRTY
Signature · 1 line
2.17.1
Reviewed-by on v4 13/39
#54 lore raw

Re: [PATCH v4 13/39] x86/mm: Start actually marking _PAGE_COW

Quoted 9 lines · Rick Edgecombe

The recently introduced _PAGE_COW should be used instead of the HW Dirty bit whenever a PTE is Write=0, in order to not inadvertently create shadow stack PTEs. Update pte_mk*() helpers to do this, and apply the same changes to pmd and pud.

Signature · 1 line
Kees Cook
#55 lore raw

PATCH v4 14/39 mm: Move VM_UFFD_MINOR_BIT from 37 to 38

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

Future patches will introduce a new VM flag VM_SHADOW_STACK that will be VM_HIGH_ARCH_BIT_5. VM_HIGH_ARCH_BIT_1 through VM_HIGH_ARCH_BIT_4 are bits 32-36, and bit 37 is the unrelated VM_UFFD_MINOR_BIT. For the sake of order, make all VM_HIGH_ARCH_BITs stay together by moving VM_UFFD_MINOR_BIT from 37 to 38. This will allow VM_SHADOW_STACK to be introduced as 37.

---
 include/linux/mm.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/mm.h +1 -1
index bfac5a166cb8..9ae6bc38d0b7 100644
@@ -354,7 +354,7 @@ extern unsigned int kobjsize(const void *objp);
 #endif
 
 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
-# define VM_UFFD_MINOR_BIT	37
+# define VM_UFFD_MINOR_BIT	38
 # define VM_UFFD_MINOR		BIT(VM_UFFD_MINOR_BIT)	/* UFFD minor faults */
 #else /* !CONFIG_HAVE_ARCH_USERFAULTFD_MINOR */
 # define VM_UFFD_MINOR		VM_NONE
Signature · 1 line
2.17.1
#56 lore raw

PATCH v4 15/39 mm: Introduce VM_SHADOW_STACK for shadow stack memory

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

A shadow stack PTE must be read-only and have _PAGE_DIRTY set. However, read-only and Dirty PTEs also exist for copy-on-write (COW) pages. These two cases are handled differently for page faults. Introduce VM_SHADOW_STACK to track shadow stack VMAs.

---

v3:
- Drop arch specific change in arch_vma_name(). The memory can show as anonymous (Kirill)
- Change CONFIG_ARCH_HAS_SHADOW_STACK to CONFIG_X86_USER_SHADOW_STACK in show_smap_vma_flags() (Boris)

 Documentation/filesystems/proc.rst | 1 +
 fs/proc/task_mmu.c                 | 3 +++
 include/linux/mm.h                 | 8 ++++++++
 3 files changed, 12 insertions(+)
Documentation/filesystems/proc.rst +1 -0
index 898c99eae8e4..05506dfa0480 100644
@@ -560,6 +560,7 @@ encoded manner. The codes are the following:
     mt    arm64 MTE allocation tags are enabled
     um    userfaultfd missing tracking
     uw    userfaultfd wr-protect tracking
+    ss    shadow stack page
     ==    =======================================
 
 Note that there is no guarantee that every flag and associated mnemonic will
fs/proc/task_mmu.c +3 -0
index fa3eea895210..9c17502e9746 100644
@@ -703,6 +703,9 @@ static void show_smap_vma_flags(struct seq_file *m, struct vm_area_struct *vma)
 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
 		[ilog2(VM_UFFD_MINOR)]	= "ui",
 #endif /* CONFIG_HAVE_ARCH_USERFAULTFD_MINOR */
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+		[ilog2(VM_SHADOW_STACK)] = "ss",
+#endif
 	};
 	size_t i;
 
include/linux/mm.h +8 -0
index 9ae6bc38d0b7..b982c2749e7b 100644
@@ -303,11 +303,13 @@ extern unsigned int kobjsize(const void *objp);
 #define VM_HIGH_ARCH_BIT_2	34	/* bit only usable on 64-bit architectures */
 #define VM_HIGH_ARCH_BIT_3	35	/* bit only usable on 64-bit architectures */
 #define VM_HIGH_ARCH_BIT_4	36	/* bit only usable on 64-bit architectures */
+#define VM_HIGH_ARCH_BIT_5	37	/* bit only usable on 64-bit architectures */
 #define VM_HIGH_ARCH_0	BIT(VM_HIGH_ARCH_BIT_0)
 #define VM_HIGH_ARCH_1	BIT(VM_HIGH_ARCH_BIT_1)
 #define VM_HIGH_ARCH_2	BIT(VM_HIGH_ARCH_BIT_2)
 #define VM_HIGH_ARCH_3	BIT(VM_HIGH_ARCH_BIT_3)
 #define VM_HIGH_ARCH_4	BIT(VM_HIGH_ARCH_BIT_4)
+#define VM_HIGH_ARCH_5	BIT(VM_HIGH_ARCH_BIT_5)
 #endif /* CONFIG_ARCH_USES_HIGH_VMA_FLAGS */
 
 #ifdef CONFIG_ARCH_HAS_PKEYS
@@ -323,6 +325,12 @@ extern unsigned int kobjsize(const void *objp);
 #endif
 #endif /* CONFIG_ARCH_HAS_PKEYS */
 
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+# define VM_SHADOW_STACK	VM_HIGH_ARCH_5
+#else
+# define VM_SHADOW_STACK	VM_NONE
+#endif
+
 #if defined(CONFIG_X86)
 # define VM_PAT		VM_ARCH_1	/* PAT reserves whole VMA at once (x86) */
 #elif defined(CONFIG_PPC)
Signature · 1 line
2.17.1
Reviewed-by on v4 15/39
#57 lore raw

Re: [PATCH v4 15/39] mm: Introduce VM_SHADOW_STACK for shadow stack memory

Quoted 7 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

Quoted 8 lines

A shadow stack PTE must be read-only and have _PAGE_DIRTY set. However, read-only and Dirty PTEs also exist for copy-on-write (COW) pages. These two cases are handled differently for page faults. Introduce VM_SHADOW_STACK to track shadow stack VMAs.

Signature · 1 line
Kees Cook
#58 lore raw

PATCH v4 16/39 x86/mm: Check Shadow Stack page fault errors

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The CPU performs "shadow stack accesses" when it expects to encounter shadow stack mappings. These accesses can be implicit (via CALL/RET instructions) or explicit (instructions like WRSS).

Shadow stacks accesses to shadow-stack mappings can see faults in normal, valid operation just like regular accesses to regular mappings. Shadow stacks need some of the same features like delayed allocation, swap and copy-on-write. The kernel needs to use faults to implement those features.

The architecture has concepts of both shadow stack reads and shadow stack writes. Any shadow stack access to non-shadow stack memory will generate a fault with the shadow stack error code bit set.

This means that, unlike normal write protection, the fault handler needs to create a type of memory that can be written to (with instructions that generate shadow stack writes), even to fulfill a read access. So in the case of COW memory, the COW needs to take place even with a shadow stack read. Otherwise the page will be left (shadow stack) writable in userspace. So to trigger the appropriate behavior, set FAULT_FLAG_WRITE for shadow stack accesses, even if the access was a shadow stack read.

Shadow stack accesses can also result in errors, such as when a shadow stack overflows, or if a shadow stack access occurs to a non-shadow-stack mapping. Also, generate the errors for invalid shadow stack accesses.

---

v4:
- Further improve comment talking about FAULT_FLAG_WRITE (Peterz)

v3:
- Improve comment talking about using FAULT_FLAG_WRITE (Peterz)

v2:
- Update commit log with verbiage/feedback from Dave Hansen
- Clarify reasoning for FAULT_FLAG_WRITE for all shadow stack accesses
- Update comments with some verbiage from Dave Hansen

Yu-cheng v30:
- Update Subject line and add a verb

 arch/x86/include/asm/trap_pf.h |  2 ++
 arch/x86/mm/fault.c            | 38 ++++++++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+)
arch/x86/include/asm/trap_pf.h +2 -0
index 10b1de500ab1..afa524325e55 100644
@@ -11,6 +11,7 @@
  *   bit 3 ==				1: use of reserved bit detected
  *   bit 4 ==				1: fault was an instruction fetch
  *   bit 5 ==				1: protection keys block access
+ *   bit 6 ==				1: shadow stack access fault
  *   bit 15 ==				1: SGX MMU page-fault
  */
 enum x86_pf_error_code {
@@ -20,6 +21,7 @@ enum x86_pf_error_code {
 	X86_PF_RSVD	=		1 << 3,
 	X86_PF_INSTR	=		1 << 4,
 	X86_PF_PK	=		1 << 5,
+	X86_PF_SHSTK	=		1 << 6,
 	X86_PF_SGX	=		1 << 15,
 };
 
arch/x86/mm/fault.c +38 -0
index 7b0d4ab894c8..3004ad044e9b 100644
@@ -1138,8 +1138,22 @@ access_error(unsigned long error_code, struct vm_area_struct *vma)
 				       (error_code & X86_PF_INSTR), foreign))
 		return 1;
 
+	/*
+	 * Shadow stack accesses (PF_SHSTK=1) are only permitted to
+	 * shadow stack VMAs. All other accesses result in an error.
+	 */
+	if (error_code & X86_PF_SHSTK) {
+		if (unlikely(!(vma->vm_flags & VM_SHADOW_STACK)))
+			return 1;
+		if (unlikely(!(vma->vm_flags & VM_WRITE)))
+			return 1;
+		return 0;
+	}
+
 	if (error_code & X86_PF_WRITE) {
 		/* write, present and write, not present: */
+		if (unlikely(vma->vm_flags & VM_SHADOW_STACK))
+			return 1;
 		if (unlikely(!(vma->vm_flags & VM_WRITE)))
 			return 1;
 		return 0;
@@ -1331,6 +1345,30 @@ void do_user_addr_fault(struct pt_regs *regs,
 
 	perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
 
+	/*
+	 * When a page becomes COW it changes from a shadow stack permissioned
+	 * page (Write=0,Dirty=1) to (Write=0,Dirty=0,CoW=1), which is simply
+	 * read-only to the CPU. When shadow stack is enabled, a RET would
+	 * normally pop the shadow stack by reading it with a "shadow stack
+	 * read" access. However, in the COW case the shadow stack memory does
+	 * not have shadow stack permissions, it is read-only. So it will
+	 * generate a fault.
+	 *
+	 * For conventionally writable pages, a read can be serviced with a
+	 * read only PTE, and COW would not have to happen. But for shadow
+	 * stack, there isn't the concept of read-only shadow stack memory.
+	 * If it is shadow stack permissioned, it can be modified via CALL and
+	 * RET instructions. So COW needs to happen before any memory can be
+	 * mapped with shadow stack permissions.
+	 *
+	 * Shadow stack accesses (read or write) need to be serviced with
+	 * shadow stack permissioned memory, so in the case of a shadow stack
+	 * read access, treat it as a WRITE fault so both COW will happen and
+	 * the write fault path will tickle maybe_mkwrite() and map the memory
+	 * shadow stack.
+	 */
+	if (error_code & X86_PF_SHSTK)
+		flags |= FAULT_FLAG_WRITE;
 	if (error_code & X86_PF_WRITE)
 		flags |= FAULT_FLAG_WRITE;
 	if (error_code & X86_PF_INSTR)
Signature · 1 line
2.17.1
maintainer
#59 lore raw

Re: [PATCH v4 16/39] x86/mm: Check Shadow Stack page fault errors

Quoted 6 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The CPU performs "shadow stack accesses" when it expects to encounter shadow stack mappings. These accesses can be implicit (via CALL/RET instructions) or explicit (instructions like WRSS).

Quoted 8 lines

Shadow stacks accesses to shadow-stack mappings can see faults in normal, valid operation just like regular accesses to regular mappings. Shadow stacks need some of the same features like delayed allocation, swap and copy-on-write. The kernel needs to use faults to implement those features.

The architecture has concepts of both shadow stack reads and shadow stack writes. Any shadow stack access to non-shadow stack memory will generate a fault with the shadow stack error code bit set.

You lost me here: by "shadow stack access to non-shadow stack memory" you mean the explicit one using WRU*SS?

Quoted 5 lines

This means that, unlike normal write protection, the fault handler needs to create a type of memory that can be written to (with instructions that generate shadow stack writes), even to fulfill a read access. So in the case of COW memory, the COW needs to take place even with a shadow stack read.

I guess I'm missing an example here: are we talking here about a user process getting its shadow stack pages allocated and them being COW first and on the first shstk operation, it would generate that fault?

arch/x86/mm/fault.c void do_user_addr_fault(struct pt_regs *regs, · line 1349

Quoted 6 lines
arch/x86/mm/fault.c +2 -0
@@ -1331,6 +1345,30 @@ void do_user_addr_fault(struct pt_regs *regs,
 
 	perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
 
+	/*
+	 * When a page becomes COW it changes from a shadow stack permissioned

Unknown word [permissioned] in comment.

arch/x86/mm/fault.c void do_user_addr_fault(struct pt_regs *regs, · line 1360

Quoted 11 lines
arch/x86/mm/fault.c +11 -0
+	 * page (Write=0,Dirty=1) to (Write=0,Dirty=0,CoW=1), which is simply
+	 * read-only to the CPU. When shadow stack is enabled, a RET would
+	 * normally pop the shadow stack by reading it with a "shadow stack
+	 * read" access. However, in the COW case the shadow stack memory does
+	 * not have shadow stack permissions, it is read-only. So it will
+	 * generate a fault.
+	 *
+	 * For conventionally writable pages, a read can be serviced with a
+	 * read only PTE, and COW would not have to happen. But for shadow
+	 * stack, there isn't the concept of read-only shadow stack memory.
+	 * If it is shadow stack permissioned, it can be modified via CALL and

Ditto.

arch/x86/mm/fault.c void do_user_addr_fault(struct pt_regs *regs, · line 1365

Quoted 5 lines
arch/x86/mm/fault.c +5 -0
+	 * RET instructions. So COW needs to happen before any memory can be
+	 * mapped with shadow stack permissions.
+	 *
+	 * Shadow stack accesses (read or write) need to be serviced with
+	 * shadow stack permissioned memory, so in the case of a shadow stack

Is this some new formulation I haven't heard about yet?

"Permissioned <something>"?

Quoted 12 lines
arch/x86/mm/fault.c +6 -0
+	 * read access, treat it as a WRITE fault so both COW will happen and
+	 * the write fault path will tickle maybe_mkwrite() and map the memory
+	 * shadow stack.
+	 */
+	if (error_code & X86_PF_SHSTK)
+		flags |= FAULT_FLAG_WRITE;
 	if (error_code & X86_PF_WRITE)
 		flags |= FAULT_FLAG_WRITE;
 	if (error_code & X86_PF_INSTR)
Signature · 1 line
2.17.1
Signature · 4 lines
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette
#60 lore raw

Re: [PATCH v4 16/39] x86/mm: Check Shadow Stack page fault errors

Quoted 23 lines · Borislav Petkov
Quoted 16 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The CPU performs "shadow stack accesses" when it expects to encounter
shadow stack mappings. These accesses can be implicit (via CALL/RET instructions) or explicit (instructions like WRSS).

Shadow stacks accesses to shadow-stack mappings can see faults in normal,
valid operation just like regular accesses to regular mappings. Shadow
stacks need some of the same features like delayed allocation, swap and
copy-on-write. The kernel needs to use faults to implement those features.

Quoted 5 lines

The architecture has concepts of both shadow stack reads and shadow stack
writes. Any shadow stack access to non-shadow stack memory will generate
a fault with the shadow stack error code bit set.

Quoted 3 lines

You lost me here: by "shadow stack access to non-shadow stack memory" you mean
the explicit one using WRU*SS?

Shadow stack accesses can be WR*SS, shadow stack pushes/pops from call/ret or incssp. Basically the instructions that intend to read or write to a shadow stack.

Quoted 11 lines
Quoted 10 lines

This means that, unlike normal write protection, the fault handler needs
to create a type of memory that can be written to (with instructions that
generate shadow stack writes), even to fulfill a read access. So in the
case of COW memory, the COW needs to take place even with a shadow stack
read.

Quoted 5 lines

I guess I'm missing an example here: are we talking here about a user process
getting its shadow stack pages allocated and them being COW first and on the
first shstk operation, it would generate that fault?

So if you have a shadow stack, then fork() so the shadow stack PTEs become read-only. Then you RET and the shadow stack get's popped to compare it to the normal stack value. In this case it only needs to read the shadow stack, but it does this with a "shadow stack read", which will fault if memory is not shadow stack. So the fault is a read fault, but it needs to make the PTE shadow stack in order to resolve it. So it needs to trigger COW, otherwise the shared page would be changeable from userspace. Make sense? I guess I can add an example if you think it would help.

Quoted 11 lines
Quoted 9 lines
arch/x86/mm/fault.c +2 -0
@@ -1331,6 +1345,30 @@ void do_user_addr_fault(struct pt_regs
 *regs,
 
 	perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
 
+	/*
+	 * When a page becomes COW it changes from a shadow stack

permissioned

Unknown word [permissioned] in comment.

I can change it.

Quoted 35 lines
Quoted 20 lines
(quoted diff) +1 -0
+	 * page (Write=0,Dirty=1) to (Write=0,Dirty=0,CoW=1), which is

simply

(quoted diff) +1 -0
+	 * read-only to the CPU. When shadow stack is enabled, a RET

would

(quoted diff) +1 -0
+	 * normally pop the shadow stack by reading it with a "shadow

stack

(quoted diff) +1 -0
+	 * read" access. However, in the COW case the shadow stack

memory does

(quoted diff) +1 -0
+	 * not have shadow stack permissions, it is read-only. So it

will

arch/x86/mm/fault.c +3 -0
+	 * generate a fault.
+	 *
+	 * For conventionally writable pages, a read can be serviced

with a

(quoted diff) +1 -0
+	 * read only PTE, and COW would not have to happen. But for

shadow

(quoted diff) +1 -0
+	 * stack, there isn't the concept of read-only shadow stack

memory.

(quoted diff) +1 -0
+	 * If it is shadow stack permissioned, it can be modified via
Quoted 1 line

CALL and

Ditto.

Quoted 8 lines
(quoted diff) +1 -0
+	 * RET instructions. So COW needs to happen before any memory

can be

arch/x86/mm/fault.c +3 -0
+	 * mapped with shadow stack permissions.
+	 *
+	 * Shadow stack accesses (read or write) need to be serviced

with

(quoted diff) +1 -0
+	 * shadow stack permissioned memory, so in the case of a shadow

stack

Is this some new formulation I haven't heard about yet?

Quoted 1 line

"Permissioned <something>"?

It looks like it's not an official dictionary word, but I've seen it from time to time:
https://en.wiktionary.org/wiki/permissioned

Quoted 17 lines
Quoted 15 lines
(quoted diff) +1 -0
+	 * read access, treat it as a WRITE fault so both COW will

happen and

(quoted diff) +1 -0
+	 * the write fault path will tickle maybe_mkwrite() and map the

memory

arch/x86/mm/fault.c +4 -0
+	 * shadow stack.
+	 */
+	if (error_code & X86_PF_SHSTK)
+		flags |= FAULT_FLAG_WRITE;
 	if (error_code & X86_PF_WRITE)
 		flags |= FAULT_FLAG_WRITE;
 	if (error_code & X86_PF_INSTR)
Signature · 1 line
2.17.1
#61 lore raw

PATCH v4 17/39 x86/mm: Update maybe_mkwrite() for shadow stack

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When serving a page fault, maybe_mkwrite() makes a PTE writable if there is a write access to it, and its vma has VM_WRITE. Shadow stack accesses to shadow stack vma's are also treated as write accesses by the fault handler. This is because setting shadow stack memory makes it writable via some instructions, so COW has to happen even for shadow stack reads.

So maybe_mkwrite() should continue to set VM_WRITE vma's as normally writable, but also set VM_WRITE|VM_SHADOW_STACK vma's as shadow stack.

Do this by adding a pte_mkwrite_shstk() and a cross-arch stub. Check for VM_SHADOW_STACK in maybe_mkwrite() and call pte_mkwrite_shstk() accordingly.

Apply the same changes to maybe_pmd_mkwrite().

---

v3:
- Remove unneeded define for maybe_mkwrite (Peterz)
- Switch to cleaner version of maybe_mkwrite() (Peterz)

v2:
- Change to handle shadow stacks that are VM_WRITE|VM_SHADOW_STACK
- Ditch arch specific maybe_mkwrite(), and make the code generic
- Move do_anonymous_page() to next patch (Kirill)

Yu-cheng v29:
- Remove likely()'s.

 arch/x86/include/asm/pgtable.h |  2 ++
 include/linux/mm.h             | 13 ++++++++++---
 include/linux/pgtable.h        | 14 ++++++++++++++
 mm/huge_memory.c               | 10 +++++++---
 4 files changed, 33 insertions(+), 6 deletions(-)
arch/x86/include/asm/pgtable.h +2 -0
index 4a149cec0c07..e4530b39f378 100644
@@ -420,6 +420,7 @@ static inline pte_t pte_mkdirty(pte_t pte)
 	return pte_set_flags(pte, dirty | _PAGE_SOFT_DIRTY);
 }
 
+#define pte_mkwrite_shstk pte_mkwrite_shstk
 static inline pte_t pte_mkwrite_shstk(pte_t pte)
 {
 	/* pte_clear_cow() also sets Dirty=1 */
@@ -556,6 +557,7 @@ static inline pmd_t pmd_mkdirty(pmd_t pmd)
 	return pmd_set_flags(pmd, dirty | _PAGE_SOFT_DIRTY);
 }
 
+#define pmd_mkwrite_shstk pmd_mkwrite_shstk
 static inline pmd_t pmd_mkwrite_shstk(pmd_t pmd)
 {
 	return pmd_clear_cow(pmd);
include/linux/mm.h +10 -3
index b982c2749e7b..f10797a1b236 100644
@@ -1004,12 +1004,19 @@ void free_compound_page(struct page *page);
  * servicing faults for write access.  In the normal case, do always want
  * pte_mkwrite.  But get_user_pages can cause write faults for mappings
  * that do not have writing enabled, when used by access_process_vm.
+ *
+ * If a vma is shadow stack (a type of writable memory), mark the pte shadow
+ * stack.
  */
 static inline pte_t maybe_mkwrite(pte_t pte, struct vm_area_struct *vma)
 {
-	if (likely(vma->vm_flags & VM_WRITE))
-		pte = pte_mkwrite(pte);
-	return pte;
+	if (!(vma->vm_flags & VM_WRITE))
+		return pte;
+
+	if (vma->vm_flags & VM_SHADOW_STACK)
+		return pte_mkwrite_shstk(pte);
+
+	return pte_mkwrite(pte);
 }
 
 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page);
include/linux/pgtable.h +14 -0
index 70e2a7e06a76..d8096578610a 100644
@@ -524,6 +524,13 @@ static inline pte_t pte_sw_mkyoung(pte_t pte)
 #define pte_mk_savedwrite pte_mkwrite
 #endif
 
+#ifndef pte_mkwrite_shstk
+static inline pte_t pte_mkwrite_shstk(pte_t pte)
+{
+	return pte;
+}
+#endif
+
 #ifndef pte_clear_savedwrite
 #define pte_clear_savedwrite pte_wrprotect
 #endif
@@ -532,6 +539,13 @@ static inline pte_t pte_sw_mkyoung(pte_t pte)
 #define pmd_savedwrite pmd_write
 #endif
 
+#ifndef pmd_mkwrite_shstk
+static inline pmd_t pmd_mkwrite_shstk(pmd_t pmd)
+{
+	return pmd;
+}
+#endif
+
 #ifndef pmd_mk_savedwrite
 #define pmd_mk_savedwrite pmd_mkwrite
 #endif
mm/huge_memory.c +7 -3
index 811d19b5c4f6..60451e588955 100644
@@ -553,9 +553,13 @@ __setup("transparent_hugepage=", setup_transparent_hugepage);
 
 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
 {
-	if (likely(vma->vm_flags & VM_WRITE))
-		pmd = pmd_mkwrite(pmd);
-	return pmd;
+	if (!(vma->vm_flags & VM_WRITE))
+		return pmd;
+
+	if (vma->vm_flags & VM_SHADOW_STACK)
+		return pmd_mkwrite_shstk(pmd);
+
+	return pmd_mkwrite(pmd);
 }
 
 #ifdef CONFIG_MEMCG
Signature · 1 line
2.17.1
Reviewed-by on v4 17/39
#62 lore raw

Re: [PATCH v4 17/39] x86/mm: Update maybe_mkwrite() for shadow stack

Quoted 15 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When serving a page fault, maybe_mkwrite() makes a PTE writable if there is a write access to it, and its vma has VM_WRITE. Shadow stack accesses to shadow stack vma's are also treated as write accesses by the fault handler. This is because setting shadow stack memory makes it writable via some instructions, so COW has to happen even for shadow stack reads.

So maybe_mkwrite() should continue to set VM_WRITE vma's as normally writable, but also set VM_WRITE|VM_SHADOW_STACK vma's as shadow stack.

Do this by adding a pte_mkwrite_shstk() and a cross-arch stub. Check for VM_SHADOW_STACK in maybe_mkwrite() and call pte_mkwrite_shstk() accordingly.

Quoted 5 lines

Apply the same changes to maybe_pmd_mkwrite().

Signature · 1 line
Kees Cook
#63 lore raw

PATCH v4 18/39 mm: Fixup places that call pte_mkwrite() directly

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

With the introduction of shadow stack memory there are two ways a pte can be writable: regular writable memory and shadow stack memory.

In past patches, maybe_mkwrite() has been updated to apply pte_mkwrite() or pte_mkwrite_shstk() depending on the VMA flag. This covers most cases where a PTE is made writable. However, there are places where pte_mkwrite() is called directly and the logic should now also create a shadow stack PTE in the case of a shadow stack VMA.

- do_anonymous_page() and migrate_vma_insert_page() check VM_WRITE directly and call pte_mkwrite(). Teach it about pte_mkwrite_shstk()

- When userfaultfd is creating a PTE after userspace handles the fault it calls pte_mkwrite() directly. Teach it about pte_mkwrite_shstk()

To make the code cleaner, introduce is_shstk_write() which simplifies checking for VM_WRITE | VM_SHADOW_STACK together.

In other cases where pte_mkwrite() is called directly, the VMA will not be VM_SHADOW_STACK, and so shadow stack memory should not be created.
- In the case of pte_savedwrite(), shadow stack VMA's are excluded.
- In the case of the "dirty_accountable" optimization in mprotect(), shadow stack VMA's won't be VM_SHARED, so it is not nessary.

---

v3:
- Restore do_anonymous_page() that accidetally moved commits (Kirill)
- Open code maybe_mkwrite() cases from v2, so the behavior doesn't change to mark that non-writable PTEs dirty. (Nadav)

v2:
- Updated commit log with comment's from Dave Hansen
- Dave also suggested (I understood) to maybe tweak vm_get_page_prot() to avoid having to call maybe_mkwrite(). After playing around with this I opted to *not* do this. Shadow stack memory memory is effectively writable, so having the default permissions be writable ended up mapping the zero page as writable and other surprises. So creating shadow stack memory needs to be done with manual logic like pte_mkwrite().
- Drop change in change_pte_range() because it couldn't actually trigger for shadow stack VMAs.
- Clarify reasoning for skipped cases of pte_mkwrite().

Yu-cheng v25:
- Apply same changes to do_huge_pmd_numa_page() as to do_numa_page().

 arch/x86/include/asm/pgtable.h |  3 +++
 arch/x86/mm/pgtable.c          |  6 ++++++
 include/linux/pgtable.h        |  7 +++++++
 mm/memory.c                    |  5 ++++-
 mm/migrate_device.c            |  4 +++-
 mm/userfaultfd.c               | 10 +++++++---
 6 files changed, 30 insertions(+), 5 deletions(-)
arch/x86/include/asm/pgtable.h +3 -0
index e4530b39f378..a89dfa9174ae 100644
@@ -918,6 +918,9 @@ static inline pgd_t pti_set_user_pgtbl(pgd_t *pgdp, pgd_t pgd)
 }
 #endif  /* CONFIG_PAGE_TABLE_ISOLATION */
 
+#define is_shstk_write is_shstk_write
+extern bool is_shstk_write(unsigned long vm_flags);
+
 #endif	/* __ASSEMBLY__ */
 
 
arch/x86/mm/pgtable.c +6 -0
index 8525f2876fb4..f0e536bea3ca 100644
@@ -876,3 +876,9 @@ int pmd_free_pte_page(pmd_t *pmd, unsigned long addr)
 
 #endif /* CONFIG_X86_64 */
 #endif	/* CONFIG_HAVE_ARCH_HUGE_VMAP */
+
+bool is_shstk_write(unsigned long vm_flags)
+{
+	return (vm_flags & (VM_SHADOW_STACK | VM_WRITE)) ==
+	       (VM_SHADOW_STACK | VM_WRITE);
+}
include/linux/pgtable.h +7 -0
index d8096578610a..b4a9d9936463 100644
@@ -1586,6 +1586,13 @@ static inline bool arch_has_pfn_modify_check(void)
 }
 #endif /* !_HAVE_ARCH_PFN_MODIFY_ALLOWED */
 
+#ifndef is_shstk_write
+static inline bool is_shstk_write(unsigned long vm_flags)
+{
+	return false;
+}
+#endif
+
 /*
  * Architecture PAGE_KERNEL_* fallbacks
  *
mm/memory.c +4 -1
index 8a6d5c823f91..c02b6421241d 100644
@@ -4128,7 +4128,10 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
 
 	entry = mk_pte(page, vma->vm_page_prot);
 	entry = pte_sw_mkyoung(entry);
-	if (vma->vm_flags & VM_WRITE)
+
+	if (is_shstk_write(vma->vm_flags))
+		entry = pte_mkwrite_shstk(pte_mkdirty(entry));
+	else if (vma->vm_flags & VM_WRITE)
 		entry = pte_mkwrite(pte_mkdirty(entry));
 
 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
mm/migrate_device.c +3 -1
index 721b2365dbca..53d417683e01 100644
@@ -645,7 +645,9 @@ static void migrate_vma_insert_page(struct migrate_vma *migrate,
 			goto abort;
 		}
 		entry = mk_pte(page, vma->vm_page_prot);
-		if (vma->vm_flags & VM_WRITE)
+		if (is_shstk_write(vma->vm_flags))
+			entry = pte_mkwrite_shstk(pte_mkdirty(entry));
+		else if (vma->vm_flags & VM_WRITE)
 			entry = pte_mkwrite(pte_mkdirty(entry));
 	}
 
mm/userfaultfd.c +7 -3
index 3a8ff47943d5..1f6d102d069b 100644
@@ -63,6 +63,7 @@ int mfill_atomic_install_pte(struct mm_struct *dst_mm, pmd_t *dst_pmd,
 	int ret;
 	pte_t _dst_pte, *dst_pte;
 	bool writable = dst_vma->vm_flags & VM_WRITE;
+	bool shstk = dst_vma->vm_flags & VM_SHADOW_STACK;
 	bool vm_shared = dst_vma->vm_flags & VM_SHARED;
 	bool page_in_cache = page_mapping(page);
 	spinlock_t *ptl;
@@ -83,9 +84,12 @@ int mfill_atomic_install_pte(struct mm_struct *dst_mm, pmd_t *dst_pmd,
 		writable = false;
 	}
 
-	if (writable)
-		_dst_pte = pte_mkwrite(_dst_pte);
-	else
+	if (writable) {
+		if (shstk)
+			_dst_pte = pte_mkwrite_shstk(_dst_pte);
+		else
+			_dst_pte = pte_mkwrite(_dst_pte);
+	} else
 		/*
 		 * We need this to make sure write bit removed; as mk_pte()
 		 * could return a pte with write bit set.
Signature · 1 line
2.17.1
Reviewed-by on v4 18/39
#64 lore raw

Re: [PATCH v4 18/39] mm: Fixup places that call pte_mkwrite() directly

Quoted 31 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

With the introduction of shadow stack memory there are two ways a pte can be writable: regular writable memory and shadow stack memory.

In past patches, maybe_mkwrite() has been updated to apply pte_mkwrite() or pte_mkwrite_shstk() depending on the VMA flag. This covers most cases where a PTE is made writable. However, there are places where pte_mkwrite() is called directly and the logic should now also create a shadow stack PTE in the case of a shadow stack VMA.

- do_anonymous_page() and migrate_vma_insert_page() check VM_WRITE directly and call pte_mkwrite(). Teach it about pte_mkwrite_shstk()

- When userfaultfd is creating a PTE after userspace handles the fault it calls pte_mkwrite() directly. Teach it about pte_mkwrite_shstk()

To make the code cleaner, introduce is_shstk_write() which simplifies checking for VM_WRITE | VM_SHADOW_STACK together.

In other cases where pte_mkwrite() is called directly, the VMA will not be VM_SHADOW_STACK, and so shadow stack memory should not be created.
- In the case of pte_savedwrite(), shadow stack VMA's are excluded.
- In the case of the "dirty_accountable" optimization in mprotect(), shadow stack VMA's won't be VM_SHARED, so it is not nessary.

Quoted 3 lines
Signature · 1 line
Kees Cook
#65 lore raw

PATCH v4 19/39 mm: Add guard pages around a shadow stack.

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

The architecture of shadow stack constrains the ability of userspace to move the shadow stack pointer (SSP) in order to prevent corrupting or switching to other shadow stacks. The RSTORSSP can move the spp to different shadow stacks, but it requires a specially placed token in order to do this. However, the architecture does not prevent incrementing the stack pointer to wander onto an adjacent shadow stack. To prevent this in software, enforce guard pages at the beginning of shadow stack vmas, such that there will always be a gap between adjacent shadow stacks.

Make the gap big enough so that no userspace SSP changing operations (besides RSTORSSP), can move the SSP from one stack to the next. The SSP can increment or decrement by CALL, RET and INCSSP. CALL and RET can move the SSP by a maximum of 8 bytes, at which point the shadow stack would be accessed.

The INCSSP instruction can also increment the shadow stack pointer. It is the shadow stack analog of an instruction like:

	addq    $0x80, %rsp

However, there is one important difference between an ADD on %rsp and INCSSP. In addition to modifying SSP, INCSSP also reads from the memory of the first and last elements that were "popped". It can be thought of as acting like this:

READ_ONCE(ssp); // read+discard top element on stack
ssp += nr_to_pop * 8; // move the shadow stack
READ_ONCE(ssp-8); // read+discard last popped stack element

The maximum distance INCSSP can move the SSP is 2040 bytes, before it would read the memory. Therefore a single page gap will be enough to prevent any operation from shifting the SSP to an adjacent stack, since it would have to land in the gap at least once, causing a fault.

This could be accomplished by using VM_GROWSDOWN, but this has a downside. The behavior would allow shadow stack's to grow, which is unneeded and adds a strange difference to how most regular stacks work.

---

v4:
- Drop references to 32 bit instructions
- Switch to generic code to drop __weak (Peterz)

v2:
- Use __weak instead of #ifdef (Dave Hansen)
- Only have start gap on shadow stack (Andy Luto)
- Create stack_guard_start_gap() to not duplicate code in an arch version of vm_start_gap() (Dave Hansen)
- Improve commit log partly with verbiage from (Dave Hansen)

Yu-cheng v25:
- Move SHADOW_STACK_GUARD_GAP to arch/x86/mm/mmap.c.

Yu-cheng v24:
- Instead changing vm_*_gap(), create x86-specific versions.

 include/linux/mm.h | 31 ++++++++++++++++++++++++++-----
 1 file changed, 26 insertions(+), 5 deletions(-)
include/linux/mm.h +26 -5
index f10797a1b236..e0991d2fc5a8 100644
@@ -2821,15 +2821,36 @@ struct vm_area_struct *vma_lookup(struct mm_struct *mm, unsigned long addr)
 	return mtree_load(&mm->mm_mt, addr);
 }
 
+static inline unsigned long stack_guard_start_gap(struct vm_area_struct *vma)
+{
+	if (vma->vm_flags & VM_GROWSDOWN)
+		return stack_guard_gap;
+
+	/*
+	 * Shadow stack pointer is moved by CALL, RET, and INCSSPQ.
+	 * INCSSPQ moves shadow stack pointer up to 255 * 8 = ~2 KB
+	 * and touches the first and the last element in the range, which
+	 * triggers a page fault if the range is not in a shadow stack.
+	 * Because of this, creating 4-KB guard pages around a shadow
+	 * stack prevents these instructions from going beyond.
+	 *
+	 * Creation of VM_SHADOW_STACK is tightly controlled, so a vma
+	 * can't be both VM_GROWSDOWN and VM_SHADOW_STACK
+	 */
+	if (vma->vm_flags & VM_SHADOW_STACK)
+		return PAGE_SIZE;
+
+	return 0;
+}
+
 static inline unsigned long vm_start_gap(struct vm_area_struct *vma)
 {
+	unsigned long gap = stack_guard_start_gap(vma);
 	unsigned long vm_start = vma->vm_start;
 
-	if (vma->vm_flags & VM_GROWSDOWN) {
-		vm_start -= stack_guard_gap;
-		if (vm_start > vma->vm_start)
-			vm_start = 0;
-	}
+	vm_start -= gap;
+	if (vm_start > vma->vm_start)
+		vm_start = 0;
 	return vm_start;
 }
 
Signature · 1 line
2.17.1
#66 lore raw

PATCH v4 20/39 mm/mmap: Add shadow stack pages to memory accounting

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

Account shadow stack pages to stack memory.

---

v3:
- Remove unneeded VM_SHADOW_STACK check in accountable_mapping() (Kirill)

v2:
- Remove is_shadow_stack_mapping() and just change it to directly bitwise and VM_SHADOW_STACK.

Yu-cheng v26:
- Remove redundant #ifdef CONFIG_MMU.

Yu-cheng v25:
- Remove #ifdef CONFIG_ARCH_HAS_SHADOW_STACK for is_shadow_stack_mapping().

 mm/mmap.c | 2 ++
 1 file changed, 2 insertions(+)
mm/mmap.c +2 -0
index 146388feb72b..7ce04d2d5a10 100644
@@ -3295,6 +3295,8 @@ void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
 		mm->exec_vm += npages;
 	else if (is_stack_mapping(flags))
 		mm->stack_vm += npages;
+	else if (flags & VM_SHADOW_STACK)
+		mm->stack_vm += npages;
 	else if (is_data_mapping(flags))
 		mm->data_vm += npages;
 }
Signature · 1 line
2.17.1
Reviewed-by on v4 20/39
#67 lore raw

Re: [PATCH v4 20/39] mm/mmap: Add shadow stack pages to memory accounting

Quoted 7 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

Quoted 5 lines

Account shadow stack pages to stack memory.

Signature · 1 line
Kees Cook
#68 lore raw

PATCH v4 21/39 mm/mprotect: Exclude shadow stack from preserve_write

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

In change_pte_range(), when a PTE is changed for prot_numa, _PAGE_RW is preserved to avoid the additional write fault after the NUMA hinting fault. However, pte_write() now includes both normal writable and shadow stack (Write=0, Dirty=1) PTEs, but the latter does not have _PAGE_RW and has no need to preserve it.

Exclude shadow stack from preserve_write test, and apply the same change to change_huge_pmd().

---

v4:
- Add "why" to comments in code (Peterz)

Yu-cheng v25:
- Move is_shadow_stack_mapping() to a separate line.

Yu-cheng v24:
- Change arch_shadow_stack_mapping() to is_shadow_stack_mapping().

 mm/huge_memory.c | 8 ++++++++
 mm/mprotect.c    | 8 ++++++++
 2 files changed, 16 insertions(+)
mm/huge_memory.c +8 -0
index 60451e588955..b6294c4ad471 100644
@@ -1803,6 +1803,14 @@ int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
 		return 0;
 
 	preserve_write = prot_numa && pmd_write(*pmd);
+
+	/*
+	 * Preserve only normal writable huge PMD, but not shadow
+	 * stack (RW=0, Dirty=1), so the restoring code doesn't
+	 * make the shadow stack memory conventionally writable.
+	 */
+	if (vma->vm_flags & VM_SHADOW_STACK)
+		preserve_write = false;
 	ret = 1;
 
 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
mm/mprotect.c +8 -0
index de7351631e21..026347f1f1ee 100644
@@ -115,6 +115,14 @@ static unsigned long change_pte_range(struct mmu_gather *tlb,
 			pte_t ptent;
 			bool preserve_write = prot_numa && pte_write(oldpte);
 
+			/*
+			 * Preserve only normal writable PTE, but not shadow
+			 * stack (RW=0, Dirty=1), so the restoring code doesn't
+			 * make the shadow stack memory conventionally writable.
+			 */
+			if (vma->vm_flags & VM_SHADOW_STACK)
+				preserve_write = false;
+
 			/*
 			 * Avoid trapping faults against the zero or KSM
 			 * pages. See similar comment in change_huge_pmd.
Signature · 1 line
2.17.1
Reviewed-by on v4 21/39
#69 lore raw

Re: [PATCH v4 21/39] mm/mprotect: Exclude shadow stack from preserve_write

Quoted 13 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

In change_pte_range(), when a PTE is changed for prot_numa, _PAGE_RW is preserved to avoid the additional write fault after the NUMA hinting fault. However, pte_write() now includes both normal writable and shadow stack (Write=0, Dirty=1) PTEs, but the latter does not have _PAGE_RW and has no need to preserve it.

Quoted 6 lines

Exclude shadow stack from preserve_write test, and apply the same change to change_huge_pmd().

Signature · 1 line
Kees Cook
#70 lore raw

PATCH v4 22/39 mm: Re-introduce vm_flags to do_mmap()

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

There was no more caller passing vm_flags to do_mmap(), and vm_flags was removed from the function's input by:

commit 45e55300f114 ("mm: remove unnecessary wrapper function do_mmap_pgoff()").

There is a new user now. Shadow stack allocation passes VM_SHADOW_STACK to do_mmap(). Thus, re-introduce vm_flags to do_mmap().

---
 fs/aio.c           |  2 +-
 include/linux/mm.h |  3 ++-
 ipc/shm.c          |  2 +-
 mm/mmap.c          | 10 +++++-----
 mm/nommu.c         |  4 ++--
 mm/util.c          |  2 +-
 6 files changed, 12 insertions(+), 11 deletions(-)
fs/aio.c +1 -1
index 5b2ff20ad322..66119297125a 100644
@@ -554,7 +554,7 @@ static int aio_setup_ring(struct kioctx *ctx, unsigned int nr_events)
 
 	ctx->mmap_base = do_mmap(ctx->aio_ring_file, 0, ctx->mmap_size,
 				 PROT_READ | PROT_WRITE,
-				 MAP_SHARED, 0, &unused, NULL);
+				 MAP_SHARED, 0, 0, &unused, NULL);
 	mmap_write_unlock(mm);
 	if (IS_ERR((void *)ctx->mmap_base)) {
 		ctx->mmap_size = 0;
include/linux/mm.h +2 -1
index e0991d2fc5a8..7c10d2a7bbfd 100644
@@ -2731,7 +2731,8 @@ extern unsigned long mmap_region(struct file *file, unsigned long addr,
 	struct list_head *uf);
 extern unsigned long do_mmap(struct file *file, unsigned long addr,
 	unsigned long len, unsigned long prot, unsigned long flags,
-	unsigned long pgoff, unsigned long *populate, struct list_head *uf);
+	vm_flags_t vm_flags, unsigned long pgoff, unsigned long *populate,
+	struct list_head *uf);
 extern int do_mas_munmap(struct ma_state *mas, struct mm_struct *mm,
 			 unsigned long start, size_t len, struct list_head *uf,
 			 bool downgrade);
ipc/shm.c +1 -1
index bd2fcc4d454e..1c5476bfec8b 100644
@@ -1662,7 +1662,7 @@ long do_shmat(int shmid, char __user *shmaddr, int shmflg,
 			goto invalid;
 	}
 
-	addr = do_mmap(file, addr, size, prot, flags, 0, &populate, NULL);
+	addr = do_mmap(file, addr, size, prot, flags, 0, 0, &populate, NULL);
 	*raddr = addr;
 	err = 0;
 	if (IS_ERR_VALUE(addr))
mm/mmap.c +5 -5
index 7ce04d2d5a10..a3ce13be0767 100644
@@ -1239,11 +1239,11 @@ static inline bool file_mmap_ok(struct file *file, struct inode *inode,
  */
 unsigned long do_mmap(struct file *file, unsigned long addr,
 			unsigned long len, unsigned long prot,
-			unsigned long flags, unsigned long pgoff,
-			unsigned long *populate, struct list_head *uf)
+			unsigned long flags, vm_flags_t vm_flags,
+			unsigned long pgoff, unsigned long *populate,
+			struct list_head *uf)
 {
 	struct mm_struct *mm = current->mm;
-	vm_flags_t vm_flags;
 	int pkey = 0;
 
 	validate_mm(mm);
@@ -1304,7 +1304,7 @@ unsigned long do_mmap(struct file *file, unsigned long addr,
 	 * to. we assume access permissions have been handled by the open
 	 * of the memory object, so we don't do any here.
 	 */
-	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
+	vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
 
 	if (flags & MAP_LOCKED)
@@ -2877,7 +2877,7 @@ SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
 
 	file = get_file(vma->vm_file);
 	ret = do_mmap(vma->vm_file, start, size,
-			prot, flags, pgoff, &populate, NULL);
+			prot, flags, 0, pgoff, &populate, NULL);
 	fput(file);
 out:
 	mmap_write_unlock(mm);
mm/nommu.c +2 -2
index 214c70e1d059..20ff1ec89091 100644
@@ -1042,6 +1042,7 @@ unsigned long do_mmap(struct file *file,
 			unsigned long len,
 			unsigned long prot,
 			unsigned long flags,
+			vm_flags_t vm_flags,
 			unsigned long pgoff,
 			unsigned long *populate,
 			struct list_head *uf)
@@ -1049,7 +1050,6 @@ unsigned long do_mmap(struct file *file,
 	struct vm_area_struct *vma;
 	struct vm_region *region;
 	struct rb_node *rb;
-	vm_flags_t vm_flags;
 	unsigned long capabilities, result;
 	int ret;
 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
@@ -1069,7 +1069,7 @@ unsigned long do_mmap(struct file *file,
 
 	/* we've determined that we can make the mapping, now translate what we
 	 * now know into VMA flags */
-	vm_flags = determine_vm_flags(file, prot, flags, capabilities);
+	vm_flags |= determine_vm_flags(file, prot, flags, capabilities);
 
 
 	/* we're going to need to record the mapping */
mm/util.c +1 -1
index 12984e76767e..aefe4fae7ecf 100644
@@ -517,7 +517,7 @@ unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
 	if (!ret) {
 		if (mmap_write_lock_killable(mm))
 			return -EINTR;
-		ret = do_mmap(file, addr, len, prot, flag, pgoff, &populate,
+		ret = do_mmap(file, addr, len, prot, flag, 0, pgoff, &populate,
 			      &uf);
 		mmap_write_unlock(mm);
 		userfaultfd_unmap_complete(mm, &uf);
Signature · 1 line
2.17.1
#71 lore raw

PATCH v4 23/39 mm: Don't allow write GUPs to shadow stack memory

In reply to Rick Edgecombe

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

Shadow stack memory is writable only in very specific, controlled ways. However, since it is writable, the kernel treats it as such. As a result there remain many ways for userspace to trigger the kernel to write to shadow stack's via get_user_pages(, FOLL_WRITE) operations. To make this a little less exposed, block writable GUPs for shadow stack VMAs.

Still allow FOLL_FORCE to write through shadow stack protections, as it does for read-only protections.

---

v3:
- Add comment in __pte_access_permitted() (Dave)
- Remove unneeded shadow stack specific check in
__pte_access_permitted() (Jann)

 arch/x86/include/asm/pgtable.h | 5 +++++
 mm/gup.c                       | 2 +-
 2 files changed, 6 insertions(+), 1 deletion(-)
arch/x86/include/asm/pgtable.h +5 -0
index a89dfa9174ae..945d58681a87 100644
@@ -1636,6 +1636,11 @@ static inline bool __pte_access_permitted(unsigned long pteval, bool write)
 {
 	unsigned long need_pte_bits = _PAGE_PRESENT|_PAGE_USER;
 
+	/*
+	 * Write=0,Dirty=1 PTEs are shadow stack, which the kernel
+	 * shouldn't generally allow access to, but since they
+	 * are already Write=0, the below logic covers both cases.
+	 */
 	if (write)
 		need_pte_bits |= _PAGE_RW;
 
mm/gup.c +1 -1
index cdff87343884..75e8d3853ff3 100644
@@ -1062,7 +1062,7 @@ static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
 		return -EFAULT;
 
 	if (write) {
-		if (!(vm_flags & VM_WRITE)) {
+		if (!(vm_flags & VM_WRITE) || (vm_flags & VM_SHADOW_STACK)) {
 			if (!(gup_flags & FOLL_FORCE))
 				return -EFAULT;
 			/*
Signature · 1 line
2.17.1
Reviewed-by on v4 23/39
#72 lore raw

Re: [PATCH v4 23/39] mm: Don't allow write GUPs to shadow stack memory

Quoted 11 lines · Rick Edgecombe

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

Shadow stack memory is writable only in very specific, controlled ways. However, since it is writable, the kernel treats it as such. As a result there remain many ways for userspace to trigger the kernel to write to shadow stack's via get_user_pages(, FOLL_WRITE) operations. To make this a little less exposed, block writable GUPs for shadow stack VMAs.

Quoted 6 lines

Still allow FOLL_FORCE to write through shadow stack protections, as it does for read-only protections.

Signature · 1 line
Kees Cook
#73 lore raw

PATCH v4 24/39 mm: Warn on shadow stack memory in wrong vma

In reply to Rick Edgecombe

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

One sharp edge is that PTEs that are both Write=0 and Dirty=1 are treated as shadow by the CPU, but this combination used to be created by the kernel on x86. Previous patches have changed the kernel to now avoid creating these PTEs unless they are for shadow stack memory. In case any missed corners of the kernel are still creating PTEs like this for non-shadow stack memory, and to catch any re-introductions of the logic, warn if any shadow stack PTEs (Write=0, Dirty=1) are found in non-shadow stack VMAs when they are being zapped. This won't catch transient cases but should have decent coverage. It will be compiled out when shadow stack is not configured.

In order to check if a pte is shadow stack in core mm code, add default implmentations for pte_shstk() and pmd_shstk().

---

v3:
- New patch

 arch/x86/include/asm/pgtable.h |  2 ++
 include/linux/pgtable.h        | 14 ++++++++++++++
 mm/huge_memory.c               |  2 ++
 mm/memory.c                    |  2 ++
 4 files changed, 20 insertions(+)
arch/x86/include/asm/pgtable.h +2 -0
index 945d58681a87..519a266ace10 100644
@@ -129,6 +129,7 @@ static inline bool pte_dirty(pte_t pte)
 	return pte_flags(pte) & _PAGE_DIRTY_BITS;
 }
 
+#define pte_shstk pte_shstk
 static inline bool pte_shstk(pte_t pte)
 {
 	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
@@ -147,6 +148,7 @@ static inline bool pmd_dirty(pmd_t pmd)
 	return pmd_flags(pmd) & _PAGE_DIRTY_BITS;
 }
 
+#define pmd_shstk pmd_shstk
 static inline bool pmd_shstk(pmd_t pmd)
 {
 	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
include/linux/pgtable.h +14 -0
index b4a9d9936463..34aa57941d57 100644
@@ -531,6 +531,20 @@ static inline pte_t pte_mkwrite_shstk(pte_t pte)
 }
 #endif
 
+#ifndef pte_shstk
+static inline bool pte_shstk(pte_t pte)
+{
+	return false;
+}
+#endif
+
+#ifndef pmd_shstk
+static inline bool pmd_shstk(pmd_t pte)
+{
+	return false;
+}
+#endif
+
 #ifndef pte_clear_savedwrite
 #define pte_clear_savedwrite pte_wrprotect
 #endif
mm/huge_memory.c +2 -0
index b6294c4ad471..64d81aa97a61 100644
@@ -1656,6 +1656,8 @@ int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
 	 */
 	orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd,
 						tlb->fullmm);
+	VM_WARN_ON_ONCE(!(vma->vm_flags & VM_SHADOW_STACK) &&
+			pmd_shstk(orig_pmd));
 	tlb_remove_pmd_tlb_entry(tlb, pmd, addr);
 	if (vma_is_special_huge(vma)) {
 		if (arch_needs_pgtable_deposit())
mm/memory.c +2 -0
index c02b6421241d..bae62b2d6696 100644
@@ -1437,6 +1437,8 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb,
 				continue;
 			ptent = ptep_get_and_clear_full(mm, addr, pte,
 							tlb->fullmm);
+			VM_WARN_ON_ONCE(!(vma->vm_flags & VM_SHADOW_STACK) &&
+					pte_shstk(ptent));
 			tlb_remove_tlb_entry(tlb, pte, addr);
 			zap_install_uffd_wp_if_needed(vma, addr, pte, details,
 						      ptent);
Signature · 1 line
2.17.1
Reviewed-by on v4 24/39
#74 lore raw

Re: [PATCH v4 24/39] mm: Warn on shadow stack memory in wrong vma

Quoted 16 lines · Rick Edgecombe

The x86 Control-flow Enforcement Technology (CET) feature includes a new type of memory called shadow stack. This shadow stack memory has some unusual properties, which requires some core mm changes to function properly.

One sharp edge is that PTEs that are both Write=0 and Dirty=1 are treated as shadow by the CPU, but this combination used to be created by the kernel on x86. Previous patches have changed the kernel to now avoid creating these PTEs unless they are for shadow stack memory. In case any missed corners of the kernel are still creating PTEs like this for non-shadow stack memory, and to catch any re-introductions of the logic, warn if any shadow stack PTEs (Write=0, Dirty=1) are found in non-shadow stack VMAs when they are being zapped. This won't catch transient cases but should have decent coverage. It will be compiled out when shadow stack is not configured.

Quoted 6 lines

In order to check if a pte is shadow stack in core mm code, add default implmentations for pte_shstk() and pmd_shstk().

Signature · 1 line
Kees Cook
#75 lore raw

PATCH v4 25/39 x86: Introduce userspace API for shadow stack

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add three new arch_prctl() handles:

- ARCH_SHSTK_ENABLE/DISABLE enables or disables the specified feature. Returns 0 on success or an error.

- ARCH_SHSTK_LOCK prevents future disabling or enabling of the specified feature. Returns 0 on success or an error

The features are handled per-thread and inherited over fork(2)/clone(2), but reset on exec().

This is preparation patch. It does not implement any features.

---

v4:
- Remove references to CET and replace with shadow stack (Peterz)

v3:
- Move shstk.c Makefile changes earlier (Kees)
- Add #ifdef around features_locked and features (Kees)
- Encapsulate features reset earlier in reset_thread_features() so features and features_locked are not referenced in code that would be compiled !CONFIG_X86_USER_SHADOW_STACK. (Kees)
- Fix typo in commit log (Kees)
- Switch arch_prctl() numbers to avoid conflict with LAM

v2:
- Only allow one enable/disable per call (tglx)
- Return error code like a normal arch_prctl() (Alexander Potapenko)
- Make CET only (tglx)

 arch/x86/include/asm/processor.h  |  5 ++++
 arch/x86/include/asm/shstk.h      | 21 +++++++++++++++
 arch/x86/include/uapi/asm/prctl.h |  6 +++++
 arch/x86/kernel/Makefile          |  2 ++
 arch/x86/kernel/process_64.c      |  6 +++++
 arch/x86/kernel/shstk.c           | 44 +++++++++++++++++++++++++++++++
 6 files changed, 84 insertions(+)
 create mode 100644 arch/x86/include/asm/shstk.h
 create mode 100644 arch/x86/kernel/shstk.c
arch/x86/include/asm/processor.h +5 -0
index 4e35c66edeb7..ff1c0b1aca8c 100644
@@ -475,6 +475,11 @@ struct thread_struct {
 	 */
 	u32			pkru;
 
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+	unsigned long		features;
+	unsigned long		features_locked;
+#endif
+
 	/* Floating point and extended processor state */
 	struct fpu		fpu;
 	/*
arch/x86/include/asm/shstk.h new file +21 -0
new file mode 100644
index 000000000000..58f9ee675be0
@@ -0,0 +1,21 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _ASM_X86_SHSTK_H
+#define _ASM_X86_SHSTK_H
+
+#ifndef __ASSEMBLY__
+#include <linux/types.h>
+
+struct task_struct;
+
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+long shstk_prctl(struct task_struct *task, int option, unsigned long features);
+void reset_thread_features(void);
+#else
+static inline long shstk_prctl(struct task_struct *task, int option,
+			     unsigned long features) { return -EINVAL; }
+static inline void reset_thread_features(void) {}
+#endif /* CONFIG_X86_USER_SHADOW_STACK */
+
+#endif /* __ASSEMBLY__ */
+
+#endif /* _ASM_X86_SHSTK_H */
arch/x86/include/uapi/asm/prctl.h +6 -0
index eb290d89cb32..8b427aea2345 100644
@@ -20,9 +20,15 @@
 #define ARCH_MAP_VDSO_32		0x2002
 #define ARCH_MAP_VDSO_64		0x2003
 
+/* Don't use 0x3001-0x3004 because of old glibcs */
+
 #define ARCH_GET_UNTAG_MASK		0x4001
 #define ARCH_ENABLE_TAGGED_ADDR		0x4002
 #define ARCH_GET_MAX_TAG_BITS		0x4003
 #define ARCH_FORCE_TAGGED_SVA		0x4004
 
+#define ARCH_SHSTK_ENABLE		0x5001
+#define ARCH_SHSTK_DISABLE		0x5002
+#define ARCH_SHSTK_LOCK			0x5003
+
 #endif /* _ASM_X86_PRCTL_H */
arch/x86/kernel/Makefile +2 -0
index 96d51bbc2bd4..2260891609b4 100644
@@ -145,6 +145,8 @@ obj-$(CONFIG_CFI_CLANG)			+= cfi.o
 
 obj-$(CONFIG_CALL_THUNKS)		+= callthunks.o
 
+obj-$(CONFIG_X86_USER_SHADOW_STACK)	+= shstk.o
+
 ###
 # 64 bit specific files
 ifeq ($(CONFIG_X86_64),y)
arch/x86/kernel/process_64.c +6 -0
index 084ec467dbb1..4ddd7d9209e1 100644
@@ -514,6 +514,8 @@ start_thread_common(struct pt_regs *regs, unsigned long new_ip,
 		load_gs_index(__USER_DS);
 	}
 
+	reset_thread_features();
+
 	loadsegment(fs, 0);
 	loadsegment(es, _ds);
 	loadsegment(ds, _ds);
@@ -916,6 +918,10 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2)
 			return put_user(0, (unsigned long __user *)arg2);
 		else
 			return put_user(LAM_U57_BITS, (unsigned long __user *)arg2);
+	case ARCH_SHSTK_ENABLE:
+	case ARCH_SHSTK_DISABLE:
+	case ARCH_SHSTK_LOCK:
+		return shstk_prctl(task, option, arg2);
 	default:
 		ret = -EINVAL;
 		break;
arch/x86/kernel/shstk.c new file +44 -0

44 lines not on this page · raw message

Signature · 1 line
2.17.1
Reviewed-by on v4 25/39
#76 lore raw

Re: [PATCH v4 25/39] x86: Introduce userspace API for shadow stack

Quoted 10 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add three new arch_prctl() handles:

- ARCH_SHSTK_ENABLE/DISABLE enables or disables the specified feature. Returns 0 on success or an error.

- ARCH_SHSTK_LOCK prevents future disabling or enabling of the specified feature. Returns 0 on success or an error

Quoted 8 lines

The features are handled per-thread and inherited over fork(2)/clone(2), but reset on exec().

This is preparation patch. It does not implement any features.

Signature · 1 line
Kees Cook
#77 lore raw

PATCH v4 26/39 x86/shstk: Add user-mode shadow stack support

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Introduce basic shadow stack enabling/disabling/allocation routines. A task's shadow stack is allocated from memory with VM_SHADOW_STACK flag and has a fixed size of min(RLIMIT_STACK, 4GB).

Keep the task's shadow stack address and size in thread_struct. This will be copied when cloning new threads, but needs to be cleared during exec, so add a function to do this.

Do not support IA32 emulation or x32.

---

v4:
- Just set MSR_IA32_U_CET when disabling shadow stack, since we don't have IBT yet. (Peterz)

v3:
- Use define for set_clr_bits_msrl() (Kees)
- Make some functions static (Kees)
- Change feature_foo() to features_foo() (Kees)
- Centralize shadow stack size rlimit checks (Kees)
- Disable x32 support

v2:
- Get rid of unnessary shstk->base checks
- Don't support IA32 emulation

v1:
- Switch to xsave helpers.
- Expand commit log.

 arch/x86/include/asm/msr.h        |  11 +++
 arch/x86/include/asm/processor.h  |   3 +
 arch/x86/include/asm/shstk.h      |   7 ++
 arch/x86/include/uapi/asm/prctl.h |   3 +
 arch/x86/kernel/shstk.c           | 146 ++++++++++++++++++++++++++++++
 5 files changed, 170 insertions(+)
arch/x86/include/asm/msr.h +11 -0
index 65ec1965cd28..a4b86eb537d6 100644
@@ -310,6 +310,17 @@ void msrs_free(struct msr *msrs);
 int msr_set_bit(u32 msr, u8 bit);
 int msr_clear_bit(u32 msr, u8 bit);
 
+/* Helper that can never get accidentally un-inlined. */
+#define set_clr_bits_msrl(msr, set, clear)	do {	\
+	u64 __val, __new_val;				\
+							\
+	rdmsrl(msr, __val);				\
+	__new_val = (__val & ~(clear)) | (set);		\
+							\
+	if (__new_val != __val)				\
+		wrmsrl(msr, __new_val);			\
+} while (0)
+
 #ifdef CONFIG_SMP
 int rdmsr_on_cpu(unsigned int cpu, u32 msr_no, u32 *l, u32 *h);
 int wrmsr_on_cpu(unsigned int cpu, u32 msr_no, u32 l, u32 h);
arch/x86/include/asm/processor.h +3 -0
index ff1c0b1aca8c..3c257a1a0757 100644
@@ -28,6 +28,7 @@ struct vm86;
 #include <asm/unwind_hints.h>
 #include <asm/vmxfeatures.h>
 #include <asm/vdso/processor.h>
+#include <asm/shstk.h>
 
 #include <linux/personality.h>
 #include <linux/cache.h>
@@ -478,6 +479,8 @@ struct thread_struct {
 #ifdef CONFIG_X86_USER_SHADOW_STACK
 	unsigned long		features;
 	unsigned long		features_locked;
+
+	struct thread_shstk	shstk;
 #endif
 
 	/* Floating point and extended processor state */
arch/x86/include/asm/shstk.h +7 -0
index 58f9ee675be0..f40414a982e8 100644
@@ -8,12 +8,19 @@
 struct task_struct;
 
 #ifdef CONFIG_X86_USER_SHADOW_STACK
+struct thread_shstk {
+	u64	base;
+	u64	size;
+};
+
 long shstk_prctl(struct task_struct *task, int option, unsigned long features);
 void reset_thread_features(void);
+void shstk_free(struct task_struct *p);
 #else
 static inline long shstk_prctl(struct task_struct *task, int option,
 			     unsigned long features) { return -EINVAL; }
 static inline void reset_thread_features(void) {}
+static inline void shstk_free(struct task_struct *p) {}
 #endif /* CONFIG_X86_USER_SHADOW_STACK */
 
 #endif /* __ASSEMBLY__ */
arch/x86/include/uapi/asm/prctl.h +3 -0
index 8b427aea2345..fc97ca7c4884 100644
@@ -31,4 +31,7 @@
 #define ARCH_SHSTK_DISABLE		0x5002
 #define ARCH_SHSTK_LOCK			0x5003
 
+/* ARCH_SHSTK_ features bits */
+#define ARCH_SHSTK_SHSTK		(1ULL <<  0)
+
 #endif /* _ASM_X86_PRCTL_H */
arch/x86/kernel/shstk.c +146 -0

160 lines not on this page · raw message

Signature · 1 line
2.17.1
Reviewed-by on v4 26/39
#78 lore raw

Re: [PATCH v4 26/39] x86/shstk: Add user-mode shadow stack support

Quoted 10 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Introduce basic shadow stack enabling/disabling/allocation routines. A task's shadow stack is allocated from memory with VM_SHADOW_STACK flag and has a fixed size of min(RLIMIT_STACK, 4GB).

Keep the task's shadow stack address and size in thread_struct. This will be copied when cloning new threads, but needs to be cleared during exec, so add a function to do this.

Quoted 5 lines

Do not support IA32 emulation or x32.

Signature · 1 line
Kees Cook
#79 lore raw

PATCH v4 27/39 x86/shstk: Handle thread shadow stack

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When a process is duplicated, but the child shares the address space with the parent, there is potential for the threads sharing a single stack to cause conflicts for each other. In the normal non-cet case this is handled in two ways.

With regular CLONE_VM a new stack is provided by userspace such that the parent and child have different stacks.

For vfork, the parent is suspended until the child exits. So as long as the child doesn't return from the vfork()/CLONE_VFORK calling function and sticks to a limited set of operations, the parent and child can share the same stack.

For shadow stack, these scenarios present similar sharing problems. For the CLONE_VM case, the child and the parent must have separate shadow stacks. Instead of changing clone to take a shadow stack, have the kernel just allocate one and switch to it.

Use stack_size passed from clone3() syscall for thread shadow stack size. A compat-mode thread shadow stack size is further reduced to 1/4. This allows more threads to run in a 32-bit address space. The clone() does not pass stack_size, which was added to clone3(). In that case, use RLIMIT_STACK size and cap to 4 GB.

For shadow stack enabled vfork(), the parent and child can share the same shadow stack, like they can share a normal stack. Since the parent is suspended until the child terminates, the child will not interfere with the parent while executing as long as it doesn't return from the vfork() and overwrite up the shadow stack. The child can safely overwrite down the shadow stack, as the parent can just overwrite this later. So CET does not add any additional limitations for vfork().

Userspace implementing posix vfork() can actually prevent the child from returning from the vfork() calling function, using CET. Glibc does this by adjusting the shadow stack pointer in the child, so that the child receives a #CP if it tries to return from vfork() calling function.

Free the shadow stack on thread exit by doing it in mm_release(). Skip this when exiting a vfork() child since the stack is shared in the parent.

During this operation, the shadow stack pointer of the new thread needs to be updated to point to the newly allocated shadow stack. Since the ability to do this is confined to the FPU subsystem, change fpu_clone() to take the new shadow stack pointer, and update it internally inside the FPU subsystem. This part was suggested by Thomas Gleixner.

---

v3:
- Fix update_fpu_shstk() stub (Mike Rapoport)
- Fix chunks around alloc_shstk() in wrong patch (Kees)
- Fix stack_size/flags swap (Kees)
- Use centalized stack size logic (Kees)

v2:
- Have fpu_clone() take new shadow stack pointer and update SSP in xsave buffer for new task. (tglx)

v1:
- Expand commit log.
- Add more comments.
- Switch to xsave helpers.

Yu-cheng v30:
- Update comments about clone()/clone3(). (Borislav Petkov)

 arch/x86/include/asm/fpu/sched.h   |  3 +-
 arch/x86/include/asm/mmu_context.h |  2 ++
 arch/x86/include/asm/shstk.h       |  7 +++++
 arch/x86/kernel/fpu/core.c         | 41 +++++++++++++++++++++++++++-
 arch/x86/kernel/process.c          | 18 +++++++++++-
 arch/x86/kernel/shstk.c            | 44 ++++++++++++++++++++++++++++--
 6 files changed, 110 insertions(+), 5 deletions(-)
arch/x86/include/asm/fpu/sched.h +2 -1
index b2486b2cbc6e..54c9c2fd1907 100644
@@ -11,7 +11,8 @@
 
 extern void save_fpregs_to_fpstate(struct fpu *fpu);
 extern void fpu__drop(struct fpu *fpu);
-extern int  fpu_clone(struct task_struct *dst, unsigned long clone_flags, bool minimal);
+extern int  fpu_clone(struct task_struct *dst, unsigned long clone_flags, bool minimal,
+		      unsigned long shstk_addr);
 extern void fpu_flush_thread(void);
 
 /*
arch/x86/include/asm/mmu_context.h +2 -0
index 32483ab3f763..8cafa3ccc027 100644
@@ -192,6 +192,8 @@ do {						\
 #else
 #define deactivate_mm(tsk, mm)			\
 do {						\
+	if (!tsk->vfork_done)			\
+		shstk_free(tsk);		\
 	load_gs_index(0);			\
 	loadsegment(fs, 0);			\
 } while (0)
arch/x86/include/asm/shstk.h +7 -0
index f40414a982e8..172a69052770 100644
@@ -15,11 +15,18 @@ struct thread_shstk {
 
 long shstk_prctl(struct task_struct *task, int option, unsigned long features);
 void reset_thread_features(void);
+int shstk_alloc_thread_stack(struct task_struct *p, unsigned long clone_flags,
+			     unsigned long stack_size,
+			     unsigned long *shstk_addr);
 void shstk_free(struct task_struct *p);
 #else
 static inline long shstk_prctl(struct task_struct *task, int option,
 			     unsigned long features) { return -EINVAL; }
 static inline void reset_thread_features(void) {}
+static inline int shstk_alloc_thread_stack(struct task_struct *p,
+					   unsigned long clone_flags,
+					   unsigned long stack_size,
+					   unsigned long *shstk_addr) { return 0; }
 static inline void shstk_free(struct task_struct *p) {}
 #endif /* CONFIG_X86_USER_SHADOW_STACK */
 
arch/x86/kernel/fpu/core.c +40 -1

54 lines not on this page · raw message

arch/x86/kernel/process.c +17 -1
index d1e83ba21130..16643f8fcded 100644
@@ -48,6 +48,7 @@
 #include <asm/unwind.h>
 #include <asm/tdx.h>
 #include <asm/mmu_context.h>
+#include <asm/shstk.h>
 
 #include "process.h"
 
@@ -119,6 +120,7 @@ void exit_thread(struct task_struct *tsk)
 
 	free_vm86(t);
 
+	shstk_free(tsk);
 	fpu__drop(fpu);
 }
 
@@ -140,6 +142,7 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
 	struct inactive_task_frame *frame;
 	struct fork_frame *fork_frame;
 	struct pt_regs *childregs;
+	unsigned long shstk_addr = 0;
 	int ret = 0;
 
 	childregs = task_pt_regs(p);
@@ -174,7 +177,13 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
 	frame->flags = X86_EFLAGS_FIXED;
 #endif
 
-	fpu_clone(p, clone_flags, args->fn);
+	/* Allocate a new shadow stack for pthread if needed */
+	ret = shstk_alloc_thread_stack(p, clone_flags, args->stack_size,
+				       &shstk_addr);
+	if (ret)
+		return ret;
+
+	fpu_clone(p, clone_flags, args->fn, shstk_addr);
 
 	/* Kernel thread ? */
 	if (unlikely(p->flags & PF_KTHREAD)) {
@@ -220,6 +229,13 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
 	if (!ret && unlikely(test_tsk_thread_flag(current, TIF_IO_BITMAP)))
 		io_bitmap_share(p);
 
+	/*
+	 * If copy_thread() if failing, don't leak the shadow stack possibly
+	 * allocated in shstk_alloc_thread_stack() above.
+	 */
+	if (ret)
+		shstk_free(p);
+
 	return ret;
 }
 
arch/x86/kernel/shstk.c +42 -2

62 lines not on this page · raw message

Signature · 1 line
2.17.1
Reviewed-by on v4 27/39
#80 lore raw

Re: [PATCH v4 27/39] x86/shstk: Handle thread shadow stack

Quoted 50 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When a process is duplicated, but the child shares the address space with the parent, there is potential for the threads sharing a single stack to cause conflicts for each other. In the normal non-cet case this is handled in two ways.

With regular CLONE_VM a new stack is provided by userspace such that the parent and child have different stacks.

For vfork, the parent is suspended until the child exits. So as long as the child doesn't return from the vfork()/CLONE_VFORK calling function and sticks to a limited set of operations, the parent and child can share the same stack.

For shadow stack, these scenarios present similar sharing problems. For the CLONE_VM case, the child and the parent must have separate shadow stacks. Instead of changing clone to take a shadow stack, have the kernel just allocate one and switch to it.

Use stack_size passed from clone3() syscall for thread shadow stack size. A compat-mode thread shadow stack size is further reduced to 1/4. This allows more threads to run in a 32-bit address space. The clone() does not pass stack_size, which was added to clone3(). In that case, use RLIMIT_STACK size and cap to 4 GB.

For shadow stack enabled vfork(), the parent and child can share the same shadow stack, like they can share a normal stack. Since the parent is suspended until the child terminates, the child will not interfere with the parent while executing as long as it doesn't return from the vfork() and overwrite up the shadow stack. The child can safely overwrite down the shadow stack, as the parent can just overwrite this later. So CET does not add any additional limitations for vfork().

Userspace implementing posix vfork() can actually prevent the child from returning from the vfork() calling function, using CET. Glibc does this by adjusting the shadow stack pointer in the child, so that the child receives a #CP if it tries to return from vfork() calling function.

Free the shadow stack on thread exit by doing it in mm_release(). Skip this when exiting a vfork() child since the stack is shared in the parent.

During this operation, the shadow stack pointer of the new thread needs to be updated to point to the newly allocated shadow stack. Since the ability to do this is confined to the FPU subsystem, change fpu_clone() to take the new shadow stack pointer, and update it internally inside the FPU subsystem. This part was suggested by Thomas Gleixner.

Quoted 4 lines
Signature · 1 line
Kees Cook
#81 lore raw

PATCH v4 28/39 x86/shstk: Introduce routines modifying shstk

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Shadow stacks are normally written to via CALL/RET or specific CET instuctions like RSTORSSP/SAVEPREVSSP. However during some Linux operations the kernel will need to write to directly using the ring-0 only WRUSS instruction.

A shadow stack restore token marks a restore point of the shadow stack, and the address in a token must point directly above the token, which is within the same shadow stack. This is distinctively different from other pointers on the shadow stack, since those pointers point to executable code area.

Introduce token setup and verify routines. Also introduce WRUSS, which is a kernel-mode instruction but writes directly to user shadow stack.

In future patches that enable shadow stack to work with signals, the kernel will need something to denote the point in the stack where sigreturn may be called. This will prevent attackers calling sigreturn at arbitrary places in the stack, in order to help prevent SROP attacks.

To do this, something that can only be written by the kernel needs to be placed on the shadow stack. This can be accomplished by setting bit 63 in the frame written to the shadow stack. Userspace return addresses can't have this bit set as it is in the kernel range. It is also can't be a valid restore token.

---

v3:
- Drop shstk_check_rstor_token()
- Fail put_shstk_data() if bit 63 is set in the data (Kees)
- Add comment in create_rstor_token() (Kees)
- Pull in create_rstor_token() changes from future patch (Kees)

v2:
- Add data helpers for writing to shadow stack.

v1:
- Use xsave helpers.

Yu-cheng v30:
- Update commit log, remove description about signals.
- Update various comments.
- Remove variable 'ssp' init and adjust return value accordingly.
- Check get_user_shstk_addr() return value.
- Replace 'ia32' with 'proc32'.

 arch/x86/include/asm/special_insns.h | 13 +++++
 arch/x86/kernel/shstk.c              | 73 ++++++++++++++++++++++++++++
 2 files changed, 86 insertions(+)
arch/x86/include/asm/special_insns.h +13 -0
index 35f709f619fb..6d51a87aea7f 100644
@@ -223,6 +223,19 @@ static inline void clwb(volatile void *__p)
 		: [pax] "a" (p));
 }
 
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+static inline int write_user_shstk_64(u64 __user *addr, u64 val)
+{
+	asm_volatile_goto("1: wrussq %[val], (%[addr])\n"
+			  _ASM_EXTABLE(1b, %l[fail])
+			  :: [addr] "r" (addr), [val] "r" (val)
+			  :: fail);
+	return 0;
+fail:
+	return -EFAULT;
+}
+#endif /* CONFIG_X86_USER_SHADOW_STACK */
+
 #define nop() asm volatile ("nop")
 
 static inline void serialize(void)
arch/x86/kernel/shstk.c +73 -0

91 lines not on this page · raw message

Signature · 1 line
2.17.1
Reviewed-by on v4 28/39
#82 lore raw

Re: [PATCH v4 28/39] x86/shstk: Introduce routines modifying shstk

Quoted 26 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Shadow stacks are normally written to via CALL/RET or specific CET instuctions like RSTORSSP/SAVEPREVSSP. However during some Linux operations the kernel will need to write to directly using the ring-0 only WRUSS instruction.

A shadow stack restore token marks a restore point of the shadow stack, and the address in a token must point directly above the token, which is within the same shadow stack. This is distinctively different from other pointers on the shadow stack, since those pointers point to executable code area.

Introduce token setup and verify routines. Also introduce WRUSS, which is a kernel-mode instruction but writes directly to user shadow stack.

In future patches that enable shadow stack to work with signals, the kernel will need something to denote the point in the stack where sigreturn may be called. This will prevent attackers calling sigreturn at arbitrary places in the stack, in order to help prevent SROP attacks.

To do this, something that can only be written by the kernel needs to be placed on the shadow stack. This can be accomplished by setting bit 63 in the frame written to the shadow stack. Userspace return addresses can't have this bit set as it is in the kernel range. It is also can't be a valid restore token.

Quoted 3 lines
Signature · 1 line
Kees Cook
#83 lore raw

PATCH v4 29/39 x86/shstk: Handle signals for shadow stack

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When a signal is handled normally the context is pushed to the stack before handling it. For shadow stacks, since the shadow stack only track's return addresses, there isn't any state that needs to be pushed. However, there are still a few things that need to be done. These things are userspace visible and which will be kernel ABI for shadow stacks.

One is to make sure the restorer address is written to shadow stack, since the signal handler (if not changing ucontext) returns to the restorer, and the restorer calls sigreturn. So add the restorer on the shadow stack before handling the signal, so there is not a conflict when the signal handler returns to the restorer.

The other thing to do is to place some type of checkable token on the thread's shadow stack before handling the signal and check it during sigreturn. This is an extra layer of protection to hamper attackers calling sigreturn manually as in SROP-like attacks.

For this token we can use the shadow stack data format defined earlier. Have the data pushed be the previous SSP. In the future the sigreturn might want to return back to a different stack. Storing the SSP (instead of a restore offset or something) allows for future functionality that may want to restore to a different stack.

So, when handling a signal push
- the SSP pointing in the shadow stack data format
- the restorer address below the restore token.

In sigreturn, verify SSP is stored in the data format and pop the shadow stack.

---

v3:
- Drop shstk_setup_rstor_token() (Kees)
- Drop x32 signal support, since x32 support is dropped

v2:
- Switch to new shstk signal format

v1:
- Use xsave helpers.
- Expand commit log.

Yu-cheng v27:
- Eliminate saving shadow stack pointer to signal context.

 arch/x86/include/asm/shstk.h |  5 ++
 arch/x86/kernel/shstk.c      | 98 ++++++++++++++++++++++++++++++++++++
 arch/x86/kernel/signal.c     |  1 +
 arch/x86/kernel/signal_64.c  |  6 +++
 4 files changed, 110 insertions(+)
arch/x86/include/asm/shstk.h +5 -0
index 172a69052770..746c040f7cb6 100644
@@ -6,6 +6,7 @@
 #include <linux/types.h>
 
 struct task_struct;
+struct ksignal;
 
 #ifdef CONFIG_X86_USER_SHADOW_STACK
 struct thread_shstk {
@@ -19,6 +20,8 @@ int shstk_alloc_thread_stack(struct task_struct *p, unsigned long clone_flags,
 			     unsigned long stack_size,
 			     unsigned long *shstk_addr);
 void shstk_free(struct task_struct *p);
+int setup_signal_shadow_stack(struct ksignal *ksig);
+int restore_signal_shadow_stack(void);
 #else
 static inline long shstk_prctl(struct task_struct *task, int option,
 			     unsigned long features) { return -EINVAL; }
@@ -28,6 +31,8 @@ static inline int shstk_alloc_thread_stack(struct task_struct *p,
 					   unsigned long stack_size,
 					   unsigned long *shstk_addr) { return 0; }
 static inline void shstk_free(struct task_struct *p) {}
+static inline int setup_signal_shadow_stack(struct ksignal *ksig) { return 0; }
+static inline int restore_signal_shadow_stack(void) { return 0; }
 #endif /* CONFIG_X86_USER_SHADOW_STACK */
 
 #endif /* __ASSEMBLY__ */
arch/x86/kernel/shstk.c +98 -0

104 lines not on this page · raw message

arch/x86/kernel/signal.c +1 -0
index 1504eb8d25aa..b2c9853ce1c5 100644
@@ -40,6 +40,7 @@
 #include <asm/syscall.h>
 #include <asm/sigframe.h>
 #include <asm/signal.h>
+#include <asm/shstk.h>
 
 static inline int is_ia32_compat_frame(struct ksignal *ksig)
 {
arch/x86/kernel/signal_64.c +6 -0
index ff9c55064223..6708ec2b00a3 100644
@@ -175,6 +175,9 @@ int x64_setup_rt_frame(struct ksignal *ksig, struct pt_regs *regs)
 	frame = get_sigframe(ksig, regs, sizeof(struct rt_sigframe), &fp);
 	uc_flags = frame_uc_flags(regs);
 
+	if (setup_signal_shadow_stack(ksig))
+		return -EFAULT;
+
 	if (!user_access_begin(frame, sizeof(*frame)))
 		return -EFAULT;
 
@@ -260,6 +263,9 @@ SYSCALL_DEFINE0(rt_sigreturn)
 	if (!restore_sigcontext(regs, &frame->uc.uc_mcontext, uc_flags))
 		goto badframe;
 
+	if (restore_signal_shadow_stack())
+		goto badframe;
+
 	if (restore_altstack(&frame->uc.uc_stack))
 		goto badframe;
 
Signature · 1 line
2.17.1
Reviewed-by on v4 29/39
#84 lore raw

Re: [PATCH v4 29/39] x86/shstk: Handle signals for shadow stack

Quoted 29 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

When a signal is handled normally the context is pushed to the stack before handling it. For shadow stacks, since the shadow stack only track's return addresses, there isn't any state that needs to be pushed. However, there are still a few things that need to be done. These things are userspace visible and which will be kernel ABI for shadow stacks.

One is to make sure the restorer address is written to shadow stack, since the signal handler (if not changing ucontext) returns to the restorer, and the restorer calls sigreturn. So add the restorer on the shadow stack before handling the signal, so there is not a conflict when the signal handler returns to the restorer.

The other thing to do is to place some type of checkable token on the thread's shadow stack before handling the signal and check it during sigreturn. This is an extra layer of protection to hamper attackers calling sigreturn manually as in SROP-like attacks.

For this token we can use the shadow stack data format defined earlier. Have the data pushed be the previous SSP. In the future the sigreturn might want to return back to a different stack. Storing the SSP (instead of a restore offset or something) allows for future functionality that may want to restore to a different stack.

So, when handling a signal push
- the SSP pointing in the shadow stack data format
- the restorer address below the restore token.

Quoted 6 lines

In sigreturn, verify SSP is stored in the data format and pop the shadow stack.

Signature · 1 line
Kees Cook
#85 lore raw

PATCH v4 30/39 x86/shstk: Introduce map_shadow_stack syscall

In reply to Rick Edgecombe

When operating with shadow stacks enabled, the kernel will automatically allocate shadow stacks for new threads, however in some cases userspace will need additional shadow stacks. The main example of this is the ucontext family of functions, which require userspace allocating and pivoting to userspace managed stacks.

Unlike most other user memory permissions, shadow stacks need to be provisioned with special data in order to be useful. They need to be setup with a restore token so that userspace can pivot to them via the RSTORSSP instruction. But, the security design of shadow stack's is that they should not be written to except in limited circumstances. This presents a problem for userspace, as to how userspace can provision this special data, without allowing for the shadow stack to be generally writable.

Previously, a new PROT_SHADOW_STACK was attempted, which could be mprotect()ed from RW permissions after the data was provisioned. This was found to not be secure enough, as other thread's could write to the shadow stack during the writable window.

The kernel can use a special instruction, WRUSS, to write directly to userspace shadow stacks. So the solution can be that memory can be mapped as shadow stack permissions from the beginning (never generally writable in userspace), and the kernel itself can write the restore token.

First, a new madvise() flag was explored, which could operate on the PROT_SHADOW_STACK memory. This had a couple downsides:
1. Extra checks were needed in mprotect() to prevent writable memory from ever becoming PROT_SHADOW_STACK.
2. Extra checks/vma state were needed in the new madvise() to prevent restore tokens being written into the middle of pre-used shadow stacks. It is ideal to prevent restore tokens being added at arbitrary locations, so the check was to make sure the shadow stack had never been written to.
3. It stood out from the rest of the madvise flags, as more of direct action than a hint at future desired behavior.

So rather than repurpose two existing syscalls (mmap, madvise) that don't quite fit, just implement a new map_shadow_stack syscall to allow userspace to map and setup new shadow stacks in one step. While ucontext is the primary motivator, userspace may have other unforeseen reasons to setup it's own shadow stacks using the WRSS instruction. Towards this provide a flag so that stacks can be optionally setup securely for the common case of ucontext without enabling WRSS. Or potentially have the kernel set up the shadow stack in some new way.

The following example demonstrates how to create a new shadow stack with map_shadow_stack:
void *shstk = map_shadow_stack(addr, stack_size, SHADOW_STACK_SET_TOKEN);

---

v3:
- Change syscall common -> 64 (Kees)
- Use bit shift notation instead of 0x1 for uapi header (Kees)
- Call do_mmap() with MAP_FIXED_NOREPLACE (Kees)
- Block unsupported flags (Kees)
- Require size >= 8 to set token (Kees)

v2:
- Change syscall to take address like mmap() for CRIU's usage

v1:
- New patch (replaces PROT_SHADOW_STACK).

 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 arch/x86/include/uapi/asm/mman.h       |  3 ++
 arch/x86/kernel/shstk.c                | 56 ++++++++++++++++++++++----
 include/linux/syscalls.h               |  1 +
 include/uapi/asm-generic/unistd.h      |  2 +-
 kernel/sys_ni.c                        |  1 +
 6 files changed, 55 insertions(+), 9 deletions(-)
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index c84d12608cd2..f65c671ce3b1 100644
@@ -372,6 +372,7 @@
 448	common	process_mrelease	sys_process_mrelease
 449	common	futex_waitv		sys_futex_waitv
 450	common	set_mempolicy_home_node	sys_set_mempolicy_home_node
+451	64	map_shadow_stack	sys_map_shadow_stack
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/x86/include/uapi/asm/mman.h +3 -0
index 775dbd3aff73..15c5a1c4fc29 100644
@@ -12,6 +12,9 @@
 		((key) & 0x8 ? VM_PKEY_BIT3 : 0))
 #endif
 
+/* Flags for map_shadow_stack(2) */
+#define SHADOW_STACK_SET_TOKEN	(1ULL << 0)	/* Set up a restore token in the shadow stack */
+
 #include <asm-generic/mman.h>
 
 #endif /* _ASM_X86_MMAN_H */
arch/x86/kernel/shstk.c +48 -8

93 lines not on this page · raw message

include/linux/syscalls.h +1 -0
index 33a0ee3bcb2e..392dc11e3556 100644
@@ -1058,6 +1058,7 @@ asmlinkage long sys_memfd_secret(unsigned int flags);
 asmlinkage long sys_set_mempolicy_home_node(unsigned long start, unsigned long len,
 					    unsigned long home_node,
 					    unsigned long flags);
+asmlinkage long sys_map_shadow_stack(unsigned long addr, unsigned long size, unsigned int flags);
 
 /*
  * Architecture-specific system calls
include/uapi/asm-generic/unistd.h +1 -1
index 45fa180cc56a..b12940ec5926 100644
@@ -887,7 +887,7 @@ __SYSCALL(__NR_futex_waitv, sys_futex_waitv)
 __SYSCALL(__NR_set_mempolicy_home_node, sys_set_mempolicy_home_node)
 
 #undef __NR_syscalls
-#define __NR_syscalls 451
+#define __NR_syscalls 452
 
 /*
  * 32 bit systems traditionally used different
kernel/sys_ni.c +1 -0
index 860b2dcf3ac4..cb9aebd34646 100644
@@ -381,6 +381,7 @@ COND_SYSCALL(vm86old);
 COND_SYSCALL(modify_ldt);
 COND_SYSCALL(vm86);
 COND_SYSCALL(kexec_file_load);
+COND_SYSCALL(map_shadow_stack);
 
 /* s390 */
 COND_SYSCALL(s390_pci_mmio_read);
Signature · 1 line
2.17.1
#86 lore raw

Re: [PATCH v4 30/39] x86/shstk: Introduce map_shadow_stack syscall

Quoted 129 lines · Rick Edgecombe

When operating with shadow stacks enabled, the kernel will automatically allocate shadow stacks for new threads, however in some cases userspace will need additional shadow stacks. The main example of this is the ucontext family of functions, which require userspace allocating and pivoting to userspace managed stacks.

Unlike most other user memory permissions, shadow stacks need to be provisioned with special data in order to be useful. They need to be setup with a restore token so that userspace can pivot to them via the RSTORSSP instruction. But, the security design of shadow stack's is that they should not be written to except in limited circumstances. This presents a problem for userspace, as to how userspace can provision this special data, without allowing for the shadow stack to be generally writable.

Previously, a new PROT_SHADOW_STACK was attempted, which could be mprotect()ed from RW permissions after the data was provisioned. This was found to not be secure enough, as other thread's could write to the shadow stack during the writable window.

The kernel can use a special instruction, WRUSS, to write directly to userspace shadow stacks. So the solution can be that memory can be mapped as shadow stack permissions from the beginning (never generally writable in userspace), and the kernel itself can write the restore token.

First, a new madvise() flag was explored, which could operate on the PROT_SHADOW_STACK memory. This had a couple downsides:
1. Extra checks were needed in mprotect() to prevent writable memory from ever becoming PROT_SHADOW_STACK.
2. Extra checks/vma state were needed in the new madvise() to prevent restore tokens being written into the middle of pre-used shadow stacks. It is ideal to prevent restore tokens being added at arbitrary locations, so the check was to make sure the shadow stack had never been written to.
3. It stood out from the rest of the madvise flags, as more of direct action than a hint at future desired behavior.

So rather than repurpose two existing syscalls (mmap, madvise) that don't quite fit, just implement a new map_shadow_stack syscall to allow userspace to map and setup new shadow stacks in one step. While ucontext is the primary motivator, userspace may have other unforeseen reasons to setup it's own shadow stacks using the WRSS instruction. Towards this provide a flag so that stacks can be optionally setup securely for the common case of ucontext without enabling WRSS. Or potentially have the kernel set up the shadow stack in some new way.

The following example demonstrates how to create a new shadow stack with map_shadow_stack:
void *shstk = map_shadow_stack(addr, stack_size, SHADOW_STACK_SET_TOKEN);

---

v3:
- Change syscall common -> 64 (Kees)
- Use bit shift notation instead of 0x1 for uapi header (Kees)
- Call do_mmap() with MAP_FIXED_NOREPLACE (Kees)
- Block unsupported flags (Kees)
- Require size >= 8 to set token (Kees)

v2:
- Change syscall to take address like mmap() for CRIU's usage

v1:
- New patch (replaces PROT_SHADOW_STACK).

 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 arch/x86/include/uapi/asm/mman.h       |  3 ++
 arch/x86/kernel/shstk.c                | 56 ++++++++++++++++++++++----
 include/linux/syscalls.h               |  1 +
 include/uapi/asm-generic/unistd.h      |  2 +-
 kernel/sys_ni.c                        |  1 +
 6 files changed, 55 insertions(+), 9 deletions(-)
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index c84d12608cd2..f65c671ce3b1 100644
@@ -372,6 +372,7 @@
 448	common	process_mrelease	sys_process_mrelease
 449	common	futex_waitv		sys_futex_waitv
 450	common	set_mempolicy_home_node	sys_set_mempolicy_home_node
+451	64	map_shadow_stack	sys_map_shadow_stack
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
arch/x86/include/uapi/asm/mman.h +3 -0
index 775dbd3aff73..15c5a1c4fc29 100644
@@ -12,6 +12,9 @@
 		((key) & 0x8 ? VM_PKEY_BIT3 : 0))
 #endif
 
+/* Flags for map_shadow_stack(2) */
+#define SHADOW_STACK_SET_TOKEN	(1ULL << 0)	/* Set up a restore token in the shadow stack */
+
 #include <asm-generic/mman.h>
 
 #endif /* _ASM_X86_MMAN_H */
arch/x86/kernel/shstk.c +4 -5
index e53225a8d39e..8f329c22728a 100644
@@ -17,6 +17,7 @@
 #include <linux/compat.h>
 #include <linux/sizes.h>
 #include <linux/user.h>
+#include <linux/syscalls.h>
 #include <asm/msr.h>
 #include <asm/fpu/xstate.h>
 #include <asm/fpu/types.h>
@@ -71,19 +72,31 @@ static int create_rstor_token(unsigned long ssp, unsigned long *token_addr)
 	return 0;
 }
 
-static unsigned long alloc_shstk(unsigned long size)
+static unsigned long alloc_shstk(unsigned long addr, unsigned long size,
+				 unsigned long token_offset, bool set_res_tok)
 {
 	int flags = MAP_ANONYMOUS | MAP_PRIVATE;
 	struct mm_struct *mm = current->mm;
-	unsigned long addr, unused;
+	unsigned long mapped_addr, unused;
 
-	mmap_write_lock(mm);
-	addr = do_mmap(NULL, 0, size, PROT_READ, flags,
-		       VM_SHADOW_STACK | VM_WRITE, 0, &unused, NULL);

arch/x86/kernel/shstk.c static int create_rstor_token(unsigned long ssp, unsigned long *token_addr) · line 90

Quoted 10 lines
arch/x86/kernel/shstk.c +6 -1
+	if (addr)
+		flags |= MAP_FIXED_NOREPLACE;
 
+	mmap_write_lock(mm);
+	mapped_addr = do_mmap(NULL, addr, size, PROT_READ, flags,
+			      VM_SHADOW_STACK | VM_WRITE, 0, &unused, NULL);
 	mmap_write_unlock(mm);
 
-	return addr;
+	if (!set_res_tok || IS_ERR_VALUE(addr))

Should this be IS_ERR_VALUE(mapped_addr) (i.e. the result of the do_mmap)?

Quoted 31 lines
arch/x86/kernel/shstk.c +11 -2
+		goto out;
+
+	if (create_rstor_token(mapped_addr + token_offset, NULL)) {
+		vm_munmap(mapped_addr, size);
+		return -EINVAL;
+	}
+
+out:
+	return mapped_addr;
 }
 
 static unsigned long adjust_shstk_size(unsigned long size)
@@ -134,7 +147,7 @@ static int shstk_setup(void)
 		return -EOPNOTSUPP;
 
 	size = adjust_shstk_size(0);
-	addr = alloc_shstk(size);
+	addr = alloc_shstk(0, size, 0, false);
 	if (IS_ERR_VALUE(addr))
 		return PTR_ERR((void *)addr);
 
@@ -179,7 +192,7 @@ int shstk_alloc_thread_stack(struct task_struct *tsk, unsigned long clone_flags,
 
 
 	size = adjust_shstk_size(stack_size);
-	addr = alloc_shstk(size);
+	addr = alloc_shstk(0, size, 0, false);
 	if (IS_ERR_VALUE(addr))
 		return PTR_ERR((void *)addr);
 

arch/x86/kernel/shstk.c static int shstk_disable(void) · line 395

Quoted 10 lines
arch/x86/kernel/shstk.c +7 -0
@@ -373,6 +386,33 @@ static int shstk_disable(void)
 	return 0;
 }
 
+SYSCALL_DEFINE3(map_shadow_stack, unsigned long, addr, unsigned long, size, unsigned int, flags)
+{
+	bool set_tok = flags & SHADOW_STACK_SET_TOKEN;
+	unsigned long aligned_size;
+
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return -ENOSYS;

Using -ENOSYS means there's no way to tell the difference between "kernel doesn't support it" and "CPU doesn't support it". Should this, perhaps return -ENOTSUP?

Quoted 63 lines
arch/x86/kernel/shstk.c +20 -0
+
+	if (flags & ~SHADOW_STACK_SET_TOKEN)
+		return -EINVAL;
+
+	/* If there isn't space for a token */
+	if (set_tok && size < 8)
+		return -EINVAL;
+
+	/*
+	 * An overflow would result in attempting to write the restore token
+	 * to the wrong location. Not catastrophic, but just return the right
+	 * error code and block it.
+	 */
+	aligned_size = PAGE_ALIGN(size);
+	if (aligned_size < size)
+		return -EOVERFLOW;
+
+	return alloc_shstk(addr, aligned_size, size, set_tok);
+}
+
 long shstk_prctl(struct task_struct *task, int option, unsigned long features)
 {
 	if (option == ARCH_SHSTK_LOCK) {
include/linux/syscalls.h +1 -0
index 33a0ee3bcb2e..392dc11e3556 100644
@@ -1058,6 +1058,7 @@ asmlinkage long sys_memfd_secret(unsigned int flags);
 asmlinkage long sys_set_mempolicy_home_node(unsigned long start, unsigned long len,
 					    unsigned long home_node,
 					    unsigned long flags);
+asmlinkage long sys_map_shadow_stack(unsigned long addr, unsigned long size, unsigned int flags);
 
 /*
  * Architecture-specific system calls
include/uapi/asm-generic/unistd.h +1 -1
index 45fa180cc56a..b12940ec5926 100644
@@ -887,7 +887,7 @@ __SYSCALL(__NR_futex_waitv, sys_futex_waitv)
 __SYSCALL(__NR_set_mempolicy_home_node, sys_set_mempolicy_home_node)
 
 #undef __NR_syscalls
-#define __NR_syscalls 451
+#define __NR_syscalls 452
 
 /*
  * 32 bit systems traditionally used different
kernel/sys_ni.c +1 -0
index 860b2dcf3ac4..cb9aebd34646 100644
@@ -381,6 +381,7 @@ COND_SYSCALL(vm86old);
 COND_SYSCALL(modify_ldt);
 COND_SYSCALL(vm86);
 COND_SYSCALL(kexec_file_load);
+COND_SYSCALL(map_shadow_stack);
 
 /* s390 */
 COND_SYSCALL(s390_pci_mmio_read);
Signature · 1 line
2.17.1

Otherwise, looks good!

Signature · 1 line
Kees Cook
#87 lore raw

Re: [PATCH v4 30/39] x86/shstk: Introduce map_shadow_stack syscall

Quoted 176 lines · Kees Cook
Quoted 175 lines · Rick Edgecombe

When operating with shadow stacks enabled, the kernel will automatically
allocate shadow stacks for new threads, however in some cases userspace
will need additional shadow stacks. The main example of this is the ucontext family of functions, which require userspace allocating and
pivoting to userspace managed stacks.

Unlike most other user memory permissions, shadow stacks need to be provisioned with special data in order to be useful. They need to be setup
with a restore token so that userspace can pivot to them via the RSTORSSP
instruction. But, the security design of shadow stack's is that they
should not be written to except in limited circumstances. This presents a
problem for userspace, as to how userspace can provision this special
data, without allowing for the shadow stack to be generally writable.

Previously, a new PROT_SHADOW_STACK was attempted, which could be mprotect()ed from RW permissions after the data was provisioned. This was
found to not be secure enough, as other thread's could write to the shadow stack during the writable window.

The kernel can use a special instruction, WRUSS, to write directly to
userspace shadow stacks. So the solution can be that memory can be mapped
as shadow stack permissions from the beginning (never generally writable
in userspace), and the kernel itself can write the restore token.

First, a new madvise() flag was explored, which could operate on the
PROT_SHADOW_STACK memory. This had a couple downsides:
1. Extra checks were needed in mprotect() to prevent writable memory from
ever becoming PROT_SHADOW_STACK.
2. Extra checks/vma state were needed in the new madvise() to prevent
restore tokens being written into the middle of pre-used shadow
stacks.
It is ideal to prevent restore tokens being added at arbitrary locations, so the check was to make sure the shadow stack had
never been
written to.
3. It stood out from the rest of the madvise flags, as more of direct
action than a hint at future desired behavior.

So rather than repurpose two existing syscalls (mmap, madvise) that don't
quite fit, just implement a new map_shadow_stack syscall to allow userspace to map and setup new shadow stacks in one step. While ucontext
is the primary motivator, userspace may have other unforeseen reasons to
setup it's own shadow stacks using the WRSS instruction. Towards this
provide a flag so that stacks can be optionally setup securely for the
common case of ucontext without enabling WRSS. Or potentially have the
kernel set up the shadow stack in some new way.

The following example demonstrates how to create a new shadow stack with
map_shadow_stack:
void *shstk = map_shadow_stack(addr, stack_size, SHADOW_STACK_SET_TOKEN);

---

v3:
- Change syscall common -> 64 (Kees)
- Use bit shift notation instead of 0x1 for uapi header (Kees)
- Call do_mmap() with MAP_FIXED_NOREPLACE (Kees)
- Block unsupported flags (Kees)
- Require size >= 8 to set token (Kees)

v2:
- Change syscall to take address like mmap() for CRIU's usage

v1:
- New patch (replaces PROT_SHADOW_STACK).

 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 arch/x86/include/uapi/asm/mman.h       |  3 ++
 arch/x86/kernel/shstk.c                | 56
++++++++++++++++++++++----
 include/linux/syscalls.h               |  1 +
 include/uapi/asm-generic/unistd.h      |  2 +-
 kernel/sys_ni.c                        |  1 +
 6 files changed, 55 insertions(+), 9 deletions(-)
arch/x86/entry/syscalls/syscall_64.tbl +0 -0
index c84d12608cd2..f65c671ce3b1 100644
@@ -372,6 +372,7 @@
 448	common	process_mrelease	sys_process_mreleas

e
449 common futex_waitv sys_futex_waitv
450 common set_mempolicy_home_node sys_set_mempolicy_h
ome_node
+451 64 map_shadow_stack sys_map_shadow_stack

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

arch/x86/include/uapi/asm/mman.h +2 -0
index 775dbd3aff73..15c5a1c4fc29 100644
@@ -12,6 +12,9 @@
 		((key) & 0x8 ? VM_PKEY_BIT3 : 0))
 #endif
 
+/* Flags for map_shadow_stack(2) */
+#define SHADOW_STACK_SET_TOKEN	(1ULL << 0)	/* Set up a restore

token in the shadow stack */

arch/x86/include/uapi/asm/mman.h +1 -0
+
 #include <asm-generic/mman.h>
 
 #endif /* _ASM_X86_MMAN_H */
arch/x86/kernel/shstk.c +9 -5
index e53225a8d39e..8f329c22728a 100644
@@ -17,6 +17,7 @@
 #include <linux/compat.h>
 #include <linux/sizes.h>
 #include <linux/user.h>
+#include <linux/syscalls.h>
 #include <asm/msr.h>
 #include <asm/fpu/xstate.h>
 #include <asm/fpu/types.h>
@@ -71,19 +72,31 @@ static int create_rstor_token(unsigned long
 ssp, unsigned long *token_addr)
 	return 0;
 }
 
-static unsigned long alloc_shstk(unsigned long size)
+static unsigned long alloc_shstk(unsigned long addr, unsigned long
 size,
+				 unsigned long token_offset, bool
 set_res_tok)
 {
 	int flags = MAP_ANONYMOUS | MAP_PRIVATE;
 	struct mm_struct *mm = current->mm;
-	unsigned long addr, unused;
+	unsigned long mapped_addr, unused;
 
-	mmap_write_lock(mm);
-	addr = do_mmap(NULL, 0, size, PROT_READ, flags,
-		       VM_SHADOW_STACK | VM_WRITE, 0, &unused, NULL);
+	if (addr)
+		flags |= MAP_FIXED_NOREPLACE;
 
+	mmap_write_lock(mm);
+	mapped_addr = do_mmap(NULL, addr, size, PROT_READ, flags,
+			      VM_SHADOW_STACK | VM_WRITE, 0, &unused,
 NULL);
 	mmap_write_unlock(mm);
 
Quoted 5 lines

arch/x86/kernel/shstk.c static int create_rstor_token(unsigned long ssp, unsigned long *token_addr) · line 90

Quoted 2 lines
arch/x86/kernel/shstk.c +1 -1
-	return addr;
+	if (!set_res_tok || IS_ERR_VALUE(addr))

Should this be IS_ERR_VALUE(mapped_addr) (i.e. the result of the do_mmap)?

Oops, yes. Thanks for pointing that.

Quoted 36 lines
Quoted 36 lines
arch/x86/kernel/shstk.c +11 -2
+		goto out;
+
+	if (create_rstor_token(mapped_addr + token_offset, NULL)) {
+		vm_munmap(mapped_addr, size);
+		return -EINVAL;
+	}
+
+out:
+	return mapped_addr;
 }
 
 static unsigned long adjust_shstk_size(unsigned long size)
@@ -134,7 +147,7 @@ static int shstk_setup(void)
 		return -EOPNOTSUPP;
 
 	size = adjust_shstk_size(0);
-	addr = alloc_shstk(size);
+	addr = alloc_shstk(0, size, 0, false);
 	if (IS_ERR_VALUE(addr))
 		return PTR_ERR((void *)addr);
 
@@ -179,7 +192,7 @@ int shstk_alloc_thread_stack(struct task_struct
 *tsk, unsigned long clone_flags,
 
 
 	size = adjust_shstk_size(stack_size);
-	addr = alloc_shstk(size);
+	addr = alloc_shstk(0, size, 0, false);
 	if (IS_ERR_VALUE(addr))
 		return PTR_ERR((void *)addr);
@@ -373,6 +386,33 @@ static int shstk_disable(void)
 	return 0;
 }
 
Quoted 13 lines

arch/x86/kernel/shstk.c static int shstk_disable(void) · line 395

Quoted 8 lines
arch/x86/kernel/shstk.c +7 -0
+SYSCALL_DEFINE3(map_shadow_stack, unsigned long, addr, unsigned
 long, size, unsigned int, flags)
+{
+	bool set_tok = flags & SHADOW_STACK_SET_TOKEN;
+	unsigned long aligned_size;
+
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return -ENOSYS;

Using -ENOSYS means there's no way to tell the difference between "kernel doesn't support it" and "CPU doesn't support it". Should this,
perhaps return -ENOTSUP?

Hmm, sure.

Quoted 67 lines
Quoted 67 lines
arch/x86/kernel/shstk.c +10 -0
+
+	if (flags & ~SHADOW_STACK_SET_TOKEN)
+		return -EINVAL;
+
+	/* If there isn't space for a token */
+	if (set_tok && size < 8)
+		return -EINVAL;
+
+	/*
+	 * An overflow would result in attempting to write the restore

token

arch/x86/kernel/shstk.c +1 -0
+	 * to the wrong location. Not catastrophic, but just return the

right

arch/x86/kernel/shstk.c +9 -0
+	 * error code and block it.
+	 */
+	aligned_size = PAGE_ALIGN(size);
+	if (aligned_size < size)
+		return -EOVERFLOW;
+
+	return alloc_shstk(addr, aligned_size, size, set_tok);
+}
+
 long shstk_prctl(struct task_struct *task, int option, unsigned

long features)
{

arch/x86/kernel/shstk.c +0 -0
 	if (option == ARCH_SHSTK_LOCK) {
include/linux/syscalls.h +1 -0
index 33a0ee3bcb2e..392dc11e3556 100644
@@ -1058,6 +1058,7 @@ asmlinkage long sys_memfd_secret(unsigned int
 flags);
 asmlinkage long sys_set_mempolicy_home_node(unsigned long start,
 unsigned long len,
 					    unsigned long home_node,
 					    unsigned long flags);
+asmlinkage long sys_map_shadow_stack(unsigned long addr, unsigned
 long size, unsigned int flags);

/*
* Architecture-specific system calls

include/uapi/asm- renamed from include/uapi/asm-generic/unistd.h +0 -0

generic/unistd.h
index 45fa180cc56a..b12940ec5926 100644

include/uapi/asm-generic/unistd.h +1 -1
@@ -887,7 +887,7 @@ __SYSCALL(__NR_futex_waitv, sys_futex_waitv)
 __SYSCALL(__NR_set_mempolicy_home_node,
 sys_set_mempolicy_home_node)
 
 #undef __NR_syscalls
-#define __NR_syscalls 451
+#define __NR_syscalls 452
 
 /*

* 32 bit systems traditionally used different

kernel/sys_ni.c +1 -0
index 860b2dcf3ac4..cb9aebd34646 100644
@@ -381,6 +381,7 @@ COND_SYSCALL(vm86old);
 COND_SYSCALL(modify_ldt);
 COND_SYSCALL(vm86);
 COND_SYSCALL(kexec_file_load);
+COND_SYSCALL(map_shadow_stack);
 
Quoted 8 lines
Quoted 5 lines
kernel/sys_ni.c +0 -0
 /* s390 */
 COND_SYSCALL(s390_pci_mmio_read);
Signature · 1 line
2.17.1

Otherwise, looks good!

Thanks for this and the reviewed-bys on other patches!

#88 lore raw

PATCH v4 31/39 x86/shstk: Support wrss for userspace

In reply to Rick Edgecombe

For the current shadow stack implementation, shadow stacks contents can't easily be provisioned with arbitrary data. This property helps apps protect themselves better, but also restricts any potential apps that may want to do exotic things at the expense of a little security.

The x86 shadow stack feature introduces a new instruction, wrss, which can be enabled to write directly to shadow stack permissioned memory from userspace. Allow it to get enabled via the prctl interface.

Only enable the userspace wrss instruction, which allows writes to userspace shadow stacks from userspace. Do not allow it to be enabled independently of shadow stack, as HW does not support using WRSS when shadow stack is disabled.

From a fault handler perspective, WRSS will behave very similar to WRUSS, which is treated like a user access from a #PF err code perspective.

---

v3:
- Make wrss_control() static
- Fix verbiage in commit log (Kees)

v2:
- Add some commit log verbiage from (Dave Hansen)

v1:
- New patch.

 arch/x86/include/uapi/asm/prctl.h |  1 +
 arch/x86/kernel/shstk.c           | 31 ++++++++++++++++++++++++++++++-
 2 files changed, 31 insertions(+), 1 deletion(-)
arch/x86/include/uapi/asm/prctl.h +1 -0
index fc97ca7c4884..f13751c6bae4 100644
@@ -33,5 +33,6 @@
 
 /* ARCH_SHSTK_ features bits */
 #define ARCH_SHSTK_SHSTK		(1ULL <<  0)
+#define ARCH_SHSTK_WRSS			(1ULL <<  1)
 
 #endif /* _ASM_X86_PRCTL_H */
arch/x86/kernel/shstk.c +30 -1
index 8f329c22728a..e59544fec96d 100644
@@ -364,6 +364,35 @@ void shstk_free(struct task_struct *tsk)
 	unmap_shadow_stack(shstk->base, shstk->size);
 }
 
+static int wrss_control(bool enable)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK))
+		return -EOPNOTSUPP;
+
+	/*
+	 * Only enable wrss if shadow stack is enabled. If shadow stack is not
+	 * enabled, wrss will already be disabled, so don't bother clearing it
+	 * when disabling.
+	 */
+	if (!features_enabled(ARCH_SHSTK_SHSTK))
+		return -EPERM;
+
+	/* Already enabled/disabled? */
+	if (features_enabled(ARCH_SHSTK_WRSS) == enable)
+		return 0;
+
+	fpregs_lock_and_load();
+	if (enable) {
+		set_clr_bits_msrl(MSR_IA32_U_CET, CET_WRSS_EN, 0);
+		features_set(ARCH_SHSTK_WRSS);
+	} else {
+		set_clr_bits_msrl(MSR_IA32_U_CET, 0, CET_WRSS_EN);
+		features_clr(ARCH_SHSTK_WRSS);
+	}
+	fpregs_unlock();
+
+	return 0;
+}
 
 static int shstk_disable(void)
 {
@@ -381,7 +410,7 @@ static int shstk_disable(void)
 	fpregs_unlock();
 
 	shstk_free(current);
-	features_clr(ARCH_SHSTK_SHSTK);
+	features_clr(ARCH_SHSTK_SHSTK | ARCH_SHSTK_WRSS);
 
 	return 0;
 }
Signature · 1 line
2.17.1
Reviewed-by on v4 31/39
#89 lore raw

Re: [PATCH v4 31/39] x86/shstk: Support wrss for userspace

Quoted 14 lines · Rick Edgecombe

For the current shadow stack implementation, shadow stacks contents can't easily be provisioned with arbitrary data. This property helps apps protect themselves better, but also restricts any potential apps that may want to do exotic things at the expense of a little security.

The x86 shadow stack feature introduces a new instruction, wrss, which can be enabled to write directly to shadow stack permissioned memory from userspace. Allow it to get enabled via the prctl interface.

Only enable the userspace wrss instruction, which allows writes to userspace shadow stacks from userspace. Do not allow it to be enabled independently of shadow stack, as HW does not support using WRSS when shadow stack is disabled.

Quoted 6 lines

From a fault handler perspective, WRSS will behave very similar to WRUSS, which is treated like a user access from a #PF err code perspective.

Signature · 1 line
Kees Cook
#90 lore raw

PATCH v4 32/39 x86: Expose thread features in /proc/$PID/status

In reply to Rick Edgecombe

Applications and loaders can have logic to decide whether to enable shadow stack. They usually don't report whether shadow stack has been enabled or not, so there is no way to verify whether an application actually is protected by shadow stack.

Add two lines in /proc/$PID/status to report enabled and locked features.

Since, this involves referring to arch specific defines in asm/prctl.h, implement an arch breakout to emit the feature lines.

---

v4:
- Remove "CET" references

v3:
- Move to /proc/pid/status (Kees)

v2:
- New patch

 arch/x86/kernel/cpu/proc.c | 23 +++++++++++++++++++++++
 fs/proc/array.c            |  6 ++++++
 include/linux/proc_fs.h    |  2 ++
 3 files changed, 31 insertions(+)
arch/x86/kernel/cpu/proc.c +23 -0
index 099b6f0d96bd..31c0e68f6227 100644
@@ -4,6 +4,8 @@
 #include <linux/string.h>
 #include <linux/seq_file.h>
 #include <linux/cpufreq.h>
+#include <asm/prctl.h>
+#include <linux/proc_fs.h>
 
 #include "cpu.h"
 
@@ -175,3 +177,24 @@ const struct seq_operations cpuinfo_op = {
 	.stop	= c_stop,
 	.show	= show_cpuinfo,
 };
+
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+static void dump_x86_features(struct seq_file *m, unsigned long features)
+{
+	if (features & ARCH_SHSTK_SHSTK)
+		seq_puts(m, "shstk ");
+	if (features & ARCH_SHSTK_WRSS)
+		seq_puts(m, "wrss ");
+}
+
+void arch_proc_pid_thread_features(struct seq_file *m, struct task_struct *task)
+{
+	seq_puts(m, "x86_Thread_features:\t");
+	dump_x86_features(m, task->thread.features);
+	seq_putc(m, '\n');
+
+	seq_puts(m, "x86_Thread_features_locked:\t");
+	dump_x86_features(m, task->thread.features_locked);
+	seq_putc(m, '\n');
+}
+#endif /* CONFIG_X86_USER_SHADOW_STACK */
fs/proc/array.c +6 -0
index d2a94eafe9a3..96ee17d68b4c 100644
@@ -433,6 +433,11 @@ static inline void task_untag_mask(struct seq_file *m, struct mm_struct *mm)
 	seq_printf(m, "untag_mask:\t%#lx\n", mm_untag_mask(mm));
 }
 
+__weak void arch_proc_pid_thread_features(struct seq_file *m,
+					  struct task_struct *task)
+{
+}
+
 int proc_pid_status(struct seq_file *m, struct pid_namespace *ns,
 			struct pid *pid, struct task_struct *task)
 {
@@ -457,6 +462,7 @@ int proc_pid_status(struct seq_file *m, struct pid_namespace *ns,
 	task_cpus_allowed(m, task);
 	cpuset_task_status_allowed(m, task);
 	task_context_switch_counts(m, task);
+	arch_proc_pid_thread_features(m, task);
 	return 0;
 }
 
include/linux/proc_fs.h +2 -0
index 81d6e4ec2294..5a8b21c0a587 100644
@@ -158,6 +158,8 @@ int proc_pid_arch_status(struct seq_file *m, struct pid_namespace *ns,
 			struct pid *pid, struct task_struct *task);
 #endif /* CONFIG_PROC_PID_ARCH_STATUS */
 
+void arch_proc_pid_thread_features(struct seq_file *m, struct task_struct *task);
+
 #else /* CONFIG_PROC_FS */
 
 static inline void proc_root_init(void)
Signature · 1 line
2.17.1
Reviewed-by on v4 32/39
#91 lore raw

Re: [PATCH v4 32/39] x86: Expose thread features in /proc/$PID/status

Quoted 5 lines · Rick Edgecombe

Applications and loaders can have logic to decide whether to enable shadow stack. They usually don't report whether shadow stack has been enabled or not, so there is no way to verify whether an application actually is protected by shadow stack.

Quoted 8 lines

Add two lines in /proc/$PID/status to report enabled and locked features.

Since, this involves referring to arch specific defines in asm/prctl.h, implement an arch breakout to emit the feature lines.

Signature · 1 line
Kees Cook
#92 lore raw

PATCH v4 33/39 x86: Prevent 32 bit operations for 64 bit shstk tasks

In reply to Rick Edgecombe

Shadow stack is only supported in 64 bit kernels. Since 64 bit kernels can run 32 bit applications using 32 bit emulation it would still be possible to support shadow stack for 32 bit applications. The challenge for this would be the shadow stack sigframe format uses noncannonical bits in the shadow stack frame, for which there are none in 32 bit. This means the 32 bit shadow stack sigframe would need either an alternate unknown solution or to not support any features that expand the shadow stack sigframe (alt shadow stack). It would add complexity to separate out these future features between the ABIs.

But shadow stack support for 32 bit would not likely be very useful. 32 bit emulation is mostly to support old apps, which should not have enabled shadow stack. So this series disables support for 32 bit apps by blocking the arch_prctl()s when made via a 32 bit syscall.

But PeterZ points out (see link) that some applications will utilize a 32 bit segment to run 32 bit code inside a 64 bit process. WINE does this to run 32 bit Windows apps. However, doing this with shadow stack is not likely to happen in practice since Windows does not support shadow stack for 32 bit applications either.

Any preexisting applications that are marked with shadow stack are unlikely to make it to the point where they can exercise any 32 bit signal interactions anyway, because the HW requires that the shadow stack pointer register needs to be in the 32 bit range in this case, but shadow stack would have been allocated in the 64 bit address space. The shadow stack enabled app would #GP when doing the long jump into the 32 bit segment.

So since 32 bit is not easy to support, and there are likely not many users. More cleanly don't support 32 bit signals in a 64 bit address space by not allowing 32 bit ABI signal handlers when shadow stack is enabled. Do this by clearing any 32 bit ABI signal handlers when shadow stack is enabled, and disallow any further 32 bit ABI signal handlers. Also, return an error code for the clone operations when in a 32 bit syscall.

---

v4:
- New patch

 arch/x86/include/asm/shstk.h       | 12 ++++++++++++
 arch/x86/include/asm/sighandling.h |  1 +
 arch/x86/kernel/shstk.c            | 10 ++++++++--
 arch/x86/kernel/signal.c           | 20 ++++++++++++++++++++
 arch/x86/kernel/signal_compat.c    |  5 +++++
 include/linux/ptrace.h             |  1 +
 kernel/signal.c                    |  8 ++++++++
 7 files changed, 55 insertions(+), 2 deletions(-)
arch/x86/include/asm/shstk.h +12 -0
index 746c040f7cb6..c82f22fd5e6d 100644
@@ -4,6 +4,7 @@
 
 #ifndef __ASSEMBLY__
 #include <linux/types.h>
+#include <asm/prctl.h>
 
 struct task_struct;
 struct ksignal;
@@ -22,6 +23,12 @@ int shstk_alloc_thread_stack(struct task_struct *p, unsigned long clone_flags,
 void shstk_free(struct task_struct *p);
 int setup_signal_shadow_stack(struct ksignal *ksig);
 int restore_signal_shadow_stack(void);
+bool features_enabled(unsigned long features);
+
+static inline bool shstk_enabled(void)
+{
+	return features_enabled(ARCH_SHSTK_SHSTK);
+}
 #else
 static inline long shstk_prctl(struct task_struct *task, int option,
 			     unsigned long features) { return -EINVAL; }
@@ -33,6 +40,11 @@ static inline int shstk_alloc_thread_stack(struct task_struct *p,
 static inline void shstk_free(struct task_struct *p) {}
 static inline int setup_signal_shadow_stack(struct ksignal *ksig) { return 0; }
 static inline int restore_signal_shadow_stack(void) { return 0; }
+
+static inline bool shstk_enabled(void)
+{
+	return false;
+}
 #endif /* CONFIG_X86_USER_SHADOW_STACK */
 
 #endif /* __ASSEMBLY__ */
arch/x86/include/asm/sighandling.h +1 -0
index e770c4fc47f4..eba88c7a6446 100644
@@ -24,4 +24,5 @@ int ia32_setup_rt_frame(struct ksignal *ksig, struct pt_regs *regs);
 int x64_setup_rt_frame(struct ksignal *ksig, struct pt_regs *regs);
 int x32_setup_rt_frame(struct ksignal *ksig, struct pt_regs *regs);
 
+void flush_32bit_signals(struct task_struct *t);
 #endif /* _ASM_X86_SIGHANDLING_H */
arch/x86/kernel/shstk.c +8 -2
index e59544fec96d..3a7bcc01d985 100644
@@ -24,11 +24,11 @@
 #include <asm/shstk.h>
 #include <asm/special_insns.h>
 #include <asm/fpu/api.h>
-#include <asm/prctl.h>
+#include <asm/sighandling.h>
 
 #define SS_FRAME_SIZE 8
 
-static bool features_enabled(unsigned long features)
+bool features_enabled(unsigned long features)
 {
 	return current->thread.features & features;
 }
@@ -146,6 +146,8 @@ static int shstk_setup(void)
 	if (!cpu_feature_enabled(X86_FEATURE_USER_SHSTK) || in_32bit_syscall())
 		return -EOPNOTSUPP;
 
+	flush_32bit_signals(current);
+
 	size = adjust_shstk_size(0);
 	addr = alloc_shstk(0, size, 0, false);
 	if (IS_ERR_VALUE(addr))
@@ -183,6 +185,10 @@ int shstk_alloc_thread_stack(struct task_struct *tsk, unsigned long clone_flags,
 	if (!features_enabled(ARCH_SHSTK_SHSTK))
 		return 0;
 
+	/* If shadow stack is enabled, 32 bit syscalls are not supported */
+	if (in_32bit_syscall())
+		return 1;
+
 	/*
 	 * For CLONE_VM, except vfork, the child needs a separate shadow
 	 * stack.
arch/x86/kernel/signal.c +20 -0
index b2c9853ce1c5..721b326d61ec 100644
@@ -352,6 +352,26 @@ void signal_fault(struct pt_regs *regs, void __user *frame, char *where)
 	force_sig(SIGSEGV);
 }
 
+void flush_32bit_signals(struct task_struct *t)
+{
+	const unsigned long flags_32 = SA_IA32_ABI | SA_X32_ABI;
+	struct k_sigaction *ka;
+	int i;
+
+	spin_lock_irq(&t->sighand->siglock);
+	ka = &t->sighand->action[0];
+	for (i = 0; i < _NSIG; i++) {
+		if (ka->sa.sa_flags & flags_32) {
+			ka->sa.sa_handler = SIG_DFL;
+			ka->sa.sa_flags = 0;
+			ka->sa.sa_restorer = NULL;
+			sigemptyset(&ka->sa.sa_mask);
+		}
+		ka++;
+	}
+	spin_unlock_irq(&t->sighand->siglock);
+}
+
 #ifdef CONFIG_DYNAMIC_SIGFRAME
 #ifdef CONFIG_STRICT_SIGALTSTACK_SIZE
 static bool strict_sigaltstack_size __ro_after_init = true;
arch/x86/kernel/signal_compat.c +5 -0
index d441804443d5..9c73435bc393 100644
@@ -177,6 +177,11 @@ static inline void signal_compat_build_tests(void)
 	/* any new si_fields should be added here */
 }
 
+bool sigaction_compat_invalid(void)
+{
+	return in_32bit_syscall() && shstk_enabled();
+}
+
 void sigaction_compat_abi(struct k_sigaction *act, struct k_sigaction *oact)
 {
 	signal_compat_build_tests();
include/linux/ptrace.h +1 -0
index c952c5ba8fab..30ec68f56caf 100644
@@ -405,6 +405,7 @@ static inline void user_single_step_report(struct pt_regs *regs)
 extern int task_current_syscall(struct task_struct *target, struct syscall_info *info);
 
 extern void sigaction_compat_abi(struct k_sigaction *act, struct k_sigaction *oact);
+bool sigaction_compat_invalid(void);
 
 /*
  * ptrace report for syscall entry and exit looks identical.
kernel/signal.c +8 -0
index d140672185a4..a75351c8fc0e 100644
@@ -4079,6 +4079,11 @@ void kernel_sigaction(int sig, __sighandler_t action)
 }
 EXPORT_SYMBOL(kernel_sigaction);
 
+bool __weak sigaction_compat_invalid(void)
+{
+	return false;
+}
+
 void __weak sigaction_compat_abi(struct k_sigaction *act,
 		struct k_sigaction *oact)
 {
@@ -4093,6 +4098,9 @@ int do_sigaction(int sig, struct k_sigaction *act, struct k_sigaction *oact)
 	if (!valid_signal(sig) || sig < 1 || (act && sig_kernel_only(sig)))
 		return -EINVAL;
 
+	if (sigaction_compat_invalid())
+		return -EINVAL;
+
 	k = &p->sighand->action[sig-1];
 
 	spin_lock_irq(&p->sighand->siglock);
Signature · 1 line
2.17.1
maintainer
#93 lore raw

Re: [PATCH v4 33/39] x86: Prevent 32 bit operations for 64 bit shstk tasks

Quoted 10 lines · Rick Edgecombe

So since 32 bit is not easy to support, and there are likely not many users. More cleanly don't support 32 bit signals in a 64 bit address space by not allowing 32 bit ABI signal handlers when shadow stack is enabled. Do this by clearing any 32 bit ABI signal handlers when shadow stack is enabled, and disallow any further 32 bit ABI signal handlers. Also, return an error code for the clone operations when in a 32 bit syscall.

This seems unfortunate. The result will be a highly incomprehensible crash. Maybe instead deny enabling shadow stack in the first place? Or at least pr_warn_once if anything gets flushed.

#94 lore raw

Re: [PATCH v4 33/39] x86: Prevent 32 bit operations for 64 bit shstk tasks

Quoted 18 lines · Andy Lutomirski
Quoted 15 lines · Rick Edgecombe

So since 32 bit is not easy to support, and there are likely not many
users. More cleanly don't support 32 bit signals in a 64 bit address
space by not allowing 32 bit ABI signal handlers when shadow stack is
enabled. Do this by clearing any 32 bit ABI signal handlers when shadow
stack is enabled, and disallow any further 32 bit ABI signal handlers.
Also, return an error code for the clone operations when in a 32 bit
syscall.

Quoted 3 lines

This seems unfortunate. The result will be a highly incomprehensible crash. Maybe instead deny enabling shadow stack in the first place? Or at least pr_warn_once if anything gets flushed.

Thanks for the suggestion! Denying seems much better, I'll change it.

#95 lore raw

Re: [PATCH v4 33/39] x86: Prevent 32 bit operations for 64 bit shstk tasks

Quoted 20 lines · Rick Edgecombe
Quoted 19 lines · Andy Lutomirski
Quoted 16 lines · Rick Edgecombe

So since 32 bit is not easy to support, and there are likely not many
users. More cleanly don't support 32 bit signals in a 64 bit address
space by not allowing 32 bit ABI signal handlers when shadow stack
is
enabled. Do this by clearing any 32 bit ABI signal handlers when shadow
stack is enabled, and disallow any further 32 bit ABI signal handlers.
Also, return an error code for the clone operations when in a 32 bit
syscall.

Quoted 7 lines
Quoted 5 lines

This seems unfortunate. The result will be a highly incomprehensible
crash. Maybe instead deny enabling shadow stack in the first place?
Or at least pr_warn_once if anything gets flushed.

Thanks for the suggestion! Denying seems much better, I'll change it.

Argh, the solution only work in the normal case where the first task enables shadow stack. Otherwise the process could:
1. Have two threads without shadow stack
2. Enable shadow stack in thread 1
3. Register 32 bit handler from thread 2
4. Handle 32 bit signal in thread 1

For this amount of special case ugliness it should fix the whole problem I think.

Trying to fix it up by adding 32 bit signal blocking state into struct sighand_struct, so it would actually be per-process, spills this into core code. I think it might not be the best solution. I'm not sure what is yet.

#96 lore raw

PATCH v4 34/39 x86/shstk: Wire in shadow stack interface

In reply to Rick Edgecombe

The kernel now has the main shadow stack functionality to support applications. Wire in the WRSS and shadow stack enable/disable functions into the existing shadow stack API skeleton.

---

v4:
- Remove "CET" references

v2:
- Split from other patches

 arch/x86/kernel/shstk.c | 8 ++++++++
 1 file changed, 8 insertions(+)
arch/x86/kernel/shstk.c +8 -0
index 3a7bcc01d985..5d91e653f77a 100644
@@ -468,9 +468,17 @@ long shstk_prctl(struct task_struct *task, int option, unsigned long features)
 		return -EINVAL;
 
 	if (option == ARCH_SHSTK_DISABLE) {
+		if (features & ARCH_SHSTK_WRSS)
+			return wrss_control(false);
+		if (features & ARCH_SHSTK_SHSTK)
+			return shstk_disable();
 		return -EINVAL;
 	}
 
 	/* Handle ARCH_SHSTK_ENABLE */
+	if (features & ARCH_SHSTK_SHSTK)
+		return shstk_setup();
+	if (features & ARCH_SHSTK_WRSS)
+		return wrss_control(true);
 	return -EINVAL;
 }
Signature · 1 line
2.17.1
#97 lore raw

PATCH v4 35/39 selftests/x86: Add shadow stack test

In reply to Rick Edgecombe

Add a simple selftest for exercising some shadow stack behavior:
- map_shadow_stack syscall and pivot
- Faulting in shadow stack memory
- Handling shadow stack violations
- GUP of shadow stack memory
- mprotect() of shadow stack memory
- Userfaultfd on shadow stack memory

Since this test exercises a recently added syscall manually, it needs to find the automatically created __NR_foo defines. Per the selftest documentation, KHDR_INCLUDES can be used to help the selftest Makefile's find the headers from the kernel source. This way the new selftest can be built inside the kernel source tree without installing the headers to the system. So also add KHDR_INCLUDES as described in the selftest docs, to facilitate this.

---

v4:
- Add test for 32 bit signal ABI blocking

v3:
- Change "+m" to "=m" in write_shstk() (Andrew Cooper)
- Fix userfaultfd test with transparent huge pages by doing a MADV_DONTNEED, since the token write faults in the while stack with huge pages.

v2:
- Change print statements to more align with other selftests
- Add more tests
- Add KHDR_INCLUDES to Makefile

v1:
- New patch.

 tools/testing/selftests/x86/Makefile          |   4 +-
 .../testing/selftests/x86/test_shadow_stack.c | 685 ++++++++++++++++++
 2 files changed, 687 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/selftests/x86/test_shadow_stack.c
tools/testing/selftests/x86/Makefile +2 -2
index c1a16a9d4f2f..7e8c937627dd 100644
@@ -18,7 +18,7 @@ TARGETS_C_32BIT_ONLY := entry_from_vm86 test_syscall_vdso unwind_vdso \
 			test_FCMOV test_FCOMI test_FISTTP \
 			vdso_restorer
 TARGETS_C_64BIT_ONLY := fsgsbase sysret_rip syscall_numbering \
-			corrupt_xstate_header amx lam
+			corrupt_xstate_header amx lam test_shadow_stack
 # Some selftests require 32bit support enabled also on 64bit systems
 TARGETS_C_32BIT_NEEDED := ldt_gdt ptrace_syscall
 
@@ -34,7 +34,7 @@ BINARIES_64 := $(TARGETS_C_64BIT_ALL:%=%_64)
 BINARIES_32 := $(patsubst %,$(OUTPUT)/%,$(BINARIES_32))
 BINARIES_64 := $(patsubst %,$(OUTPUT)/%,$(BINARIES_64))
 
-CFLAGS := -O2 -g -std=gnu99 -pthread -Wall
+CFLAGS := -O2 -g -std=gnu99 -pthread -Wall $(KHDR_INCLUDES)
 
 # call32_from_64 in thunks.S uses absolute addresses.
 ifeq ($(CAN_BUILD_WITH_NOPIE),1)
tools/testing/selftests/x86/test_shadow_stack.c new file +685 -0

685 lines not on this page · raw message

Signature · 1 line
2.17.1
#98 lore raw

PATCH v4 36/39 x86/fpu: Add helper for initing features

In reply to Rick Edgecombe

If an xfeature is saved in a buffer, the xfeature's bit will be set in xsave->header.xfeatures. The CPU may opt to not save the xfeature if it is in it's init state. In this case the xfeature buffer address cannot be retrieved with get_xsave_addr().

Future patches will need to handle the case of writing to an xfeature that may not be saved. So provide helpers to init an xfeature in an xsave buffer.

This could of course be done directly by reaching into the xsave buffer, however this would not be robust against future changes to optimize the xsave buffer by compacting it. In that case the xsave buffer would need to be re-arranged as well. So the logic properly belongs encapsulated in a helper where the logic can be unified.

---

v2:
- New patch

 arch/x86/kernel/fpu/xstate.c | 58 +++++++++++++++++++++++++++++-------
 arch/x86/kernel/fpu/xstate.h |  6 ++++
 2 files changed, 53 insertions(+), 11 deletions(-)
arch/x86/kernel/fpu/xstate.c +47 -11
index 13a80521dd51..3ff80be0a441 100644
@@ -934,6 +934,24 @@ static void *__raw_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
 	return (void *)xsave + xfeature_get_offset(xcomp_bv, xfeature_nr);
 }
 
+static int xsave_buffer_access_checks(int xfeature_nr)
+{
+	/*
+	 * Do we even *have* xsave state?
+	 */
+	if (!boot_cpu_has(X86_FEATURE_XSAVE))
+		return 1;
+
+	/*
+	 * We should not ever be requesting features that we
+	 * have not enabled.
+	 */
+	if (WARN_ON_ONCE(!xfeature_enabled(xfeature_nr)))
+		return 1;
+
+	return 0;
+}
+
 /*
  * Given the xsave area and a state inside, this function returns the
  * address of the state.
@@ -954,17 +972,7 @@ static void *__raw_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
  */
 void *get_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
 {
-	/*
-	 * Do we even *have* xsave state?
-	 */
-	if (!boot_cpu_has(X86_FEATURE_XSAVE))
-		return NULL;
-
-	/*
-	 * We should not ever be requesting features that we
-	 * have not enabled.
-	 */
-	if (WARN_ON_ONCE(!xfeature_enabled(xfeature_nr)))
+	if (xsave_buffer_access_checks(xfeature_nr))
 		return NULL;
 
 	/*
@@ -984,6 +992,34 @@ void *get_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
 	return __raw_xsave_addr(xsave, xfeature_nr);
 }
 
+/*
+ * Given the xsave area and a state inside, this function
+ * initializes an xfeature in the buffer.
+ *
+ * get_xsave_addr() will return NULL if the feature bit is
+ * not present in the header. This function will make it so
+ * the xfeature buffer address is ready to be retrieved by
+ * get_xsave_addr().
+ *
+ * Inputs:
+ *	xstate: the thread's storage area for all FPU data
+ *	xfeature_nr: state which is defined in xsave.h (e.g. XFEATURE_FP,
+ *	XFEATURE_SSE, etc...)
+ * Output:
+ *	1 if the feature cannot be inited, 0 on success
+ */
+int init_xfeature(struct xregs_state *xsave, int xfeature_nr)
+{
+	if (xsave_buffer_access_checks(xfeature_nr))
+		return 1;
+
+	/*
+	 * Mark the feature inited.
+	 */
+	xsave->header.xfeatures |= BIT_ULL(xfeature_nr);
+	return 0;
+}
+
 #ifdef CONFIG_ARCH_HAS_PKEYS
 
 /*
arch/x86/kernel/fpu/xstate.h +6 -0
index a4ecb04d8d64..dc06f63063ee 100644
@@ -54,6 +54,12 @@ extern void fpu__init_cpu_xstate(void);
 extern void fpu__init_system_xstate(unsigned int legacy_size);
 
 extern void *get_xsave_addr(struct xregs_state *xsave, int xfeature_nr);
+extern int init_xfeature(struct xregs_state *xsave, int xfeature_nr);
+
+static inline int xfeature_saved(struct xregs_state *xsave, int xfeature_nr)
+{
+	return xsave->header.xfeatures & BIT_ULL(xfeature_nr);
+}
 
 static inline u64 xfeatures_mask_supervisor(void)
 {
Signature · 1 line
2.17.1
#99 lore raw

PATCH v4 37/39 x86: Add PTRACE interface for shadow stack

In reply to Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Some applications (like GDB) would like to tweak shadow stack state via ptrace. This allows for existing functionality to continue to work for seized shadow stack applications. Provide an regset interface for manipulating the shadow stack pointer (SSP).

There is already ptrace functionality for accessing xstate, but this does not include supervisor xfeatures. So there is not a completely clear place for where to put the shadow stack state. Adding it to the user xfeatures regset would complicate that code, as it currently shares logic with signals which should not have supervisor features.

Don't add a general supervisor xfeature regset like the user one, because it is better to maintain flexibility for other supervisor xfeatures to define their own interface. For example, an xfeature may decide not to expose all of it's state to userspace, as is actually the case for shadow stack ptrace functionality. A lot of enum values remain to be used, so just put it in dedicated shadow stack regset.

The only downside to not having a generic supervisor xfeature regset, is that apps need to be enlightened of any new supervisor xfeature exposed this way (i.e. they can't try to have generic save/restore logic). But maybe that is a good thing, because they have to think through each new xfeature instead of encountering issues when new a new supervisor xfeature was added.

By adding a shadow stack regset, it also has the effect of including the shadow stack state in a core dump, which could be useful for debugging.

The shadow stack specific xstate includes the SSP, and the shadow stack and WRSS enablement status. Enabling shadow stack or wrss in the kernel involves more than just flipping the bit. The kernel is made aware that it has to do extra things when cloning or handling signals. That logic is triggered off of separate feature enablement state kept in the task struct. So the flipping on HW shadow stack enforcement without notifying the kernel to change its behavior would severely limit what an application could do without crashing, and the results would depend on kernel internal implementation details. There is also no known use for controlling this state via prtace today. So only expose the SSP, which is something that userspace already has indirect control over.

---

v4:
- Make shadow stack only. Reduce to only supporting SSP register, and remove CET references (peterz)
- Add comment to not use 0x203, becuase binutils already looks for it in coredumps. (Christina Schimpe)

v3:
- Drop dependence on thread.shstk.size, and use thread.features bits
- Drop 32 bit support

v2:
- Check alignment on ssp.
- Block IBT bits.
- Handle init states instead of returning error.
- Add verbose commit log justifying the design.

Yu-Cheng v12:
- Return -ENODEV when CET registers are in INIT state.
- Check reserved/non-support bits from user input.

 arch/x86/include/asm/fpu/regset.h |  7 +--
 arch/x86/kernel/fpu/regset.c      | 87 +++++++++++++++++++++++++++++++
 arch/x86/kernel/ptrace.c          | 12 +++++
 include/uapi/linux/elf.h          |  2 +
 4 files changed, 105 insertions(+), 3 deletions(-)
arch/x86/include/asm/fpu/regset.h +4 -3
index 4f928d6a367b..697b77e96025 100644
@@ -7,11 +7,12 @@
 
 #include <linux/regset.h>
 
-extern user_regset_active_fn regset_fpregs_active, regset_xregset_fpregs_active;
+extern user_regset_active_fn regset_fpregs_active, regset_xregset_fpregs_active,
+				ssp_active;
 extern user_regset_get2_fn fpregs_get, xfpregs_get, fpregs_soft_get,
-				 xstateregs_get;
+				 xstateregs_get, ssp_get;
 extern user_regset_set_fn fpregs_set, xfpregs_set, fpregs_soft_set,
-				 xstateregs_set;
+				 xstateregs_set, ssp_set;
 
 /*
  * xstateregs_active == regset_fpregs_active. Please refer to the comment
arch/x86/kernel/fpu/regset.c +87 -0

99 lines not on this page · raw message

arch/x86/kernel/ptrace.c +12 -0
index dfaa270a7cc9..095f04bdabdc 100644
@@ -58,6 +58,7 @@ enum x86_regset_64 {
 	REGSET64_FP,
 	REGSET64_IOPERM,
 	REGSET64_XSTATE,
+	REGSET64_SSP,
 };
 
 #define REGSET_GENERAL \
@@ -1267,6 +1268,17 @@ static struct user_regset x86_64_regsets[] __ro_after_init = {
 		.active		= ioperm_active,
 		.regset_get	= ioperm_get
 	},
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+	[REGSET64_SSP] = {
+		.core_note_type	= NT_X86_SHSTK,
+		.n		= 1,
+		.size		= sizeof(u64),
+		.align		= sizeof(u64),
+		.active		= ssp_active,
+		.regset_get	= ssp_get,
+		.set		= ssp_set
+	},
+#endif
 };
 
 static const struct user_regset_view user_x86_64_view = {
include/uapi/linux/elf.h +2 -0
index c7b056af9ef0..e9283f0641c4 100644
@@ -406,6 +406,8 @@ typedef struct elf64_shdr {
 #define NT_386_TLS	0x200		/* i386 TLS slots (struct user_desc) */
 #define NT_386_IOPERM	0x201		/* x86 io permission bitmap (1=deny) */
 #define NT_X86_XSTATE	0x202		/* x86 extended state using xsave */
+/* Old binutils treats 0x203 as a CET state */
+#define NT_X86_SHSTK	0x204		/* x86 SHSTK state */
 #define NT_S390_HIGH_GPRS	0x300	/* s390 upper register halves */
 #define NT_S390_TIMER	0x301		/* s390 timer register */
 #define NT_S390_TODCMP	0x302		/* s390 TOD clock comparator register */
Signature · 1 line
2.17.1
Reviewed-by on v4 37/39
#100 lore raw

Re: [PATCH v4 37/39] x86: Add PTRACE interface for shadow stack

Quoted 42 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Some applications (like GDB) would like to tweak shadow stack state via ptrace. This allows for existing functionality to continue to work for seized shadow stack applications. Provide an regset interface for manipulating the shadow stack pointer (SSP).

There is already ptrace functionality for accessing xstate, but this does not include supervisor xfeatures. So there is not a completely clear place for where to put the shadow stack state. Adding it to the user xfeatures regset would complicate that code, as it currently shares logic with signals which should not have supervisor features.

Don't add a general supervisor xfeature regset like the user one, because it is better to maintain flexibility for other supervisor xfeatures to define their own interface. For example, an xfeature may decide not to expose all of it's state to userspace, as is actually the case for shadow stack ptrace functionality. A lot of enum values remain to be used, so just put it in dedicated shadow stack regset.

The only downside to not having a generic supervisor xfeature regset, is that apps need to be enlightened of any new supervisor xfeature exposed this way (i.e. they can't try to have generic save/restore logic). But maybe that is a good thing, because they have to think through each new xfeature instead of encountering issues when new a new supervisor xfeature was added.

By adding a shadow stack regset, it also has the effect of including the shadow stack state in a core dump, which could be useful for debugging.

The shadow stack specific xstate includes the SSP, and the shadow stack and WRSS enablement status. Enabling shadow stack or wrss in the kernel involves more than just flipping the bit. The kernel is made aware that it has to do extra things when cloning or handling signals. That logic is triggered off of separate feature enablement state kept in the task struct. So the flipping on HW shadow stack enforcement without notifying the kernel to change its behavior would severely limit what an application could do without crashing, and the results would depend on kernel internal implementation details. There is also no known use for controlling this state via prtace today. So only expose the SSP, which is something that userspace already has indirect control over.

Quoted 4 lines
Signature · 1 line
Kees Cook
maintainer
#101 lore raw

Re: [PATCH v4 37/39] x86: Add PTRACE interface for shadow stack

In reply to Rick Edgecombe

Hi Rick,

Quoted 108 lines · Rick Edgecombe

From: Yu-cheng Yu <[email protected]>

Some applications (like GDB) would like to tweak shadow stack state via ptrace. This allows for existing functionality to continue to work for seized shadow stack applications. Provide an regset interface for manipulating the shadow stack pointer (SSP).

There is already ptrace functionality for accessing xstate, but this does not include supervisor xfeatures. So there is not a completely clear place for where to put the shadow stack state. Adding it to the user xfeatures regset would complicate that code, as it currently shares logic with signals which should not have supervisor features.

Don't add a general supervisor xfeature regset like the user one, because it is better to maintain flexibility for other supervisor xfeatures to define their own interface. For example, an xfeature may decide not to expose all of it's state to userspace, as is actually the case for shadow stack ptrace functionality. A lot of enum values remain to be used, so just put it in dedicated shadow stack regset.

The only downside to not having a generic supervisor xfeature regset, is that apps need to be enlightened of any new supervisor xfeature exposed this way (i.e. they can't try to have generic save/restore logic). But maybe that is a good thing, because they have to think through each new xfeature instead of encountering issues when new a new supervisor xfeature was added.

By adding a shadow stack regset, it also has the effect of including the shadow stack state in a core dump, which could be useful for debugging.

The shadow stack specific xstate includes the SSP, and the shadow stack and WRSS enablement status. Enabling shadow stack or wrss in the kernel involves more than just flipping the bit. The kernel is made aware that it has to do extra things when cloning or handling signals. That logic is triggered off of separate feature enablement state kept in the task struct. So the flipping on HW shadow stack enforcement without notifying the kernel to change its behavior would severely limit what an application could do without crashing, and the results would depend on kernel internal implementation details. There is also no known use for controlling this state via prtace today. So only expose the SSP, which is something that userspace already has indirect control over.

---

v4:
- Make shadow stack only. Reduce to only supporting SSP register, and remove CET references (peterz)
- Add comment to not use 0x203, becuase binutils already looks for it in coredumps. (Christina Schimpe)

v3:
- Drop dependence on thread.shstk.size, and use thread.features bits
- Drop 32 bit support

v2:
- Check alignment on ssp.
- Block IBT bits.
- Handle init states instead of returning error.
- Add verbose commit log justifying the design.

Yu-Cheng v12:
- Return -ENODEV when CET registers are in INIT state.
- Check reserved/non-support bits from user input.

 arch/x86/include/asm/fpu/regset.h |  7 +--
 arch/x86/kernel/fpu/regset.c      | 87 +++++++++++++++++++++++++++++++
 arch/x86/kernel/ptrace.c          | 12 +++++
 include/uapi/linux/elf.h          |  2 +
 4 files changed, 105 insertions(+), 3 deletions(-)
arch/x86/include/asm/fpu/regset.h +4 -3
index 4f928d6a367b..697b77e96025 100644
@@ -7,11 +7,12 @@
 
 #include <linux/regset.h>
 
-extern user_regset_active_fn regset_fpregs_active, regset_xregset_fpregs_active;
+extern user_regset_active_fn regset_fpregs_active, regset_xregset_fpregs_active,
+				ssp_active;
 extern user_regset_get2_fn fpregs_get, xfpregs_get, fpregs_soft_get,
-				 xstateregs_get;
+				 xstateregs_get, ssp_get;
 extern user_regset_set_fn fpregs_set, xfpregs_set, fpregs_soft_set,
-				 xstateregs_set;
+				 xstateregs_set, ssp_set;
 
 /*
  * xstateregs_active == regset_fpregs_active. Please refer to the comment
arch/x86/kernel/fpu/regset.c +1 -0
index 6d056b68f4ed..00f3d5c9b682 100644
@@ -8,6 +8,7 @@
 #include <asm/fpu/api.h>
 #include <asm/fpu/signal.h>
 #include <asm/fpu/regset.h>
+#include <asm/prctl.h>
 
 #include "context.h"
 #include "internal.h"

arch/x86/kernel/fpu/regset.c int xstateregs_set(struct task_struct *target, const struct user_regset *regset, · line 182

Quoted 8 lines
arch/x86/kernel/fpu/regset.c +5 -0
@@ -174,6 +175,92 @@ int xstateregs_set(struct task_struct *target, const struct user_regset *regset,
 	return ret;
 }
 
+
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+int ssp_active(struct task_struct *target, const struct user_regset *regset)
+{
+	if (shstk_enabled())

This is not going to work with ptrace as shstk_enabled() checks current rather than target.

Quoted 130 lines
arch/x86/kernel/fpu/regset.c +81 -0
+		return regset->n;
+
+	return 0;
+}
+
+int ssp_get(struct task_struct *target, const struct user_regset *regset,
+		struct membuf to)
+{
+	struct fpu *fpu = &target->thread.fpu;
+	struct cet_user_state *cetregs;
+
+	if (!boot_cpu_has(X86_FEATURE_USER_SHSTK))
+		return -ENODEV;
+
+	sync_fpstate(fpu);
+	cetregs = get_xsave_addr(&fpu->fpstate->regs.xsave, XFEATURE_CET_USER);
+	if (!cetregs) {
+		/*
+		 * The registers are the in the init state. The init values for
+		 * these regs are zero, so just zero the output buffer.
+		 */
+		membuf_zero(&to, sizeof(cetregs->user_ssp));
+		return 0;
+	}
+
+	return membuf_write(&to, (unsigned long *)&cetregs->user_ssp,
+			    sizeof(cetregs->user_ssp));
+}
+
+int ssp_set(struct task_struct *target, const struct user_regset *regset,
+		  unsigned int pos, unsigned int count,
+		  const void *kbuf, const void __user *ubuf)
+{
+	struct fpu *fpu = &target->thread.fpu;
+	struct xregs_state *xsave = &fpu->fpstate->regs.xsave;
+	struct cet_user_state *cetregs;
+	unsigned long user_ssp;
+	int r;
+
+	if (!boot_cpu_has(X86_FEATURE_USER_SHSTK) ||
+	    !ssp_active(target, regset))
+		return -ENODEV;
+
+	r = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &user_ssp, 0, -1);
+	if (r)
+		return r;
+
+	/*
+	 * Some kernel instructions (IRET, etc) can cause exceptions in the case
+	 * of disallowed CET register values. Just prevent invalid values.
+	 */
+	if ((user_ssp >= TASK_SIZE_MAX) || !IS_ALIGNED(user_ssp, 8))
+		return -EINVAL;
+
+	fpu_force_restore(fpu);
+
+	/*
+	 * Don't want to init the xfeature until the kernel will definetely
+	 * overwrite it, otherwise if it inits and then fails out, it would
+	 * end up initing it to random data.
+	 */
+	if (!xfeature_saved(xsave, XFEATURE_CET_USER) &&
+	    WARN_ON(init_xfeature(xsave, XFEATURE_CET_USER)))
+		return -ENODEV;
+
+	cetregs = get_xsave_addr(xsave, XFEATURE_CET_USER);
+	if (WARN_ON(!cetregs)) {
+		/*
+		 * This shouldn't ever be NULL because it was successfully
+		 * inited above if needed. The only scenario would be if an
+		 * xfeature was somehow saved in a buffer, but not enabled in
+		 * xsave.
+		 */
+		return -ENODEV;
+	}
+
+	cetregs->user_ssp = user_ssp;
+	return 0;
+}
+#endif /* CONFIG_X86_USER_SHADOW_STACK */
+
 #if defined CONFIG_X86_32 || defined CONFIG_IA32_EMULATION
 
 /*
arch/x86/kernel/ptrace.c +12 -0
index dfaa270a7cc9..095f04bdabdc 100644
@@ -58,6 +58,7 @@ enum x86_regset_64 {
 	REGSET64_FP,
 	REGSET64_IOPERM,
 	REGSET64_XSTATE,
+	REGSET64_SSP,
 };
 
 #define REGSET_GENERAL \
@@ -1267,6 +1268,17 @@ static struct user_regset x86_64_regsets[] __ro_after_init = {
 		.active		= ioperm_active,
 		.regset_get	= ioperm_get
 	},
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+	[REGSET64_SSP] = {
+		.core_note_type	= NT_X86_SHSTK,
+		.n		= 1,
+		.size		= sizeof(u64),
+		.align		= sizeof(u64),
+		.active		= ssp_active,
+		.regset_get	= ssp_get,
+		.set		= ssp_set
+	},
+#endif
 };
 
 static const struct user_regset_view user_x86_64_view = {
include/uapi/linux/elf.h +2 -0
index c7b056af9ef0..e9283f0641c4 100644
@@ -406,6 +406,8 @@ typedef struct elf64_shdr {
 #define NT_386_TLS	0x200		/* i386 TLS slots (struct user_desc) */
 #define NT_386_IOPERM	0x201		/* x86 io permission bitmap (1=deny) */
 #define NT_X86_XSTATE	0x202		/* x86 extended state using xsave */
+/* Old binutils treats 0x203 as a CET state */
+#define NT_X86_SHSTK	0x204		/* x86 SHSTK state */
 #define NT_S390_HIGH_GPRS	0x300	/* s390 upper register halves */
 #define NT_S390_TIMER	0x301		/* s390 timer register */
 #define NT_S390_TODCMP	0x302		/* s390 TOD clock comparator register */
Signature · 1 line
2.17.1
Signature · 2 lines
Sincerely yours,
Mike.
#102 lore raw

Re: [PATCH v4 37/39] x86: Add PTRACE interface for shadow stack

Quoted 21 lines · Mike Rapoport
Quoted 21 lines

/*
* xstateregs_active == regset_fpregs_active. Please refer to the
comment

arch/x86/kernel/fpu/regset.c +1 -0
index 6d056b68f4ed..00f3d5c9b682 100644
@@ -8,6 +8,7 @@
  #include <asm/fpu/api.h>
  #include <asm/fpu/signal.h>
  #include <asm/fpu/regset.h>
+#include <asm/prctl.h>
 
  #include "context.h"
  #include "internal.h"
@@ -174,6 +175,92 @@ int xstateregs_set(struct task_struct *target,
 const struct user_regset *regset,
       return ret;
  }
 
Quoted 10 lines

arch/x86/kernel/fpu/regset.c int xstateregs_set(struct task_struct *target, const struct user_regset *regset, · line 182

Quoted 6 lines
arch/x86/kernel/fpu/regset.c +5 -0
+
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+int ssp_active(struct task_struct *target, const struct
 user_regset *regset)
+{
+     if (shstk_enabled())

This is not going to work with ptrace as shstk_enabled() checks current
rather than target.

Oh right, thanks. I can change shstk_enabled() to take a task_struct.

#103 lore raw

PATCH v4 38/39 x86/shstk: Add ARCH_SHSTK_UNLOCK

In reply to Rick Edgecombe

From: Mike Rapoport <[email protected]>

Userspace loaders may lock features before a CRIU restore operation has the chance to set them to whatever state is required by the process being restored. Allow a way for CRIU to unlock features. Add it as an arch_prctl() like the other shadow stack operations, but restrict it being called by the ptrace arch_pctl() interface.

[Merged into recent API changes, added commit log and docs]

---

v4:
- Add to docs that it is ptrace only.
- Remove "CET" references

v3:
- Depend on CONFIG_CHECKPOINT_RESTORE (Kees)

 Documentation/x86/shstk.rst       | 4 ++++
 arch/x86/include/uapi/asm/prctl.h | 1 +
 arch/x86/kernel/process_64.c      | 1 +
 arch/x86/kernel/shstk.c           | 9 +++++++--
 4 files changed, 13 insertions(+), 2 deletions(-)
Documentation/x86/shstk.rst +4 -0
index 8e0b2fe83ef8..0d7d1ccfff06 100644
@@ -73,6 +73,10 @@ arch_prctl(ARCH_SHSTK_LOCK, unsigned long features)
     are ignored. The mask is ORed with the existing value. So any feature bits
     set here cannot be enabled or disabled afterwards.
 
+arch_prctl(ARCH_SHSTK_UNLOCK, unsigned long features)
+    Unlock features. 'features' is a mask of all features to unlock. All
+    bits set are processed, unset bits are ignored. Only works via ptrace.
+
 The return values are as following:
     On success, return 0. On error, errno can be::
 
arch/x86/include/uapi/asm/prctl.h +1 -0
index f13751c6bae4..0c95688cf58e 100644
@@ -30,6 +30,7 @@
 #define ARCH_SHSTK_ENABLE		0x5001
 #define ARCH_SHSTK_DISABLE		0x5002
 #define ARCH_SHSTK_LOCK			0x5003
+#define ARCH_SHSTK_UNLOCK		0x5004
 
 /* ARCH_SHSTK_ features bits */
 #define ARCH_SHSTK_SHSTK		(1ULL <<  0)
arch/x86/kernel/process_64.c +1 -0
index 4ddd7d9209e1..2be6e01fb144 100644
@@ -921,6 +921,7 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2)
 	case ARCH_SHSTK_ENABLE:
 	case ARCH_SHSTK_DISABLE:
 	case ARCH_SHSTK_LOCK:
+	case ARCH_SHSTK_UNLOCK:
 		return shstk_prctl(task, option, arg2);
 	default:
 		ret = -EINVAL;
arch/x86/kernel/shstk.c +7 -2
index 5d91e653f77a..95579f7bace3 100644
@@ -455,9 +455,14 @@ long shstk_prctl(struct task_struct *task, int option, unsigned long features)
 		return 0;
 	}
 
-	/* Don't allow via ptrace */
-	if (task != current)
+	/* Only allow via ptrace */
+	if (task != current) {
+		if (option == ARCH_SHSTK_UNLOCK && IS_ENABLED(CONFIG_CHECKPOINT_RESTORE)) {
+			task->thread.features_locked &= ~features;
+			return 0;
+		}
 		return -EINVAL;
+	}
 
 	/* Do not allow to change locked features */
 	if (features & task->thread.features_locked)
Signature · 1 line
2.17.1
Reviewed-by on v4 38/39
#104 lore raw

Re: [PATCH v4 38/39] x86/shstk: Add ARCH_SHSTK_UNLOCK

Quoted 11 lines · Rick Edgecombe

From: Mike Rapoport <[email protected]>

Userspace loaders may lock features before a CRIU restore operation has the chance to set them to whatever state is required by the process being restored. Allow a way for CRIU to unlock features. Add it as an arch_prctl() like the other shadow stack operations, but restrict it being called by the ptrace arch_pctl() interface.

Signature · 1 line
Kees Cook
#105 lore raw

PATCH v4 39/39 x86/shstk: Add ARCH_SHSTK_STATUS

In reply to Rick Edgecombe

CRIU and GDB need to get the current shadow stack and WRSS enablement status. This information is already available via /proc/pid/status, but this is incovienent for CRIU because it involves parsing the text output in an area of the code where this is difficult. Provide a status arch_prctl(), ARCH_SHSTK_STATUS for retrieving the status. Have arg2 be a userspace address, and make the new arch_prctl simply copy the features out to userspace.

---

v4:
- New patch

 Documentation/x86/shstk.rst       | 6 ++++++
 arch/x86/include/asm/shstk.h      | 4 ++--
 arch/x86/include/uapi/asm/prctl.h | 1 +
 arch/x86/kernel/process_64.c      | 1 +
 arch/x86/kernel/shstk.c           | 8 +++++++-
 5 files changed, 17 insertions(+), 3 deletions(-)
Documentation/x86/shstk.rst +6 -0
index 0d7d1ccfff06..b3eb87046c27 100644
@@ -77,6 +77,11 @@ arch_prctl(ARCH_SHSTK_UNLOCK, unsigned long features)
     Unlock features. 'features' is a mask of all features to unlock. All
     bits set are processed, unset bits are ignored. Only works via ptrace.
 
+arch_prctl(ARCH_SHSTK_STATUS, unsigned long addr)
+    Copy the currently enabled features to the address passed in addr. The
+    features are described using the bits passed into the others in
+    'features'.
+
 The return values are as following:
     On success, return 0. On error, errno can be::
 
@@ -84,6 +89,7 @@ The return values are as following:
         -EOPNOTSUPP if the feature is not supported by the hardware or
          disabled by kernel parameter.
         -EINVAL arguments (non existing feature, etc)
+        -EFAULT if could not copy information back to userspace
 
 The feature's bits supported are::
 
arch/x86/include/asm/shstk.h +2 -2
index c82f22fd5e6d..23bfb63c597d 100644
@@ -15,7 +15,7 @@ struct thread_shstk {
 	u64	size;
 };
 
-long shstk_prctl(struct task_struct *task, int option, unsigned long features);
+long shstk_prctl(struct task_struct *task, int option, unsigned long arg2);
 void reset_thread_features(void);
 int shstk_alloc_thread_stack(struct task_struct *p, unsigned long clone_flags,
 			     unsigned long stack_size,
@@ -31,7 +31,7 @@ static inline bool shstk_enabled(void)
 }
 #else
 static inline long shstk_prctl(struct task_struct *task, int option,
-			     unsigned long features) { return -EINVAL; }
+			     unsigned long arg2) { return -EINVAL; }
 static inline void reset_thread_features(void) {}
 static inline int shstk_alloc_thread_stack(struct task_struct *p,
 					   unsigned long clone_flags,
arch/x86/include/uapi/asm/prctl.h +1 -0
index 0c95688cf58e..abe3fe6db6d2 100644
@@ -31,6 +31,7 @@
 #define ARCH_SHSTK_DISABLE		0x5002
 #define ARCH_SHSTK_LOCK			0x5003
 #define ARCH_SHSTK_UNLOCK		0x5004
+#define ARCH_SHSTK_STATUS		0x5005
 
 /* ARCH_SHSTK_ features bits */
 #define ARCH_SHSTK_SHSTK		(1ULL <<  0)
arch/x86/kernel/process_64.c +1 -0
index 2be6e01fb144..5dcf5426241b 100644
@@ -922,6 +922,7 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2)
 	case ARCH_SHSTK_DISABLE:
 	case ARCH_SHSTK_LOCK:
 	case ARCH_SHSTK_UNLOCK:
+	case ARCH_SHSTK_STATUS:
 		return shstk_prctl(task, option, arg2);
 	default:
 		ret = -EINVAL;
arch/x86/kernel/shstk.c +7 -1
index 95579f7bace3..05f8dcc19dbc 100644
@@ -448,8 +448,14 @@ SYSCALL_DEFINE3(map_shadow_stack, unsigned long, addr, unsigned long, size, unsi
 	return alloc_shstk(addr, aligned_size, size, set_tok);
 }
 
-long shstk_prctl(struct task_struct *task, int option, unsigned long features)
+long shstk_prctl(struct task_struct *task, int option, unsigned long arg2)
 {
+	unsigned long features = arg2;
+
+	if (option == ARCH_SHSTK_STATUS) {
+		return put_user(task->thread.features, (unsigned long __user *)arg2);
+	}
+
 	if (option == ARCH_SHSTK_LOCK) {
 		task->thread.features_locked |= features;
 		return 0;
Signature · 1 line
2.17.1
Reviewed-by on v4 39/39
#106 lore raw

Re: [PATCH v4 39/39] x86/shstk: Add ARCH_SHSTK_STATUS

Quoted 99 lines · Rick Edgecombe

CRIU and GDB need to get the current shadow stack and WRSS enablement status. This information is already available via /proc/pid/status, but this is incovienent for CRIU because it involves parsing the text output in an area of the code where this is difficult. Provide a status arch_prctl(), ARCH_SHSTK_STATUS for retrieving the status. Have arg2 be a userspace address, and make the new arch_prctl simply copy the features out to userspace.

---

v4:
- New patch

 Documentation/x86/shstk.rst       | 6 ++++++
 arch/x86/include/asm/shstk.h      | 4 ++--
 arch/x86/include/uapi/asm/prctl.h | 1 +
 arch/x86/kernel/process_64.c      | 1 +
 arch/x86/kernel/shstk.c           | 8 +++++++-
 5 files changed, 17 insertions(+), 3 deletions(-)
Documentation/x86/shstk.rst +6 -0
index 0d7d1ccfff06..b3eb87046c27 100644
@@ -77,6 +77,11 @@ arch_prctl(ARCH_SHSTK_UNLOCK, unsigned long features)
     Unlock features. 'features' is a mask of all features to unlock. All
     bits set are processed, unset bits are ignored. Only works via ptrace.
 
+arch_prctl(ARCH_SHSTK_STATUS, unsigned long addr)
+    Copy the currently enabled features to the address passed in addr. The
+    features are described using the bits passed into the others in
+    'features'.
+
 The return values are as following:
     On success, return 0. On error, errno can be::
 
@@ -84,6 +89,7 @@ The return values are as following:
         -EOPNOTSUPP if the feature is not supported by the hardware or
          disabled by kernel parameter.
         -EINVAL arguments (non existing feature, etc)
+        -EFAULT if could not copy information back to userspace
 
 The feature's bits supported are::
 
arch/x86/include/asm/shstk.h +2 -2
index c82f22fd5e6d..23bfb63c597d 100644
@@ -15,7 +15,7 @@ struct thread_shstk {
 	u64	size;
 };
 
-long shstk_prctl(struct task_struct *task, int option, unsigned long features);
+long shstk_prctl(struct task_struct *task, int option, unsigned long arg2);
 void reset_thread_features(void);
 int shstk_alloc_thread_stack(struct task_struct *p, unsigned long clone_flags,
 			     unsigned long stack_size,
@@ -31,7 +31,7 @@ static inline bool shstk_enabled(void)
 }
 #else
 static inline long shstk_prctl(struct task_struct *task, int option,
-			     unsigned long features) { return -EINVAL; }
+			     unsigned long arg2) { return -EINVAL; }
 static inline void reset_thread_features(void) {}
 static inline int shstk_alloc_thread_stack(struct task_struct *p,
 					   unsigned long clone_flags,
arch/x86/include/uapi/asm/prctl.h +1 -0
index 0c95688cf58e..abe3fe6db6d2 100644
@@ -31,6 +31,7 @@
 #define ARCH_SHSTK_DISABLE		0x5002
 #define ARCH_SHSTK_LOCK			0x5003
 #define ARCH_SHSTK_UNLOCK		0x5004
+#define ARCH_SHSTK_STATUS		0x5005
 
 /* ARCH_SHSTK_ features bits */
 #define ARCH_SHSTK_SHSTK		(1ULL <<  0)
arch/x86/kernel/process_64.c +1 -0
index 2be6e01fb144..5dcf5426241b 100644
@@ -922,6 +922,7 @@ long do_arch_prctl_64(struct task_struct *task, int option, unsigned long arg2)
 	case ARCH_SHSTK_DISABLE:
 	case ARCH_SHSTK_LOCK:
 	case ARCH_SHSTK_UNLOCK:
+	case ARCH_SHSTK_STATUS:
 		return shstk_prctl(task, option, arg2);
 	default:
 		ret = -EINVAL;
arch/x86/kernel/shstk.c +0 -0
index 95579f7bace3..05f8dcc19dbc 100644
@@ -448,8 +448,14 @@ SYSCALL_DEFINE3(map_shadow_stack, unsigned long, addr, unsigned long, size, unsi
 	return alloc_shstk(addr, aligned_size, size, set_tok);

arch/x86/kernel/shstk.c SYSCALL_DEFINE3(map_shadow_stack, unsigned long, addr, unsigned long, size, unsi · line 457

Quoted 10 lines
arch/x86/kernel/shstk.c +6 -1
 }
 
-long shstk_prctl(struct task_struct *task, int option, unsigned long features)
+long shstk_prctl(struct task_struct *task, int option, unsigned long arg2)
 {
+	unsigned long features = arg2;
+
+	if (option == ARCH_SHSTK_STATUS) {
+		return put_user(task->thread.features, (unsigned long __user *)arg2);
+	}

Doesn't need the braces, but that's fine by me.

Quoted 7 lines
arch/x86/kernel/shstk.c +1 -0
+
 	if (option == ARCH_SHSTK_LOCK) {
 		task->thread.features_locked |= features;
 		return 0;
Signature · 1 line
2.17.1
Signature · 1 line
Kees Cook