@@ -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.
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(+)
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>
---
v28:
- Add XFEATURE_MASK_CET_USER to XFEATURES_INIT_FPSTATE_HANDLED (Rebase to
upstream changes).
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 | 19 +++++++++++++++++++
arch/x86/kernel/fpu/xstate.c | 11 ++++++++++-
4 files changed, 54 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 | \
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
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.
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(-)
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>
---
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 | 63 ++++++++++++++++++++++++++++++
include/uapi/asm-generic/siginfo.h | 3 +-
5 files changed, 74 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,68 @@ 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)){+pr_emerg("PANIC: unexpected kernel control protection fault\n");+die("kernel control protection fault",regs,error_code);+panic("Machine halted.");+}++cond_local_irq_enable(regs);++if(!boot_cpu_has(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;
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)
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>
---
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(+)
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
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(-)
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(+)
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(-)
@@ -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);
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(+)
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(-)
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(+)
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;}
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(). Return success when shadow
stack feature is not present, because this is a setup init function
and when the feature is not present, no setup is necessary.
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;/*
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>
---
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);
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>
---
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 | 138 +++++++++++++++++++++++++++
3 files changed, 175 insertions(+)
@@ -193,3 +194,140 @@ 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.+*/+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;+}
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(-)
@@ -331,3 +331,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;+}
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;}
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(+)
There are three possible options to create a shadow stack allocation API:
an arch_prctl, a new syscall, or adding PROT_SHADOW_STACK to mmap() and
mprotect(). Each has its advantages and compromises.
An arch_prctl() is the least intrusive. However, the existing x86
arch_prctl() takes only two parameters. Multiple parameters must be
passed in a memory buffer. There is a proposal to pass more parameters in
registers [1], but no active discussion on that.
A new syscall minimizes compatibility issues and offers an extensible frame
work to other architectures, but this will likely result in some overlap of
mmap()/mprotect().
The introduction of PROT_SHADOW_STACK to mmap()/mprotect() takes advantage
of existing APIs. The x86-specific PROT_SHADOW_STACK is translated to
VM_SHADOW_STACK and a shadow stack mapping is created without reinventing
the wheel. There are potential pitfalls though. The most obvious one
would be using this as a bypass to shadow stack protection. However, the
attacker would have to get to the syscall first.
[1] https://lore.kernel.org/lkml/20200828121624.108243-1-hjl.tools@gmail.com/
Signed-off-by: Yu-cheng Yu <redacted>
Reviewed-by: Kirill A. Shutemov <redacted>
Cc: Kees Cook <redacted>
---
arch/x86/include/asm/mman.h | 60 +++++++++++++++++++++++++++++++-
arch/x86/include/uapi/asm/mman.h | 2 ++
include/linux/mm.h | 1 +
3 files changed, 62 insertions(+), 1 deletion(-)
From: Dave Hansen <hidden> Date: 2021-07-22 21:05:36
On 7/22/21 1:52 PM, Yu-cheng Yu wrote:
+ if (!stack_size)
+ stack_size = min_t(unsigned long long, rlimit(RLIMIT_STACK), SZ_4G);
+
+ if (!shstk->size)
+ return 0;
+
+ /*
+ * For CLONE_VM, except vfork, the child needs a separate shadow
+ * stack.
+ */
+ if ((clone_flags & (CLONE_VFORK | CLONE_VM)) != CLONE_VM)
+ return 0;
+
+ /*
+ * This is in clone() syscall and fpu__copy() already copies xstates
+ * from the parent. If get_xsave_addr() returns null, then XFEATURE_
+ * CET_USER is still in init state, which certainly is an error.
+ */
+ state = get_xsave_addr(&tsk->thread.fpu.state.xsave, XFEATURE_CET_USER);
+ if (!state)
+ return -EINVAL;
I don't care much for that comment.
This code is meant to copy shadow stack config information into children
when it is already enabled. We *just* checked for that above in the
"shstk->size" check. The fact that this is called from clone() is
irrelevant. The shadow stack enabling status *is*.
I think I'd rather this be more along the lines of:
/*
* 'tsk' is configured with a shadow stack and the fpu.state is
* up to date since it was just copied from the parent. There
* must be a valid non-init CET state location in the buffer.
*/
There is also a strong enough assumption violation that I'd probably
WARN() in addition to returning -EINVAL.
From: Dave Hansen <hidden> Date: 2021-07-22 21:08:15
On 7/22/21 1:51 PM, Yu-cheng Yu wrote:
Linux distributions with CET are available now, and Intel processors with CET
are already on the market. It would be nice if CET support can be accepted
into the kernel.
Changes in v28:
- Rebase to Linus tree v5.14-rc2.
- Patch #1: Update Document to indicate no-user-shstk also disables IBT.
- Patch #23: Update shstk_setup() with wrmsrl_safe(). Update return value.
- Patch #25: Split out copy_thread() changes. Add support for old clone().
Add comments.
- Add comments for get_xsave_addr() (Patch #25, #26).
Could you characterize where this whole thing is?
Are we at the point where the feedback is slowing down? What kind of
feedback are you getting? How stable is the ABI versus the last revision?
Linux distributions with CET are available now, and Intel processors with CET
are already on the market. It would be nice if CET support can be accepted
into the kernel.
Changes in v28:
- Rebase to Linus tree v5.14-rc2.
- Patch #1: Update Document to indicate no-user-shstk also disables IBT.
- Patch #23: Update shstk_setup() with wrmsrl_safe(). Update return value.
- Patch #25: Split out copy_thread() changes. Add support for old clone().
Add comments.
- Add comments for get_xsave_addr() (Patch #25, #26).
Could you characterize where this whole thing is?
Are we at the point where the feedback is slowing down? What kind of
feedback are you getting? How stable is the ABI versus the last revision?
The ABI has not changed since last version, except the addition of
shadow stack support for legacy clone(). This does not de-stabilize the
ABI.
Looking back at recent feedback:
- Boris had given lots of comments on code flow, syntax, etc. Those are
all addressed.
- Andy L. commented on the signal handling part, especially the
introduction of a ucontext extension. That is eliminated and now there
is the UC_WAIT_ENDBR flag.
- Kirill commented a few issues on mm patches. Those are addressed.
- Peter Z. requested splitting shadow stack and ibt. That is done.
As for running/testing of the series, overall it is stable.
Yu-cheng
+ if (!stack_size)
+ stack_size = min_t(unsigned long long, rlimit(RLIMIT_STACK), SZ_4G);
+
+ if (!shstk->size)
+ return 0;
+
+ /*
+ * For CLONE_VM, except vfork, the child needs a separate shadow
+ * stack.
+ */
+ if ((clone_flags & (CLONE_VFORK | CLONE_VM)) != CLONE_VM)
+ return 0;
+
+ /*
+ * This is in clone() syscall and fpu__copy() already copies xstates
+ * from the parent. If get_xsave_addr() returns null, then XFEATURE_
+ * CET_USER is still in init state, which certainly is an error.
+ */
+ state = get_xsave_addr(&tsk->thread.fpu.state.xsave, XFEATURE_CET_USER);
+ if (!state)
+ return -EINVAL;
I don't care much for that comment.
This code is meant to copy shadow stack config information into children
when it is already enabled. We *just* checked for that above in the
"shstk->size" check. The fact that this is called from clone() is
irrelevant. The shadow stack enabling status *is*.
I think I'd rather this be more along the lines of:
/*
* 'tsk' is configured with a shadow stack and the fpu.state is
* up to date since it was just copied from the parent. There
* must be a valid non-init CET state location in the buffer.
*/
There is also a strong enough assumption violation that I'd probably
WARN() in addition to returning -EINVAL.
Yes, I will update the comment and put in the WARN().
Thanks,
Yu-cheng
+ 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
+ * null, XFEAUTRE_CET_USER is in init state. Shadow stack
+ * pointer is null in this case, so return zero.
+ */
+ p = get_xsave_addr(&fpu->state.xsave, XFEATURE_CET_USER);
+ if (p)
+ ssp = p->user_ssp;
+ }
+
+ fpregs_unlock();
Why are we even calling into this code if shadow stacks might be
disabled? Seems like we should have just errored out long before
getting here.
That is true. When this function is called, shadow stack is enabled.
If get_xsave_addr() returns null, it is possible xstates is messed up.
Maybe I can update the comments to explain it?
Thanks,
Yu-cheng
On Thu, Jul 22, 2021 at 01:51:56PM -0700, Yu-cheng Yu wrote:
quoted hunk
@@ -153,13 +178,23 @@ 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 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);
Well, this is weird: if some kernel code queries a shstk page and this
here function says it is writable but then goes and tries to write into
it and that write fails, then it'll confuse the user.
IOW, from where I'm standing, that should be:
return (pte_flags(pte) & _PAGE_RW) && !pte_shstk(pte);
as in, a writable page is one which has _PAGE_RW and it is *not* a
shadow stack page because latter is special and not really writable.
Hmmm?
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
On Thu, Jul 22, 2021 at 01:51:59PM -0700, Yu-cheng Yu wrote:
quoted hunk
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(+)
Why is that try_cmpxchg() call doing casting to its operands instead of
like the pte one above?
I.e., why aren't you doing here the same thing as above:
...
} while (!try_cmpxchg(&pmdp->pmd, &old_pmd.pmd, new_pmd.pmd));
?
Thx.
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
On Thu, Jul 22, 2021 at 01:51:56PM -0700, Yu-cheng Yu wrote:
quoted
@@ -153,13 +178,23 @@ 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 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);
Well, this is weird: if some kernel code queries a shstk page and this
here function says it is writable but then goes and tries to write into
it and that write fails, then it'll confuse the user.
IOW, from where I'm standing, that should be:
return (pte_flags(pte) & _PAGE_RW) && !pte_shstk(pte);
as in, a writable page is one which has _PAGE_RW and it is *not* a
shadow stack page because latter is special and not really writable.
quoted
Hmmm?
Indeed, this can be looked at in a few ways. We can visualize
pte_write() as 'CPU can write to it with MOV' or 'CPU can write to it
with any opcodes'. Depending on whatever pte_write() is, copy-on-write
code can be adjusted accordingly.
Yu-cheng
On Thu, Jul 22, 2021 at 01:51:59PM -0700, Yu-cheng Yu wrote:
quoted
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(+)
Why is that try_cmpxchg() call doing casting to its operands instead of
like the pte one above?
I.e., why aren't you doing here the same thing as above:
...
} while (!try_cmpxchg(&pmdp->pmd, &old_pmd.pmd, new_pmd.pmd));
?
If !(CONFIG_PGTABLE_LEVELS > 2), we don't have pmd_t.pmd.
ERROR: spaces required around that '=' (ctx:VxW)
#109: FILE: fs/proc/task_mmu.c:666:
+ [ilog2(VM_SHADOW_STACK)]= "ss",
^
total: 1 errors, 0 warnings, 49 lines checked
Please integrate scripts/checkpatch.pl into your patch creation
workflow. Some of the warnings/errors *actually* make sense.
On Tue, Aug 17, 2021 at 11:24:29AM -0700, Yu, Yu-cheng wrote:
Indeed, this can be looked at in a few ways. We can visualize pte_write()
as 'CPU can write to it with MOV' or 'CPU can write to it with any opcodes'.
Depending on whatever pte_write() is, copy-on-write code can be adjusted
accordingly.
Can be?
I think you should exclude shadow stack pages from being writable
and treat them as read-only. How the CPU writes them is immaterial -
pte/pmd_write() is used by normal kernel code to query whether the page
is writable or not by any instruction - not by the CPU.
And since normal kernel code cannot write shadow stack pages, then for
that code those pages are read-only.
If special kernel code using shadow stack management insns needs
to modify a shadow stack, then it can check whether a page is
pte/pmd_shstk() but that code is special anyway.
Hell, a shadow stack page is (Write=0, Dirty=1) so calling it writable
^^^^^^^
is simply wrong.
Thx.
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
From: Andy Lutomirski <luto@amacapital.net> Date: 2021-08-17 20:13:17
On Aug 17, 2021, at 12:53 PM, Borislav Petkov [off-list ref] wrote:
On Tue, Aug 17, 2021 at 11:24:29AM -0700, Yu, Yu-cheng wrote:
quoted
Indeed, this can be looked at in a few ways. We can visualize pte_write()
as 'CPU can write to it with MOV' or 'CPU can write to it with any opcodes'.
Depending on whatever pte_write() is, copy-on-write code can be adjusted
accordingly.
Can be?
I think you should exclude shadow stack pages from being writable
and treat them as read-only. How the CPU writes them is immaterial -
pte/pmd_write() is used by normal kernel code to query whether the page
is writable or not by any instruction - not by the CPU.
And since normal kernel code cannot write shadow stack pages, then for
that code those pages are read-only.
If special kernel code using shadow stack management insns needs
to modify a shadow stack, then it can check whether a page is
pte/pmd_shstk() but that code is special anyway.
Hell, a shadow stack page is (Write=0, Dirty=1) so calling it writable
^^^^^^^
is simply wrong.
But it *is* writable using WRUSS, and it’s also writable by CALL, WRSS, etc.
Now if the mm code tries to write protect it and expects sensible semantics, the results could be interesting. At the very least, someone would need to validate that RET reading a read only shadow stack page does the right thing.
On Tue, Aug 17, 2021 at 01:13:09PM -0700, Andy Lutomirski wrote:
quoted
If special kernel code using shadow stack management insns needs
to modify a shadow stack, then it can check whether a page is
pte/pmd_shstk() but that code is special anyway.
Hell, a shadow stack page is (Write=0, Dirty=1) so calling it writable
^^^^^^^
is simply wrong.
But it *is* writable using WRUSS, and it’s also writable by CALL,
Well, if we have to be precise, CALL doesn't write it directly - it
causes for shadow stack to be written as part of CALL's execution. Yeah
yeah, potato potato.
WRSS, etc.
Thus the "special kernel code" thing above. I've left it in instead of
snipping it.
Now if the mm code tries to write protect it and expects sensible
semantics, the results could be interesting. At the very least,
someone would need to validate that RET reading a read only shadow
stack page does the right thing.
On Tue, Aug 17, 2021, at 1:24 PM, Borislav Petkov wrote:
On Tue, Aug 17, 2021 at 01:13:09PM -0700, Andy Lutomirski wrote:
quoted
quoted
If special kernel code using shadow stack management insns needs
to modify a shadow stack, then it can check whether a page is
pte/pmd_shstk() but that code is special anyway.
Hell, a shadow stack page is (Write=0, Dirty=1) so calling it writable
^^^^^^^
is simply wrong.
But it *is* writable using WRUSS, and it’s also writable by CALL,
Well, if we have to be precise, CALL doesn't write it directly - it
causes for shadow stack to be written as part of CALL's execution. Yeah
yeah, potato potato.
Potahto.
quoted
WRSS, etc.
Thus the "special kernel code" thing above. I've left it in instead of
snipping it.
WRSS can be used from user mode depending on the configuration.
quoted
Now if the mm code tries to write protect it and expects sensible
semantics, the results could be interesting. At the very least,
someone would need to validate that RET reading a read only shadow
stack page does the right thing.
Huh?
A shadow stack page is RO (W=0).
Double-you shmouble-you. You can't write it with MOV, but you can write it from user code and from kernel code. As far as the mm is concerned, I think it should be considered writable.
Although... anyone who tries to copy_to_user() it is going to be a bit surprised. Hmm.
On Tue, Aug 17, 2021 at 01:51:52PM -0700, Andy Lutomirski wrote:
WRSS can be used from user mode depending on the configuration.
My point being, if you're going to do shadow stack management
operations, you should check whether the target you're writing to is a
shadow stack page. Clearly userspace can't do that but userspace will
get notified of that pretty timely.
Double-you shmouble-you. You can't write it with MOV, but you can
write it from user code and from kernel code. As far as the mm is
concerned, I think it should be considered writable.
Because?
Although... anyone who tries to copy_to_user() it is going to be a bit
surprised. Hmm.
Ok, so you see the confusion.
In any case, I don't think you can simply look at a shadow stack page as
simple writable page. There are cases where it is going to be fun.
So why are we even saying that a shadow stack page is writable? Why
can't we simply say that a shadow stack page is, well, something
special?
--
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquette
On Tue, Aug 17, 2021 at 01:51:52PM -0700, Andy Lutomirski wrote:
quoted
WRSS can be used from user mode depending on the configuration.
My point being, if you're going to do shadow stack management
operations, you should check whether the target you're writing to is a
shadow stack page. Clearly userspace can't do that but userspace will
get notified of that pretty timely.
quoted
Double-you shmouble-you. You can't write it with MOV, but you can
write it from user code and from kernel code. As far as the mm is
concerned, I think it should be considered writable.
Because?
quoted
Although... anyone who tries to copy_to_user() it is going to be a bit
surprised. Hmm.
Ok, so you see the confusion.
copy_to_user() can run into normal read-only areas too. The caller can
handle that just fine.
In any case, I don't think you can simply look at a shadow stack page as
simple writable page. There are cases where it is going to be fun.
So why are we even saying that a shadow stack page is writable? Why
can't we simply say that a shadow stack page is, well, something
special?
We can visualize the type of a mm area by looking at vma->vm_flags, e.g.
maybe_mkwrite(), and PTE macros as lower-level operatives. These two
have some relations but not one-to-one. Note that a PTE in a writable
area is not always pte_write().
I have considered and implemented a shadow stack PTE either pte_write()
or not. Making shadow stack as pte_write() results in less arch_*
macros and less confusion in copy-on-write code. That is one more thing
to consider.
Thanks,
Yu-cheng
On Wed, Aug 18, 2021 at 09:38:30AM -0700, Yu, Yu-cheng wrote:
We can visualize the type of a mm area by looking at vma->vm_flags, e.g.
visualize?
maybe_mkwrite(), and PTE macros as lower-level operatives. These two have
some relations but not one-to-one. Note that a PTE in a writable area is
not always pte_write().
I have considered and implemented a shadow stack PTE either pte_write() or
not. Making shadow stack as pte_write() results in less arch_* macros and
less confusion in copy-on-write code. That is one more thing to consider.