x86/shstk: More shadow stack enablement and path to IDT support
cover x86/shstk: More shadow stack enablement and path to IDT support
Disclaimer: A large part of my understanding of shadow stack and some parts of this series are from interactions with AI agents. Please forgive any slop.
Introduction
============
A query on supervisor shadow stacks brought Dave's series [1] to my attention and getting it to boot on a zEn6 machine revealed a couple early problems.
1. AMD processors supporting FRED don't have SERIALIZE and sync_core() defaults to IRET-to-self which tries to pop a { CS, LIP, SS } frame that doesn't exist on shadow stack.
2. The kernel text patching requires emulating RET and CALL instructions. RET is simple enough and follows similar footsteps as regs_set_return_ip() but emulating CALL is more challenging since, unlike the regular stack that has FRED REDZONE, the shadow stack has no gaps to push a return frame.
The code that got to prompt was horrible so over the past couple of weeks I tried to understand shadow stacks better and hopefully have turned the essence of initial slop that booted to prompt into a reviewable series.
This is a more principled approach to enabling a bunch of features to work with shadow stacks on FRED enabled systems and beyond. Ugly is reserved for the end.
Write-to-CR2 for serialization
==============================
CPUs that don't have SERIALIZE and have X86_FEATURE_KERN_SHSTK will default to using write-to-CR2 as serializing step. write-to-CR2 is available widely and although the comment in sync_core() suggests XEN may have some issues here, CONFIG_X86_KERE_SHADOW_STACK cannot be compiled with XEN yet so we'll consider write-to-CR2 as a temporary measure.
Making IRET-to-self work needs 3 dummy CALLs + 3 WRSS to setup the shadow stack which might be too heavy handed for sync_core().
Enabling shaddow stack at early boot
====================================
The idle tasks are given their own shadow stack and are switched in with restorprevss at early boot just after enabling shadow stacks in S_CET. This avoids complicated handling in context switch path.
Note: Enable, disable kernel shadow stack helpers are ugly since they have to be __always_inline so they can be called from spots with a shallow stack to enable shadow stack with a single return entry.
start_kernel() and start_secondary() both are noreturn and a shallow call location in their chain is a good point to enable shadow stacks with just a single return slot whose corresponding RET jumps into the noreturn function.
CALL emulation
==============
Call emulation requires a RET frame to be inserted below the FRED entry frame. FRED frame is a { CS, LIP, SSP } pushed onto the shadow stack.
To make our lives easy, we push a corresponding metadata frame onto the regula stack on top of pt_regs to make the following container:
struct {
u64 metadata; /* Context */
u64 ssp; /* SSP at FRED_ENTRY */
pt_rega *regs;}
For CALL emulation, regs_emulate_call() helper will use the SSP from this context to overwrite the CS in the FRED frame with the return IP. The original CS and LIP are moved one slot up to make:
... ...
+-----+ +-----+
| CS | | RET |
| LIP | -> +-----+
| SSP | | CS |
+-----+ | LIP | <- Jump to CALL site
+-----+ <- Top of stackText patching events always occur at same FRED level and SSP always points to address 3 slots down. regs_emulate_call() will then notify FRED_EXIT of the patching by setting a flag in the metadata.
FRED_EXIT will see this flag and do a dummy call, fixup stack, and overwrite the top of shadow stack with a SSP of three slots down to complete the FRED frame which matches for ERETS. After an ERETS, the fist RET will mismatch but rest of the RETs are balanced in RSB.
This is also the same method of doing a direct call via ORIG_RAX in ftrace_regs_caller and has been adopted here.
Ftrace, Kprobe, Rethooks
========================
Tracing can occur in three context - int3, fentry call, or a fentry trampoline like:
caller
traced function
int3
asm_fred_entrypoint_kernel
exec_int3()
rethook_hook() caller
call traced_function
call ftrace_caller
call ftrace_handlers
rethook_hook()
caller
call traced_function
jmp optprobe_template_entry
call probe_handlers
rethook_hook()
In each of these context, regs->ip modification, and regs->sp[0] changes need to target a specific shadow stack frame to ensure the shadow stack is consistent with the actual redirection.
Each context builds a copy of pt_regs and the same metadata frame can be constructed here with the SSP at the time of pt_regs snapshot. The metadata advertises if it came from a FRED entrypoint, ftrace caller, or optprobe.
Based on the context, either FRED frame is modified, or corresponding slot on shadows tack is modified to either hijack the return from function, or return from ftrac caller.
Note: To keep any exploit surface minimal, the ftrace_.*caller do not correct the shadow stack. The ftrace / kprobe handlers are expected to use the CET aware regs_* helper to steer regs->ip or add a return trampoline.
The return trampolines are also made context aware to set regs->ip back to the original caller.
Note: This may break a bunch of modules but for everyone's safety, they must adapt. It is easy to sync the shadow stack at ftrace_.*caller but is that the right thing to do?
BPF JIT
=======
BPF JIT only unwinds the stack (incsspq), skip's ftrace_caller's return from the direct trampoline (incsspq) or can override return with a trampoline (error injection).
All three are covered with the addition of context information. BPF JIT only has to emit an incsspq in the unwinder and tasmpoline return.
Retpolines, SRSO, CALL Thunks
=============================
All three can fix their shadow stack by either doing a WRSS of the correct return address for retpoline, or do an incsspq for SRSO and CALL depth stuffing.
Fill RSB loop also uses incsspq to dispose the frames injected by the stuffing.
As a consequence, all the thunks are much bigger since registers cannot be clobbered and rdsspq, incsspq both need a register operand. SRSO loses the handle_interrupted_saferet() fixup since it emulates a CALL, LEA, RET sequence and an incsspq between that is complicated thus making those systems slower and unsafe to interrupts during Safe-RET :-(
A possible way to solve this is to push a stack canary before pushing additional data to restore and use the canary position + whether regs->ip is past incsspq to emulate the RET while restoring register state and stack.
When this started out, I didn't realize we may get to IDT systems so interrupted SRSO is still unhandled in the series.
Since shadow stacks can be disabled during offline, suspend, kexec, and during early start_secondary, patched retpoline, SRSO thunk cannot assume wrss / incsspq is available else it will fault. All thunks need to first do a rdsspq to see if shadow stack is enabled or not and then continue which adds to the thunk size.
KEXEC, Suspend-Resume, Hibernation
==================================
All have to save SSP and disable shadow stack on the way out. On the way back in, read the saved data to enable shadow stacks again and restore the SSP at the same nesting level.
All are adapted to fit the existing save restore pattern in their path except KDUMP.
Path to IDT
===========
At this point, the handling of patching was very modular and just pushing the metadata frame around the pt_regs at IDT entry just worked since the same { CS, LIP, SSP } is pushed for kernel events.
There are additional setssbsy, clrssbsy handling to assert the SSP0 token in the syscall path and there is a need for supervisor token at base for INT_SSP_TAB but apart from that, things are simple.
Nested NMI is as complicated as stack management and the NMI from kernel has to clear the IST gate 1 shadow stack (which makes SSP0), switch back to the same shadow stack past the hardware populated frames, write two copies (inner and outer) on top and continue.
The structure of shadow stack is as follows:
+-------------------------------+ | supervisor token | +-------------------------------+ | Original CS | | Original LIP | Hardware overwrites this slot | Original SSP | +-------------------------------+ | Inner CS | | Inner LIP | Copied from first NMI | Inner SSP | +-------------------------------+ | Outer CS | | Outer LIP | For the IRET from first NMI | Outer SSP | +-------------------------------+
A nested NMI will use the same shadow stack, the hardware overxrwrites the lower frames, sees it is nested, and will modify the outer shadow stack frame to make the first NMI return back to repeat_nmi.
If there are no nested NMIs, the outer frame is used for IRET which is same as th original frame. This has been tested on a DEBUG_ENTRY kernel with sysrq trigger, kprobe on NMI, and perf record going at it but did not #CP/#GP/#DF do I'm assuming it works.
Testing
=======
Changes have been tested on a Zen6 (1024 CPUs; FRED), Zen4 (512 CPUs; IDT, SRSO), and a Granite Rapids (256 CPUs; IDT) server with Ftrace selftest, BPF selftest, and NMI stress test on a DEBUG_ENTRY kernel.
Credits
=======
All the credits for the effort goes to Dave. Without the strong foundations from his series, this iteration would not have been possible.
How to apply
============
These patches cleany apply on top of Dave's series from [1] which in turn in applied on top of v7.3-rc6. For convenience a tree is present at:
https://github.com/kudureranganath/linux.git x86/shstk_rfc_v1
Tree also contains a reference build config that I have been testing with. Your mileage may vary.
References
==========
[1] https://lore.kernel.org/all/[email protected]/
---
Andrew Cooper (1):
x86/entry: Parameterize kernel shadow stack handling at FRED entry
K Prateek Nayak (26):
x86/perf_regs: Rename pt_regs_offset array to prevent build failure x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACK x86/cet: Make kernel shadow stack #CP fatal instead of livelocking x86/sync_core: Don't use IRET-to-self with kernel shadow stacks x86/process: Initialize and enable kernel shadow stack at boot x86/entry: Handle int3 text patching with kernel shadow stack x86/retpoline: Handle retpolies and thunks with kernel shadow stack x86/ftrace: Prepare ftrace trampolines to handle shadow stack x86/kprobes: Prepare optprobe trampoline to handle shadow stacks x86/rethook: Prepare the rethook trampoline to handle shadow stack x86/cet: Make regs_set_return_ip() helpers context aware x86/cet: Introduce regs_set_return_trampoline() for rethook trampoline x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and
trampoline redirection
x86/rethook: Make the trampoline insert and return shadow stack aware x86/error_inject: Use CET helpers to insert just_return_func
trampoline
x86/kprobes: Use CET helpers in kprobe core to modify regs->ip x86/bpf: Make BPF JIT aware of CET handling
x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACK x86/shstk: Disable kenrel shadow stack when CPU is offlined x86/shstsk: Allow suspend-resume and hibernation with kernel shadow
stack
x86/shstk: Save and restore shadow stack pointer during kexec x86/idt: Map MCE shadow stack and populate the INT_SPP table x86/process: Initialize shadow stack for IDT systems x86/entry: Prepare IDT entry for shadow stacks x86/syscall: Toggle shadow stack busy on entry and exit from syscall x86/entry: Handle shadow stack on nested NMI
arch/x86/Kconfig | 51 ---- arch/x86/entry/calling.h | 99 ++++++++ arch/x86/entry/entry_64.S | 350 ++++++++++++++++++++------ arch/x86/entry/entry_64_compat.S | 10 + arch/x86/entry/entry_64_fred.S | 39 +-- arch/x86/include/asm/alternative.h | 3 +- arch/x86/include/asm/cpu.h | 106 ++++++++ arch/x86/include/asm/cpu_entry_area.h | 2 + arch/x86/include/asm/entry-common.h | 19 +- arch/x86/include/asm/fred.h | 7 - arch/x86/include/asm/ftrace.h | 7 +- arch/x86/include/asm/insn-eval.h | 27 +- arch/x86/include/asm/nospec-branch.h | 82 +++++- arch/x86/include/asm/suspend.h | 2 + arch/x86/include/asm/sync_core.h | 11 + arch/x86/include/asm/text-patching.h | 7 +- arch/x86/include/asm/traps.h | 1 + arch/x86/kernel/Makefile | 3 +- arch/x86/kernel/acpi/wakeup_64.S | 6 + arch/x86/kernel/alternative.c | 4 +- arch/x86/kernel/asm-offsets.c | 3 + arch/x86/kernel/cet.c | 348 +++++++++++++++++++++++-- arch/x86/kernel/cpu/common.c | 2 + arch/x86/kernel/ftrace.c | 20 +- arch/x86/kernel/ftrace_64.S | 121 +++++++-- arch/x86/kernel/idt.c | 30 +++ arch/x86/kernel/kprobes/core.c | 14 +- arch/x86/kernel/kprobes/ftrace.c | 2 + arch/x86/kernel/kprobes/opt.c | 28 ++- arch/x86/kernel/machine_kexec_64.c | 4 + arch/x86/kernel/perf_regs.c | 6 +- arch/x86/kernel/process.c | 68 ++++- arch/x86/kernel/rethook.c | 42 +++- arch/x86/kernel/shstk.c | 8 +- arch/x86/kernel/smpboot.c | 3 + arch/x86/kernel/traps.c | 4 +- arch/x86/kernel/vmlinux.lds.S | 8 + arch/x86/lib/error-inject.c | 2 +- arch/x86/lib/retpoline.S | 92 ++++++- arch/x86/mm/cpu_entry_area.c | 27 ++ arch/x86/mm/pat/set_memory.c | 17 ++ arch/x86/net/bpf_jit_comp.c | 18 +- arch/x86/power/hibernate.c | 2 + arch/x86/power/hibernate_32.c | 16 +- arch/x86/power/hibernate_asm_64.S | 7 + kernel/bpf/helpers.c | 3 +- kernel/trace/fgraph.c | 1 + 47 files changed, 1471 insertions(+), 261 deletions(-)
Signature · 1 line
2.43.0
RFC PATCH 1/27 x86/entry: Parameterize kernel shadow stack handling at FRED entry
From: Andrew Cooper <[email protected]>
Picked from feedback on Dave's RFC.
(Not-yet-)Signed-off-by: Andrew Cooper <[email protected]>
--- arch/x86/entry/entry_64_fred.S | 42 +++++++++++++--------------------- 1 file changed, 16 insertions(+), 26 deletions(-)
arch/x86/entry/entry_64_fred.S +16 -26
@@ -16,35 +16,27 @@ .code64 .section .noinstr.text, "ax" -/* - * Kernel-mode events: save the SSP of the shadow stack frame FRED - * pushed (old SSP, LIP, CS) just below pt_regs. See struct - * fred_kernel_frame. - */ -.macro PUSH_KERNEL_EVENT_SSP -#ifdef CONFIG_X86_USER_SHADOW_STACK - xorl %eax, %eax - rdsspq %rax /* nop if shadow stacks are off */ - pushq %rax - UNWIND_HINT_REGS offset=8 -#endif -.endm - -.macro POP_KERNEL_EVENT_SSP -#ifdef CONFIG_X86_USER_SHADOW_STACK - addq $8, %rsp -#endif -.endm - -.macro FRED_ENTER +.macro FRED_ENTER ssp=0 UNWIND_HINT_END_OF_STACK ANNOTATE_NOENDBR PUSH_AND_CLEAR_REGS ENCODE_FRAME_POINTER movq %rsp, %rdi /* %rdi -> pt_regs */ + +#ifdef CONFIG_X86_KERN_SHADOW_STACK + .if \ssp + rdsspq %rax /* NOP if SHSTK is off. Pre-zeroed. */ + push %rax + .endif +#endif .endm -.macro FRED_EXIT +.macro FRED_EXIT ssp=0 +#ifdef CONFIG_X86_KERN_SHADOW_STACK + .if \ssp + pop %rax /* Any dead register */ + .endif +#endif UNWIND_HINT_REGS POP_REGS .endm
@@ -73,11 +65,9 @@ SYM_CODE_END(asm_fred_entrypoint_user) */ .org asm_fred_entrypoint_user + 256, 0xcc SYM_CODE_START_NOALIGN(asm_fred_entrypoint_kernel) - FRED_ENTER - PUSH_KERNEL_EVENT_SSP + FRED_ENTER ssp=1 call fred_entry_from_kernel - POP_KERNEL_EVENT_SSP - FRED_EXIT + FRED_EXIT ssp=1 ERETS SYM_CODE_END(asm_fred_entrypoint_kernel)
Signature · 1 line
2.43.0
RFC PATCH 2/27 x86/perf_regs: Rename pt_regs_offset array to prevent build failure
In reply to K Prateek NayakSubsequent patches will add header dependency that will conflict with "pt_regs_offset" naming. Since "pt_regs_offset" is a static array used only by perf_regs, rename it to "__pt_regs_offset" to prevent build conflicts with asm/insn-eval.h version.
No functional changes intended.
--- arch/x86/kernel/perf_regs.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
arch/x86/kernel/perf_regs.c +3 -3
@@ -17,7 +17,7 @@#define PT_REGS_OFFSET (id, r) [id] = offsetof(struct pt_regs, r) -static unsigned int pt_regs_offset[PERF_REG_X86_MAX ] = { +static unsigned int __pt_regs_offset[PERF_REG_X86_MAX ] = {PT_REGS_OFFSET (PERF_REG_X86_AX , ax),PT_REGS_OFFSET (PERF_REG_X86_BX , bx),PT_REGS_OFFSET (PERF_REG_X86_CX , cx),
@@ -68,10 +68,10 @@ u64 perf_reg_value(struct pt_regs *regs, int idx)return perf_regs->xmm_regs[idx -PERF_REG_X86_XMM0 ]; } -if (WARN_ON_ONCE (idx >=ARRAY_SIZE (pt_regs_offset))) +if (WARN_ON_ONCE (idx >=ARRAY_SIZE (__pt_regs_offset)))return 0 ; -return regs_get_register (regs, pt_regs_offset[idx]); +return regs_get_register (regs, __pt_regs_offset[idx]); }#define PERF_REG_X86_RESERVED (((1ULL << PERF_REG_X86_XMM0) - 1) & \
Signature · 1 line
2.43.0
RFC PATCH 3/27 x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACK
In reply to K Prateek NayakSince shstk.c is only compiled when X86_USER_SHADOW_STACK in enabled, a build that only enables X86_KERN_SHADOW_STACK fails to link since arch_init_thread_stacks() is not compiled in.
Add a defbool X86_SHADOW_STACK option that gets toggled when either user, or kernel shadow stack support is toggled and use that to build shstk.o.
No functional changes intended.
--- arch/x86/kernel/Makefile | 3 +-- arch/x86/kernel/shstk.c | 8 +++++++- 2 files changed, 8 insertions(+), 3 deletions(-)
arch/x86/kernel/Makefile +1 -2
@@ -167,8 +167,7 @@ obj-$(CONFIG_CFI) += cfi.o obj-$(CONFIG_CALL_THUNKS) += callthunks.o obj-$(CONFIG_X86_CET) += cet.o - -obj-$(CONFIG_X86_USER_SHADOW_STACK) += shstk.o +obj-$(CONFIG_X86_CET) += shstk.o ### # 64 bit specific files
arch/x86/kernel/shstk.c +7 -1
@@ -26,6 +26,8 @@#include <asm/fpu/api.h> #include <asm/prctl.h> +#ifdef CONFIG_X86_USER_SHADOW_STACK +#define SS_FRAME_SIZE 8static bool features_enabled (unsigned long features)
@@ -631,7 +633,10 @@ bool shstk_is_enabled(void)return features_enabled (ARCH_SHSTK_SHSTK ); } +#endif /* CONFIG_X86_USER_SHADOW_STACK */ +#ifdef CONFIG_X86_KERN_SHADOW_STACK +static inline int set_shstk_pte (pte_t *ptep,unsigned long addr,void *data) {set_pte (ptep,pte_mkwrite_shstk (pte_wrprotect (ptep_get (ptep))));
@@ -650,4 +655,5 @@ void arch_init_thread_stacks(struct thread_stacks *ts) set_shstk_pte, NULL); flush_tlb_kernel_range(shstk_vaddr, shstk_vaddr + shstk_size); } -#endif + +#endif /* CONFIG_X86_KERN_SHADOW_STACK */
Signature · 1 line
2.43.0
RFC PATCH 4/27 x86/cet: Make kernel shadow stack #CP fatal instead of livelocking
In reply to K Prateek NayakA kernel-mode shadow stack #CP (NEAR-RET or FAR-RET/IRET) ends up in do_unexpected_cp(), which does WARN_ONCE() and returns to a shadow stack with mismatch. Returning executes that instruction again and faults again. After the first WARN this repeats silently forever. For example, IRET-to-self in sync_core() on a CPU without SERIALIZE just hangs the machine.
Nothing can be fixed up at that point. Handle kernel-mode shadow stack regular stack top vs the shadow stack top for RET, and the RIP in the IRET/ERETS frame vs the shadow stack LIP for FAR-RET/IRET. Then die(). A code path that returns somewhere the shadow stack doesn't expect now shows up as a one-line oops naming both targets, instead of a hang or a WARN storm.
--- arch/x86/kernel/cet.c | 101 ++++++++++++++++++++++++++++++++---------- 1 file changed, 77 insertions(+), 24 deletions(-)
arch/x86/kernel/cet.c +77 -24
@@ -1,7 +1,9 @@// SPDX-License-Identifier: GPL-2.0 #include <linux/ptrace.h> +#include <linux/uaccess.h> #include <asm/bugs.h> +#include <asm/kdebug.h> #include <asm/msr.h> #include <asm/traps.h> #include <asm/insn-eval.h>
@@ -112,6 +114,77 @@ static void ibt_clear_fred_wfe(struct pt_regs *regs) regs->fred_cs.wfe =0 ; } +/* +* FRED hardware pushes this frame on to the shadow stack for +* kernel=>kernel entry. First (lowest address) in this struct +* is the last entry pushed by the hardware. +*/ +struct fred_shstk_entry_frame { +u64 ssef_ssp; +u64 ssef_lip; +u64 ssef_cs; +}; + +/* +* The kernel=>kernel entry code pushes SSP on to the entry stack. +* This only occurs for kernel=>kernel entry. Not userspace. +* +* SSP is pushed on to the frame below pt_regs. At the point it is +* pushed, it points to a special FRED entry frame. +*/ +struct fred_kernel_frame { +struct fred_shstk_entry_frame *ssef; +struct pt_regs regs; +}; + +static unsigned long cp_peek (unsigned long addr) +{ +unsigned long val =0 ; + +copy_from_kernel_nofault (&val, (void *)addr,sizeof (val)); +return val; +} + +/* +* Shadow stack #CPs are faults: regs->ip is the RET/IRET/ERETS that found +* the mismatch and returning from here would just execute it again. There +* is no way to recover, so say which two return addresses disagreed and +* die. +*/ +static void do_kernel_shstk_cp (struct pt_regs *regs,unsigned long error_code) +{ +struct fred_shstk_entry_frame *ssef; +static const u8 erets[] = {0xf2 ,0x0f ,0x01 ,0xca }; +unsigned long ssp, ip, shstk_ip, sp_off =0 ; +u8 insn[sizeof (erets)] = { }; + + ssef = container_of(regs, struct fred_kernel_frame, regs)->ssef; + ssp =cp_peek ((unsigned long )&ssef->ssef_ssp); + +switch (error_code &CP_EC ) { +case CP_RET : + ip =cp_peek (regs->sp); + shstk_ip =cp_peek (ssp); +break ; +case CP_IRET : +/* ERETS skips the error code slot, IRET does not. */ +copy_from_kernel_nofault (insn, (void *)regs->ip,sizeof (insn)); +if (!memcmp (insn, erets,sizeof (erets))) + sp_off =8 ; + ip =cp_peek (regs->sp + sp_off); + shstk_ip =cp_peek (ssp +8 ); +break ; +default : + ip = shstk_ip =0 ; +break ; + } + +pr_emerg ("Kernel shadow stack violation (%s) at %pS: stack: %pS shadow stack: %pS (ssp=%lx)\n" , +cp_err_string (error_code), (void *)regs->ip, (void *)ip, + (void *)shstk_ip, ssp); +die ("control protection fault" , regs, error_code); +} +static void do_kernel_cp_fault (struct pt_regs *regs,unsigned long error_code) {if ((error_code &CP_EC ) !=CP_ENDBR ) {
@@ -156,36 +229,16 @@ DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)else do_unexpected_cp (regs, error_code); }else { -if (cpu_feature_enabled (X86_FEATURE_IBT )) +if (cpu_feature_enabled (X86_FEATURE_KERN_SHSTK ) && + (error_code &CP_EC ) !=CP_ENDBR ) +do_kernel_shstk_cp (regs, error_code); +else if (cpu_feature_enabled (X86_FEATURE_IBT ))do_kernel_cp_fault (regs, error_code);else do_unexpected_cp (regs, error_code); } } -/* -* FRED hardware pushes this frame on to the shadow stack for -* kernel=>kernel entry. First (lowest address) in this struct -* is the last entry pushed by the hardware. -*/ -struct fred_shstk_entry_frame { -u64 ssef_ssp; -u64 ssef_lip; -u64 ssef_cs; -}; - -/* -* The kernel=>kernel entry code pushes SSP on to the entry stack. -* This only occurs for kernel=>kernel entry. Not userspace. -* -* SSP is pushed on to the frame below pt_regs. At the point it is -* pushed, it points to a special FRED entry frame. -*/ -struct fred_kernel_frame { -struct fred_shstk_entry_frame *ssef; -struct pt_regs regs; -}; -/* * Change the return IP of an event. Use this instead of directly * manipulating regs->ip.
Signature · 1 line
2.43.0
Re: [RFC PATCH 04/27] x86/cet: Make kernel shadow stack #CP fatal instead of livelocking
Quoted 8 lines · K Prateek Nayak
arch/x86/kernel/cet.c +0
-0@@ -112,6 +114,77 @@ static void ibt_clear_fred_wfe(struct pt_regs *regs) regs->fred_cs.wfe =0 ; }
arch/x86/kernel/cet.c static void ibt_clear_fred_wfe(struct pt_regs *regs) · line 126
Quoted 10 lines
arch/x86/kernel/cet.c +10
-0+/* +* FRED hardware pushes this frame on to the shadow stack for +* kernel=>kernel entry. First (lowest address) in this struct +* is the last entry pushed by the hardware. +*/ +struct fred_shstk_entry_frame { +u64 ssef_ssp; +u64 ssef_lip; +u64 ssef_cs; +};
The fred_ prefix should be removed. This is plain CET-SS, and the format is the same in IDT mode too.
~Andrew
RFC PATCH 5/27 x86/sync_core: Don't use IRET-to-self with kernel shadow stacks
In reply to K Prateek NayakOn CPUs without SERIALIZE (Zen6), sync_core() serializes with IRET-to-self. With kernel shadow stacks enabled, IRET at CPL0 also pops a {SSP, LIP, CS} frame from the shadow stack and checks it against the RIP and CS it returns to.
IRET-to-self only builds the frame on the regular stack, so the IRET raises:
Unexpected kernel mode #CP, error_code: far/iret
WARNING: arch/x86/kernel/cet.c:42 at exc_control_protection+0xe2/0x3b0 RIP: 0010:do_sync_core+0x24/0x30 smp_call_function_many_cond+0x3e7/0x5f0 smp_text_poke_batch_finish+0x12f/0x590 arch_jump_label_transform_apply+0x1a/0x30 static_key_disable_cpuslocked+0x90/0xa0
LFENCE is not enough for cross-modifying code and making IRET-to-self shadow stack compatible would need three CALLs plus three WRSSs to fake the frame.
Use write-to-cr2 as the serializing operation for systems that have X86_FEATURE_KERN_SHSTK but don't support SERIALIZE instruction.
--- arch/x86/include/asm/sync_core.h | 11 +++++++++++ 1 file changed, 11 insertions(+)
arch/x86/include/asm/sync_core.h +11 -0
@@ -66,6 +66,17 @@ static __always_inline void sync_core(void)return ; } +/* +* IRET-to-self fabricates a frame on the regular stack only. With +* supervisor shadow stacks enabled, IRET (and ERETS) also pop and +* verify a {SSP, LIP, CS} frame from the shadow stack, which isn't +* there -> #CP(FAR-RET/IRET). Use MOV-to-CR2 to serialize. +*/ +if (cpu_feature_enabled (X86_FEATURE_KERN_SHSTK )) { +native_write_cr2 (native_read_cr2 ()); +return ; + } +/* * For all other processors, there are quite a few ways to do this. * IRET-to-self is nice because it works on every CPU, at any CPL
Signature · 1 line
2.43.0
RFC PATCH 6/27 x86/process: Initialize and enable kernel shadow stack at boot
In reply to K Prateek NayakCurrent scheme of dynamically toggling shadow stacks at context-switch is heavy handed and unnecessary if all tasks start off with kernel shadow stack initialized before the CPU can context-switch.
Initialize forked task with a restore token and enable shadow stacks early into the boot after the CPU has been identified and feature flags are patched.
This gets us the simple pattern for SSP handling at context-switch of:
rstorssp -8(%rax)
saveprevssp
The init_task has its shadow stack data mapped into the kernel image and needs the CPA helper to change it to RO mapping unlike AP which goes via copy_process() and has its shadow stack area vmalloced.
The first context switch is only possible after BSP has patched alternatives and it is safe to patch out the shadow stack handling in the switch path.
--- arch/x86/entry/entry_64.S | 88 ++++------------------------------- arch/x86/include/asm/cpu.h | 62 ++++++++++++++++++++++++ arch/x86/kernel/cpu/common.c | 2 + arch/x86/kernel/process.c | 54 ++++++++++++++++----- arch/x86/kernel/smpboot.c | 2 + arch/x86/kernel/vmlinux.lds.S | 8 ++++ arch/x86/mm/pat/set_memory.c | 17 +++++++ 7 files changed, 141 insertions(+), 92 deletions(-)
arch/x86/entry/entry_64.S +8 -80
@@ -170,83 +170,14 @@ SYM_INNER_LABEL(entry_SYSRETQ_end, SYM_L_GLOBAL) int3 SYM_CODE_END(entry_SYSCALL_64) -.macro SAVE_KERNEL_SHADOW_STACK +.macro SWITCH_KERNEL_SHADOW_STACK #ifdef CONFIG_X86_KERN_SHADOW_STACK - /* kshstk_ssp==0 means no kernel shadow stack, skip handling */ - cmpq $0, TASK_thread_kshstk_ssp(%rdi) - je .Lprev_no_shstk\@ - rdsspq %rax - movq %rax, TASK_thread_kshstk_ssp(%rdi) -.Lprev_no_shstk\@: -#endif -.endm - -.macro ENABLE_KERNEL_SHADOW_STACK - movl $MSR_IA32_S_CET, %ecx - rdmsr - orl $(CET_SHSTK_EN | CET_WRSS_EN), %eax - wrmsr -.endm - -.macro DISABLE_KERNEL_SHADOW_STACK - movl $MSR_IA32_S_CET, %ecx - rdmsr - andl $~(CET_SHSTK_EN | CET_WRSS_EN), %eax - wrmsr -.endm - -/* - * Clobbers rax, rcx, rdx, r8, r9. rdi/rsi must survive for the rest - * of __switch_to_asm. - * - * Dumb and slow. Always does WRMSR, regardless of if changes need to - * be made. - */ -.macro LOAD_KERNEL_SHADOW_STACK -#ifdef CONFIG_X86_KERN_SHADOW_STACK - movq TASK_thread_kshstk_ssp(%rsi), %r8 - testq %r8, %r8 - jz .Lnext_no_shstk\@ - - ENABLE_KERNEL_SHADOW_STACK - - /* - * This should be just a: - * - * rstorssp - * saveprevssp - * - * sequence. But, currently, the previous task might not - * have a valid SSP, like the init_task. This needs fixing. - * But, for now, just hack a Prev-SSP token in. - * - * The right fix is to give all tasks a valid SSP universally - * and then initialize the token once at task creation time, - * probably near the spot that ret_from_fork_asm is also - * written to the shadow stack. - */ - leaq -8(%r8), %r9 - movq %r8, %rax - /* - * Set type=0. Indicates a "Restore token" to satisfy RSTORSSP: - * Set mode=1. Indicates 64-bit mode. - * */ - orq $SHSTK_TOKEN_MODE64, %rax - wrssq %rax, (%r9) - - rstorssp (%r9) - - /* - * Discard the Previous-SSP token left by RSTORSSP. - * - * This will go away once SAVEPREVSSP is being used properly. - */ - movl $1, %eax - incsspq %rax - jmp .Lshstk_done\@ - -.Lnext_no_shstk\@: - DISABLE_KERNEL_SHADOW_STACK + ALTERNATIVE "jmp .Lshstk_done\@", "", X86_FEATURE_KERN_SHSTK + rdsspq %rbx + movq %rbx, TASK_thread_kshstk_ssp(%rdi) + movq TASK_thread_kshstk_ssp(%rsi), %rbx + rstorssp -8(%rbx) + saveprevssp .Lshstk_done\@: #endif .endm
@@ -273,7 +204,7 @@ SYM_FUNC_START(__switch_to_asm) movq %rsp, TASK_threadsp(%rdi) movq TASK_threadsp(%rsi), %rsp - SAVE_KERNEL_SHADOW_STACK + SWITCH_KERNEL_SHADOW_STACK #ifdef CONFIG_STACKPROTECTOR movq TASK_stack_canary(%rsi), %rbx
@@ -289,9 +220,6 @@ SYM_FUNC_START(__switch_to_asm) */ FILL_RETURN_BUFFER %r12, RSB_CLEAR_LOOPS, X86_FEATURE_RSB_CTXSW - /* Note that this clobbers tons of stuff: */ - LOAD_KERNEL_SHADOW_STACK - /* restore callee-saved registers */ popq %r15 popq %r14
arch/x86/include/asm/cpu.h +62 -0
74 lines not on this page · raw message
arch/x86/kernel/cpu/common.c +2 -0
@@ -2648,6 +2648,8 @@ void __init arch_cpu_finalize_init(void)alternative_instructions (); +cpu_setup_kernel_shstk (true); +if (IS_ENABLED (CONFIG_X86_64 )) {USER_PTR_MAX =TASK_SIZE_MAX ;
arch/x86/kernel/process.c +42 -12
95 lines not on this page · raw message
arch/x86/kernel/smpboot.c +2 -0
@@ -189,6 +189,8 @@ static void ap_starting(void)/* Save the processor parameters. */ identify_secondary_cpu (cpuid); +cpu_setup_kernel_shstk (false); +/* * The topology information must be up to date before * notify_cpu_starting().
arch/x86/kernel/vmlinux.lds.S +8 -0
@@ -185,6 +185,14 @@ SECTIONS /* init_task */ INIT_TASK_DATA(THREAD_SIZE) +#ifdef CONFIG_X86_KERN_SHADOW_STACK + /* + * The rest of init_thread_union: init_task's shadow stack, + * i.e. thread_union.stacks.shadow_stack[]. + */ + . += TASK_SHADOW_STACK_SIZE; +#endif + /* equivalent to task_pt_regs(&init_task) */ __top_init_kernel_stack = __end_init_stack - TOP_OF_KERNEL_STACK_PADDING - PTREGS_SIZE;
arch/x86/mm/pat/set_memory.c +17 -0
@@ -24,6 +24,7 @@#include <linux/memregion.h> #include <linux/cleanup.h> +#include <asm/cpu.h> #include <asm/e820/api.h> #include <asm/processor.h> #include <asm/tlbflush.h>
@@ -2823,6 +2824,22 @@ int __init kernel_unmap_pages_in_pgd(pgd_t *pgd, unsigned long address,return retval; } +#ifdef CONFIG_X86_KERN_SHADOW_STACK + +int set_init_task_shstk_attr (struct task_struct *tsk) +{ +int numpages =TASK_SHADOW_STACK_SIZE >>PAGE_SHIFT ; +unsigned long addr; + + addr = (unsigned long )task_thread_union (tsk)->stacks.shadow_stack; +return change_page_attr_set_clr (&addr, numpages, +__pgprot (_PAGE_DIRTY), +__pgprot (_PAGE_RW), +0 ,0 ,NULL ); +} + +#endif +/* * The testcases use internal knowledge of the implementation that shouldn't * be exposed to the rest of the kernel. Include these directly here.
Signature · 1 line
2.43.0
RFC PATCH 7/27 x86/entry: Handle int3 text patching with kernel shadow stack
In reply to K Prateek NayakKernel running with shadow stacks enabled explode early into the boot during text-poke like:
RIP: 0010:asm_fred_entrypoint_kernel+0x5f/0x70 <- ERETS, #CP
RIP: 0010:native_send_call_func_ipi+0x11/0xf0 <- after emulated NOP5
smp_call_function_many_cond+0x2c0/0x5f0
smp_text_poke_batch_finish+0x12f/0x590
static_key_enable+0x1f/0x30
_cpu_up+0x11a/0x260With kernel shadow stacks, a same-level FRED event pushes {CS, LIP, SSP} onto the shadow stack. ERETS raises #CP unless LIP and CS match the RIP and CS on the regular stack. The extable code already updates the frame through regs_set_return_ip() but this has not been extended to generic int3 based text patching.
Emulating JMP and RET are simple enough - jmp sets the ret->ip like extables and ret too does this with an addition of an emulated stack pop to direct to the return IP which has to adjust the SSP accordingly by moving it one slot lower.
Emulating a CALL is slightly more complicated - CALL pushes the return address onto the stack and jumps to the function as if it was called from LIP.
FRED stacks add a redzone on the stack that can be used for the call emulation but there is no gap in shadow stack for the same.
There are two ways to solve this:
o Inspired by IDT handling, add a dummy shadow stack slot on shadow stack for X86_TRAP_BP. This slot can then be used for CALL emulation to push a ret frame below the FRED shadow stack frame and then steer the FRED shadow stack frame to return to the caller.
In practice it looks like:
.macro PUSH_KERN_SHSTK_FRAME
xor %eax, %eax
pushq %rax
rdsspq %rax
cmpb $X86_TRAP_BP, PTREGS_fred_vector(%rdi)
jne .Lpush_shstk_done\@
ANNOTATE_INTRA_FUNCTION_CALL
call 1f
int3
1:
/* Indicate one extra slot is available on frame */
add $8, %rsp
incq (%rsp) .Lpush_shstk_done\@:
push %rax
.endm
.macro POP_KERN_SHSTK_FRAME
pop %rax
pop %rax
/* Spare slots are recalimed here. */
incsspq %rax.endm
The CALL emulation moves the FRED frame up by one slot to occupy the spare slot, sets 8(%rsp) to 0 to indicate that spare slot has been consumed
This has one key disadvantage that the INTRA_FUNCTION_CALL for every #BP will unbalance the RSB and CPU will mis-speculate every return after the handler has finished. Not ideal.
o (Implemented here) Use the same spare frame flags at 8(%rsp) to insert a tail call at POP_KERN_SHSTK_FRAME during FRED_EXIT. This adds a matching RSB to call entry much like the orig_rax path in the ftrace_regs_call.
The call emulation would have adjusted the SS frame to insert the ret frame, CS, and LIP. POP_KERN_SHSTK_FRAME adds the missing SSP to slot by pointing it to SPP + 32 after the INTRA_FUNCTION_CALL.
The emulation functions are marked noisntr since subsequent patches enable Ftrace caller hooks which can recurse if the patching function can be probed.
--- arch/x86/entry/entry_64_fred.S | 92 ++++++++++++++--- arch/x86/include/asm/insn-eval.h | 22 ++++- arch/x86/include/asm/text-patching.h | 7 +- arch/x86/kernel/alternative.c | 4 +- arch/x86/kernel/asm-offsets.c | 3 + arch/x86/kernel/cet.c | 142 +++++++++++++++++++++++++-- arch/x86/kernel/traps.c | 4 +- 7 files changed, 247 insertions(+), 27 deletions(-)
arch/x86/entry/entry_64_fred.S +81 -11
@@ -3,6 +3,7 @@ * The actual FRED entry points. */ +#include <linux/annotate.h> #include <linux/export.h> #include <linux/kvm_types.h>
@@ -16,6 +17,79 @@ .code64 .section .noinstr.text, "ax" +#ifdef CONFIG_X86_KERN_SHADOW_STACK + +/* + * A INT3 breakpoint can emulate a CALL which requires pushing the + * return frame below this FRED event. Allow the handlers to communicate + * if it emulated a CALL by setting a flag on the stack. + * + * FRED event pushes { SSP, LIP, CS } onto the shadow stack and SSP + * points to record three slots for top here and it should stay that + * way. + * + * CALL emulation will consume the SSP, push a return frame below, and + * set a flag on stack. If the flag is set, FRED_EXIT will add an + * shadow stack frame on top by doing an INTRA_FUNCTION_CALL and + * populate the top with a pointer to three slots below, thus recreating + * the correct FRED frame. + */ +.macro PUSH_KERN_SHSTK_FRAME + xor %eax, %eax + rdsspq %rax /* NOP if SHSTK is off. */ + pushq %rax + /* + * Frame metadata: + * + * [15:8] Context (FRED_EVENT) + * [ 7:0] fred_exit_work_flags + * + * Context data is used by CET helpers to interpret + * SSP frame. fred_exit_work_flags is used to fixup + * shadow stack for CALL emulation. + */ + pushq $0x100 +.endm + +/* Clobbers RAX, RCX; Both will be restored later. */ +.macro POP_KERN_SHSTK_FRAME + popq %rax /* fred_exit_work_flags */ + + /* Only one action is supported currently. */ + test %al, %al + jz .Lpop_shstk_done\@ + + /* + * CALL Emulation has overwritten the shadow-stack frame and + * SSP is lost. Point it back to 3 slots down where the real + * return has to go. + * + * Doing a CALL here will add a RSB which the next RET will + * mispredict on but all RETs after that are balanced. + */ + ANNOTATE_INTRA_FUNCTION_CALL + call 1f + int3 +1: + /* Synthesize the corrct SSP to fix the FRED Frame. */ + addq $8, %rsp + rdsspq %rax + leaq 24(%rax), %rcx + wrssq %rcx, (%rax) + +.Lpop_shstk_done\@: + popq %rax +.endm + +#else /* !CONFIG_X86_KERN_SHADOW_STACK */ + +.macro PUSH_KERN_SHSTK_FRAME +.endm +.macro POP_KERN_SHSTK_FRAME +.endm + +#endif /* CONFIG_X86_KERN_SHADOW_STACK */ + .macro FRED_ENTER ssp=0 UNWIND_HINT_END_OF_STACK ANNOTATE_NOENDBR
@@ -23,20 +97,16 @@ ENCODE_FRAME_POINTER movq %rsp, %rdi /* %rdi -> pt_regs */ -#ifdef CONFIG_X86_KERN_SHADOW_STACK - .if \ssp - rdsspq %rax /* NOP if SHSTK is off. Pre-zeroed. */ - push %rax - .endif -#endif +.if \ssp + PUSH_KERN_SHSTK_FRAME +.endif .endm .macro FRED_EXIT ssp=0 -#ifdef CONFIG_X86_KERN_SHADOW_STACK - .if \ssp - pop %rax /* Any dead register */ - .endif -#endif +.if \ssp + POP_KERN_SHSTK_FRAME +.endif + UNWIND_HINT_REGS POP_REGS .endm
arch/x86/include/asm/insn-eval.h +20 -2
@@ -83,8 +83,13 @@ static inline void insn_assign_reg(unsigned long *reg, u64 val, int bytes) }#ifdef CONFIG_X86_CET +void regs_set_return_ip (struct pt_regs *regs,unsigned long ip); -#else +void regs_emulate_call (struct pt_regs *regs,unsigned long ret,unsigned long func); +void regs_emulate_ret (struct pt_regs *regs,unsigned long ret_ip); + +#else /* !CONFIG_X86_CET */ +static inline void regs_set_return_ip (struct pt_regs *regs,unsigned long ip) {/* This is only for changing kernel return addresses: */
@@ -92,6 +97,19 @@ static inline void regs_set_return_ip(struct pt_regs *regs, unsigned long ip) regs->ip = ip; } -#endif + +static inline void regs_emulate_call (struct pt_regs *regs, +unsigned long ret, +unsigned long func) +{ +regs_set_return_ip (regs, func); +} + +static inline void regs_emulate_ret (struct pt_regs *regs,unsigned long ret_ip) +{ +regs_set_return_ip (regs, ret_ip); +} + +#endif /* CONFIG_X86_CET */ #endif /* _ASM_X86_INSN_EVAL_H */
arch/x86/include/asm/text-patching.h +4 -3
@@ -5,6 +5,7 @@#include <linux/types.h> #include <linux/stddef.h> #include <asm/ptrace.h> +#include <asm/insn-eval.h> /* * Currently, the max observed size in the kernel code is
@@ -135,7 +136,7 @@ extern __ro_after_init unsigned long text_poke_mm_addr;static __always_inline void int3_emulate_jmp(struct pt_regs *regs, unsigned long ip) { - regs->ip = ip; +regs_set_return_ip (regs, ip); } static __always_inline
@@ -167,14 +168,14 @@ static __always_inlinevoid int3_emulate_call (struct pt_regs *regs,unsigned long ip,unsigned long func) {int3_emulate_push (regs, ip); -int3_emulate_jmp (regs, func); +regs_emulate_call (regs, ip, func); }static __always_inline void int3_emulate_ret(struct pt_regs *regs) {unsigned long ip =int3_emulate_pop (regs); -int3_emulate_jmp (regs, ip); +regs_emulate_ret (regs, ip); } static __always_inline
arch/x86/kernel/alternative.c +2 -2
@@ -1981,7 +1981,7 @@ static bool decode_fineibt_preamble(struct pt_regs *regs, unsigned long *target,* Since regs->ip points to the middle of an instruction; it cannot * continue with the normal fixup. */ - regs->ip = *target; +regs_set_return_ip (regs, *target);return true;
@@ -2085,7 +2085,7 @@ static bool decode_fineibt_paranoid(struct pt_regs *regs, unsigned long *target, *target = regs->r11 + fineibt_prefix_size; *type = regs->ax; - regs->ip = *target; +regs_set_return_ip (regs, *target);return true; }
arch/x86/kernel/asm-offsets.c +3 -0
@@ -112,6 +112,9 @@ static void __used common(void)BLANK ();DEFINE (PTREGS_SIZE ,sizeof (struct pt_regs ));OFFSET (C_PTREGS_SIZE , pt_regs, orig_ax); +#ifdef CONFIG_X86_KERN_SHADOW_STACK +DEFINE (PTREGS_fred_vector, offsetof(struct pt_regs , fred_ss) +4 ); +#endif /* TLB state for the entry code */ OFFSET (TLB_STATE_user_pcid_flush_mask, tlb_state, user_pcid_flush_mask);
arch/x86/kernel/cet.c +135 -7
175 lines not on this page · raw message
arch/x86/kernel/traps.c +2 -2
@@ -466,9 +466,9 @@ noinstr bool handle_bug(struct pt_regs *regs)*/ if (handled) {if (regs->ip == addr) - regs->ip += ud_len; +regs_set_return_ip (regs, addr + ud_len); }else { - regs->ip = addr; +regs_set_return_ip (regs, addr); }if (regs->flags &X86_EFLAGS_IF )
Signature · 1 line
2.43.0
RFC PATCH 8/27 x86/retpoline: Handle retpolies and thunks with kernel shadow stack
In reply to K Prateek NayakRetpolines need to correct the return address on the shadow stack to match that of the indirect call target such that the return doesn't lead to a #CP. Direct jump to an out of line trampoline that handles shadow stack and does the final RET which allows keeping the retpoline thunk size below 32-bytes.
SRSO adds a CALL, LEA, RET pattern which needs to pop an intermediate shadow stack slot since the correct return address exists right below.
The handle_interrupted_saferet() handling with shadow stack is hard and there are no processors that need Safe-RET sequence to mitigate SRSO and support FRED (touch wood!).
Make any CPUs that toggle Safe-RET with X86_FEATURE_KERN_SHSTK call an alternalte Safe-RET thunk that handle_interrupted_saferet() is unaware of. If FRED enabled systems ever need Safe-RET (hopefully never), handle_interrupted_saferet() has to spot if the control is past incsspq or not (perhaps using another global symbol):
o If control is past incsspq, emulate a POP + RET like normal.
o If incsspq has not yet executed, use the FRED shadow stack frame's SSP to redirect the SSP at return to one slot above (similar to how int3_emulate_ret() does) in addition to handling the rest of the LEA + RET sequence.
Call depth thunk only needs to pop 16 entries when the RSB is stuffed which is also copied for the RSB_FILL_LOOP.
Retpolines cannot clobber registers and need to handle it on stack :-( Saferet sequences are longer :-(
Survives a spectre_v2=retpolines,generic :-)
--- arch/x86/Kconfig | 12 ---- arch/x86/include/asm/alternative.h | 3 +- arch/x86/include/asm/nospec-branch.h | 27 +++++++- arch/x86/lib/retpoline.S | 92 +++++++++++++++++++++++++++- 4 files changed, 116 insertions(+), 18 deletions(-)
arch/x86/Kconfig +0 -12
@@ -1907,18 +1907,6 @@ config X86_KERN_SHADOW_STACK depends on VMAP_STACK depends on AS_WRUSS select X86_CET - # The retpoline sequence is "call; mov %reg,(%rsp); ret": the - # CALL pushes a shadow stack entry and the RET then uses a - # rewritten return address. Mismatch every time. - depends on !MITIGATION_RETPOLINE - # The indirect call thunks are retpoline-based (see above) and - # call_depth_return_thunk() refills the RSB with 16 CALLs, then - # does "add $128,%rsp; ret", leaving 16 stale shadow stack entries. - depends on !MITIGATION_CALL_DEPTH_TRACKING - # Safe-RET is "call srso_safe_ret" followed by - # "lea 8(%rsp),%rsp; ret": the RET consumes the caller's return - # address while the shadow stack top holds the CALL's. - depends on !MITIGATION_SRSO # Replaces return addresses on the stack with return_to_handler, # and return_to_handler itself returns with a retpoline-style # "call; mov %rdi,(%rsp); ret".
arch/x86/include/asm/alternative.h +2 -1
@@ -329,7 +329,8 @@ void nop_func(void); .endm .macro ALTERNATIVE_3 oldinstr, newinstr1, ft_flags1, newinstr2, ft_flags2, newinstr3, ft_flags3 - __ALTERNATIVE(ALTERNATIVE_2(\oldinstr, \newinstr1, \ft_flags1, \newinstr2, \ft_flags2), + __ALTERNATIVE(__ALTERNATIVE(__ALTERNATIVE(\oldinstr, \newinstr1, \ft_flags1), + \newinstr2, \ft_flags2), \newinstr3, \ft_flags3) .endm
arch/x86/include/asm/nospec-branch.h +24 -3
@@ -121,6 +121,7 @@*/ #define RETPOLINE_THUNK_SIZE 32 +#define RSB_CLEAR_LOOPS 32/* To forcibly overwrite all entries */ /*
@@ -132,6 +133,24 @@int3 ; \ 772: +#ifdef CONFIG_X86_KERN_SHADOW_STACK + +/* INCSSP #UDs when the supervisor shadow stack is not enabled. */ +#define __FIXUP_SHSTK_SLOTS (reg, nr) \ + xor reg, reg; \ + rdsspq reg; \ + test reg, reg; \ + jz 773f; \ + mov $nr, reg; \ + incsspq reg; \ +773: + +#else /* !CONFIG_X86_KERN_SHADOW_STACK */ + +#define __FIXUP_SHSTK_SLOTS (reg, nr) + +#endif /* CONFIG_X86_KERN_SHADOW_STACK */ +/* * Stuff the entire RSB. *
@@ -149,6 +168,7 @@dec reg; \ jnz 771b; \/* barrier for jnz misprediction */ \ +__FIXUP_SHSTK_SLOTS (reg, nr); \ lfence; \CREDIT_CALL_DEPTH \CALL_THUNKS_DEBUG_INC_CTXSW
@@ -173,10 +193,11 @@* On PBRSB-vulnerable CPUs, it is not safe for a RET to be executed * before this point. */ -#define __FILL_ONE_RETURN \ +#define __FILL_ONE_RETURN (reg) \ __FILL_RETURN_SLOT \ add $(BITS_PER_LONG/8), %_ASM_SP; \ - lfence; + lfence; \ + __FIXUP_SHSTK_SLOTS(reg, 1);/* * Helper for detecting if an interrupt occurred at an unsafe location within
@@ -289,7 +310,7 @@ .macro FILL_RETURN_BUFFER reg:req nr:req ftr:req ftr2=ALT_NOT(X86_FEATURE_ALWAYS)ALTERNATIVE_2 "jmp .Lskip_rsb_\@" , \ __stringify(__FILL_RETURN_BUFFER(\reg,\nr)), \ftr, \ - __stringify(nop;nop;__FILL_ONE_RETURN), \ftr2 + __stringify(nop;nop;__FILL_ONE_RETURN(\reg)), \ftr2 .Lskip_rsb_\@: .endm
arch/x86/lib/retpoline.S +90 -2
127 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 9/27 x86/ftrace: Prepare ftrace trampolines to handle shadow stack
In reply to K Prateek NayakKprobes can hook onto function entry via optprobes, int3 kprobes, or via ftrace_regs_caller and hijack the return. From a shadow stack perspective, the ftrace_caller's stack looks like:
caller
call traced_function
call ftrace_regs_caller
Rethooks and return_to_handler can hijack the return address from traced_function; IPMODIFY and direct caller ftrace handlers can steer the return from traced function.
To be aware of the shadow stack context that needs correction, the CET helpers need to know the context from where pt_regs came from.
Similar to the FRED frame handling, push the SSP at ftrace_regs_caller and a context metadata flag onto the stack that can be inspected from the handler.
Based on the event type, the CET helpers can be made aware if the slot that needs modifying is at SSP, or just below. return_to_handler() now does the INTRA_FUNCTION_CALL early which allows using the stack slot pushed for the pt_regs container. !X86_KERN_SHADOW_STACK build will now do an extra pop.
Note: The return_to_handler now sets regs->cs to 0 to prevent false positives of !user_mode_regs() in CET helpers. Since a full pt_regs is not present, it also blocks the ftrace helper from returning the incomplete pt_regs pointer.
--- arch/x86/kernel/cet.c | 4 +- arch/x86/kernel/ftrace_64.S | 121 +++++++++++++++++++++++++++++++----- 2 files changed, 108 insertions(+), 17 deletions(-)
arch/x86/kernel/cet.c +3 -1
@@ -119,7 +119,9 @@ enum fred_exit_work { };enum frame_context { -FRED_ENTRY =1 +FRED_ENTRY =1 , +FTRACE_CALLER , +RETURN_TRAMPOLINE };/*
arch/x86/kernel/ftrace_64.S +105 -16
184 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 10/27 x86/kprobes: Prepare optprobe trampoline to handle shadow stacks
In reply to K Prateek NayakOptimized probes can be executed from a trampoline where, although it cannot hijack the regs->ip to steer return from the caller, it can still be used to attach a retprobe trampoline.
The path into the optprobe trampoline looks like:
caller
call traced_function
jmp optprobe_template_entry
Similar to FRED frame, extend a container outside pt_regs to notify this is an optprobe frame the handler is on using frame metadata.
The return trampoline will be populated at the top of SSP such that traced function's return jumps to the return trampoline and the trampoline can direct the return from within in case there are multiple trampolines chained on the same function.
--- arch/x86/kernel/cet.c | 3 ++- arch/x86/kernel/ftrace_64.S | 2 +- arch/x86/kernel/kprobes/opt.c | 26 ++++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-)
arch/x86/kernel/cet.c +2 -1
@@ -121,7 +121,8 @@ enum fred_exit_work {enum frame_context {FRED_ENTRY =1 ,FTRACE_CALLER , -RETURN_TRAMPOLINE +RETURN_TRAMPOLINE , +OPTPORBE_TRAMPOLINE };/*
arch/x86/kernel/ftrace_64.S +1 -1
@@ -459,7 +459,7 @@ SYM_CODE_START(return_to_handler) movq %rsp, %rdi /* - * Final RET will jump back to the old return address. Since, the return + * Final RET will jump back to the old return address. Since the return * frame was hijacked, use a retpoline here to keep the RSB balanced. * * For shadow stack, this adds the frame to stuff the return address into.
arch/x86/kernel/kprobes/opt.c +26 -0
@@ -34,6 +34,30 @@#include "common.h" +#ifdef CONFIG_X86_KERN_SHADOW_STACK + +/* +* Push a NULL on the stack to such that CET helpers will +* see Shadow stack pointer as NULL and skip shadow stack +* corrects internally. +*/ +#define OPTPROBE_PUSH_SHSTK_FRAME \ + " xor %eax, %eax\n" \ + " rdsspq %rax\n" \ + " pushq %rax\n" \ + " pushq $0x400\n" + +/* RAX is dead and will be restored after. */ +#define OPTPROBE_POP_SHSTK_FRAME \ + " addq $16, %rsp\n" + +#else /* !CONFIG_X86_KERN_SHADOW_STACK */ + +#define OPTPROBE_PUSH_SHSTK_FRAME +#define OPTPROBE_POP_SHSTK_FRAME + +#endif /* CONFIG_X86_KERN_SHADOW_STACK */ +unsigned long __recover_optprobed_insn (kprobe_opcode_t *buf,unsigned long addr) {struct optimized_kprobe *op;
@@ -115,6 +139,7 @@ asm (ASM_NOP3 SAVE_REGS_STRING" movq %rsp, %rsi\n" +OPTPROBE_PUSH_SHSTK_FRAME ".global optprobe_template_val\n" "optprobe_template_val:\n" ASM_NOP5
@@ -122,6 +147,7 @@ asm (".global optprobe_template_call\n" "optprobe_template_call:\n" ASM_NOP5 +OPTPROBE_POP_SHSTK_FRAME /* Copy 'regs->flags' into 'regs->ss'. */ " movq 18*8(%rsp), %rdx\n" " movq %rdx, 20*8(%rsp)\n"
Signature · 1 line
2.43.0
RFC PATCH 11/27 x86/rethook: Prepare the rethook trampoline to handle shadow stack
In reply to K Prateek NayakRethook prepare caches the original return IP from the regs->sp state it was presented and insert the trampoline that later returns back to the cached IP.
It is possible for multiple handlers to install multiple return trampolines such that the return from one jumps to another, and eventually landing to traced functions' caller's frame.
Since return trampoline has hijacked a genuine return, it must balance the call, not only from the RSB perspective but also from shadow stack perspective.
Similar to the return_to_handler, populate a dummy slot before triggering the rethook handlers. The rethook handler must populate the correct return IP in the slot using regs_set_return_ip() or expect a #CP for missing redirection.
Since the return trampolines (although limited to two) can be chained in weird manner to jump between each other based on the order of pre-handler's running, the tail call technique to populate the return from the ftrace handler turn complicated.
Instead, use a retpoline to return into the next trampoline until the execution finds its way back to the correct caller.
--- arch/x86/kernel/rethook.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+)
arch/x86/kernel/rethook.c +34 -0
@@ -6,6 +6,9 @@#include <linux/rethook.h> #include <linux/kprobes.h> #include <linux/objtool.h> +#include <linux/annotate.h> + +#include <asm/insn-eval.h> #include "kprobes/common.h"
@@ -15,6 +18,35 @@ __visible void arch_rethook_trampoline_callback(struct pt_regs *regs);#define ANNOTATE_NOENDBR #endif +#ifdef CONFIG_X86_KERN_SHADOW_STACK + +/* +* The return to caller of traced function was hijacked by the trampoline and +* the trampoline now corrects the return address. Add a spare slot at SSP that +* the fixup function can use to syncing the return IP on stack from +* arch_rethook_trampoline_callback(). +* +* Clobbers RAX which is dead in both context. +*/ +#define RETHOOK_PUSH_SHSTK_FRAME \ + ANNOTATE_INTRA_FUNCTION_CALL "\n" \ + " call 1f\n" \ + " int3\n" \ + "1:\n" \ + " xor %eax, %eax\n" \ + " rdsspq %rax\n" \ + " movq %rax, (%rsp)\n" \ + " pushq $0x300\n" + +#define RETHOOK_POP_SHSTK_FRAME \ + " addq $16, %rsp\n" + +#else /* !CONFIG_X86_KERN_SHADOW_STACK */ + +#define RETHOOK_PUSH_SHSTK_FRAME +#define RETHOOK_POP_SHSTK_FRAME + +#endif /* CONFIG_X86_KERN_SHADOW_STACK */ /* * When a target function returns, this code saves registers and calls * arch_rethook_trampoline_callback(), which calls the rethook handler.
@@ -35,7 +67,9 @@ asm(" pushfq\n" SAVE_REGS_STRING " movq %rsp, %rdi\n" +RETHOOK_PUSH_SHSTK_FRAME " call arch_rethook_trampoline_callback\n" +RETHOOK_POP_SHSTK_FRAME RESTORE_REGS_STRING /* In the callback function, 'regs->flags' is copied to 'regs->ss'. */ " addq $16, %rsp\n"
Signature · 1 line
2.43.0
RFC PATCH 12/27 x86/cet: Make regs_set_return_ip() helpers context aware
In reply to K Prateek NayakAll the known locations that can genuinely change the control flow have been instrumented to advertise their context. Use the context information to set the return IP to the correct shadow stack slot from regs_set_return_ip().
All the emulation helpers are still expected to be called from a #BP that inserts a FRED frame and any violations from other contexts are warned about to help debugs and any shadow stack adjustments for these contexts are skipped.
--- arch/x86/kernel/cet.c | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-)
arch/x86/kernel/cet.c +38 -3
@@ -275,6 +275,7 @@ DEFINE_IDTENTRY_ERRORCODE(exc_control_protection) noinstr void regs_set_return_ip(struct pt_regs *regs, unsigned long ip) {struct fred_shstk_entry_frame *ssef; +struct kernel_event_frame *frame; regs->ip = ip;
@@ -284,11 +285,34 @@ noinstr void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)/* Only kernel-mode events save the 'ssef' pointer. */ WARN_ON_ONCE (user_mode (regs)); - ssef = container_of(regs, struct kernel_event_frame, regs)->ssef; + frame = container_of(regs, struct kernel_event_frame, regs); + + ssef = frame->ssef;if (!ssef)return ; -wrss (ip, &ssef->ssef_lip); +switch (frame->context) { +case FRED_ENTRY : +wrss (ip, &ssef->ssef_lip); +break ; +case FTRACE_CALLER : + fallthrough; +case RETURN_TRAMPOLINE : +/* +* In case of both RETURN_TRAMPOLINE and FTRACE_CALLER, +* regs_set_return_ip() is used to hijack the return +* from the current frame. Just set the location at SSP. +*/ +wrss (ip, frame->ssp); +break ; +case OPTPORBE_TRAMPOLINE : +/* regs->ip changes from optprobes are ignored. */ +break ; +default : +WARN_ONCE (1 ,"Unknown calling context %d! Expect #CP\n" , + frame->context); +break ; + } }/*
@@ -317,6 +341,10 @@ noinstr void regs_emulate_call(struct pt_regs *regs, unsigned long ret, unsignedif (!ssef)return ; +/* A CALL emulation for !INT3 events are ignored. */ +if (WARN_ON_ONCE (frame->context !=FRED_ENTRY )) +return ; +/* Someone else emulated a CALL for same frame? */ if (WARN_ON_ONCE (frame->fred_exit_work_flags))return ;
@@ -371,6 +399,7 @@ noinstr void regs_emulate_call(struct pt_regs *regs, unsigned long ret, unsigned noinstr void regs_emulate_ret(struct pt_regs *regs, unsigned long ip) {struct fred_shstk_entry_frame *ssef; +struct kernel_event_frame *frame; regs->ip = ip;
@@ -379,10 +408,16 @@ noinstr void regs_emulate_ret(struct pt_regs *regs, unsigned long ip)WARN_ON_ONCE (user_mode (regs)); - ssef = container_of(regs, struct kernel_event_frame, regs)->ssef; + frame = container_of(regs, struct kernel_event_frame, regs); + + ssef = frame->ssef;if (!ssef)return ; +/* A RET emulation for !INT3 events are ignored. */ +if (WARN_ON_ONCE (frame->context !=FRED_ENTRY )) +return ; +/* * Return target should point to the old SP on top of the shadow * stack that was popped from the regular stack.
Signature · 1 line
2.43.0
RFC PATCH 13/27 x86/cet: Introduce regs_set_return_trampoline() for rethook trampoline
In reply to K Prateek NayakRethooks hijack the function return to jump to a return trampoline and then to the actual caller. Rethooks can be added from three contexts:
caller
traced function
int3
asm_fred_entrypoint_kernel
exec_int3()
rethook_hook() caller
call traced_function
call ftrace_caller
call ftrace_handlers
rethook_hook()
caller
call traced_function
jmp optprobe_template_entry
call probe_handlers
rethook_hook()
In each case, the return trampoline frame needs to be handled distinctly relative to the frame where pt_regs are created and SSP is stashed.
Provide a regs_set_return_trampoline() that will be used in subsequent commits to hijacks the shadow stack entry of return from traced function correctly using the context saved in the entry metadata.
The trampolines will use a retpoline to insert a shadow stack slot corresponding to correct return address and return to the caller correctly.
--- arch/x86/include/asm/insn-eval.h | 5 +++ arch/x86/kernel/cet.c | 77 ++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+)
arch/x86/include/asm/insn-eval.h +5 -0
@@ -87,6 +87,7 @@ static inline void insn_assign_reg(unsigned long *reg, u64 val, int bytes)void regs_set_return_ip (struct pt_regs *regs,unsigned long ip);void regs_emulate_call (struct pt_regs *regs,unsigned long ret,unsigned long func);void regs_emulate_ret (struct pt_regs *regs,unsigned long ret_ip); +void regs_set_ret_trampoline (struct pt_regs *regs,unsigned long ret);#else /* !CONFIG_X86_CET */
@@ -110,6 +111,10 @@ static inline void regs_emulate_ret(struct pt_regs *regs, unsigned long ret_ip)regs_set_return_ip (regs, ret_ip); } +static inline void regs_set_ret_trampoline (struct pt_regs *regs,unsigned long ret) +{ +} +#endif /* CONFIG_X86_CET */ #endif /* _ASM_X86_INSN_EVAL_H */
arch/x86/kernel/cet.c +77 -0
80 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 14/27 x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and trampoline redirection
In reply to K Prateek NayakFtrace core uses ftrace_regs_set_instruction_pointer() to redirect regs->ip both from ftrace_caller and from ftrace_return_to_handler return trampoline. Use regs_set_return_ip() to redirect function execution while correcting the shadow stack.
Livepatch too uses ftrace_regs_set_instruction_pointer() to redirect the execution to the livepatched function. As a consequence, using CET helper for the regs->ip redirection also enables livepatching.
Use regs_set_ret_trampoline() to insert the return_to_handler trampoline.
--- arch/x86/include/asm/ftrace.h | 7 +++++-- arch/x86/kernel/ftrace.c | 20 ++++++++++++++++++-- kernel/trace/fgraph.c | 1 + 3 files changed, 24 insertions(+), 4 deletions(-)
arch/x86/include/asm/ftrace.h +5 -2
@@ -68,9 +68,12 @@ arch_ftrace_get_regs(struct ftrace_regs *fregs) (_regs)->flags =0 ; \ }while (0 ) -#define ftrace_regs_set_instruction_pointer (fregs, _ip) \ - do { arch_ftrace_regs(fregs)->regs.ip = (_ip); } while (0) +void ftrace_regs_set_instruction_pointer(struct ftrace_regs *fregs, + unsigned long ip); + +#define ftrace_regs_set_instruction_pointer \ + ftrace_regs_set_instruction_pointerstatic __always_inline unsigned long ftrace_regs_get_return_address (struct ftrace_regs *fregs)
arch/x86/kernel/ftrace.c +18 -2
@@ -651,11 +651,16 @@ void prepare_ftrace_return(unsigned long ip, unsigned long *parent,if (unlikely (skip_ftrace_return ()))return ; +/* +* This is only used for !CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS +* (implying !X86_64) and does not need shadow stack handling. +*/ if (!function_graph_enter (*parent, ip, frame_pointer, parent)) *parent = return_hooker; }#ifdef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS +void ftrace_graph_func (unsigned long ip,unsigned long parent_ip,struct ftrace_ops *op,struct ftrace_regs *fregs) {
@@ -668,9 +673,20 @@ void ftrace_graph_func(unsigned long ip, unsigned long parent_ip,return ; -if (!function_graph_enter_regs (*parent, ip,0 , parent, fregs)) +if (!function_graph_enter_regs (*parent, ip,0 , parent, fregs)) { +regs_set_ret_trampoline (regs, return_hooker); *parent = return_hooker; + } } -#endif + +void ftrace_regs_set_instruction_pointer (struct ftrace_regs *fregs, +unsigned long ip) +{ +struct pt_regs *regs = &arch_ftrace_regs (fregs)->regs; + +regs_set_return_ip (regs, ip); +} + +#endif /* CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS */ #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
kernel/trace/fgraph.c +1 -0
@@ -822,6 +822,7 @@ __ftrace_return_to_handler(struct ftrace_regs *fregs, unsigned long frame_pointeftrace_graph_stop ();WARN_ON (1 );/* Might as well panic. What else to do? */ +ftrace_regs_set_instruction_pointer (fregs, (unsigned long )panic);return (unsigned long )panic; }
Signature · 1 line
2.43.0
RFC PATCH 15/27 x86/rethook: Make the trampoline insert and return shadow stack aware
In reply to K Prateek NayakUse the CET helper regs_set_ret_trampoline() to insert the rethook trampoline and regs_set_return_ip() to correct the return address to the caller from the return trampoline's handler.
--- arch/x86/kernel/rethook.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
arch/x86/kernel/rethook.c +7 -1
@@ -145,17 +145,23 @@ void arch_rethook_fixup_return(struct pt_regs *regs,/* Replace fake return address with real one. */ *frame_pointer = correct_ret_addr; +regs_set_return_ip (regs, correct_ret_addr); }NOKPROBE_SYMBOL (arch_rethook_fixup_return);void arch_rethook_prepare (struct rethook_node *rh,struct pt_regs *regs,bool mcount) { +unsigned long ip = (unsigned long )arch_rethook_trampoline;unsigned long *stack = (unsigned long *)regs->sp; rh->ret_addr = stack[0 ]; rh->frame = regs->sp;/* Replace the return addr with trampoline addr */ - stack[0 ] = (unsigned long ) arch_rethook_trampoline; + stack[0 ] = ip; + +/* First return trampoline; Override shadow stack. */ +if (rh->ret_addr != ip) +regs_set_ret_trampoline (regs, ip); }NOKPROBE_SYMBOL (arch_rethook_prepare);
Signature · 1 line
2.43.0
RFC PATCH 16/27 x86/error_inject: Use CET helpers to insert just_return_func trampoline
In reply to K Prateek NayakUse regs_set_return_ip() to insert the retun to just_return_func. Unlike a return trampoline, the just_return_func hijacks the return from ftrace_regs_caller / int3 breakpoint (much like the direct hump path from ftrace_regs_caller) to jump to execute just_return_func which directly returns to the caller's slot.
--- arch/x86/lib/error-inject.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/lib/error-inject.c +1 -1
@@ -20,6 +20,6 @@ asm(void override_function_with_return (struct pt_regs *regs) { - regs->ip = (unsigned long )&just_return_func; +regs_set_return_ip (regs, (unsigned long )&just_return_func); }NOKPROBE_SYMBOL (override_function_with_return);
Signature · 1 line
2.43.0
RFC PATCH 17/27 x86/kprobes: Use CET helpers in kprobe core to modify regs->ip
In reply to K Prateek NayakUse regs_set_return_ip() in kprobe core to that modifies regs->ip. Open-coded kprobe_emulate_call_indirect() has been converted to use int3_emulate_call() to the indirect call target.
--- arch/x86/kernel/kprobes/core.c | 14 +++++++------- arch/x86/kernel/kprobes/ftrace.c | 2 ++ arch/x86/kernel/kprobes/opt.c | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-)
arch/x86/kernel/kprobes/core.c +7 -7
@@ -498,7 +498,7 @@ static void kprobe_emulate_ifmodifiers(struct kprobe *p, struct pt_regs *regs) regs->flags =int3_emulate_pop (regs);break ; } - regs->ip = regs->ip -INT3_INSN_SIZE + p->ainsn.size; +regs_set_return_ip (regs, regs->ip -INT3_INSN_SIZE + p->ainsn.size); }NOKPROBE_SYMBOL (kprobe_emulate_ifmodifiers);
@@ -593,9 +593,9 @@ static const int addrmode_regoffs[] = {static void kprobe_emulate_call_indirect (struct kprobe *p,struct pt_regs *regs) {unsigned long offs = addrmode_regoffs[p->ainsn.indirect.reg]; +unsigned long ret = regs->ip -INT3_INSN_SIZE + p->ainsn.size; -int3_emulate_push (regs, regs->ip -INT3_INSN_SIZE + p->ainsn.size); -int3_emulate_jmp (regs,regs_get_register (regs, offs)); +int3_emulate_call (regs, ret,regs_get_register (regs, offs)); }NOKPROBE_SYMBOL (kprobe_emulate_call_indirect);
@@ -872,7 +872,7 @@ static void setup_singlestep(struct kprobe *p, struct pt_regs *regs,* nor set current_kprobe, because it doesn't use single * stepping. */ - regs->ip = (unsigned long )p->ainsn.insn; +regs_set_return_ip (regs, (unsigned long )p->ainsn.insn); return; }#endif
@@ -891,7 +891,7 @@ static void setup_singlestep(struct kprobe *p, struct pt_regs *regs,/* Disable interrupt, and set ip register on trampoline */ regs->flags &= ~X86_EFLAGS_IF ; - regs->ip = (unsigned long )p->ainsn.insn; +regs_set_return_ip (regs, (unsigned long )p->ainsn.insn); }NOKPROBE_SYMBOL (setup_singlestep);
@@ -922,7 +922,7 @@ static void resume_singlestep(struct kprobe *p, struct pt_regs *regs,/* Restore saved interrupt flag and ip register */ regs->flags |= kcb->kprobe_saved_flags;/* Note that regs->ip is executed int3 so must be a step back */ - regs->ip += (orig_ip - copy_ip) -INT3_INSN_SIZE ; +regs_set_return_ip (regs, regs->ip + (orig_ip - copy_ip) -INT3_INSN_SIZE ); }NOKPROBE_SYMBOL (resume_singlestep);
@@ -1042,7 +1042,7 @@ int kprobe_fault_handler(struct pt_regs *regs, int trapnr)* and allow the page fault handler to continue as a * normal page fault. */ - regs->ip = (unsigned long )cur->addr; +regs_set_return_ip (regs, (unsigned long )cur->addr);/* * If the IF flag was set before the kprobe hit,
arch/x86/kernel/kprobes/ftrace.c +2 -0
@@ -56,6 +56,8 @@ void kprobe_ftrace_handler(unsigned long ip, unsigned long parent_ip, }/* Recover IP address */ instruction_pointer_set (regs, orig_ip); +/* Recover the shadow stack too. */ +regs_set_return_ip (regs, orig_ip); }/* * If pre_handler returns !0, it changes regs->ip. We have to
arch/x86/kernel/kprobes/opt.c +1 -1
@@ -566,7 +566,7 @@ int setup_detour_execution(struct kprobe *p, struct pt_regs *regs, int reenter)/* This kprobe is really able to run optimized path. */ op = container_of(p, struct optimized_kprobe, kp);/* Detour through copied instructions */ - regs->ip = (unsigned long )op->optinsn.insn +TMPL_END_IDX ; +regs_set_return_ip (regs, (unsigned long )op->optinsn.insn +TMPL_END_IDX );if (!reenter)reset_current_kprobe ();return 1 ;
Signature · 1 line
2.43.0
RFC PATCH 18/27 x86/bpf: Make BPF JIT aware of CET handling
In reply to K Prateek NayakThe retpolies that BPF JIT uses are already aware of shadow stack handling.
Emit a incsspq %ecx for the trampoline that return to parent directly when a function return hook is active and BPF runs the function body as part of the trampoline.
For the unwinding case, use incsspq %rcx again with %rcx set to (unwinding depth + 1) when transferring the control back to a caller in chain for do_exception callback. The "+ 1" is for the extra frame that call to "bpf_exception_cb" adds.
Since unwinding and call to bpf_exception_cb is done from the bpf core, use the 4th argument to pass the unwinding depth.
--- arch/x86/net/bpf_jit_comp.c | 18 +++++++++++++++++- kernel/bpf/helpers.c | 3 ++- 2 files changed, 19 insertions(+), 2 deletions(-)
arch/x86/net/bpf_jit_comp.c +17 -1
@@ -560,6 +560,12 @@ static void emit_prologue(u8 **pprog, u8 *ip, u32 stack_depth, bool ebpf_from_cb }/* Exception callback receives FP as third parameter */ if (is_exception_cb) { +/* +* The number of slots to unwind to reach the +* return address is in the fourth parameter. +*/ +if (cpu_feature_enabled (X86_FEATURE_KERN_SHSTK )) +EMIT5 (0xF3 ,0x48 ,0x0F ,0xAE ,0xE9 );/* incsspq rcx */ EMIT3 (0x48 ,0x89 ,0xF4 );/* mov rsp, rsi */ EMIT3 (0x48 ,0x89 ,0xD5 );/* mov rbp, rdx */ /* The main frame must have exception_boundary as true, so we
@@ -1530,7 +1536,7 @@ bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)/* jump over faulting load and clear dest register */ if (reg !=DONT_CLEAR ) *(unsigned long *)((void *)regs + reg) =0 ; - regs->ip += insn_len; +regs_set_return_ip (regs, regs->ip + insn_len);return true; }
@@ -3756,6 +3762,16 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_imif (flags &BPF_TRAMP_F_SKIP_FRAME ) {/* skip our return address and return to parent */ EMIT4 (0x48 ,0x83 ,0xC4 ,8 );/* add rsp, 8 */ + +/* +* Drop the same return address from the shadow stack. The +* traced function is returning here, so every caller-saved +* register except RAX is dead. +*/ +if (cpu_feature_enabled (X86_FEATURE_KERN_SHSTK )) { +EMIT1_off32 (0xB9 ,1 );/* mov ecx, 1 */ +EMIT5 (0xF3 ,0x48 ,0x0F ,0xAE ,0xE9 );/* incsspq rcx */ + } }emit_return (&prog, image + (prog - (u8 *)rw_image));/* Make sure the trampoline generation logic doesn't overflow */
kernel/bpf/helpers.c +2 -1
@@ -3402,7 +3402,8 @@ __bpf_kfunc void bpf_throw(u64 cookie)* architectures cannot recover sp while unwinding, so fall back to bp. */ kasan_unpoison_task_stack_below ((void *)(long )(ctx.sp ?: ctx.bp)); - ctx.aux->bpf_exception_cb (cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp,0 ,0 ); + ctx.aux->bpf_exception_cb (cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, + ctx.bp, ctx.cnt +1 ,0 );WARN (1 ,"A call to BPF exception callback should never return\n" ); }
Signature · 1 line
2.43.0
RFC PATCH 19/27 x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACK
In reply to K Prateek NayakFtrace, optprobes, kprobes, rethooks, livepatch (ftrace direct call), error injection, and BPF JIT have now been adjusted to handle shadow stacks for control-flow changes.
Remove the config dependencies to allow building CONFIG_KERN_SHADOW_STACK with the above configs enabled.
--- arch/x86/Kconfig | 28 ---------------------------- 1 file changed, 28 deletions(-)
arch/x86/Kconfig +0 -28
@@ -1907,34 +1907,6 @@ config X86_KERN_SHADOW_STACK depends on VMAP_STACK depends on AS_WRUSS select X86_CET - # Replaces return addresses on the stack with return_to_handler, - # and return_to_handler itself returns with a retpoline-style - # "call; mov %rdi,(%rsp); ret". - depends on !FUNCTION_GRAPH_TRACER - # kprobe_emulate_call(), kprobe_emulate_ret() and - # kprobe_emulate_call_indirect() emulate CALL and RET by moving - # the return address on the regular stack only. KRETPROBES and - # OPTPROBES hang off this symbol as well. - depends on !KPROBES - # arch_rethook_trampoline() is a return address hijack: the - # probed function RETs to the trampoline instead of its caller. - # FPROBE selects RETHOOK. - depends on !RETHOOK - depends on !FPROBE - # klp_ftrace_handler() redirects execution by changing the - # ftrace_regs IP. ftrace_regs_caller writes that IP into the - # return slot and RETs to it, but the shadow stack still holds - # the original address. - depends on !LIVEPATCH - # override_function_with_return() points regs->ip at - # just_return_func, a bare RET that pops the probed function's - # return address without the function's own RET ever running. - depends on !FUNCTION_ERROR_INJECTION - # BPF trampolines with BPF_TRAMP_F_SKIP_FRAME do "add $8,%rsp; ret" - # to return to the grandparent. bpf_throw() unwinds BPF frames by - # walking the stack and resuming at the exception callback with - # the unwound RSP, skipping the intervening RETs. - depends on !BPF_JIT # relocate_kernel() switches CR3 and CR4 with a shadow stack live # and uses "pushq $0 ... ret" as the handoff into purgatory. It # needs S_CET.SH_STK_EN cleared first, which nothing does yet.
Signature · 1 line
2.43.0
RFC PATCH 20/27 x86/shstk: Disable kenrel shadow stack when CPU is offlined
In reply to K Prateek NayakOnce the CPU is marked dead, disable kernel shadow stacks just before the play_dead() noreturn function.
A subsequent online will setup the shadow stack again from start_secondary. This prepares the hotplug path for subsequent suspend resume / hibernation handling.
disable_kernel_shstk() is proactively made to push a restore token on top of the shadow stack and return the pointer just below to allow for error handling on the hibernation restore path if the switching to saved image fails.
--- arch/x86/include/asm/cpu.h | 40 ++++++++++++++++++++++++++++++++++++++ arch/x86/kernel/smpboot.c | 1 + 2 files changed, 41 insertions(+)
arch/x86/include/asm/cpu.h +40 -0
@@ -79,6 +79,9 @@ extern void prep_kernel_shadow_stack(struct task_struct *tsk,*/ static __always_inline void enable_kernel_shstk(unsigned long shstk_top) { +if (!cpu_feature_enabled (X86_FEATURE_KERN_SHSTK )) +return ; + asmvolatile ("rdmsr\n" "orl %1, %%eax\n" "wrmsr\n"
@@ -92,6 +95,38 @@ static __always_inline void enable_kernel_shstk(unsigned long shstk_top) : "eax", "edx", "cc", "memory"); } +/* +* This function should always be inlined. disable_kernel_shstk() +* returns the token to shstk_top that can be supplied later to +* enable_kernel_shstk() for error handling such that shadow stack +* can be re-enabled in the same function. Used for hotplug and +* and suspend-resume / hibernation. +*/ +static __always_inline unsigned long disable_kernel_shstk (void ) +{ +unsigned long ssp =0 , tok; + +if (!cpu_feature_enabled (X86_FEATURE_KERN_SHSTK )) +return ssp; + + asmvolatile ("rdsspq %0\n" +"test %0, %0\n" +"jz 1f\n" +"lea 1(%0), %1\n" +"wrssq %1, -8(%0)\n" +"rdmsr\n" +"andl %3, %%eax\n" +"wrmsr\n" +"1:" + :"+r" (ssp), +"=&r" (tok) + :"c" (MSR_IA32_S_CET ), +"i" (~(u32)(CET_SHSTK_EN |CET_WRSS_EN )) + :"eax" ,"edx" ,"cc" ,"memory" ); + +return ssp; +} +/* * Setup the shadow stack for this CPU. *
@@ -121,6 +156,11 @@ static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu)#else /* !CONFIG_X86_KERN_SHADOW_STACK */ +static inline void enable_kernel_shstk (unsigned long shstk_top) { } +static inline unsigned long disable_kernel_shstk (void ) +{ +return 0 ; +}static inline void cpu_setup_kernel_shstk (bool boot_cpu) { }#endif /* CONFIG_X86_KERN_SHADOW_STACK */
arch/x86/kernel/smpboot.c +1 -0
@@ -1510,6 +1510,7 @@ void __noreturn native_play_dead(void)play_dead_common ();tboot_shutdown (TB_SHUTDOWN_WFS ); +disable_kernel_shstk ();/* Below returns only on error. */ cpuidle_play_dead ();
Signature · 1 line
2.43.0
RFC PATCH 21/27 x86/shstsk: Allow suspend-resume and hibernation with kernel shadow stack
In reply to K Prateek NayakSave and restore the shadow stack pointers from the CPUs driving the suspend-resume / hibernation while disabling kernel shadow stack just before the system is suspended.
Since APs are taken down, they would have disabled shadow stack before hitting the idle routine and only the BSP (CPU doing the final bits of suspend-resume) needs to cache its SSP with restore token, disable kernel shadow stack and execute the suspend routine.
The caches SSP is restored on resume such that it finds the matching ret on the way out.
For hibernation, the CPU restoring the image disables shadow stacks, and the restored kernel then enables and restores the SSP it had cached before the hibernation.
Tested with:
rtcwake -m mem -s 20
rtcwake -m freeze -s 30
rtcwake -m disk -s 100
--- arch/x86/Kconfig | 7 ---- arch/x86/include/asm/nospec-branch.h | 55 ++++++++++++++++++++++++++++ arch/x86/include/asm/suspend.h | 2 + arch/x86/kernel/acpi/wakeup_64.S | 6 +++ arch/x86/power/hibernate.c | 2 + arch/x86/power/hibernate_32.c | 16 +++++--- arch/x86/power/hibernate_asm_64.S | 7 ++++ 7 files changed, 83 insertions(+), 12 deletions(-)
arch/x86/Kconfig +0 -7
@@ -1911,13 +1911,6 @@ config X86_KERN_SHADOW_STACK # and uses "pushq $0 ... ret" as the handoff into purgatory. It # needs S_CET.SH_STK_EN cleared first, which nothing does yet. depends on !KEXEC_CORE - # restore_registers() RETs on a stack reloaded from the image - # with S_CET, the PLx/FRED_SSPx MSRs and SSP itself never saved or - # restored. Same problem for do_suspend_lowlevel()/wakeup_long64(), - # which resume with "jmp *%rax" into the middle of the function - # and then RET. - depends on !HIBERNATION - depends on !SUSPEND # __efi64_thunk() drops into 32-bit firmware with LRETQ and comes # back with LRET. Far returns are shadow stack checked and expect # a far CALL frame that was never pushed.
arch/x86/include/asm/nospec-branch.h +55 -0
61 lines not on this page · raw message
arch/x86/include/asm/suspend.h +2 -0
@@ -9,6 +9,8 @@ extern unsigned long jump_address_phys;extern unsigned long restore_cr3 __visible;extern unsigned long temp_pgt __visible;extern unsigned long relocated_restore_code __visible; +extern unsigned long restore_ssp __visible; +extern unsigned long restore_s_cet __visible;extern int relocate_restore_code (void );/* Defined in hibernate_asm_32/64.S */ extern asmlinkage __visible int restore_image(void);
arch/x86/kernel/acpi/wakeup_64.S +6 -0
@@ -79,6 +79,8 @@ SYM_FUNC_START(do_suspend_lowlevel) movq %rdi, saved_rdi(%rip) movq %rsi, saved_rsi(%rip) + SUSPEND_KERNEL_SHSTK saved_ssp, saved_s_cet + addq $8, %rsp movl $3, %edi xorl %eax, %eax
@@ -126,6 +128,8 @@ SYM_FUNC_START(do_suspend_lowlevel) call kasan_unpoison_task_stack_below #endif + RESUME_KERNEL_SHSTK saved_ssp, saved_s_cet + xorl %eax, %eax addq $8, %rsp FRAME_END
@@ -141,5 +145,7 @@ saved_rbx: .quad 0 saved_rip: .quad 0 saved_rsp: .quad 0 +saved_ssp: .quad 0 +saved_s_cet: .quad 0 SYM_DATA(saved_magic, .quad 0)
arch/x86/power/hibernate.c +2 -0
@@ -39,6 +39,8 @@ unsigned long jump_address_phys;unsigned long restore_cr3 __visible;unsigned long temp_pgt __visible;unsigned long relocated_restore_code __visible; +unsigned long restore_ssp __visible; +unsigned long restore_s_cet __visible;/** * pfn_is_nosave - check if given pfn is in the 'nosave' section
arch/x86/power/hibernate_32.c +11 -5
@@ -170,29 +170,35 @@ static int set_up_temporary_text_mapping(pgd_t *pgd_base) asmlinkage int swsusp_arch_resume(void) { +unsigned long ssp =disable_kernel_shstk ();int error; resume_pg_dir = (pgd_t *)get_safe_page (GFP_ATOMIC ); -if (!resume_pg_dir) -return -ENOMEM ; +if (!resume_pg_dir) { + error = -ENOMEM ; + goto out_error; + }resume_init_first_level_page_table (resume_pg_dir); error =set_up_temporary_text_mapping (resume_pg_dir);if (error) -return error; + goto out_error; error =resume_physical_mapping_init (resume_pg_dir);if (error) -return error; + goto out_error; temp_pgt =__pa (resume_pg_dir); error =relocate_restore_code ();if (error) -return error; + goto out_error;/* We have got enough memory and from now on we cannot recover */ restore_image ();return 0 ; +out_error: +disable_kernel_shstk (ssp); +return err; }
arch/x86/power/hibernate_asm_64.S +7 -0
@@ -62,6 +62,8 @@ SYM_FUNC_START(restore_registers) /* Saved in save_processor_state. */ lgdt saved_context_gdt_desc(%rax) + RESUME_KERNEL_SHSTK restore_ssp, restore_s_cet + xorl %eax, %eax /* tell the hibernation core that we've just restored the memory */
@@ -94,9 +96,14 @@ SYM_FUNC_START(swsusp_arch_suspend) movq %cr3, %rax movq %rax, restore_cr3(%rip) + SUSPEND_KERNEL_SHSTK restore_ssp, restore_s_cet + FRAME_BEGIN call swsusp_save FRAME_END + + RESUME_KERNEL_SHSTK restore_ssp, restore_s_cet + RET SYM_FUNC_END(swsusp_arch_suspend)
Signature · 1 line
2.43.0
RFC PATCH 22/27 x86/shstk: Save and restore shadow stack pointer during kexec
In reply to K Prateek NayakTo support KEXEC and KEXEC_JUMP, save and restore shadow stack token on either side of relocate_kernel_ptr(). On regual kexec path, disable_kernel_shstk() from stop_this_cpu() will disable shadow stack on APs after the APIC is turned off. KEXEC_JUMP would disable the shadow stack from the offline callback.
restore_processor_state() populates the CR4 and FRED exceptions, RSPs and SSPs on the way back - restore the shadow stack token on the way back in machine_kexec() after the necessary FRED bits have been initialized.
APs re-enable shadow stack when coming online in start_secondary.
--- arch/x86/Kconfig | 4 ---- arch/x86/kernel/machine_kexec_64.c | 4 ++++ arch/x86/kernel/process.c | 1 + 3 files changed, 5 insertions(+), 4 deletions(-)
arch/x86/Kconfig +0 -4
@@ -1907,10 +1907,6 @@ config X86_KERN_SHADOW_STACK depends on VMAP_STACK depends on AS_WRUSS select X86_CET - # relocate_kernel() switches CR3 and CR4 with a shadow stack live - # and uses "pushq $0 ... ret" as the handoff into purgatory. It - # needs S_CET.SH_STK_EN cleared first, which nothing does yet. - depends on !KEXEC_CORE # __efi64_thunk() drops into 32-bit firmware with LRETQ and comes # back with LRET. Far returns are shadow stack checked and expect # a far CALL frame that was never pushed.
arch/x86/kernel/machine_kexec_64.c +4 -0
@@ -386,6 +386,7 @@ void __nocfi machine_kexec(struct kimage *image)unsigned long reloc_start = (unsigned long )__relocate_kernel_start;relocate_kernel_fn *relocate_kernel_ptr;unsigned int relocate_kernel_flags; +unsigned long shstk_token;int save_ftrace_enabled;void *control_page;
@@ -399,6 +400,8 @@ void __nocfi machine_kexec(struct kimage *image)/* Interrupts aren't acceptable while we reboot */ local_irq_disable ();hw_breakpoint_disable (); + + shstk_token =disable_kernel_shstk ();cet_disable ();if (image->preserve_context) {
@@ -461,6 +464,7 @@ void __nocfi machine_kexec(struct kimage *image)restore_processor_state ();#endif +enable_kernel_shstk (shstk_token);__ftrace_enabled_restore (save_ftrace_enabled); }/*
arch/x86/kernel/process.c +1 -0
@@ -902,6 +902,7 @@ void __noreturn stop_this_cpu(void *dummy)set_cpu_online (cpu, false);disable_local_APIC ();mcheck_cpu_clear (c); +disable_kernel_shstk ();if (this_cpu_read (cache_state_incoherent))wbinvd ();
Signature · 1 line
2.43.0
RFC PATCH 23/27 x86/idt: Map MCE shadow stack and populate the INT_SPP table
In reply to K Prateek NayakIn preparation for IDT handling of shadow stacks, allocate the MCE shadow stack too and map it similar to other shadow stack areas on IDT init path.
IDT systems need a supervisor token to mark shadow stack busy at the top entry. Use the R/W estacks alias to populate the entry corresponding to the linear address of the top slot.
IDT systems additionally require populating the INT_SSP table that maps the shadow stacks to IST gates. Initialize the SSP table in MSR_IA32_INT_SSP_TAB before enabling shadow stacks.
--- arch/x86/include/asm/cpu.h | 2 ++ arch/x86/include/asm/cpu_entry_area.h | 2 ++ arch/x86/include/asm/traps.h | 1 + arch/x86/kernel/idt.c | 30 +++++++++++++++++++++++++++ arch/x86/mm/cpu_entry_area.c | 27 ++++++++++++++++++++++++ 5 files changed, 62 insertions(+)
arch/x86/include/asm/cpu.h +2 -0
@@ -9,6 +9,7 @@#include <linux/percpu.h> #include <asm/ibt.h> +#include <asm/traps.h> #include <asm/msr-index.h> #include <asm/thread_info.h> #include <asm/special_insns.h>
@@ -150,6 +151,7 @@ static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu)BUG_ON (!tsk->thread.kshstk_ssp); shstk_top = (unsigned long )tsk->thread.kshstk_ssp; +load_ssp_table ();wrmsrq (MSR_IA32_FRED_SSP0 , shstk_top);enable_kernel_shstk (shstk_top); }
arch/x86/include/asm/cpu_entry_area.h +2 -0
@@ -34,6 +34,7 @@char DB_shadow_stack[EXCEPTION_SHADOW_STKSZ ]; \char DB_stack[EXCEPTION_STKSZ ]; \char MCE_stack_guard[guardsize]; \ +char MCE_shadow_stack[EXCEPTION_SHADOW_STKSZ ]; \char MCE_stack[EXCEPTION_STKSZ ]; \char VC_stack_guard[guardsize]; \char VC_stack[optional_stack_size]; \
@@ -145,6 +146,7 @@ DECLARE_PER_CPU(struct cpu_entry_area *, cpu_entry_area); DECLARE_PER_CPU(struct cea_exception_stacks *, cea_exception_stacks);extern void setup_cpu_entry_areas (void ); +extern void init_idt_shadows_stacks (unsigned int cpu);extern void cea_set_pte (void *cea_vaddr,phys_addr_t pa,pgprot_t flags);extern struct cpu_entry_area *get_cpu_entry_area (int cpu);
arch/x86/include/asm/traps.h +1 -0
@@ -19,6 +19,7 @@ asmlinkage __visible noinstr struct pt_regs *vc_switch_off_ist(struct pt_regs *eextern int ibt_selftest (void );extern int ibt_selftest_noendbr (void ); +extern void load_ssp_table (void );#ifdef CONFIG_X86_F00F_BUG /* For handling the FOOF bug */
arch/x86/kernel/idt.c +30 -0
@@ -180,10 +180,40 @@ static struct desc_ptr idt_descr __ro_after_init = { .address = (unsigned long) idt_table, }; +#define INT_SSP_TABLE_SIZE 8 + +struct int_ssp_table { +unsigned long *int_ssp[INT_SSP_TABLE_SIZE ]; +}; + +static DEFINE_PER_CPU(struct int_ssp_table, ssp_table); + +#define load_int_ssp_table (_vec) \ + do { \ + unsigned long *__shstk = (unsigned long *)__this_cpu_shadow_top_va(_vec); \ + table->int_ssp[IST_INDEX_ ##_vec + 1] = __shstk - 1; \ + } while(0) + +void load_ssp_table (void ) +{ +struct int_ssp_table *table =this_cpu_ptr (&ssp_table); + +if (cpu_feature_enabled (X86_FEATURE_FRED )) +return ; + +load_int_ssp_table (DB ); +load_int_ssp_table (NMI ); +load_int_ssp_table (DF ); +load_int_ssp_table (MCE ); + +wrmsrq (MSR_IA32_INT_SSP_TAB , (u64 )table->int_ssp); +} +void load_current_idt (void ) {lockdep_assert_irqs_disabled ();load_idt (&idt_descr); +init_idt_shadows_stacks (smp_processor_id ()); }#ifdef CONFIG_X86_F00F_BUG
arch/x86/mm/cpu_entry_area.c +27 -0
@@ -167,6 +167,29 @@ static void __init percpu_setup_exception_stacks(unsigned int cpu)cea_map_stack (DB , shadow_stack,PAGE_KERNEL_SHSTK );cea_map_stack (NMI , shadow_stack,PAGE_KERNEL_SHSTK );cea_map_stack (DF , shadow_stack,PAGE_KERNEL_SHSTK ); + cea_map_stack(MCE, shadow_stack, PAGE_KERNEL_SHSTK); +} + +#define shstk_get_top_slot (ptr, stack) \ + (unsigned long *)((u8*)(ptr)->stack## _shadow_stack + \ + EXCEPTION_SHADOW_STKSZ) - 1 + +#define cea_init_shadow_stack (name) do { \ + unsigned long *estacks_alias = shstk_get_top_slot(estacks, name); \ + unsigned long *cae_alias = shstk_get_top_slot(&cea->estacks, name); \ + *estacks_alias = (unsigned long)cae_alias; \ + } while (0) + +void init_idt_shadows_stacks (unsigned int cpu) +{ +struct exception_stacks *estacks =per_cpu_ptr (&exception_stacks, cpu); +struct cpu_entry_area *cea =get_cpu_entry_area (cpu); + +/* Map the per-CPU exception shadow stacks: */ +cea_init_shadow_stack (DB ); +cea_init_shadow_stack (NMI ); +cea_init_shadow_stack (DF ); +cea_init_shadow_stack (MCE ); }#else static void __init percpu_setup_exception_stacks (unsigned int cpu)
@@ -176,6 +199,10 @@ static void __init percpu_setup_exception_stacks(unsigned int cpu)cea_map_percpu_pages (&cea->doublefault_stack, &per_cpu(doublefault_stack, cpu), 1, PAGE_KERNEL); } + +void init_idt_shadows_stacks (unsigned int cpu) +{ +}#endif /* Setup the fixmap mappings only once per-processor */
Signature · 1 line
2.43.0
RFC PATCH 24/27 x86/process: Initialize shadow stack for IDT systems
In reply to K Prateek NayakOn IDT systems, the bottom of the stack should always have a supervisor token that can be marked busy by the hardware. Populate the supervisor token in the fist slot and, like FRED path, populate the first return address and the restore token below.
Since SSP0 should point to the supervisor slot, set SSP0 to one slot below task_shstk_top() that contains the supervisor token.
The SSP0 reset is no longer limited to FRED enabled systems. Use MSR_IA32_PL0_SSP to reference the MSR instead of the FRED alias.
--- arch/x86/include/asm/cpu.h | 4 +++- arch/x86/include/asm/entry-common.h | 19 ++++++++++++++++++- arch/x86/include/asm/fred.h | 7 ------- arch/x86/kernel/process.c | 17 +++++++++++++++-- 4 files changed, 36 insertions(+), 11 deletions(-)
arch/x86/include/asm/cpu.h +3 -1
@@ -138,8 +138,10 @@ static __always_inline unsigned long disable_kernel_shstk(void) static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu) {struct task_struct *tsk = current; +u64 ssp0 = (u64 )task_shstk_top (tsk) -sizeof (unsigned long );unsigned long shstk_top; +if (!cpu_feature_enabled (X86_FEATURE_KERN_SHSTK ))return ;
@@ -152,7 +154,7 @@ static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu) shstk_top = (unsigned long )tsk->thread.kshstk_ssp;load_ssp_table (); -wrmsrq (MSR_IA32_FRED_SSP0 , shstk_top); +wrmsrq (MSR_IA32_PL0_SSP , ssp0);enable_kernel_shstk (shstk_top); }
arch/x86/include/asm/entry-common.h +18 -1
@@ -56,6 +56,23 @@ static inline void arch_exit_work(unsigned long ti_work)switch_fpu_return (); } +#ifdef CONFIG_X86_KERN_SHADOW_STACK +static inline void update_ssp0 (void ) +{ +if (current->thread.kshstk_ssp) { +u64 top = (u64 )task_shstk_top (current); + +/* On IDT systems, restore past the token. */ +if (!cpu_feature_enabled (X86_FEATURE_FRED )) + top -=sizeof (unsigned long ); + +wrmsrns (MSR_IA32_PL0_SSP , top); + } +} +#else /* !CONFIG_X86_KERN_SHADOW_STACK */ +static inline void update_ssp0 (void ) { } +#endif /* CONFIG_X86_KERN_SHADOW_STACK */ +static inline void arch_exit_to_user_mode_prepare (struct pt_regs *regs,unsigned long ti_work) {
@@ -65,7 +82,7 @@ static inline void arch_exit_to_user_mode_prepare(struct pt_regs *regs,arch_exit_work (ti_work);fred_update_rsp0 (); -fred_update_ssp0 (); +update_ssp0 ();#ifdef CONFIG_COMPAT /* * Compat syscalls set TS_COMPAT. Make sure we clear it before
arch/x86/include/asm/fred.h +0 -7
@@ -105,13 +105,6 @@ static __always_inline void fred_update_rsp0(void) __this_cpu_write(fred_rsp0, rsp0); } } -static __always_inline void fred_update_ssp0(void) -{ -#ifdef CONFIG_X86_KERN_SHADOW_STACK -if (current->thread.kshstk_ssp) -wrmsrns (MSR_IA32_FRED_SSP0 , (u64 )task_shstk_top (current)); -#endif -}#else /* CONFIG_X86_FRED */ static __always_inline unsigned long fred_event_data (struct pt_regs *regs) {return 0 ; }static inline void cpu_init_fred_exceptions (void ) { }
arch/x86/kernel/process.c +15 -2
@@ -206,8 +206,21 @@ void prep_kernel_shadow_stack(struct task_struct *tsk,* Write the return address for the first RET: and point the task's * kshstk_ssp to the top slot. */ - *ss_top_slot = (unsigned long )ret_addr; - tsk->thread.kshstk_ssp =task_shstk_top (tsk) -sizeof (unsigned long ); +if (cpu_feature_enabled (X86_FEATURE_FRED )) { + *ss_top_slot = (unsigned long )ret_addr; + tsk->thread.kshstk_ssp =task_shstk_top (tsk) -sizeof (unsigned long ); + + }else { +unsigned long *shstk_top =task_shstk_top (tsk); + +/* Supervisor token for PL0_SSP */ + *ss_top_slot = (unsigned long )(shstk_top -1 ); + + ss_top_slot -=1 ; +/* Token for first return. */ + *ss_top_slot = (unsigned long )ret_addr; + tsk->thread.kshstk_ssp = shstk_top -2 ; + }/* * Back up one more frame and write the token for rstorssp when this
Signature · 1 line
2.43.0
RFC PATCH 25/27 x86/entry: Prepare IDT entry for shadow stacks
In reply to K Prateek NayakSimilar to FRED entry, IDT entry must populate a metadata frame around the pt_regs. Unlike FRED entry point which clearly distinguishes entry form kernel vs entry from user, IDT entry has a common entry point.
The POP_KERN_SHSTK_FRAME needs a consistent stack state to locate CS and pop accordingly which makes the handling complicated. Always push two slots - two blank ones for user entry and the correct FRED frame for entry from kernel such that POP_KERN_SHSTK_FRAME can always see a consistent state.
Once the CET helpers see a non-NULL shadow stack pointer, it can operate on the shadow stack frames for kernel events.
--- arch/x86/entry/calling.h | 85 ++++++++++++++++++++++++++++++++++ arch/x86/entry/entry_64.S | 24 ++++++++++ arch/x86/entry/entry_64_fred.S | 73 ----------------------------- 3 files changed, 109 insertions(+), 73 deletions(-)
arch/x86/entry/calling.h +85 -0
@@ -381,6 +381,91 @@ For 32-bit we have the following conventions - kernel is built with wrgsbase \scratch_reg .endm +#ifdef CONFIG_X86_KERN_SHADOW_STACK + +/* +* A INT3 breakpoint can emulate a CALL which requires pushing the +* return frame below this FRED event. Allow the handlers to communicate +* if it emulated a CALL by setting a flag on the stack. +* +* FRED event pushes { SSP, LIP, CS } onto the shadow stack and SSP +* points to record three slots for top here and it should stay that +* way. +* +* CALL emulation will consume the SSP, push a return frame below, and +* set a flag on stack. If the flag is set, FRED_EXIT will add an +* shadow stack frame on top by doing an INTRA_FUNCTION_CALL and +* populate the top with a pointer to three slots below, thus recreating +* the correct FRED frame. +*/ +.macro PUSH_KERN_SHSTK_FRAME + xor %eax, %eax + rdsspq %rax + pushq %rax + /* + * Frame metadata: + * + * [15:8] Context (FRED_EVENT) + * [ 7:0] fred_exit_work_flags + * + * Context data is used by CET helpers to interpret + * SSP frame. fred_exit_work_flags is used to fixup + * shadow stack for CALL emulation. + */ + pushq $0x100 +.endm + +/* Clobbers RAX, RCX; Both will be restored later. */ +.macro POP_KERN_SHSTK_FRAME + popq %rax /* fred_exit_work_flags */ + +/* Only one action is supported currently. */ + test %al, %al + jz .Lpop_shstk_done\@ + +/* +* CALL Emulation has overwritten the shadow-stack frame and +* SSP is lost. Point it back to 3 slots down where the real +* return has to go. +* +* Doing a CALL here will add a RSB which the next RET will +* mispredict on but all RETs after that are balanced. +*/ + ANNOTATE_INTRA_FUNCTION_CALL + call 1f + int3 +1: +/* Synthesize the corrct SSP to fix the FRED Frame. */ + addq $8, %rsp + rdsspq %rax + leaq 24(%rax), %rcx + wrssq %rcx, (%rax) + +.Lpop_shstk_done\@: + popq %rax +.endm + +.macro PUSH_USER_SHSTK_FRAME + subq $16, %rsp +.endm + +.macro POP_USER_SHSTK_FRAME + addq $16, %rsp +.endm + +#else /* !CONFIG_X86_KERN_SHADOW_STACK */ + +.macro PUSH_KERN_SHSTK_FRAME +.endm +.macro POP_KERN_SHSTK_FRAME +.endm +.macro PUSH_USER_SHSTK_FRAME +.endm +.macro POP_USER_SHSTK_FRAME +.endm + +#endif /* CONFIG_X86_KERN_SHADOW_STACK */ + #else /* CONFIG_X86_64 */ # undef UNWIND_HINT_IRET_REGS # define UNWIND_HINT_IRET_REGS
arch/x86/entry/entry_64.S +24 -0
@@ -296,6 +296,26 @@ SYM_CODE_START(xen_error_entry) RET SYM_CODE_END(xen_error_entry) +.macro PUSH_IDT_SHSTK_FRAME + testb $3, CS(%rsp) + jnz .Lpush_from_usermode\@ + PUSH_KERN_SHSTK_FRAME + jmp .Lpush_shstk_done\@ +.Lpush_from_usermode\@: + PUSH_USER_SHSTK_FRAME +.Lpush_shstk_done\@: +.endm + +.macro POP_IDT_SHSTK_FRAME + testb $3, CS+16(%rsp) + jnz .Lpop_from_usermode\@ + POP_KERN_SHSTK_FRAME + jmp .Lpush_shstk_done\@ +.Lpop_from_usermode\@: + POP_USER_SHSTK_FRAME +.Lpush_shstk_done\@: +.endm + /** * idtentry_body - Macro to emit code calling the C function * @cfunc: C function to be called
@@ -324,10 +344,14 @@ SYM_CODE_END(xen_error_entry) movq $-1, ORIG_RAX(%rsp) /* no syscall to restart */ .endif + PUSH_IDT_SHSTK_FRAME + /* For some configurations \cfunc ends up being a noreturn. */ ANNOTATE_REACHABLE call \cfunc + POP_IDT_SHSTK_FRAME + jmp error_return .endm
arch/x86/entry/entry_64_fred.S +0 -73
79 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 26/27 x86/syscall: Toggle shadow stack busy on entry and exit from syscall
In reply to K Prateek NayakOn IDT systems, a syscall to Ring-0 will set SSP to 0. Intel SDM for "SYSENTER - Fast System Call" reads:
When shadow stacks are enabled at privilege level where SYSENTER instruction is invoked, the SSP is saved to the IA32_PL3_SSP MSR. If shadow stacks are enabled at privilege level 0, the SSP is loaded with 0.
Before IRQs are enable, execute a setssbsy to load the SSP0 shadow stack and clear the busy status before SYSRET to allow IST Gate 0 events from userspace to mark it busy.
Kernel events at level 0 will not inspect the busy bit.
--- arch/x86/entry/calling.h | 14 ++++++++++++++ arch/x86/entry/entry_64.S | 6 ++++++ arch/x86/entry/entry_64_compat.S | 10 ++++++++++ 3 files changed, 30 insertions(+)
arch/x86/entry/calling.h +14 -0
@@ -453,6 +453,16 @@ For 32-bit we have the following conventions - kernel is built with addq $16, %rsp .endm +.macro SET_SHSTK_BUSY +ALTERNATIVE "" ,"setssbsy" ,X86_FEATURE_KERN_SHSTK +.endm + +.macro CLEAR_SHSTK_BUSY scratch_reg +ALTERNATIVE "" , \ + __stringify(rdsspq \scratch_reg; clrssbsy (\scratch_reg)), \ +X86_FEATURE_KERN_SHSTK +.endm + #else /* !CONFIG_X86_KERN_SHADOW_STACK */ .macro PUSH_KERN_SHSTK_FRAME
@@ -463,6 +473,10 @@ For 32-bit we have the following conventions - kernel is built with .endm .macro POP_USER_SHSTK_FRAME .endm +.macro SET_SHSTK_BUSY +.endm +.macro CLEAR_SHSTK_BUSY scratch_reg +.endm#endif /* CONFIG_X86_KERN_SHADOW_STACK */
arch/x86/entry/entry_64.S +6 -0
@@ -109,6 +109,9 @@ SYM_INNER_LABEL(entry_SYSCALL_64_after_hwframe, SYM_L_GLOBAL) PUSH_AND_CLEAR_REGS rax=$-ENOSYS + /* SYSCALL zeroed SSP; claim the task's supervisor token before any CALL. */ + SET_SHSTK_BUSY + /* IRQs are off. */ movq %rsp, %rdi /* Sign extend the lower 32bit as syscall numbers are treated as int */
@@ -156,6 +159,9 @@ syscall_return_via_sysret: */ STACKLEAK_ERASE_NOCLOBBER + /* SYSRET does not free the token; SSP is back on it here. */ + CLEAR_SHSTK_BUSY scratch_reg=%rdi + SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi popq %rdi
arch/x86/entry/entry_64_compat.S +10 -0
@@ -87,6 +87,9 @@ SYM_INNER_LABEL(entry_SYSENTER_compat_after_hwframe, SYM_L_GLOBAL) PUSH_AND_CLEAR_REGS rax=$-ENOSYS UNWIND_HINT_REGS + /* SYSENTER zeroed SSP; claim the task's supervisor token before any CALL. */ + SET_SHSTK_BUSY + cld /*
@@ -210,6 +213,9 @@ SYM_INNER_LABEL(entry_SYSCALL_compat_after_hwframe, SYM_L_GLOBAL) PUSH_AND_CLEAR_REGS rcx=%rbp rax=$-ENOSYS UNWIND_HINT_REGS + /* SYSCALL zeroed SSP; claim the task's supervisor token before any CALL. */ + SET_SHSTK_BUSY + IBRS_ENTER UNTRAIN_RET CLEAR_BRANCH_HISTORY
@@ -271,6 +277,10 @@ SYM_INNER_LABEL(entry_SYSRETL_compat_unsafe_stack, SYM_L_GLOBAL) * * %r8/%r9 are zeroed before the sysret, thus safe to clobber. */ + + /* SYSRET does not free the token; SSP is back on it here. */ + CLEAR_SHSTK_BUSY scratch_reg=%r8 + SWITCH_TO_USER_CR3_NOSTACK scratch_reg=%r8 scratch_reg2=%r9 xorl %r8d, %r8d
Signature · 1 line
2.43.0
RFC PATCH 27/27 x86/entry: Handle shadow stack on nested NMI
In reply to K Prateek NayakIDT sets NMI on IST gate 1 and teh corresponding shadow shadows from INT_SSP_TAB is asserted and marked busy.
On userspace NMIs that use the task's stack, clear the busy bit from the NMI shadow stack to allow nesting and switch to PL0_SSP stack. Since it is an NMI from userspace, the PL0SSP stack is empty and the stack can be used safely from the top.
NMI from kernel needs special handling. Similar to the NMI from userspace handling, clear the busy bit on the IST gate token, and switch back to the same shadow stack at Gate 1 via restorssp.
Once back, the shadow stack establishes the same pattern as the regular stack by duplicating { CS, LIP, SS } on top as the inner frame. The NMI entry in "repeat NMI" will replicate the entries a second time to stablish the outer frame.
The structure of shadow stack is as follows:
+-------------------------------+ | supervisor token | +-------------------------------+ | Original CS | | Original LIP | Hardware overwrites this slot | Original SSP | +-------------------------------+ | Inner CS | | Inner LIP | Copied from first NMI | Inner SSP | +-------------------------------+ | Outer CS | | Outer LIP | For the IRET from first NMI | Outer SSP | (BUILD_NMI_REPEAT_SHSTK_FRAME) +-------------------------------+
At the beginning, all three copies are same when it is established by the first NMI. A nested NMI, will point outer SSP to Inner SSP's slot, sets CS to, __KERNEL_CS and modify the LIP to jump to repeat_nmi just like it populates the outer IRET frame on the stack.
Since the replication is consistent, the address of the outer frame is known beforehand. IRET of first NMI is supposed to consume the outer frame.
If there was nesting, repeat_nmi will rebuild the outer frame it consumed during IRET in BUILD_NMI_REPEAT_SHSTK_FRAME and continue. Any nested NMI at this point will simply take the nested_nmi_out path without modifying anything on the shadow stack.
If there is no nested NMI, the outer frame, which is a replica of the hardware populated frame, will transfer the control back into the kernel.
This is super convoluted like the stack handling and severely unbalances the RSB.
--- arch/x86/entry/entry_64.S | 232 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+)
arch/x86/entry/entry_64.S +232 -0
@@ -1145,6 +1145,214 @@ SYM_CODE_START_LOCAL(error_return) jmp swapgs_restore_regs_and_return_to_usermode SYM_CODE_END(error_return) +#ifdef CONFIG_X86_KERN_SHADOW_STACK + +/* + * This allocates three dummy slots on the shadow stack frame + * and copies the previous top 3 slots on to the newly + * created dummy slots. + */ +.macro BUILD_NMI_REPEAT_SHSTK_FRAME needs_scratch=1 + /* Save the scratch that will be clobbered. */ + .if \needs_scratch + pushq %rax /* Extra scratch. */ + pushq %rdx + .endif + + xor %rdx, %rdx + rdsspq %rdx + testq %rdx, %rdx + jz .Lskip_shstk\@ + + /* Replicate top 3 frames below. */ + .rept 3 + ANNOTATE_INTRA_FUNCTION_CALL + call 7771f + int3 +7771: + movq 16(%rdx), %rax + wrssq %rax, -8(%rdx) + leaq -8(%rdx), %rdx + .endr + addq $24, %rsp +.Lskip_shstk\@: + + /* Restore scratch. */ + .if \needs_scratch + popq %rdx + popq %rax + .endif +.endm + +/* + * Nested NMI Shadow Stack handling + * + * On IDT systems, the hardware asserts the IST Gate-1 token and pushes + * a { CS, LIP, SS } package onto the shadow stack. Until the token is + * occupied, a nested NMI will #GP. + * + * We mark the shadow stack non-busy and use rstorssp to switch back to + * the same shadow stack. Then, like NMI handler does on regular stack, + * we construct a similar inner frame, outer frame structure, on the + * shadow stack: + * + * +-------------------------------+ + * | supervisor token | + * +-------------------------------+ + * | Original CS | + * | Original LIP | Hardware overwrites this slot + * | Original SSP | + * +-------------------------------+ + * | Inner CS | + * | Inner LIP | Copied from first NMI + * | Inner SSP | + * +-------------------------------+ + * | Outer CS | + * | Outer LIP | For the IRET from first NMI + * | Outer SSP | (BUILD_NMI_REPEAT_SHSTK_FRAME) + * +-------------------------------+ + * + * At the beginning, all three copies are same when first NMI arrives. + * A nested NMI, will point outer SSP to Inner SSP's slot, set CS to, + * __KERNEL_CS and modify the LIP to jump to repeat_nmi just like it + * populates the stack frame. + * + * repeat_nmi will rebuild the outer frame it consumed in + * BUILD_NMI_REPEAT_SHSTK_FRAME and continue. Any nested NMI at this + * point will simply take the nested_nmi_out path to jump out. + * + * If there is no other NMI in-between, the outer frame is same as + * hardware populated one and the transfer jumps back at IRET. + * + * Note: RSB is severely unbalanced by the time we exit here. + */ +.macro INIT_NMI_SHSTK_STATE + xor %rdx, %rdx + rdsspq %rdx + testq %rdx, %rdx + jz .Lskip_shstk_init\@ + + /* Write a restore token. */ + pushq %rax /* Extra scratch. */ + movq %rdx, %rax + orq $1, %rax + wrssq %rax, -8(%rdx) + + /* + * Supervisor token is 3 slots up, at the IST SSP. + * Clear the busy bit to allow nesting. + * NMIs are still disabled. + */ + clrssbsy 24(%rdx) + + /* Switch back to the same shadow stack */ + rstorssp -8(%rdx) + movq $1, %rdx + incsspq %rdx + + /* + * Build the original copy. first_nmi falls through into + * repeat_nmi, which builds the outer copy from it. + */ + BUILD_NMI_REPEAT_SHSTK_FRAME needs_scratch=0 + + popq %rax /* Restore scratch. */ + +.Lskip_shstk_init\@: +.endm + +/* + * For CONFIG_DEBUG_ENTRY build a shadow stack frame that + * IRET-to-self can pop out. + */ +.macro BUILD_NMI_DEBUG_SHSTK_FRAME + pushq %rax /* Extra scratch. */ + pushq %rdx + + xor %eax, %eax + rdsspq %rax + testq %rax, %rax + jz .Lskip_shstk_debug\@ + + .rept 3 + ANNOTATE_INTRA_FUNCTION_CALL + call 7772f + int3 +7772: + .endr + addq $24, %rsp + + rdsspq %rdx + wrssq %rax, (%rdx) /* SSP */ + movq 16(%rsp), %rax + wrssq %rax, 8(%rdx) /* LIP */ + movq 24(%rsp), %rax + wrssq %rax, 16(%rdx) /* CS */ + +.Lskip_shstk_debug\@: + popq %rdx + popq %rax +.endm + +/* + * Fixup the outer frame to jump to "repeat_nmi" and point the + * CS, SSP to correct location to jump back to the inner copy + * 3 slots down the same shadow stack. + */ +.macro FIX_NESTED_NMI_SHSTK_FRAME + xor %rdx, %rdx + rdsspq %rdx + testq %rdx, %rdx + jz .Lskip_shstk_fix\@ + + pushq %rax + + /* + * %rdx is S0-24. Redirect the outer copy (S0-56..S0-72) to + * repeat_nmi, resuming on top of the original copy (S0-48). + */ + movq $__KERNEL_CS, %rax + wrssq %rax, -32(%rdx) /* CS */ + + movabsq $repeat_nmi, %rax + wrssq %rax, -40(%rdx) /* LIP */ + + leaq -24(%rdx), %rax + wrssq %rax, -48(%rdx) /* SSP */ + + popq %rax +.Lskip_shstk_fix\@: +.endm + +/* + * NMI from userspace uses the thread's stack. + * + * Set NMI shadow stack as non-busy to accommodate nested NMIs and + * switch to PL0_SSP stack. Simce this comes from userspace, the + * SSP0 stack is currently unused. + */ +.macro SWITCH_TO_TASK_SHSTK + rdsspq %rdx + clrssbsy (%rdx) + setssbsy +.endm + +#else + +.macro BUILD_NMI_REPEAT_SHSTK_FRAME +.endm +.macro INIT_NMI_SHSTK_STATE +.endm +.macro BUILD_NMI_DEBUG_SHSTK_FRAME +.endm +.macro FIX_NESTED_NMI_SHSTK_FRAME +.endm +.macro SWITCH_TO_TASK_SHSTK +.endm + +#endif + + /* * Runs on exception stack. Xen PV does not go through this path at all, * so we can use real assembly here.
@@ -1231,6 +1439,13 @@ SYM_CODE_START(asm_exc_nmi) PUSH_AND_CLEAR_REGS rdx=(%rdx) ENCODE_FRAME_POINTER + /* + * Like the data stack, leave the NMI IST shadow stack so a nested + * NMI can claim its token, and run on the task's shadow stack. + * The IRET to user frees the task token again. + */ + ALTERNATIVE "", __stringify(SWITCH_TO_TASK_SHSTK), X86_FEATURE_KERN_SHSTK + IBRS_ENTER UNTRAIN_RET
@@ -1354,6 +1569,14 @@ nested_nmi: * iteration of NMI handling. */ subq $8, %rsp + + /* + * Fix needs to be done here since we have + * 5 spare stack frame we can use that gets + * overwritten by the later push. + */ + FIX_NESTED_NMI_SHSTK_FRAME + leaq -10*8(%rsp), %rdx pushq $__KERNEL_DS pushq %rdx
@@ -1371,6 +1594,9 @@ nested_nmi_out: iretq first_nmi: + + INIT_NMI_SHSTK_STATE + /* Restore rdx. */ movq (%rsp), %rdx
@@ -1399,6 +1625,9 @@ first_nmi: pushfq /* RFLAGS */ pushq $__KERNEL_CS /* CS */ pushq $1f /* RIP */ + + BUILD_NMI_DEBUG_SHSTK_FRAME + iretq /* continues at repeat_nmi below */ UNWIND_HINT_IRET_REGS 1:
@@ -1433,6 +1662,9 @@ repeat_nmi: pushq -6*8(%rsp) .endr subq $(5*8), %rsp + + BUILD_NMI_REPEAT_SHSTK_FRAME + end_repeat_nmi: ANNOTATE_NOENDBR // this code
Signature · 1 line
2.43.0
Quoted 9 lines · K Prateek Nayak
Write-to-CR2 for serialization
==============================CPUs that don't have SERIALIZE and have
X86_FEATURE_KERN_SHSTKwill default to using write-to-CR2 as serializing step. write-to-CR2 is available widely and although the comment insync_core()suggests XEN may have some issues here,CONFIG_X86_KERE_SHADOW_STACKcannot be compiled with XEN yet so we'll consider write-to-CR2 as a temporary measure.
There is no legitimate dependency CONFIG_X86_KERNEL_SHADOW_STACK and XEN; it's bogus and needs dropping.
Xen PV guests will never see CET (SS or IBT) and never enter the CONFIG_X86_KERNEL_SHADOW_STACK paths. Xen HVM guests will, and they will work as per native, just like KVM guests/etc.
The change you've made in sync core is fine. IRET is used because for both XenPV and for UML, it will serialise without trapping; it's a performance concern only.
Quoted 31 lines
CALL emulation
==============Call emulation requires a RET frame to be inserted below the FRED entry frame. FRED frame is a { CS, LIP, SSP } pushed onto the shadow stack.
To make our lives easy, we push a corresponding metadata frame onto the regula stack on top of
pt_regsto make the following container:struct { u64 metadata; /* Context */ u64 ssp; /* SSP at FRED_ENTRY */ pt_rega *regs;}
For CALL emulation,
regs_emulate_call()helper will use the SSP from this context to overwrite the CS in the FRED frame with the return IP. The original CS and LIP are moved one slot up to make:... ... +-----+ +-----+ | CS | | RET | | LIP | -> +-----+ | SSP | | CS | +-----+ | LIP | <- Jump to CALL site +-----+ <- Top of stackText patching events always occur at same FRED level and SSP always points to address 3 slots down.
regs_emulate_call()will then notifyFRED_EXITof the patching by setting a flag in the metadata.
Quoted 7 lines
FRED_EXITwill see this flag and do a dummy call, fixup stack, and overwrite the top of shadow stack with a SSP of three slots down to complete the FRED frame which matches for ERETS. After an ERETS, the fist RET will mismatch but rest of the RETs are balanced in RSB.This is also the same method of doing a direct call via
ORIG_RAXinftrace_regs_callerand has been adopted here.
MSR_FRED_CONFIG.SSP (bit 3) exists exclusively for this purpose.
There was a reasonable amount of spirited debate required to get that into the FRED spec. It would be a shame not to use it.
~Andrew
Hello Andrew,
Quoted 11 lines · Andrew Cooper
Quoted 9 lines · K Prateek Nayak
Write-to-CR2 for serialization
==============================CPUs that don't have SERIALIZE and have
X86_FEATURE_KERN_SHSTKwill default to using write-to-CR2 as serializing step. write-to-CR2 is available widely and although the comment insync_core()suggests XEN may have some issues here,CONFIG_X86_KERE_SHADOW_STACKcannot be compiled with XEN yet so we'll consider write-to-CR2 as a temporary measure.
Quoted 6 lines
There is no legitimate dependency
CONFIG_X86_KERNEL_SHADOW_STACKand XEN; it's bogus and needs dropping.Xen PV guests will never see CET (SS or IBT) and never enter the
CONFIG_X86_KERNEL_SHADOW_STACKpaths. Xen HVM guests will, and they will work as per native, just like KVM guests/etc.
Ack! Thank you for clarifying. I only thought they won't see FRED but now that I look at your comment on Deve's thread, I see you mention CET_SS as a whole. Sorry for getting that mixed up.
Quoted 3 lines
The change you've made in sync core is fine. IRET is used because for both XenPV and for UML, it will serialise without trapping; it's a performance concern only.
Ack! And since you say CET_SS will not be visible, the guests will continue to user the IRET-to-self path and there should be no concern.
Quoted 37 lines
Quoted 37 lines
CALL emulation
==============Call emulation requires a RET frame to be inserted below the FRED entry frame. FRED frame is a { CS, LIP, SSP } pushed onto the shadow stack.
To make our lives easy, we push a corresponding metadata frame onto the regula stack on top of
pt_regsto make the following container:struct { u64 metadata; /* Context */ u64 ssp; /* SSP at FRED_ENTRY */ pt_rega *regs; }For CALL emulation,
regs_emulate_call()helper will use the SSP from this context to overwrite the CS in the FRED frame with the return IP. The original CS and LIP are moved one slot up to make:... ... +-----+ +-----+ | CS | | RET | | LIP | -> +-----+ | SSP | | CS | +-----+ | LIP | <- Jump to CALL site +-----+ <- Top of stackText patching events always occur at same FRED level and SSP always points to address 3 slots down.
regs_emulate_call()will then notifyFRED_EXITof the patching by setting a flag in the metadata.
FRED_EXITwill see this flag and do a dummy call, fixup stack, and overwrite the top of shadow stack with a SSP of three slots down to complete the FRED frame which matches for ERETS. After an ERETS, the fist RET will mismatch but rest of the RETs are balanced in RSB.
Quoted 7 lines
Quoted 2 lines
This is also the same method of doing a direct call via
ORIG_RAXinftrace_regs_callerand has been adopted here.MSR_FRED_CONFIG.SSP (bit 3) exists exclusively for this purpose.
There was a reasonable amount of spirited debate required to get that into the FRED spec. It would be a shame not to use it.
Ooo! That should do well too and save a few WRSS for CALL handling on the FRED path.
Signature · 2 lines
Thanks and Regards, Prateek
Quoted 3 lines · K Prateek Nayak
Disclaimer: A large part of my understanding of shadow stack and some parts of this series are from interactions with AI agents. Please forgive any slop.
Honestly, I don't think I can even look at a series that comes with a disclaimer like this up front. This doesn't sound like code that you're confident in and proud of putting *your* name on it.
Instead of trying to add thousands of lines of potential slop on top of basic functionality, how about we all focus our brainpower and token budgets on getting _some_ kernel shadow stack support in the kernel first?
For instance, should I be spending time on reviewing this? Or should I go spend time on trying to get the FRED-only series in shape to be merged?
Hello Dave,
Quoted 8 lines · Dave Hansen
Quoted 3 lines · K Prateek Nayak
Disclaimer: A large part of my understanding of shadow stack and some parts of this series are from interactions with AI agents. Please forgive any slop.
Honestly, I don't think I can even look at a series that comes with a disclaimer like this up front. This doesn't sound like code that you're confident in and proud of putting *your* name on it.
That disclaimer was carried on based on Boris' suggestion on an earlier version. I'm confident enough to sign off on this iteration of code which might have a bit of human slop from my side more than AIs - like me being unaware of FRED_CONFIG[3] for CALL emulation and how I've instead done a ftrace_regs_caller like handling at FRED_EXIT.
Quoted 3 lines
Instead of trying to add thousands of lines of potential slop on top of basic functionality, how about we all focus our brainpower and token budgets on getting _some_ kernel shadow stack support in the kernel first?
Ack! I'm all for it. This code came from an internal ask that required supervisor shadow stack on linux with a configuration closer to a distro config to confirm an observation. In the process, the implementation turned presentable enough to warrant a series hence this RFC.
If nothing, please consider a version for Patch 5 for your next iteration since there is no SERIALIZE on Zen6 and IRET-to-self will #CP.
Other than that, I'm sure your series will address the bit I've stumbled on. Please do keep me in Cc: and I'll be more than happy to test your iterations on a Zen6 machine and provide feedback if I run into something funny.
Quoted 2 lines
For instance, should I be spending time on reviewing this? Or should I go spend time on trying to get the FRED-only series in shape to be merged?
I would suggest glossing over the cover letter once for the account of all the sharp edges I stumbled on. If you feel anything is worth substance, maybe take a look but otherwise, you can just skip over - whatever gets the kernel shadow stack support mainline quicker, I'm all for it.
I did not mean to step over your work and I'm happy to be a fly on the wall on this, buzzing occasionally :-)
Signature · 2 lines
Thanks and Regards, Prateek