Skip to content

RFC x86/shstk: More shadow stack enablement and path to IDT support

K Prateek Nayak lkml 1 version In review

Get series with b4
b4 am [email protected]

Versions newest first

  1. v1 RFC Latest27 patches 5 repliesIn review

Patches in v1 No applies recorded yet

#Subject and filesSizeRepliesApplied
1/27x86/entry: Parameterize kernel shadow stack handling at FRED entryarch/x86/entry/entry_64_fred.S+16 -260 replies
2/27x86/perf_regs: Rename pt_regs_offset array to prevent build failurearch/x86/kernel/perf_regs.c+3 -30 replies
3/27x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACKarch/x86/kernel/Makefile arch/x86/kernel/shstk.c+8 -30 replies
4/27x86/cet: Make kernel shadow stack #CP fatal instead of livelockingarch/x86/kernel/cet.c+77 -241 reply
5/27x86/sync_core: Don't use IRET-to-self with kernel shadow stacksarch/x86/include/asm/sync_core.h+11 -00 replies
6/27x86/process: Initialize and enable kernel shadow stack at bootarch/x86/entry/entry_64.S arch/x86/include/asm/cpu.h arch/x86/kernel/cpu/common.c +4 more+141 -920 replies
7/27x86/entry: Handle int3 text patching with kernel shadow stackarch/x86/entry/entry_64_fred.S arch/x86/include/asm/insn-eval.h arch/x86/include/asm/text-patching.h +4 more+247 -270 replies
8/27x86/retpoline: Handle retpolies and thunks with kernel shadow stackarch/x86/Kconfig arch/x86/include/asm/alternative.h arch/x86/include/asm/nospec-branch.h +1 more+116 -180 replies
9/27x86/ftrace: Prepare ftrace trampolines to handle shadow stackarch/x86/kernel/cet.c arch/x86/kernel/ftrace_64.S+108 -170 replies
10/27x86/kprobes: Prepare optprobe trampoline to handle shadow stacksarch/x86/kernel/cet.c arch/x86/kernel/ftrace_64.S arch/x86/kernel/kprobes/opt.c+29 -20 replies
11/27x86/rethook: Prepare the rethook trampoline to handle shadow stackarch/x86/kernel/rethook.c+34 -00 replies
12/27x86/cet: Make regs_set_return_ip() helpers context awarearch/x86/kernel/cet.c+38 -30 replies
13/27x86/cet: Introduce regs_set_return_trampoline() for rethook trampolinearch/x86/include/asm/insn-eval.h arch/x86/kernel/cet.c+82 -00 replies
14/27x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and trampoline redirectionarch/x86/include/asm/ftrace.h arch/x86/kernel/ftrace.c kernel/trace/fgraph.c+24 -40 replies
15/27x86/rethook: Make the trampoline insert and return shadow stack awarearch/x86/kernel/rethook.c+7 -10 replies
16/27x86/error_inject: Use CET helpers to insert just_return_func trampolinearch/x86/lib/error-inject.c+1 -10 replies
17/27x86/kprobes: Use CET helpers in kprobe core to modify regs->iparch/x86/kernel/kprobes/core.c arch/x86/kernel/kprobes/ftrace.c arch/x86/kernel/kprobes/opt.c+10 -80 replies
18/27x86/bpf: Make BPF JIT aware of CET handlingarch/x86/net/bpf_jit_comp.c kernel/bpf/helpers.c+19 -20 replies
19/27x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACKarch/x86/Kconfig+0 -280 replies
20/27x86/shstk: Disable kenrel shadow stack when CPU is offlinedarch/x86/include/asm/cpu.h arch/x86/kernel/smpboot.c+41 -00 replies
21/27x86/shstsk: Allow suspend-resume and hibernation with kernel shadow stackarch/x86/Kconfig arch/x86/include/asm/nospec-branch.h arch/x86/include/asm/suspend.h +4 more+83 -120 replies
22/27x86/shstk: Save and restore shadow stack pointer during kexecarch/x86/Kconfig arch/x86/kernel/machine_kexec_64.c arch/x86/kernel/process.c+5 -40 replies
23/27x86/idt: Map MCE shadow stack and populate the INT_SPP tablearch/x86/include/asm/cpu.h arch/x86/include/asm/cpu_entry_area.h arch/x86/include/asm/traps.h +2 more+62 -00 replies
24/27x86/process: Initialize shadow stack for IDT systemsarch/x86/include/asm/cpu.h arch/x86/include/asm/entry-common.h arch/x86/include/asm/fred.h +1 more+36 -110 replies
25/27x86/entry: Prepare IDT entry for shadow stacksarch/x86/entry/calling.h arch/x86/entry/entry_64.S arch/x86/entry/entry_64_fred.S+109 -730 replies
26/27x86/syscall: Toggle shadow stack busy on entry and exit from syscallarch/x86/entry/calling.h arch/x86/entry/entry_64.S arch/x86/entry/entry_64_compat.S+30 -00 replies
27/27x86/entry: Handle shadow stack on nested NMIarch/x86/entry/entry_64.S+232 -00 replies

Reviews trailers per patch

No Reviewed-by, Acked-by or Tested-by trailers for v1 yet.

Read the v1 thread

Cover letter [RFC PATCH 00/27] 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 stack

Text 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