Shadow Stack provides protection 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.
Signed-off-by: Yu-cheng Yu <redacted>
Cc: Kees Cook <redacted>
---
v25:
- Remove X86_CET and use X86_SHADOW_STACK directly.
v24:
- Update for the splitting X86_CET to X86_SHADOW_STACK and X86_IBT.
---
arch/x86/Kconfig | 22 ++++++++++++++++++++++
arch/x86/Kconfig.assembler | 5 +++++
2 files changed, 27 insertions(+)
@@ -0,0 +1,139 @@+.. SPDX-License-Identifier: GPL-2.0++=========================================+Control-flow Enforcement Technology (CET)+=========================================++[1] Overview+============++Control-flow Enforcement Technology (CET) is an Intel processor feature+that provides protection against return/jump-oriented programming (ROP)+attacks. It can be set up to protect both applications and the kernel.+Only user-mode protection is implemented in the 64-bit kernel, including+shadow stack support for running legacy 32-bit applications. IBT is not+supported for 32-bit applications.++CET introduces Shadow Stack and Indirect Branch Tracking. Shadow stack is+a secondary stack allocated from memory and cannot be directly modified by+applications. When executing a CALL instruction, the processor pushes the+return address to both the normal stack and the shadow stack. Upon+function return, the processor pops the shadow stack copy and compares it+to the normal stack copy. If the two differ, the processor raises a+control-protection fault. Indirect branch tracking verifies indirect+CALL/JMP targets are intended as marked by the compiler with 'ENDBR'+opcodes.++There are two Kconfig options:++ X86_SHADOW_STACK, and X86_IBT.++To build a CET-enabled kernel, Binutils v2.31 and GCC v8.1 or LLVM v10.0.1+or later are required. To build a CET-enabled application, GLIBC v2.28 or+later is also required.++There are two command-line options for disabling CET features::++ no_user_shstk - disables user shadow stack, and+ no_user_ibt - disables user indirect branch tracking.++ Note: Disabling shadow stack also disables IBT.++At run time, /proc/cpuinfo shows CET features if the processor supports+CET.++[2] Application Enabling+========================++An application's CET capability is marked in its ELF header and can be+verified from readelf/llvm-readelf output:++ readelf -n <application> | grep -a SHSTK+ properties: x86 feature: IBT, SHSTK++If an application supports CET and is statically linked, it will run with+CET protection. If the application needs any shared libraries, the loader+checks all dependencies and enables CET when all requirements are met.++[3] Backward Compatibility+==========================++GLIBC provides a few CET tunables via the GLIBC_TUNABLES environment+variable:++GLIBC_TUNABLES=glibc.tune.hwcaps=-SHSTK,-IBT+ Turn off SHSTK/IBT.++GLIBC_TUNABLES=glibc.tune.x86_shstk=<on, permissive>+ This controls how dlopen() handles SHSTK legacy libraries::++ on - continue with SHSTK enabled;+ permissive - continue with SHSTK off.++Details can be found in the GLIBC manual pages.++[4] CET arch_prctl()'s+======================++Several arch_prctl()'s have been added for CET:++arch_prctl(ARCH_X86_CET_STATUS, u64 *addr)+ Return CET feature status.++ The parameter 'addr' is a pointer to a user buffer.+ On returning to the caller, the kernel fills the following+ information::++ *addr = shadow stack/indirect branch tracking status+ *(addr + 1) = shadow stack base address+ *(addr + 2) = shadow stack size++arch_prctl(ARCH_X86_CET_DISABLE, unsigned int features)+ Disable shadow stack and/or indirect branch tracking as specified in+ 'features'. Return -EPERM if CET is locked.++arch_prctl(ARCH_X86_CET_LOCK)+ Lock in all CET features. They cannot be turned off afterwards.++Note:+ There is no CET-enabling arch_prctl function. By design, CET is enabled+ automatically if the binary and the system can support it.++[5] The implementation of the Shadow Stack+==========================================++Shadow Stack size+-----------------++A task's shadow stack is allocated from memory to a fixed size of+MIN(RLIMIT_STACK, 4 GB). In other words, the shadow stack is allocated to+the maximum size of the normal stack, but capped to 4 GB. However,+a compat-mode application's address space is smaller, each of its thread's+shadow stack size is MIN(1/4 RLIMIT_STACK, 4 GB).++Signal+------++The main program and its signal handlers use the same shadow stack.+Because the shadow stack stores only return addresses, a large shadow+stack covers the condition that both the program stack and the signal+alternate stack run out.++The kernel creates a restore token for the shadow stack restoring address+and verifies that token when restoring from the signal handler.++Fork+----++The shadow stack's vma has VM_SHADOW_STACK flag set; its PTEs are required+to be read-only and dirty. When a shadow stack PTE is not RO and dirty, a+shadow access triggers a page fault with the shadow stack access bit set+in the page fault error code.++When a task forks a child, its shadow stack PTEs are copied and both the+parent's and the child's shadow stack PTEs are cleared of the dirty bit.+Upon the next shadow stack access, the resulting shadow stack page fault+is handled by page copy/re-use.++When a pthread child is created, the kernel allocates a new shadow stack+for the new thread.
Control-flow Enforcement Technology (CET) introduces these MSRs:
MSR_IA32_U_CET (user-mode CET settings),
MSR_IA32_PL3_SSP (user-mode shadow stack pointer),
MSR_IA32_PL0_SSP (kernel-mode shadow stack pointer),
MSR_IA32_PL1_SSP (Privilege Level 1 shadow stack pointer),
MSR_IA32_PL2_SSP (Privilege Level 2 shadow stack pointer),
MSR_IA32_S_CET (kernel-mode CET settings),
MSR_IA32_INT_SSP_TAB (exception shadow stack table).
The two user-mode MSRs belong to XFEATURE_CET_USER. The first three of
kernel-mode MSRs belong to XFEATURE_CET_KERNEL. Both XSAVES states are
supervisor states. This means that there is no direct, unprivileged access
to these states, making it harder for an attacker to subvert CET.
For sigreturn and future ptrace() support, shadow stack address and MSR
reserved bits are checked before written to the supervisor states.
Signed-off-by: Yu-cheng Yu <redacted>
Cc: Kees Cook <redacted>
---
v29:
- Move CET MSR definition up in msr-index.h.
v28:
- Add XFEATURE_MASK_CET_USER to XFEATURES_INIT_FPSTATE_HANDLED.
v25:
- Update xsave_cpuid_features[]. Now CET XSAVES features depend on
X86_FEATURE_SHSTK (vs. the software-defined X86_FEATURE_CET).
---
arch/x86/include/asm/fpu/types.h | 23 +++++++++++++++++++++--
arch/x86/include/asm/fpu/xstate.h | 6 ++++--
arch/x86/include/asm/msr-index.h | 20 ++++++++++++++++++++
arch/x86/kernel/fpu/xstate.c | 11 ++++++++++-
4 files changed, 55 insertions(+), 5 deletions(-)
@@ -44,7 +44,8 @@(XFEATURE_MASK_USER_SUPPORTED&~XFEATURE_MASK_PKRU)/* 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)/**Asupervisorstatecomponentmaynotalwayscontainvaluableinformation,
@@ -71,7 +72,8 @@*Unsupportedsupervisorfeatures.Whenasupervisorfeatureinthismaskis*supportedinthefuture,moveittothesupportedsupervisorfeaturemask.*/-#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 | \
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; or an indirect JMP instruction, without the NOTRACK
prefix, arrives at a non-ENDBR opcode.
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.
Signed-off-by: Yu-cheng Yu <redacted>
Cc: Kees Cook <redacted>
Cc: Michael Kerrisk <redacted>
---
v29:
- Remove pr_emerg() since it is followed by die().
- Change boot_cpu_has() to cpu_feature_enabled().
v25:
- Change CONFIG_X86_CET to CONFIG_X86_SHADOW_STACK.
- Change X86_FEATURE_CET to X86_FEATURE_SHSTK.
---
arch/x86/include/asm/idtentry.h | 4 ++
arch/x86/kernel/idt.c | 4 ++
arch/x86/kernel/signal_compat.c | 2 +-
arch/x86/kernel/traps.c | 62 ++++++++++++++++++++++++++++++
include/uapi/asm-generic/siginfo.h | 3 +-
5 files changed, 73 insertions(+), 2 deletions(-)
@@ -562,6 +562,10 @@ DECLARE_IDTENTRY_ERRORCODE(X86_TRAP_SS, exc_stack_segment);DECLARE_IDTENTRY_ERRORCODE(X86_TRAP_GP,exc_general_protection);DECLARE_IDTENTRY_ERRORCODE(X86_TRAP_AC,exc_alignment_check);+#ifdef CONFIG_X86_SHADOW_STACK+DECLARE_IDTENTRY_ERRORCODE(X86_TRAP_CP,exc_control_protection);+#endif+/* Raw exception entries which need extra work */DECLARE_IDTENTRY_RAW(X86_TRAP_UD,exc_invalid_op);DECLARE_IDTENTRY_RAW(X86_TRAP_BP,exc_int3);
@@ -607,6 +608,67 @@ DEFINE_IDTENTRY_ERRORCODE(exc_general_protection)cond_local_irq_disable(regs);}+#ifdef CONFIG_X86_SHADOW_STACK+staticconstchar*constcontrol_protection_err[]={+"unknown",+"near-ret",+"far-ret/iret",+"endbranch",+"rstorssp",+"setssbsy",+"unknown",+};++staticDEFINE_RATELIMIT_STATE(cpf_rate,DEFAULT_RATELIMIT_INTERVAL,+DEFAULT_RATELIMIT_BURST);++/*+*Whenacontrolprotectionexceptionoccurs,sendasignaltotheresponsible+*application.Currently,controlprotectionisonlyenabledforusermode.+*Thisexceptionshouldnotcomefromkernelmode.+*/+DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)+{+structtask_struct*tsk;++if(!user_mode(regs)){+die("kernel control protection fault",regs,error_code);+panic("Unexpected kernel control protection fault. Machine halted.");+}++cond_local_irq_enable(regs);++if(!cpu_feature_enabled(X86_FEATURE_SHSTK))+WARN_ONCE(1,"Control protection fault with CET support disabled\n");++tsk=current;+tsk->thread.error_code=error_code;+tsk->thread.trap_nr=X86_TRAP_CP;++/*+*Ratelimittopreventlogspamming.+*/+if(show_unhandled_signals&&unhandled_signal(tsk,SIGSEGV)&&+__ratelimit(&cpf_rate)){+unsignedlongssp;+intcpf_type;++cpf_type=array_index_nospec(error_code,ARRAY_SIZE(control_protection_err));++rdmsrl(MSR_IA32_PL3_SSP,ssp);+pr_emerg("%s[%d] control protection ip:%lx sp:%lx ssp:%lx error:%lx(%s)",+tsk->comm,task_pid_nr(tsk),+regs->ip,regs->sp,ssp,error_code,+control_protection_err[cpf_type]);+print_vma_addr(KERN_CONT" in ",regs->ip);+pr_cont("\n");+}++force_sig_fault(SIGSEGV,SEGV_CPERR,(void__user*)0);+cond_local_irq_disable(regs);+}+#endif+staticbooldo_int3(structpt_regs*regs){intres;
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.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
---
arch/x86/include/asm/pgtable.h | 24 ++++++++++++------------
1 file changed, 12 insertions(+), 12 deletions(-)
The x86 family of processors do not directly create read-only and Dirty
PTEs. These PTEs are created by software. One such case is that kernel
read-only pages are historically setup as Dirty.
New processors that support Shadow Stack regard read-only and Dirty PTEs as
shadow stack pages. This results in ambiguity between shadow stack and
kernel read-only pages. To resolve this, removed Dirty from kernel read-
only pages.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: "H. Peter Anvin" <hpa@zytor.com>
Cc: Kees Cook <redacted>
Cc: Thomas Gleixner <redacted>
Cc: Dave Hansen <dave.hansen@linux.intel.com>
Cc: Christoph Hellwig <hch@lst.de>
Cc: Andy Lutomirski <luto@kernel.org>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: Borislav Petkov <bp@alien8.de>
Cc: Peter Zijlstra <peterz@infradead.org>
---
arch/x86/include/asm/pgtable_types.h | 6 +++---
arch/x86/mm/pat/set_memory.c | 2 +-
2 files changed, 4 insertions(+), 4 deletions(-)
@@ -1940,7 +1940,7 @@ int set_memory_nx(unsigned long addr, int numpages)intset_memory_ro(unsignedlongaddr,intnumpages){-returnchange_page_attr_clear(&addr,numpages,__pgprot(_PAGE_RW),0);+returnchange_page_attr_clear(&addr,numpages,__pgprot(_PAGE_RW|_PAGE_DIRTY),0);}intset_memory_rw(unsignedlongaddr,intnumpages)
There is essentially no room left in the x86 hardware PTEs on some OSes
(not 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.
The reason it's lightly used is that Dirty=1 is normally set by hardware
and cannot normally be set by hardware on a Write=0 PTE. Software must
normally be involved to create one of these PTEs, so software can simply
opt to not create them.
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. This
clearly separates shadow stack from other data, and results in the
following:
(a) A modified, copy-on-write (COW) page: (Write=0, Cow=1)
(b) A R/O page that has been COW'ed: (Write=0, Cow=1)
The user page is in a R/O VMA, and get_user_pages() 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.
(c) A shadow stack PTE: (Write=0, Dirty=1)
(d) A shared shadow stack PTE: (Write=0, Cow=1)
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.
(e) A page where the processor observed a Write=1 PTE, started a write, set
Dirty=1, but then observed a Write=0 PTE. That's possible today, but
will not happen on processors that support shadow stack.
Define _PAGE_COW and update pte_*() helpers and apply the same changes to
pmd and pud.
After this, there are six free bits left in the 64-bit PTE, and no more
free bits in the 32-bit PTE (except for PAE) and Shadow Stack is not
implemented for the 32-bit kernel.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
---
arch/x86/include/asm/pgtable.h | 196 ++++++++++++++++++++++++---
arch/x86/include/asm/pgtable_types.h | 42 +++++-
2 files changed, 217 insertions(+), 21 deletions(-)
@@ -21,7 +21,8 @@#define _PAGE_BIT_SOFTW2 10 /* " */#define _PAGE_BIT_SOFTW3 11 /* " */#define _PAGE_BIT_PAT_LARGE 12 /* On 2MB or 1GB pages */-#define _PAGE_BIT_SOFTW4 58 /* available for programmer */+#define _PAGE_BIT_SOFTW4 57 /* available for programmer */+#define _PAGE_BIT_SOFTW5 58 /* available for programmer */#define _PAGE_BIT_PKEY_BIT0 59 /* Protection Keys, bit 1/4 */#define _PAGE_BIT_PKEY_BIT1 60 /* Protection Keys, bit 2/4 */#define _PAGE_BIT_PKEY_BIT2 61 /* Protection Keys, bit 3/4 */
@@ -34,6 +35,15 @@#define _PAGE_BIT_SOFT_DIRTY _PAGE_BIT_SOFTW3 /* software dirty tracking */#define _PAGE_BIT_DEVMAP _PAGE_BIT_SOFTW4+/*+*Indicatesacopy-on-writepage.+*/+#ifdef CONFIG_X86_SHADOW_STACK+#define _PAGE_BIT_COW _PAGE_BIT_SOFTW5 /* copy-on-write */+#else+#define _PAGE_BIT_COW 0+#endif+/* If _PAGE_BIT_PRESENT is clear, we use these: *//* - if the user mapped it with PROT_NONE; pte_present gives true */#define _PAGE_BIT_PROTNONE _PAGE_BIT_GLOBAL
From: "Edgecombe, Rick P" <rick.p.edgecombe@intel.com> Date: 2021-08-21 19:20:43
+KVM list.
On Fri, 2021-08-20 at 11:11 -0700, Yu-cheng Yu wrote:
static inline int pte_write(pte_t pte)
{
- return pte_flags(pte) & _PAGE_RW;
+ /*
+ * Shadow stack pages are always writable - but not by normal
+ * instructions, and only by shadow stack operations.
Therefore,
+ * the W=0,D=1 test with pte_shstk().
+ */
+ return (pte_flags(pte) & _PAGE_RW) || pte_shstk(pte);
}
KVM uses this in a couple places when checking EPT ptes. But bit 6
(dirty) is a totally different meaning in EPT. I think it's just used
to trigger an optimization, but wondering if KVM should have its own
TDP specific function instead of using pte_write().
From: "Edgecombe, Rick P" <rick.p.edgecombe@intel.com> Date: 2021-08-22 03:00:19
On Sat, 2021-08-21 at 19:20 +0000, Edgecombe, Rick P wrote:
+KVM list.
On Fri, 2021-08-20 at 11:11 -0700, Yu-cheng Yu wrote:
quoted
static inline int pte_write(pte_t pte)
{
- return pte_flags(pte) & _PAGE_RW;
+ /*
+ * Shadow stack pages are always writable - but not by
normal
+ * instructions, and only by shadow stack operations.
Therefore,
+ * the W=0,D=1 test with pte_shstk().
+ */
+ return (pte_flags(pte) & _PAGE_RW) || pte_shstk(pte);
}
KVM uses this in a couple places when checking EPT ptes. But bit 6
(dirty) is a totally different meaning in EPT. I think it's just used
to trigger an optimization, but wondering if KVM should have its own
TDP specific function instead of using pte_write().
Argh, never mind. I misread the new KVM mmu notifier refactor.
After the introduction of _PAGE_COW, a modified page's PTE can have either
_PAGE_DIRTY or _PAGE_COW. Change _PAGE_DIRTY to _PAGE_DIRTY_BITS.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kees Cook <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: David Airlie <redacted>
Cc: Joonas Lahtinen <joonas.lahtinen@linux.intel.com>
Cc: Jani Nikula <jani.nikula@linux.intel.com>
Cc: Daniel Vetter <redacted>
Cc: Rodrigo Vivi <rodrigo.vivi@intel.com>
Cc: Zhenyu Wang <redacted>
Cc: Zhi Wang <redacted>
---
drivers/gpu/drm/i915/gvt/gtt.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
The read-only and Dirty PTE has been used to indicate copy-on-write pages.
However, newer x86 processors also regard a read-only and Dirty PTE as a
shadow stack page. In order to separate the two, the software-defined
_PAGE_COW is created to replace _PAGE_DIRTY for the copy-on-write case, and
pte_*() are updated.
Pte_modify() changes a PTE to 'newprot', but it doesn't use the pte_*().
Introduce fixup_dirty_pte(), which sets a dirty PTE, based on _PAGE_RW,
to either _PAGE_DIRTY or _PAGE_COW.
Apply the same changes to pmd_modify().
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
---
arch/x86/include/asm/pgtable.h | 37 ++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
When Shadow Stack is introduced, [R/O + _PAGE_DIRTY] PTE is reserved for
shadow stack. Copy-on-write PTEs have [R/O + _PAGE_COW].
When a PTE goes from [R/W + _PAGE_DIRTY] to [R/O + _PAGE_COW], 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 read-only 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.
Dave Hansen, Jann Horn, Andy Lutomirski, and Peter Zijlstra provided many
insights to the issue. Jann Horn provided the cmpxchg solution.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kees Cook <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
---
arch/x86/include/asm/pgtable.h | 36 ++++++++++++++++++++++++++++++++++
1 file changed, 36 insertions(+)
On Fri, Aug 20, 2021 at 11:11:41AM -0700, Yu-cheng Yu wrote:
quoted hunk
@@ -1322,6 +1340,24 @@ 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) {+ /*+ * 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. Use try_cmpxchg() to detect+ * PMD changes and update old_pmd, then try again.+ */+ if (cpu_feature_enabled(X86_FEATURE_SHSTK)) {+ pmd_t old_pmd, new_pmd;++ old_pmd = READ_ONCE(*pmdp);+ do {+ new_pmd = pmd_wrprotect(old_pmd);+ } while (!try_cmpxchg((pmdval_t *)pmdp, (pmdval_t *)&old_pmd, pmd_val(new_pmd)));
From the previous thread:
If !(CONFIG_PGTABLE_LEVELS > 2), we don't have pmd_t.pmd.
So I guess you can do this, in line with how the pmd folding is done in
the rest of the mm headers. There's no need to make this more complex
than it is just so that 32-bit !PAE builds but where CET is not even
enabled.
---
To introduce VM_SHADOW_STACK as VM_HIGH_ARCH_BIT (37), and make all
VM_HIGH_ARCH_BITs stay together, move VM_UFFD_MINOR_BIT from 37 to 38.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Axel Rasmussen <axelrasmussen@google.com>
Cc: Peter Xu <peterx@redhat.com>
Cc: Mike Kravetz <redacted>
---
include/linux/mm.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
Shadow stack accesses are those that are performed by the CPU where it
expects to encounter a shadow stack mapping. These accesses are performed
implicitly by CALL/RET at the site of the shadow stack pointer. These
accesses are made explicitly by shadow stack management instructions like
WRUSSQ.
Shadow stacks accesses to shadow-stack mapping 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.
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.
In handling a shadow stack page fault, verify it occurs within a shadow
stack mapping. It is always an error otherwise. For valid shadow stack
accesses, set FAULT_FLAG_WRITE to effect copy-on-write. Because clearing
_PAGE_DIRTY (vs. _PAGE_RW) is used to trigger the fault, shadow stack read
fault and shadow stack write fault are not differentiated and both are
handled as a write access.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kees Cook <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
---
arch/x86/include/asm/trap_pf.h | 2 ++
arch/x86/mm/fault.c | 19 +++++++++++++++++++
2 files changed, 21 insertions(+)
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.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: Kees Cook <redacted>
---
Documentation/filesystems/proc.rst | 1 +
arch/x86/mm/mmap.c | 2 ++
fs/proc/task_mmu.c | 3 +++
include/linux/mm.h | 8 ++++++++
4 files changed, 14 insertions(+)
@@ -553,6 +553,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
When serving a page fault, maybe_mkwrite() makes a PTE writable if its vma
has VM_WRITE.
A shadow stack vma has VM_SHADOW_STACK. Its PTEs have _PAGE_DIRTY, but not
_PAGE_WRITE. In fork(), _PAGE_DIRTY is cleared to cause copy-on-write,
and in the page fault handler, _PAGE_DIRTY is restored and the shadow stack
page is writable again.
Introduce an x86 version of maybe_mkwrite(), which sets proper PTE bits
according to VM flags.
Apply the same changes to maybe_pmd_mkwrite().
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: Kees Cook <redacted>
---
v29:
- Remove likely()'s.
---
arch/x86/include/asm/pgtable.h | 6 ++++++
arch/x86/mm/pgtable.c | 20 ++++++++++++++++++++
include/linux/mm.h | 2 ++
mm/huge_memory.c | 2 ++
4 files changed, 30 insertions(+)
When serving a page fault, maybe_mkwrite() makes a PTE writable if it is in
a writable vma. A shadow stack vma is writable, but its PTEs need
_PAGE_DIRTY to be set to become writable. For this reason, maybe_mkwrite()
has been updated.
There are a few places that call pte_mkwrite() directly, but have the
same result as from maybe_mkwrite(). These sites need to be updated for
shadow stack as well. Thus, change them to maybe_mkwrite():
- do_anonymous_page() and migrate_vma_insert_page() check VM_WRITE directly
and call pte_mkwrite(), which is the same as maybe_mkwrite(). Change
them to maybe_mkwrite().
- In do_numa_page(), if the numa entry was writable, then pte_mkwrite()
is called directly. Fix it by doing maybe_mkwrite(). Make the same
changes to do_huge_pmd_numa_page().
- In change_pte_range(), pte_mkwrite() is called directly. Replace it with
maybe_mkwrite().
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: Kees Cook <redacted>
---
v25:
- Apply same changes to do_huge_pmd_numa_page() as to do_numa_page().
---
mm/huge_memory.c | 2 +-
mm/memory.c | 5 ++---
mm/migrate.c | 3 +--
mm/mprotect.c | 2 +-
4 files changed, 5 insertions(+), 7 deletions(-)
INCSSP(Q/D) increments shadow stack pointer and 'pops and discards' the
first and the last elements in the range, effectively touches those memory
areas.
The maximum moving distance by INCSSPQ is 255 * 8 = 2040 bytes and
255 * 4 = 1020 bytes by INCSSPD. Both ranges are far from PAGE_SIZE.
Thus, putting a gap page on both ends of a shadow stack prevents INCSSP,
CALL, and RET from going beyond.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: Kees Cook <redacted>
---
v25:
- Move SHADOW_STACK_GUARD_GAP to arch/x86/mm/mmap.c.
v24:
- Instead changing vm_*_gap(), create x86-specific versions.
---
arch/x86/include/asm/page_types.h | 7 +++++
arch/x86/mm/mmap.c | 46 +++++++++++++++++++++++++++++++
include/linux/mm.h | 4 +++
3 files changed, 57 insertions(+)
Can_follow_write_pte() ensures a read-only page is COWed by checking the
FOLL_COW flag, and uses pte_dirty() to validate the flag is still valid.
Like a writable data page, a shadow stack page is writable, and becomes
read-only during copy-on-write, but it is always dirty. Thus, in the
can_follow_write_pte() check, it belongs to the writable page case and
should be excluded from the read-only page pte_dirty() check. Apply
the same changes to can_follow_write_pmd().
While at it, also split the long line into smaller ones.
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: Kees Cook <redacted>
---
v26:
- Instead of passing vm_flags, pass down vma pointer to can_follow_write_*().
v25:
- Split long line into smaller ones.
v24:
- Change arch_shadow_stack_mapping() to is_shadow_stack_mapping().
---
mm/gup.c | 16 ++++++++++++----
mm/huge_memory.c | 16 ++++++++++++----
2 files changed, 24 insertions(+), 8 deletions(-)
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
(RW=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().
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
---
v25:
- Move is_shadow_stack_mapping() to a separate line.
v24:
- Change arch_shadow_stack_mapping() to is_shadow_stack_mapping().
---
mm/huge_memory.c | 7 +++++++
mm/mprotect.c | 7 +++++++
2 files changed, 14 insertions(+)
@@ -1061,6 +1061,7 @@ unsigned long do_mmap(struct file *file,unsignedlonglen,unsignedlongprot,unsignedlongflags,+vm_flags_tvm_flags,unsignedlongpgoff,unsignedlong*populate,structlist_head*uf)
@@ -1068,7 +1069,6 @@ unsigned long do_mmap(struct file *file,structvm_area_struct*vma;structvm_region*region;structrb_node*rb;-vm_flags_tvm_flags;unsignedlongcapabilities,result;intret;
@@ -1087,7 +1087,7 @@ unsigned long do_mmap(struct file *file,/* we've determined that we can make the mapping, now translate what we*nowknowintoVMAflags*/-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 */region=kmem_cache_zalloc(vm_region_jar,GFP_KERNEL);
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).
Signed-off-by: Yu-cheng Yu <redacted>
Cc: Kees Cook <redacted>
---
v28:
- Update shstk_setup() with wrmsrl_safe(), returns success when shadow
stack feature is not present (since this is a setup function).
v27:
- Change 'struct cet_status' to 'struct thread_shstk', and change member
types from unsigned long to u64.
- Re-order local variables in reverse order of length.
- WARN_ON_ONCE() when vm_munmap() fails.
---
arch/x86/include/asm/cet.h | 30 +++++++
arch/x86/include/asm/processor.h | 5 ++
arch/x86/kernel/Makefile | 1 +
arch/x86/kernel/shstk.c | 134 +++++++++++++++++++++++++++++++
4 files changed, 170 insertions(+)
create mode 100644 arch/x86/include/asm/cet.h
create mode 100644 arch/x86/kernel/shstk.c
@@ -527,6 +528,10 @@ struct thread_struct {*/u32pkru;+#ifdef CONFIG_X86_SHADOW_STACK+structthread_shstkshstk;+#endif+/* Floating point and extended processor state */structfpufpu;/*
You're setting CET_U with the MSR writes below. Why do you need to do
XRSTOR here? To zero out PL[012]_SSP?
If so, you can WRMSR those too - no need for a full XRSTOR...
On Fri, Aug 20, 2021 at 11:11:52AM -0700, Yu-cheng Yu wrote:
[...]
quoted
+
+int shstk_setup(void)
+{
+ struct thread_shstk *shstk = ¤t->thread.shstk;
+ unsigned long addr, size;
+ int err;
+
+ if (!cpu_feature_enabled(X86_FEATURE_SHSTK))
+ return 0;
+
+ size = round_up(min_t(unsigned long long, rlimit(RLIMIT_STACK), SZ_4G), PAGE_SIZE);
+ addr = alloc_shstk(size);
+ if (IS_ERR_VALUE(addr))
+ return PTR_ERR((void *)addr);
+
+ start_update_msrs();
You're setting CET_U with the MSR writes below. Why do you need to do
XRSTOR here? To zero out PL[012]_SSP?
If so, you can WRMSR those too - no need for a full XRSTOR...
Because on context switches the whole xstates are switched together, we
need to make sure all are in registers.
On Fri, Aug 27, 2021 at 11:10:31AM -0700, Yu, Yu-cheng wrote:
Because on context switches the whole xstates are switched together,
we need to make sure all are in registers.
There's context switch code which does that already.
Why would shstk_setup() be responsible for switching the whole extended
states buffer instead of only the shadow stack stuff only?
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
On Fri, Aug 27, 2021 at 11:10:31AM -0700, Yu, Yu-cheng wrote:
quoted
Because on context switches the whole xstates are switched together,
we need to make sure all are in registers.
There's context switch code which does that already.
Why would shstk_setup() be responsible for switching the whole extended
states buffer instead of only the shadow stack stuff only?
Right now, the kernel does lazy restore, and it waits until right before
a task goes back to ring-3 to restore xstates. If a task needs to write
to any xstate registers before that (e.g. for signals), it restores the
whole xstates first and clears TIF_NEED_FPU_LOAD, which will prevent
xstates being restored again later.
On Fri, Aug 27, 2021 at 11:37:34AM -0700, Yu, Yu-cheng wrote:
Right now, the kernel does lazy restore, and it waits until right before a
task goes back to ring-3 to restore xstates. If a task needs to write to
any xstate registers before that (e.g. for signals), it restores the whole
xstates first and clears TIF_NEED_FPU_LOAD, which will prevent xstates being
restored again later.
shstk_setup() allocates a shadow stack for the task and puts its pointer
in MSR_IA32_PL3_SSP.
What does that have to do with a task having to write any xstate
registers?
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
From: Dave Hansen <hidden> Date: 2021-08-27 20:25:36
On 8/27/21 11:21 AM, Borislav Petkov wrote:
On Fri, Aug 27, 2021 at 11:10:31AM -0700, Yu, Yu-cheng wrote:
quoted
Because on context switches the whole xstates are switched together,
we need to make sure all are in registers.
There's context switch code which does that already.
Why would shstk_setup() be responsible for switching the whole extended
states buffer instead of only the shadow stack stuff only?
I don't think this has anything to do with context-switching, really.
The code lands in shstk_setup() which wants to make sure that the new
MSR values are set before the task goes out to userspace. If
TIF_NEED_FPU_LOAD was set, it could do that by going out to the XSAVE
buffer and setting the MSR state in the buffer. Before returning to
userspace, it would be XRSTOR'd. A WRMSR by itself would not be
persistent because that XRSTOR would overwrite it.
But, if TIF_NEED_FPU_LOAD is *clear* it means the XSAVE buffer is
out-of-date and the registers are live. WRMSR can be used and there
will be a XSAVE* to the task buffer during a context switch.
So, this code takes the coward's way out: it *forces* TIF_NEED_FPU_LOAD
to be clear by making the registers live with fpregs_restore_userregs().
That lets it just use WRMSR instead of dealing with the XSAVE buffer
directly. If it didn't do this with the *WHOLE* set of user FPU state,
we'd need more fine-granted "NEED_*_LOAD" tracking than our one FPU bit.
This is also *only* safe because the task is newly-exec()'d and the FPU
state was just reset. Otherwise, we might have had to worry that the
non-PL3 SSPs have garbage or that non-SHSTK bits are set in MSR_IA32_U_CET.
That said, after staring at it, I *think* this code is functionally
correct and OK performance-wise. I suspect that the (very blunt) XRSTOR
inside of start_update_msrs()->fpregs_restore_userregs() is quite rare
because TIF_NEED_FPU_LOAD will usually be clear due to the proximity to
execve(). So, adding direct XSAVE buffer manipulation would probably
only make it more error prone.
First of all,
thanks a lot Dave for taking the time to communicate properly with me!
On Fri, Aug 27, 2021 at 01:25:29PM -0700, Dave Hansen wrote:
I don't think this has anything to do with context-switching, really.
The code lands in shstk_setup() which wants to make sure that the new
MSR values are set before the task goes out to userspace. If
TIF_NEED_FPU_LOAD was set, it could do that by going out to the XSAVE
buffer and setting the MSR state in the buffer. Before returning to
userspace, it would be XRSTOR'd. A WRMSR by itself would not be
persistent because that XRSTOR would overwrite it.
But, if TIF_NEED_FPU_LOAD is *clear* it means the XSAVE buffer is
out-of-date and the registers are live. WRMSR can be used and there
will be a XSAVE* to the task buffer during a context switch.
So, this code takes the coward's way out: it *forces* TIF_NEED_FPU_LOAD
to be clear by making the registers live with fpregs_restore_userregs().
That lets it just use WRMSR instead of dealing with the XSAVE buffer
directly. If it didn't do this with the *WHOLE* set of user FPU state,
we'd need more fine-granted "NEED_*_LOAD" tracking than our one FPU bit.
This is also *only* safe because the task is newly-exec()'d and the FPU
state was just reset. Otherwise, we might have had to worry that the
non-PL3 SSPs have garbage or that non-SHSTK bits are set in MSR_IA32_U_CET.
That said, after staring at it, I *think* this code is functionally
correct and OK performance-wise.
Right, except that that is being done in
setup_signal_shadow_stack()/restore_signal_shadow_stack() too, for the
restore token.
Which means, a potential XRSTOR each time just for a single MSR. That
means, twice per signal in the worst case.
Which means, shadow stack should be pretty noticeable in signal-heavy
benchmarks...
I suspect that the (very blunt) XRSTOR inside of
start_update_msrs()->fpregs_restore_userregs() is quite rare because
TIF_NEED_FPU_LOAD will usually be clear due to the proximity to
execve(). So, adding direct XSAVE buffer manipulation would probably
only make it more error prone.
@Yu-cheng: please take Dave's explanation as is and stick it over
start_update_msrs() so that it is clear what that thing is doing.
Thx.
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
From: Dave Hansen <hidden> Date: 2021-09-01 15:24:34
On 9/1/21 6:00 AM, Borislav Petkov wrote:
quoted
So, this code takes the coward's way out: it *forces* TIF_NEED_FPU_LOAD
to be clear by making the registers live with fpregs_restore_userregs().
That lets it just use WRMSR instead of dealing with the XSAVE buffer
directly. If it didn't do this with the *WHOLE* set of user FPU state,
we'd need more fine-granted "NEED_*_LOAD" tracking than our one FPU bit.
This is also *only* safe because the task is newly-exec()'d and the FPU
state was just reset. Otherwise, we might have had to worry that the
non-PL3 SSPs have garbage or that non-SHSTK bits are set in MSR_IA32_U_CET.
That said, after staring at it, I *think* this code is functionally
correct and OK performance-wise.
Right, except that that is being done in
setup_signal_shadow_stack()/restore_signal_shadow_stack() too, for the
restore token.
Which means, a potential XRSTOR each time just for a single MSR. That
means, twice per signal in the worst case.
Which means, shadow stack should be pretty noticeable in signal-heavy
benchmarks...
Ahh, good point. I totally missed the signal side.
Yu-cheng, it would probably be wise to take a look at where
TIF_NEED_FPU_LOAD is set in the signal paths. I suspect the new shadow
stack code is clearing it pretty quickly. That's not *necessarily* a
waste because it has to be XRSTOR'd somewhere before returning to
userspace. But, it does impose an extra XSAVE/XRSTOR burden if the code
is preempted somewhere between
setup_signal_shadow_stack()/restore_signal_shadow_stack() and the return
to usersspace.
Some performance numbers would be nice.
Even nicer would be to make your code work without requiring
TIF_NEED_FPU_LOAD to be clear, or actively clearing it.
The single call site of copy_thread() passes stack size in 'arg'. To make
this clear and in preparation of using this argument for shadow stack
allocation, change 'arg' to 'stack_size'. No functional changes.
Signed-off-by: Yu-cheng Yu <redacted>
---
arch/x86/kernel/process.c | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
@@ -116,8 +116,9 @@ static int set_new_tls(struct task_struct *p, unsigned long tls)returndo_set_thread_area_64(p,ARCH_SET_FS,tls);}-intcopy_thread(unsignedlongclone_flags,unsignedlongsp,unsignedlongarg,-structtask_struct*p,unsignedlongtls)+intcopy_thread(unsignedlongclone_flags,unsignedlongsp,+unsignedlongstack_size,structtask_struct*p,+unsignedlongtls){structinactive_task_frame*frame;structfork_frame*fork_frame;
@@ -158,7 +159,7 @@ int copy_thread(unsigned long clone_flags, unsigned long sp, unsigned long arg,if(unlikely(p->flags&PF_KTHREAD)){p->thread.pkru=pkru_get_init_value();memset(childregs,0,sizeof(structpt_regs));-kthread_frame_init(frame,sp,arg);+kthread_frame_init(frame,sp,stack_size);return0;}
@@ -191,7 +192,7 @@ int copy_thread(unsigned long clone_flags, unsigned long sp, unsigned long arg,*/childregs->sp=0;childregs->ip=0;-kthread_frame_init(frame,sp,arg);+kthread_frame_init(frame,sp,stack_size);return0;}
For clone() with CLONE_VM, except vfork, the child and the parent must have
separate shadow stacks. Thus, the kernel allocates, and frees on thread
exit a new shadow stack for the child.
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 earlier version of clone() did not have stack_size passed in. In that
case, use RLIMIT_STACK size and cap to 4 GB.
Signed-off-by: Yu-cheng Yu <redacted>
---
v29:
- WARN_ON_ONCE() when get_xsave_addr() returns NULL, and update comments.
(Dave Hansen)
v28:
- Split out copy_thread() argument name changes to a new patch.
- Add compatibility for earlier clone(), which does not pass stack_size.
- Add comment for get_xsave_addr(), explain the handling of null return
value.
---
arch/x86/include/asm/cet.h | 5 +++
arch/x86/include/asm/mmu_context.h | 3 ++
arch/x86/kernel/process.c | 6 +++
arch/x86/kernel/shstk.c | 63 +++++++++++++++++++++++++++++-
4 files changed, 76 insertions(+), 1 deletion(-)
@@ -200,6 +202,10 @@ int copy_thread(unsigned long clone_flags, unsigned long sp,if(clone_flags&CLONE_SETTLS)ret=set_new_tls(p,tls);+/* Allocate a new shadow stack for pthread */+if(!ret)+ret=shstk_alloc_thread_stack(p,clone_flags,stack_size);+if(!ret&&unlikely(test_tsk_thread_flag(current,TIF_IO_BITMAP)))io_bitmap_share(p);
On Thu, Aug 26, 2021 at 10:22:29AM -0700, H.J. Lu wrote:
quoted
quoted
+ /*
+ * Earlier clone() does not pass stack_size. Use RLIMIT_STACK and
What is "earlier clone()"?
clone() doesn't have stack size info which was added to clone3().
/me goes and reads the manpage...
clone3()
The clone3() system call provides a superset of the functionality of the older
clone() interface. It also provides a number of API improvements, including:
space for additional flags bits; cleaner separation in the use of various argu‐
ments; and the ability to specify the size of the child's stack area.
Aha, Yu-cheng, pls use those words to make your comment understandable.
Thx.
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
On Thu, Aug 26, 2021 at 10:22:29AM -0700, H.J. Lu wrote:
quoted
quoted
quoted
+ /*
+ * Earlier clone() does not pass stack_size. Use RLIMIT_STACK and
What is "earlier clone()"?
clone() doesn't have stack size info which was added to clone3().
/me goes and reads the manpage...
clone3()
The clone3() system call provides a superset of the functionality of the older
clone() interface. It also provides a number of API improvements, including:
space for additional flags bits; cleaner separation in the use of various argu‐
ments; and the ability to specify the size of the child's stack area.
Aha, Yu-cheng, pls use those words to make your comment understandable.
Thx.
A signal handler (if not changing ucontext) returns to the restorer, and
the restorer calls sigreturn. Thus, when setting up a signal frame, the
kernel:
- installs a shadow stack restore token pointing to the current shadow
stack address, and
- installs the restorer address below the restore token.
In sigreturn, the restore token is verified and shadow stack pointer is
restored.
Signed-off-by: Yu-cheng Yu <redacted>
Cc: Andy Lutomirski <luto@kernel.org>
Cc: Cyrill Gorcunov <redacted>
Cc: Florian Weimer <redacted>
Cc: H. Peter Anvin <hpa@zytor.com>
Cc: Kees Cook <redacted>
---
v27:
- Eliminate saving shadow stack pointer to signal context.
v25:
- Update commit log/comments for the sc_ext struct.
- Use restorer address already calculated.
- Change CONFIG_X86_CET to CONFIG_X86_SHADOW_STACK.
- Change X86_FEATURE_CET to X86_FEATURE_SHSTK.
- Eliminate writing to MSR_IA32_U_CET for shadow stack.
- Change wrmsrl() to wrmsrl_safe() and handle error.
---
arch/x86/ia32/ia32_signal.c | 25 +++++++++++++++++-----
arch/x86/include/asm/cet.h | 4 ++++
arch/x86/kernel/shstk.c | 42 +++++++++++++++++++++++++++++++++++++
arch/x86/kernel/signal.c | 13 ++++++++++++
4 files changed, 79 insertions(+), 5 deletions(-)
@@ -333,3 +333,45 @@ int shstk_check_rstor_token(bool proc32, unsigned long *new_ssp)return0;}++intsetup_signal_shadow_stack(intia32,void__user*restorer)+{+structthread_shstk*shstk=¤t->thread.shstk;+unsignedlongnew_ssp;+interr;++if(!cpu_feature_enabled(X86_FEATURE_SHSTK)||!shstk->size)+return0;++err=shstk_setup_rstor_token(ia32,(unsignedlong)restorer,+&new_ssp);+if(err)+returnerr;++start_update_msrs();+err=wrmsrl_safe(MSR_IA32_PL3_SSP,new_ssp);+end_update_msrs();++returnerr;+}++intrestore_signal_shadow_stack(void)+{+structthread_shstk*shstk=¤t->thread.shstk;+intia32=in_ia32_syscall();+unsignedlongnew_ssp;+interr;++if(!cpu_feature_enabled(X86_FEATURE_SHSTK)||!shstk->size)+return0;++err=shstk_check_rstor_token(ia32,&new_ssp);+if(err)+returnerr;++start_update_msrs();+err=wrmsrl_safe(MSR_IA32_PL3_SSP,new_ssp);+end_update_msrs();++returnerr;+}
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.
The restore token can be used as an extra protection for signal handling.
To deliver a signal, create a shadow stack restore token and put the token
and the signal restorer address on the shadow stack. In sigreturn, verify
the token and restore from it the shadow stack pointer.
Introduce token setup and verify routines. Also introduce WRUSS, which is
a kernel-mode instruction but writes directly to user shadow stack. It is
used to construct user signal stack as described above.
Signed-off-by: Yu-cheng Yu <redacted>
Cc: Kees Cook <redacted>
---
v29:
- Update comments for the use of get_xsave_addr().
v28:
- Add comments for get_xsave_addr().
v27:
- For shstk_check_rstor_token(), instead of an input param, use current
shadow stack pointer.
- In response to comments, fix/simplify a few syntax/format issues.
v25:
- Update inline assembly syntax, use %[].
- Change token address from (unsigned long) to (u64/u32 __user *).
- Change -EPERM to -EFAULT.
---
arch/x86/include/asm/cet.h | 7 ++
arch/x86/include/asm/special_insns.h | 30 ++++++
arch/x86/kernel/shstk.c | 140 +++++++++++++++++++++++++++
3 files changed, 177 insertions(+)
@@ -193,3 +194,142 @@ void shstk_disable(void)shstk_free(current);}++staticunsignedlongget_user_shstk_addr(void)+{+structfpu*fpu=¤t->thread.fpu;+unsignedlongssp=0;++fpregs_lock();++if(fpregs_state_valid(fpu,smp_processor_id())){+rdmsrl(MSR_IA32_PL3_SSP,ssp);+}else{+structcet_user_state*p;++/*+*When!fpregs_state_valid()andget_xsave_addr()returns+*null,XFEAUTRE_CET_USERisininitstate.Shadowstack+*pointerisnullinthiscase,soreturnzero.Thiscan+*happenwhenshadowstackisenabled,butitsxstatesin+*memoryiscorrupted.+*/+p=get_xsave_addr(&fpu->state.xsave,XFEATURE_CET_USER);+if(p)+ssp=p->user_ssp;+}++fpregs_unlock();++returnssp;+}++/*+*Createarestoretokenontheshadowstack.Atokenisalways8-byte+*andalignedto8.+*/+staticintcreate_rstor_token(boolia32,unsignedlongssp,+unsignedlong*token_addr)+{+unsignedlongaddr;++/* Aligned to 8 is aligned to 4, so test 8 first */+if((!ia32&&!IS_ALIGNED(ssp,8))||!IS_ALIGNED(ssp,4))+return-EINVAL;++addr=ALIGN_DOWN(ssp,8)-8;++/* Is the token for 64-bit? */+if(!ia32)+ssp|=BIT(0);++if(write_user_shstk_64((u64__user*)addr,(u64)ssp))+return-EFAULT;++*token_addr=addr;++return0;+}++/*+*Createarestoretokenonshadowstack,andthenpushtheuser-mode+*functionreturnaddress.+*/+intshstk_setup_rstor_token(boolia32,unsignedlongret_addr,+unsignedlong*new_ssp)+{+structthread_shstk*shstk=¤t->thread.shstk;+unsignedlongssp,token_addr;+interr;++if(!shstk->size)+return0;++if(!ret_addr)+return-EINVAL;++ssp=get_user_shstk_addr();+if(!ssp)+return-EINVAL;++err=create_rstor_token(ia32,ssp,&token_addr);+if(err)+returnerr;++if(ia32){+ssp=token_addr-sizeof(u32);+err=write_user_shstk_32((u32__user*)ssp,(u32)ret_addr);+}else{+ssp=token_addr-sizeof(u64);+err=write_user_shstk_64((u64__user*)ssp,(u64)ret_addr);+}++if(!err)+*new_ssp=ssp;++returnerr;+}++/*+*Verifytoken_addrpointstoavalidtoken,andthenset*new_ssp+*accordingtothetoken.+*/+intshstk_check_rstor_token(boolproc32,unsignedlong*new_ssp)+{+unsignedlongtoken_addr;+unsignedlongtoken;+boolshstk32;++token_addr=get_user_shstk_addr();++if(get_user(token,(unsignedlong__user*)token_addr))+return-EFAULT;++/* Is mode flag correct? */+shstk32=!(token&BIT(0));+if(proc32^shstk32)+return-EINVAL;++/* Is busy flag set? */+if(token&BIT(1))+return-EINVAL;++/* Mask out flags */+token&=~3UL;++/*+*Restoreaddressaligned?+*/+if((!proc32&&!IS_ALIGNED(token,8))||!IS_ALIGNED(token,4))+return-EINVAL;++/*+*Tokenplacedproperly?+*/+if(((ALIGN_DOWN(token,8)-8)!=token_addr)||token>=TASK_SIZE_MAX)+return-EINVAL;++*new_ssp=token;++return0;+}
On Fri, Aug 20, 2021 at 11:11:55AM -0700, Yu-cheng Yu wrote:
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.
The restore token can be used as an extra protection for signal handling.
To deliver a signal, create a shadow stack restore token and put the token
and the signal restorer address on the shadow stack. In sigreturn, verify
the token and restore from it the shadow stack pointer.
I guess this all bla about signals needs to go now too...
Introduce token setup and verify routines. Also introduce WRUSS, which is
a kernel-mode instruction but writes directly to user shadow stack. It is
used to construct user signal stack as described above.
Signed-off-by: Yu-cheng Yu <redacted>
Cc: Kees Cook <redacted>
+
+ fpregs_lock();
+
+ if (fpregs_state_valid(fpu, smp_processor_id())) {
+ rdmsrl(MSR_IA32_PL3_SSP, ssp);
+ } else {
+ struct cet_user_state *p;
+
+ /*
+ * When !fpregs_state_valid() and get_xsave_addr() returns
What does "!fpregs_state_valid()" mean in English?
+ * null, XFEAUTRE_CET_USER is in init state. Shadow stack
XFEATURE_CET_USER
+ * pointer is null in this case, so return zero. This can
+ * happen when shadow stack is enabled, but its xstates in
s/its xstates/the shadow stack component/
+ * memory is corrupted.
+ */
+ p = get_xsave_addr(&fpu->state.xsave, XFEATURE_CET_USER);
+ if (p)
+ ssp = p->user_ssp;
else
ssp = 0;
and this way it is absolutely unambiguous what the comment says.
+ }
+
+ fpregs_unlock();
+
+ return ssp;
+}
+
+/*
+ * Create a restore token on the shadow stack. A token is always 8-byte
+ * and aligned to 8.
+ */
+static int create_rstor_token(bool ia32, unsigned long ssp,
s/ia32/proc32/g
+ unsigned long *token_addr)
+{
+ unsigned long addr;
+
+ /* Aligned to 8 is aligned to 4, so test 8 first */
+ if ((!ia32 && !IS_ALIGNED(ssp, 8)) || !IS_ALIGNED(ssp, 4))
+ return -EINVAL;
+
+ addr = ALIGN_DOWN(ssp, 8) - 8;
+
+ /* Is the token for 64-bit? */
+ if (!ia32)
+ ssp |= BIT(0);
+
+ if (write_user_shstk_64((u64 __user *)addr, (u64)ssp))
+ return -EFAULT;
+
+ *token_addr = addr;
+
+ return 0;
+}
...
+/*
+ * Verify token_addr points to a valid token, and then set *new_ssp
"Verify the user shadow stack has a valid token on it, ... "
+ * according to the token.
+ */
+int shstk_check_rstor_token(bool proc32, unsigned long *new_ssp)
+{
+ unsigned long token_addr;
+ unsigned long token;
+ bool shstk32;
+
+ token_addr = get_user_shstk_addr();
if (!token_addr)
return -EINVAL;
+
+ if (get_user(token, (unsigned long __user *)token_addr))
+ return -EFAULT;
+
+ /* Is mode flag correct? */
+ shstk32 = !(token & BIT(0));
+ if (proc32 ^ shstk32)
+ return -EINVAL;
+
+ /* Is busy flag set? */
+ if (token & BIT(1))
+ return -EINVAL;
+
+ /* Mask out flags */
+ token &= ~3UL;
+
+ /*
+ * Restore address aligned?
+ */
Single line comment works too:
/* Restore address aligned? */
An ELF file's .note.gnu.property indicates arch features supported by the
file. These features are extracted by arch_parse_elf_property() and stored
in 'arch_elf_state'.
Introduce x86 feature definitions and arch_setup_elf_property(), which
enables such features. The first use-case of this function is Shadow
Stack.
ARM64 is the other arch that has ARCH_USE_GNU_PROPERTY and arch_parse_elf_
property(). Add arch_setup_elf_property() for it.
Signed-off-by: Yu-cheng Yu <redacted>
Acked-by: Catalin Marinas <catalin.marinas@arm.com>
Cc: Dave Martin <Dave.Martin@arm.com>
Cc: Kees Cook <redacted>
Cc: Mark Brown <broonie@kernel.org>
---
v27:
- Make X86_64 select ARCH_USE_GNU_PROPERTY and ARCH_BINFMT_ELF_STATE and
remove #ifdef's.
- Add link to x86-64-psABI document.
---
arch/arm64/include/asm/elf.h | 5 +++++
arch/x86/Kconfig | 2 ++
arch/x86/include/asm/elf.h | 11 +++++++++++
arch/x86/kernel/process_64.c | 27 +++++++++++++++++++++++++++
fs/binfmt_elf.c | 4 ++++
include/linux/elf.h | 6 ++++++
include/uapi/linux/elf.h | 14 ++++++++++++++
7 files changed, 69 insertions(+)
arch_prctl(ARCH_X86_CET_STATUS, u64 *args)
Get CET feature status.
The parameter 'args' is a pointer to a user buffer. The kernel returns
the following information:
*args = shadow stack/IBT status
*(args + 1) = shadow stack base address
*(args + 2) = shadow stack size
32-bit binaries use the same interface, but only lower 32-bits of each
item.
arch_prctl(ARCH_X86_CET_DISABLE, unsigned int features)
Disable CET features specified in 'features'. Return -EPERM if CET is
locked.
arch_prctl(ARCH_X86_CET_LOCK)
Lock in CET features.
Also change do_arch_prctl_common()'s parameter 'cpuid_enabled' to
'arg2', as it is now also passed to prctl_cet().
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kees Cook <redacted>
---
arch/x86/include/asm/cet.h | 7 ++++
arch/x86/include/uapi/asm/prctl.h | 4 +++
arch/x86/kernel/Makefile | 1 +
arch/x86/kernel/cet_prctl.c | 60 +++++++++++++++++++++++++++++++
arch/x86/kernel/process.c | 6 ++--
5 files changed, 75 insertions(+), 3 deletions(-)
create mode 100644 arch/x86/kernel/cet_prctl.c
When newer VM flags are being created, such as VM_MTE, it becomes necessary
for mmap/mprotect to verify if certain flags are being applied to an
anonymous VMA.
To solve this, one approach is adding a VM flag to track that MAP_ANONYMOUS
is specified [1], and then using the flag in arch_validate_flags().
Another approach is passing the VMA to arch_validate_flags(), and check
vma_is_anonymous().
To prepare the introduction of PROT_SHADOW_STACK, which creates a shadow
stack mapping and can be applied only to an anonymous VMA, update
arch_validate_flags() to pass in the VMA.
[1] commit 9f3419315f3c ("arm64: mte: Add PROT_MTE support to mmap() and mprotect()"),
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Acked-by: Catalin Marinas <catalin.marinas@arm.com>
Cc: Kees Cook <redacted>
Cc: Vincenzo Frascino <vincenzo.frascino@arm.com>
Cc: Will Deacon <will@kernel.org>
---
arch/arm64/include/asm/mman.h | 4 ++--
arch/sparc/include/asm/mman.h | 4 ++--
include/linux/mman.h | 2 +-
mm/mmap.c | 2 +-
mm/mprotect.c | 2 +-
5 files changed, 7 insertions(+), 7 deletions(-)
@@ -82,6 +82,6 @@ static inline bool arch_validate_flags(unsigned long vm_flags)/* only allow VM_MTE if VM_MTE_ALLOWED has been set previously */return!(vm_flags&VM_MTE)||(vm_flags&VM_MTE_ALLOWED);}-#define arch_validate_flags(vm_flags) arch_validate_flags(vm_flags)+#define arch_validate_flags(vma, vm_flags) arch_validate_flags(vma, vm_flags)#endif /* ! __ASM_MMAN_H__ */
@@ -60,11 +60,11 @@ static inline int sparc_validate_prot(unsigned long prot, unsigned long addr)return1;}-#define arch_validate_flags(vm_flags) arch_validate_flags(vm_flags)+#define arch_validate_flags(vma, vm_flags) arch_validate_flags(vma, vm_flags)/* arch_validate_flags() - Ensure combination of flags is valid for a*VMA.*/-staticinlineboolarch_validate_flags(unsignedlongvm_flags)+staticinlineboolarch_validate_flags(structvm_area_struct*vma,unsignedlongvm_flags){/* If ADI is being enabled on this VMA, check for ADI*capabilityontheplatformandensureVMAissuitable
@@ -1853,7 +1853,7 @@ unsigned long mmap_region(struct file *file, unsigned long addr,}/* Allow architectures to sanity-check the vm_flags */-if(!arch_validate_flags(vma->vm_flags)){+if(!arch_validate_flags(vma,vma->vm_flags)){error=-EINVAL;if(file)gotounmap_and_free_vma;
@@ -621,7 +621,7 @@ static int do_mprotect_pkey(unsigned long start, size_t len,}/* Allow architectures to sanity-check the new flags */-if(!arch_validate_flags(newflags)){+if(!arch_validate_flags(vma,newflags)){error=-EINVAL;gotoout;}