riscv control-flow integrity for usermode
Subsystems (10)
cover riscv control-flow integrity for usermode
From: Deepak Gupta <[email protected]>
It's been almost an year since I posted my last patch series [1] to enable CPU assisted control-flow integrity for usermode on riscv. A lot has changed since then and so has the patches. It's been a while and since this is a reboot of series, starting with RFC and v1.
Securing control-flow integrity for usermode requires following
- Securing forward control flow : All callsites must reach reach a target that they actually intend to reach.
- Securing backward control flow : All function returns must return to location where they were called from.
This patch series use riscv cpu extension zicfilp [2] to secure forward control flow and zicfiss [2] to secure backward control flow. zicfilp enforces that all indirect calls or jmps must land on a landing pad instr and label embedded in landing pad instr must match a value programmed in x7 register (at callsite via compiler). zicfiss introduces shadow stack which can only be writeable via shadow stack instructions (sspush and ssamoswap) and thus can't be tampered with via inadvertent stores. More details about extension can be read from [2] and there are details in documentation as well (in this patch series).
Using config CONFIG_RISCV_USER_CFI, kernel support for riscv control flow integrity for user mode programs can be compiled in the kernel.
Enabling of control flow integrity for user programs is left to user runtime (specifically expected from dynamic loader). There has been a lot of earlier discussion on the enabling topic around x86 shadow stack enabling [3, 4, 5] and overall consensus had been to let dynamic loader (or usermode) to decide for enabling the feature.
This patch series introduces arch agnostic prctls to enable shadow stack and indirect branch tracking. And implements them on riscv. arm64 is expected to implement shadow stack part of these arch agnostic prctls [6]
Changes since last time
***********************
Spec changes
------------
- Forward cfi spec has become much simpler. lpad instruction is pseudo for auipc rd, <20bit_imm>. lpad checks x7 against 20bit embedded in instr. Thus label width is 20bit.
- Shadow stack management instructions are reduced to sspush - to push x1/x5 on shadow stack
sspopchk - pops from shadow stack and comapres with x1/x5. ssamoswap - atomically swap value on shadow stack. rdssp - reads current shadow stack pointer
- Shadow stack accesses on readonly memory always raise AMO/store page fault. sspopchk is load but if underlying page is readonly, it'll raise a store page fault. It simplifies hardware and kernel for COW handling for shadow stack pages.
- riscv defines a new exception type software check exception and control flow violations raise software check exception.
- enabling controls for shadow stack and landing are in xenvcfg CSR and controls lower privilege mode enabling. As an example senvcfg controls enabling for U and menvcfg controls enabling for S mode.
core mm shadow stack enabling
-----------------------------
Shadow stack for x86 usermode are now in mainline and thus this patch series builds on top of that for arch-agnostic mm related changes. Big thanks and shout out to Rick Edgecombe for that.
selftests
---------
Created some minimal selftests to test the patch series.
[1] - https://lore.kernel.org/lkml/[email protected]/
[2] - https://github.com/riscv/riscv-cfi
[3] - https://lore.kernel.org/lkml/[email protected]/T/#mb121cd8b33d564e64234595a0ec52211479cf474
[4] - https://lore.kernel.org/all/[email protected]/
[5] - https://lore.kernel.org/lkml/CAHk-=wgP5mk3poVeejw16Asbid0ghDt4okHnWaWKLBkRhQntRA@mail.gmail.com/
[6] - https://lore.kernel.org/linux-mm/[email protected]/
Deepak Gupta (27):
riscv: abstract envcfg CSR
riscv: envcfg save and restore on trap entry/exit
riscv: define default value for envcfg
riscv/Kconfig: enable HAVE_EXIT_THREAD for riscv
riscv: zicfiss/zicfilp enumeration
riscv: zicfiss/zicfilp extension csr and bit definitions
riscv: kernel handling on trap entry/exit for user cfi
mm: Define VM_SHADOW_STACK for RISC-V
mm: abstract shadow stack vma behind arch_is_shadow_stack riscv/mm : Introducing new protection flag "PROT_SHADOWSTACK"
riscv: Implementing "PROT_SHADOWSTACK" on riscv
riscv mm: manufacture shadow stack pte
riscv mmu: teach pte_mkwrite to manufacture shadow stack PTEs riscv mmu: write protect and shadow stack
riscv/mm: Implement map_shadow_stack() syscall riscv/shstk: If needed allocate a new shadow stack on clone
prctl: arch-agnostic prtcl for indirect branch tracking
riscv: Implements arch agnostic shadow stack prctls
riscv: Implements arch argnostic indirect branch tracking prctls riscv/traps: Introduce software check exception
riscv sigcontext: adding cfi state field in sigcontext riscv signal: Save and restore of shadow stack for signal
riscv: select config for shadow stack and landing pad instr support riscv/ptrace: riscv cfi status and state via ptrace and in core files
riscv: Documentation for landing pad / indirect branch tracking
riscv: Documentation for shadow stack on riscv kselftest/riscv: kselftest for user mode cfi
Mark Brown (1):
prctl: arch-agnostic prctl for shadow stack
Documentation/arch/riscv/zicfilp.rst | 104 ++++ Documentation/arch/riscv/zicfiss.rst | 169 ++++++ arch/riscv/Kconfig | 16 + arch/riscv/include/asm/asm-prototypes.h | 1 + arch/riscv/include/asm/cpufeature.h | 18 + arch/riscv/include/asm/csr.h | 20 + arch/riscv/include/asm/hwcap.h | 2 + arch/riscv/include/asm/mman.h | 42 ++ arch/riscv/include/asm/pgtable.h | 32 +- arch/riscv/include/asm/processor.h | 2 + arch/riscv/include/asm/thread_info.h | 4 + arch/riscv/include/asm/usercfi.h | 106 ++++ arch/riscv/include/uapi/asm/ptrace.h | 18 + arch/riscv/include/uapi/asm/sigcontext.h | 5 + arch/riscv/kernel/Makefile | 2 + arch/riscv/kernel/asm-offsets.c | 6 +- arch/riscv/kernel/cpufeature.c | 4 +- arch/riscv/kernel/entry.S | 32 ++ arch/riscv/kernel/process.c | 16 + arch/riscv/kernel/ptrace.c | 83 +++ arch/riscv/kernel/signal.c | 45 ++ arch/riscv/kernel/sys_riscv.c | 19 + arch/riscv/kernel/traps.c | 38 ++ arch/riscv/kernel/usercfi.c | 497 ++++++++++++++++++ arch/riscv/mm/init.c | 2 +- arch/riscv/mm/pgtable.c | 21 + include/linux/mm.h | 35 +- include/uapi/asm-generic/mman.h | 1 + include/uapi/linux/elf.h | 1 + include/uapi/linux/prctl.h | 49 ++ kernel/sys.c | 60 +++ mm/gup.c | 5 +- mm/internal.h | 2 +- mm/mmap.c | 1 + tools/testing/selftests/riscv/Makefile | 2 +- tools/testing/selftests/riscv/cfi/Makefile | 10 + .../testing/selftests/riscv/cfi/cfi_rv_test.h | 85 +++ .../selftests/riscv/cfi/riscv_cfi_test.c | 91 ++++ .../testing/selftests/riscv/cfi/shadowstack.c | 376 +++++++++++++ .../testing/selftests/riscv/cfi/shadowstack.h | 39 ++ 40 files changed, 2050 insertions(+), 11 deletions(-) create mode 100644 Documentation/arch/riscv/zicfilp.rst create mode 100644 Documentation/arch/riscv/zicfiss.rst create mode 100644 arch/riscv/include/asm/mman.h create mode 100644 arch/riscv/include/asm/usercfi.h create mode 100644 arch/riscv/kernel/usercfi.c create mode 100644 tools/testing/selftests/riscv/cfi/Makefile create mode 100644 tools/testing/selftests/riscv/cfi/cfi_rv_test.h create mode 100644 tools/testing/selftests/riscv/cfi/riscv_cfi_test.c create mode 100644 tools/testing/selftests/riscv/cfi/shadowstack.c create mode 100644 tools/testing/selftests/riscv/cfi/shadowstack.h
Signature · 1 line
2.43.0
RFC PATCH 1/28 riscv: abstract envcfg CSR
From: Deepak Gupta <[email protected]>
This patch abstracts envcfg CSR in kernel (as is done for other homonyn CSRs). CSR_ENVCFG is used as alias for CSR_SENVCFG or CSR_MENVCFG depending on how kernel is compiled.
Additionally it changes CBZE enabling to start using CSR_ENVCFG instead of CSR_SENVCFG.
--- arch/riscv/include/asm/csr.h | 2 ++ arch/riscv/kernel/cpufeature.c | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-)
arch/riscv/include/asm/csr.h +2 -0
@@ -415,6 +415,7 @@# define CSR_STATUS CSR_MSTATUS# define CSR_IE CSR_MIE# define CSR_TVEC CSR_MTVEC +# define CSR_ENVCFG CSR_MENVCFG# define CSR_SCRATCH CSR_MSCRATCH# define CSR_EPC CSR_MEPC# define CSR_CAUSE CSR_MCAUSE
@@ -439,6 +440,7 @@# define CSR_STATUS CSR_SSTATUS# define CSR_IE CSR_SIE# define CSR_TVEC CSR_STVEC +# define CSR_ENVCFG CSR_SENVCFG# define CSR_SCRATCH CSR_SSCRATCH# define CSR_EPC CSR_SEPC# define CSR_CAUSE CSR_SCAUSE
arch/riscv/kernel/cpufeature.c +1 -1
@@ -725,7 +725,7 @@ arch_initcall(check_unaligned_access_all_cpus);void riscv_user_isa_enable (void ) {if (riscv_cpu_has_extension_unlikely (smp_processor_id (),RISCV_ISA_EXT_ZICBOZ )) -csr_set (CSR_SENVCFG ,ENVCFG_CBZE ); +csr_set (CSR_ENVCFG ,ENVCFG_CBZE ); }#ifdef CONFIG_RISCV_ALTERNATIVE
Signature · 1 line
2.43.0
RFC PATCH 2/28 riscv: envcfg save and restore on trap entry/exit
In reply to [email protected]From: Deepak Gupta <[email protected]>
envcfg CSR defines enabling bits for cache management instructions and soon will control enabling for control flow integrity and pointer masking features.
Control flow integrity enabling for forward cfi and backward cfi is controlled via envcfg and thus need to be enabled on per thread basis.
This patch creates a place holder for envcfg CSR in thread_info and adds logic to save and restore on trap entry and exits.
--- arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/asm-offsets.c | 1 + arch/riscv/kernel/entry.S | 4 ++++ 3 files changed, 6 insertions(+)
arch/riscv/include/asm/thread_info.h +1 -0
@@ -57,6 +57,7 @@ struct thread_info {long user_sp;/* User stack pointer */ int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ +unsigned long envcfg;#ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;
arch/riscv/kernel/asm-offsets.c +1 -0
@@ -39,6 +39,7 @@ void asm_offsets(void)OFFSET (TASK_TI_PREEMPT_COUNT , task_struct, thread_info.preempt_count);OFFSET (TASK_TI_KERNEL_SP , task_struct, thread_info.kernel_sp);OFFSET (TASK_TI_USER_SP , task_struct, thread_info.user_sp); +OFFSET (TASK_TI_ENVCFG , task_struct, thread_info.envcfg);#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif
arch/riscv/kernel/entry.S +4 -0
@@ -129,6 +129,10 @@ SYM_CODE_START_NOALIGN(ret_from_exception) addi s0, sp, PT_SIZE_ON_STACK REG_S s0, TASK_TI_KERNEL_SP(tp) + /* restore envcfg bits for current thread */ + REG_L s0, TASK_TI_ENVCFG(tp) + csrw CSR_ENVCFG, s0 + /* Save the kernel shadow call stack pointer */ scs_save_current
Signature · 1 line
2.43.0
RFC PATCH 3/28 riscv: define default value for envcfg
In reply to [email protected]From: Deepak Gupta <[email protected]>
Defines a base default value for envcfg per task. By default all tasks should have cache zeroing capability. Any future capabilities can be turned on.
--- arch/riscv/include/asm/csr.h | 2 ++ arch/riscv/kernel/process.c | 1 + 2 files changed, 3 insertions(+)
arch/riscv/include/asm/csr.h +2 -0
@@ -202,6 +202,8 @@#define ENVCFG_CBIE_FLUSH _AC(0x1, UL)#define ENVCFG_CBIE_INV _AC(0x3, UL)#define ENVCFG_FIOM _AC(0x1, UL) +/* by default all threads should be able to zero cache */ +#define ENVCFG_BASE ENVCFG_CBZE/* Smstateen bits */ #define SMSTATEEN0_AIA_IMSIC_SHIFT 58
arch/riscv/kernel/process.c +1 -0
@@ -152,6 +152,7 @@ void start_thread(struct pt_regs *regs, unsigned long pc, else regs->status |= SR_UXL_64;#endif + current->thread_info.envcfg =ENVCFG_BASE ; }void flush_thread (void )
Signature · 1 line
2.43.0
RFC PATCH 4/28 riscv/Kconfig: enable HAVE_EXIT_THREAD for riscv
In reply to [email protected]From: Deepak Gupta <[email protected]>
riscv will need an implementation for exit_thread to clean up shadow stack when thread exits. If current thread had shadow stack enabled, shadow stack is allocated by default for any new thread.
--- arch/riscv/Kconfig | 1 + arch/riscv/kernel/process.c | 5 +++++ 2 files changed, 6 insertions(+)
arch/riscv/Kconfig +1 -0
@@ -142,6 +142,7 @@ config RISCV select HAVE_RSEQ select HAVE_STACKPROTECTOR select HAVE_SYSCALL_TRACEPOINTS + select HAVE_EXIT_THREAD select HOTPLUG_CORE_SYNC_DEAD if HOTPLUG_CPU select IRQ_DOMAIN select IRQ_FORCED_THREADING
arch/riscv/kernel/process.c +5 -0
@@ -192,6 +192,11 @@ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src)return 0 ; } +void exit_thread (struct task_struct *tsk) +{ +return ; +} +int copy_thread (struct task_struct *p,const struct kernel_clone_args *args) {unsigned long clone_flags = args->flags;
Signature · 1 line
2.43.0
RFC PATCH 5/28 riscv: zicfiss/zicfilp enumeration
In reply to [email protected]From: Deepak Gupta <[email protected]>
This patch adds support for detecting zicfiss and zicfilp. zicfiss and zicfilp stands for unprivleged integer spec extension for shadow stack and branch tracking on indirect branches, respectively.
This patch looks for zicfiss and zicfilp in device tree and accordinlgy lights up bit in cpu feature bitmap. Furthermore this patch adds detection utility functions to return whether shadow stack or landing pads are supported by cpu.
--- arch/riscv/include/asm/cpufeature.h | 18 ++++++++++++++++++ arch/riscv/include/asm/hwcap.h | 2 ++ arch/riscv/include/asm/processor.h | 1 + arch/riscv/kernel/cpufeature.c | 2 ++ 4 files changed, 23 insertions(+)
arch/riscv/include/asm/cpufeature.h +18 -0
@@ -133,4 +133,22 @@ static __always_inline bool riscv_cpu_has_extension_unlikely(int cpu, const unsi return __riscv_isa_extension_available(hart_isa[cpu].isa, ext); } +static inline bool cpu_supports_shadow_stack (void ) +{ +#ifdef CONFIG_RISCV_USER_CFI +return riscv_isa_extension_available (NULL ,ZICFISS ); +#else +return false; +#endif +} + +static inline bool cpu_supports_indirect_br_lp_instr (void ) +{ +#ifdef CONFIG_RISCV_USER_CFI +return riscv_isa_extension_available (NULL ,ZICFILP ); +#else +return false; +#endif +} +#endif
arch/riscv/include/asm/hwcap.h +2 -0
@@ -57,6 +57,8 @@#define RISCV_ISA_EXT_ZIHPM 42#define RISCV_ISA_EXT_SMSTATEEN 43#define RISCV_ISA_EXT_ZICOND 44 +#define RISCV_ISA_EXT_ZICFISS 45 +#define RISCV_ISA_EXT_ZICFILP 46#define RISCV_ISA_EXT_MAX 64
arch/riscv/include/asm/processor.h +1 -0
@@ -13,6 +13,7 @@#include <vdso/processor.h> #include <asm/ptrace.h> +#include <asm/hwcap.h> #ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))
arch/riscv/kernel/cpufeature.c +2 -0
@@ -185,6 +185,8 @@ const struct riscv_isa_ext_data riscv_isa_ext[] = {__RISCV_ISA_EXT_DATA (svinval,RISCV_ISA_EXT_SVINVAL ),__RISCV_ISA_EXT_DATA (svnapot,RISCV_ISA_EXT_SVNAPOT ),__RISCV_ISA_EXT_DATA (svpbmt,RISCV_ISA_EXT_SVPBMT ), +__RISCV_ISA_EXT_DATA (zicfiss,RISCV_ISA_EXT_ZICFISS ), + __RISCV_ISA_EXT_DATA(zicfilp, RISCV_ISA_EXT_ZICFILP), };const size_t riscv_isa_ext_count =ARRAY_SIZE (riscv_isa_ext);
Signature · 1 line
2.43.0
RFC PATCH 6/28 riscv: zicfiss/zicfilp extension csr and bit definitions
In reply to [email protected]From: Deepak Gupta <[email protected]>
zicfiss and zicfilp extension gets enabled via b3 and b2 in xenvcfg CSR. menvcfg controls enabling for S/HS mode. henvcfg control enabling for VS while senvcfg controls enabling for U/VU mode.
zicfilp extension extends xstatus CSR to hold expected landing pad bit. A trap or interrupt can occur between an indirect jmp/call and target instr. expected landing pad bit from CPU is recorded into xstatus CSR so that when supervisor performs xret, expected landing pad state of CPU can be restored.
zicfiss adds one new CSR
- CSR_SSP: CSR_SSP contains current shadow stack pointer.
--- arch/riscv/include/asm/csr.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
arch/riscv/include/asm/csr.h +16 -0
@@ -18,6 +18,15 @@#define SR_MPP _AC(0x00001800, UL)/* Previously Machine */ #define SR_SUM _AC(0x00040000, UL)/* Supervisor User Memory Access */ +/* zicfilp landing pad status bit */ +#define SR_SPELP _AC(0x00800000, UL) +#define SR_MPELP _AC(0x020000000000, UL) +#ifdef CONFIG_RISCV_M_MODE +#define SR_ELP SR_MPELP +#else +#define SR_ELP SR_SPELP +#endif +#define SR_FS _AC(0x00006000, UL)/* Floating-point Status */ #define SR_FS_OFF _AC(0x00000000, UL)#define SR_FS_INITIAL _AC(0x00002000, UL)
@@ -196,6 +205,8 @@#define ENVCFG_PBMTE (_AC(1, ULL) << 62)#define ENVCFG_CBZE (_AC(1, UL) << 7)#define ENVCFG_CBCFE (_AC(1, UL) << 6) +#define ENVCFG_LPE (_AC(1, UL) << 2) +#define ENVCFG_SSE (_AC(1, UL) << 3)#define ENVCFG_CBIE_SHIFT 4#define ENVCFG_CBIE (_AC(0x3, UL) << ENVCFG_CBIE_SHIFT)#define ENVCFG_CBIE_ILL _AC(0x0, UL)
@@ -216,6 +227,11 @@#define SMSTATEEN0_HSENVCFG (_ULL(1) << SMSTATEEN0_HSENVCFG_SHIFT)#define SMSTATEEN0_SSTATEEN0_SHIFT 63#define SMSTATEEN0_SSTATEEN0 (_ULL(1) << SMSTATEEN0_SSTATEEN0_SHIFT) +/* +* zicfiss user mode csr +* CSR_SSP holds current shadow stack pointer. +*/ +#define CSR_SSP 0x011/* symbolic CSR names: */ #define CSR_CYCLE 0xc00
Signature · 1 line
2.43.0
RFC PATCH 7/28 riscv: kernel handling on trap entry/exit for user cfi
In reply to [email protected]From: Deepak Gupta <[email protected]>
Carves out space in arch specific thread struct for cfi status and shadow stack in usermode on riscv.
This patch does following
- defines a new structure cfi_status with status bit for cfi feature
- defines shadow stack pointer, base and size in cfi_status structure
- defines offsets to new member fields in thread in asm-offsets.c
- Saves and restore shadow stack pointer on trap entry (U --> S) and exit (S --> U)
--- arch/riscv/include/asm/processor.h | 1 + arch/riscv/include/asm/thread_info.h | 3 +++ arch/riscv/include/asm/usercfi.h | 24 ++++++++++++++++++++++++ arch/riscv/kernel/asm-offsets.c | 5 ++++- arch/riscv/kernel/entry.S | 25 +++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 arch/riscv/include/asm/usercfi.h
arch/riscv/include/asm/processor.h +1 -0
@@ -14,6 +14,7 @@#include <asm/ptrace.h> #include <asm/hwcap.h> +#include <asm/usercfi.h> #ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))
arch/riscv/include/asm/thread_info.h +3 -0
@@ -58,6 +58,9 @@ struct thread_info {int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ unsigned long envcfg; +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status user_cfi_state; +#endif #ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;
arch/riscv/include/asm/usercfi.h new file +24 -0
@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 +* Copyright (C) 2023 Rivos, Inc. +* Deepak Gupta <[email protected]> +*/ +#ifndef _ASM_RISCV_USERCFI_H +#define _ASM_RISCV_USERCFI_H + +#ifndef __ASSEMBLY__ +#include <linux/types.h> + +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status { +unsigned long ubcfi_en :1 ;/* Enable for backward cfi. */ +unsigned long rsvd : ((sizeof (unsigned long )*8 ) -1 ); +unsigned long user_shdw_stk;/* Current user shadow stack pointer */ +unsigned long shdw_stk_base;/* Base address of shadow stack */ +unsigned long shdw_stk_size;/* size of shadow stack */ +}; + +#endif /* CONFIG_RISCV_USER_CFI */ + +#endif /* __ASSEMBLY__ */ + +#endif /* _ASM_RISCV_USERCFI_H */
arch/riscv/kernel/asm-offsets.c +4 -1
@@ -43,8 +43,11 @@ void asm_offsets(void)#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif -OFFSET (TASK_TI_CPU_NUM , task_struct, thread_info.cpu); +#ifdef CONFIG_RISCV_USER_CFI +OFFSET (TASK_TI_CFI_STATUS , task_struct, thread_info.user_cfi_state); +OFFSET (TASK_TI_USER_SSP , task_struct, thread_info.user_cfi_state.user_shdw_stk); +#endif OFFSET (TASK_THREAD_F0 , task_struct, thread.fstate.f[0 ]);OFFSET (TASK_THREAD_F1 , task_struct, thread.fstate.f[1 ]);OFFSET (TASK_THREAD_F2 , task_struct, thread.fstate.f[2 ]);
arch/riscv/kernel/entry.S +25 -0
@@ -49,6 +49,21 @@ SYM_CODE_START(handle_exception) REG_S x5, PT_T0(sp) save_from_x6_to_x31 +#ifdef CONFIG_RISCV_USER_CFI + /* + * we need to save cfi status only when previous mode was U + */ + csrr s2, CSR_STATUS + andi s2, s2, SR_SPP + bnez s2, skip_bcfi_save + /* load cfi status word */ + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_save + csrr s3, CSR_SSP + REG_S s3, TASK_TI_USER_SSP(tp) /* save user ssp in thread_info */ +skip_bcfi_save: +#endif /* * Disable user-mode memory access as it should only be set in the * actual user copy routines.
@@ -141,6 +156,16 @@ SYM_CODE_START_NOALIGN(ret_from_exception) * structures again. */ csrw CSR_SCRATCH, tp + +#ifdef CONFIG_RISCV_USER_CFI + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_resume + REG_L s3, TASK_TI_USER_SSP(tp) /* restore user ssp from thread struct */ + csrw CSR_SSP, s3 +skip_bcfi_resume: +#endif + 1: REG_L a0, PT_STATUS(sp) /*
Signature · 1 line
2.43.0
RFC PATCH 8/28 mm: Define VM_SHADOW_STACK for RISC-V
In reply to [email protected]From: Deepak Gupta <[email protected]>
VM_SHADOW_STACK is defined by x86 as vm flag to mark a shadow stack vma.
x86 uses VM_HIGH_ARCH_5 bit but that limits shadow stack vma to 64bit only. arm64 follows same path
https://lore.kernel.org/lkml/[email protected]/#r
On RISC-V, write-only page table encodings are shadow stack pages. This patch re-defines VM_WRITE only to be VM_SHADOW_STACK.
Next set of patches will set guard rail that no other mm flow can set VM_WRITE only in vma except when specifically creating shadow stack.
--- include/linux/mm.h | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
include/linux/mm.h +13 -1
@@ -352,7 +352,19 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 -#else +#endif + +#ifdef CONFIG_RISCV_USER_CFI +/* +* On RISC-V pte encodings for shadow stack is R=0, W=1, X=0 and thus RISCV +* choosing to use similar mechanism on vm_flags where VM_WRITE only means +* VM_SHADOW_STACK. RISCV as well doesn't support VM_SHADOW_STACK to be set +* with VM_SHARED. +*/ +#define VM_SHADOW_STACK VM_WRITE +#endif + +#ifndef VM_SHADOW_STACK # define VM_SHADOW_STACK VM_NONE#endif
Signature · 1 line
2.43.0
RFC PATCH 9/28 mm: abstract shadow stack vma behind `arch_is_shadow_stack`
In reply to [email protected]From: Deepak Gupta <[email protected]>
x86 has used VM_SHADOW_STACK (alias to VM_HIGH_ARCH_5) to encode shadow stack VMA. VM_SHADOW_STACK is thus not possible on 32bit. Some arches may need a way to encode shadow stack on 32bit and 64bit both and they may encode this information differently in VMAs.
This patch changes checks of VM_SHADOW_STACK flag in generic code to call to a function arch_is_shadow_stack which will return true if arch supports shadow stack and vma is shadow stack else stub returns false.
There was a suggestion to name it as vma_is_shadow_stack. I preferred to keep arch prefix in there because it's each arch specific.
--- include/linux/mm.h | 18 +++++++++++++++++- mm/gup.c | 5 +++-- mm/internal.h | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-)
include/linux/mm.h +17 -1
@@ -352,6 +352,10 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return (vm_flags &VM_SHADOW_STACK ); +}#endif #ifdef CONFIG_RISCV_USER_CFI
@@ -362,10 +366,22 @@ extern unsigned int kobjsize(const void *objp);* with VM_SHARED. */ #define VM_SHADOW_STACK VM_WRITE + +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return ((vm_flags & (VM_WRITE |VM_READ |VM_EXEC )) ==VM_WRITE ); +} +#endif #ifndef VM_SHADOW_STACK # define VM_SHADOW_STACK VM_NONE + +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return false; +} +#endif #if defined(CONFIG_X86 )
@@ -3464,7 +3480,7 @@ static inline unsigned long stack_guard_start_gap(struct vm_area_struct *vma)return stack_guard_gap;/* See reasoning around the VM_SHADOW_STACK definition */ -if (vma->vm_flags &VM_SHADOW_STACK ) +if (vma->vm_flags &&arch_is_shadow_stack (vma->vm_flags))return PAGE_SIZE ;return 0 ;
mm/gup.c +3 -2
@@ -1051,7 +1051,7 @@ static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags) !writable_file_mapping_allowed(vma, gup_flags))return -EFAULT ; -if (!(vm_flags &VM_WRITE ) || (vm_flags &VM_SHADOW_STACK )) { +if (!(vm_flags &VM_WRITE ) ||arch_is_shadow_stack (vm_flags)) {if (!(gup_flags &FOLL_FORCE ))return -EFAULT ;/* hugetlb does not support FOLL_FORCE|FOLL_WRITE. */
@@ -1069,7 +1069,8 @@ static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)if (!is_cow_mapping (vm_flags))return -EFAULT ; } - }else if (!(vm_flags &VM_READ )) { + }else if (!(vm_flags &VM_READ ) && !arch_is_shadow_stack (vm_flags)) { +/* reads allowed if its shadow stack vma */ if (!(gup_flags &FOLL_FORCE ))return -EFAULT ;/*
mm/internal.h +1 -1
@@ -572,7 +572,7 @@ static inline bool is_exec_mapping(vm_flags_t flags)*/ static inline bool is_stack_mapping (vm_flags_t flags) { -return ((flags &VM_STACK ) ==VM_STACK ) || (flags &VM_SHADOW_STACK ); +return ((flags &VM_STACK ) ==VM_STACK ) ||arch_is_shadow_stack (flags); }/*
Signature · 1 line
2.43.0
RFC PATCH 10/28 riscv/mm : Introducing new protection flag "PROT_SHADOWSTACK"
In reply to [email protected]From: Deepak Gupta <[email protected]>
x86 and arm64 are using VM_SHADOW_STACK (which actually is VM_HIGH_ARCH_5) vma flag and thus restrict it to 64bit implementation only. RISC-V is choosing to encode presence of only VM_WRITE in vma flags as shadow stack vma. This allows 32bit RISC-V ecosystem leverage shadow stack as well.
This means that existing users of do_mmap who had been using VM_WRITE and expecting read and write permissions will break.
Thus introducing PROT_SHADOWSTACK to allow do_mmap disambiguate between read write v/s shadow stack mappings. Thus any kernel driver/module using do_mmap and only passing VM_WRITE would still get read-write mappings. Although any user of do_mmap intending to map a shaodw stack should pass PROT_SHADOWSTACK to get a shadow stack mapping.
Although for userspace still want to rely on map_shadow_stack and not expose PROT_SHADOWSTACK to userspace and that's why this prot flag is not exposed in uapi headers.
--- arch/riscv/include/asm/mman.h | 25 +++++++++++++++++++++++++ mm/mmap.c | 1 + 2 files changed, 26 insertions(+) create mode 100644 arch/riscv/include/asm/mman.h
arch/riscv/include/asm/mman.h new file +25 -0
@@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef __ASM_MMAN_H__ +#define __ASM_MMAN_H__ + +#include <linux/compiler.h> +#include <linux/types.h> +#include <uapi/asm/mman.h> + +/* +* Major architectures (x86, aarch64, riscv) have shadow stack now. x86 and +* arm64 choose to use VM_SHADOW_STACK (which actually is VM_HIGH_ARCH_5) vma +* flag, however that restrict it to 64bit implementation only. risc-v shadow +* stack encodings in page tables is PTE.R=0, PTE.W=1, PTE.D=1 which used to be +* reserved until now. risc-v is choosing to encode presence of only VM_WRITE in +* vma flags as shadow stack vma. However this means that existing users of mmap +* (and do_mmap) who were relying on passing only PROT_WRITE (or VM_WRITE from +* kernel driver) but still getting read and write mappings, should still work. +* x86 and arm64 followed the direction of a new system call `map_shadow_stack`. +* risc-v would like to converge on that so that shadow stacks flows are as much +* arch agnostic. Thus a conscious decision to define PROT_XXX definition for +* shadow stack here (and not exposed to uapi) +*/ +#define PROT_SHADOWSTACK 0x40 + +#endif /* ! __ASM_MMAN_H__ */
mm/mmap.c +1 -0
@@ -47,6 +47,7 @@#include <linux/oom.h> #include <linux/sched/mm.h> #include <linux/ksm.h> +#include <linux/processor.h> #include <linux/uaccess.h> #include <asm/cacheflush.h>
Signature · 1 line
2.43.0
RFC PATCH 11/28 riscv: Implementing "PROT_SHADOWSTACK" on riscv
In reply to [email protected]From: Deepak Gupta <[email protected]>
This patch implements new risc-v specific protection flag PROT_SHADOWSTACK (only for kernel) on riscv.
PROT_SHADOWSTACK protection flag is only limited to kernel and not exposed to userspace. Shadow stack is a security construct to prevent against ROP attacks. map_shadow_stack is a new syscall to manufacture shadow stack. In order to avoid multiple methods to create shadow stack, PROT_SHADOWSTACK is not allowed for user space mmap call. mprotect wouldn't allow because arch_validate_prot already takes care of this for risc-v.
arch_calc_vm_prot_bits is implemented on risc-v to return VM_SHADOW_STACK (alias for VM_WRITE) if PROT_SHADOWSTACK is supplied (such as call to do_mmap will) and underlying CPU supports shadow stack. PROT_WRITE will be converted to VM_READ | VM_WRITE so that existing case where PROT_WRITE is specified keep working but don't collide with VM_WRITE` only encoding which now denotes a shadow stack.
risc-v mmap wrapper enforces if PROT_WRITE is specified and PROT_READ is left out then PROT_READ is enforced.
Earlier protection_map[VM_WRITE] used to pick read-write (and copy on write) PTE encodings. Now all non-shadow stack writeable mappings will pick protection_map[VM_WRITE | VM_READ] PTE encodings. protection[VM_WRITE]` are programmed to pick PAGE_SHADOWSTACK PTE encordings.
--- arch/riscv/include/asm/mman.h | 17 +++++++++++++++++ arch/riscv/include/asm/pgtable.h | 1 + arch/riscv/kernel/sys_riscv.c | 19 +++++++++++++++++++ arch/riscv/mm/init.c | 2 +- 4 files changed, 38 insertions(+), 1 deletion(-)
arch/riscv/include/asm/mman.h +17 -0
@@ -22,4 +22,21 @@*/ #define PROT_SHADOWSTACK 0x40 +static inline unsigned long arch_calc_vm_prot_bits (unsigned long prot, +unsigned long pkey__always_unused ) +{ +unsigned long ret =0 ; + +if (cpu_supports_shadow_stack ()) + ret = (prot &PROT_SHADOWSTACK ) ?VM_SHADOW_STACK :0 ; +/* +* If PROT_WRITE was specified, force it to VM_READ | VM_WRITE. +* Only VM_WRITE means shadow stack. +*/ +if (prot &PROT_WRITE ) + ret = (VM_READ |VM_WRITE ); +return ret; +} +#define arch_calc_vm_prot_bits (prot, pkey) arch_calc_vm_prot_bits(prot, pkey) +#endif /* ! __ASM_MMAN_H__ */
arch/riscv/include/asm/pgtable.h +1 -0
@@ -184,6 +184,7 @@ extern struct pt_alloc_ops pt_ops __initdata;#define PAGE_READ_EXEC __pgprot(_PAGE_BASE | _PAGE_READ | _PAGE_EXEC)#define PAGE_WRITE_EXEC __pgprot(_PAGE_BASE | _PAGE_READ | \ _PAGE_EXEC | _PAGE_WRITE) +#define PAGE_SHADOWSTACK __pgprot(_PAGE_BASE | _PAGE_WRITE)#define PAGE_COPY PAGE_READ#define PAGE_COPY_EXEC PAGE_READ_EXEC
arch/riscv/kernel/sys_riscv.c +19 -0
@@ -16,6 +16,7 @@#include <asm/unistd.h> #include <asm-generic/mman-common.h> #include <vdso/vsyscall.h> +#include <asm/mman.h> static long riscv_sys_mmap(unsigned long addr, unsigned long len, unsigned long prot, unsigned long flags,
@@ -25,6 +26,24 @@ static long riscv_sys_mmap(unsigned long addr, unsigned long len,if (unlikely (offset & (~PAGE_MASK >> page_shift_offset)))return -EINVAL ; +/* +* If only PROT_WRITE is specified then extend that to PROT_READ +* protection_map[VM_WRITE] is now going to select shadow stack encodings. +* So specifying PROT_WRITE actually should select protection_map [VM_WRITE | VM_READ] +* If user wants to create shadow stack then they should use `map_shadow_stack` syscall. +*/ +if (unlikely ((prot &PROT_WRITE ) && !(prot &PROT_READ ))) + prot |=PROT_READ ; + +/* +* PROT_SHADOWSTACK is a kernel only protection flag on risc-v. +* mmap doesn't expect PROT_SHADOWSTACK to be set by user space. +* User space can rely on `map_shadow_stack` syscall to create +* shadow stack pages. +*/ +if (unlikely (prot &PROT_SHADOWSTACK )) +return -EINVAL ; +return ksys_mmap_pgoff (addr, len, prot, flags, fd, offset >> (PAGE_SHIFT - page_shift_offset)); }
arch/riscv/mm/init.c +1 -1
@@ -296,7 +296,7 @@ pgd_t early_pg_dir[PTRS_PER_PGD] __initdata __aligned(PAGE_SIZE);static const pgprot_t protection_map[16 ] = { [VM_NONE ] =PAGE_NONE , [VM_READ ] =PAGE_READ , - [VM_WRITE ] =PAGE_COPY , + [VM_WRITE ] =PAGE_SHADOWSTACK , [VM_WRITE |VM_READ ] =PAGE_COPY , [VM_EXEC ] =PAGE_EXEC , [VM_EXEC |VM_READ ] =PAGE_READ_EXEC ,
Signature · 1 line
2.43.0
RFC PATCH 12/28 riscv mm: manufacture shadow stack pte
In reply to [email protected]From: Deepak Gupta <[email protected]>
This patch implements creating shadow stack pte (on riscv). Creating shadow stack PTE on riscv means that clearing RWX and then setting W=1.
--- arch/riscv/include/asm/pgtable.h | 12 ++++++++++++ 1 file changed, 12 insertions(+)
arch/riscv/include/asm/pgtable.h +12 -0
@@ -408,6 +408,12 @@ static inline pte_t pte_mkwrite_novma(pte_t pte)return __pte (pte_val (pte) | _PAGE_WRITE); } +static inline pte_t pte_mkwrite_shstk (pte_t pte) +{ +/* shadow stack on risc-v is XWR = 010. Clear everything and only set _PAGE_WRITE */ +return __pte ((pte_val (pte) & ~(_PAGE_LEAF)) | _PAGE_WRITE); +} +/* static inline pte_t pte_mkexec(pte_t pte) */ static inline pte_t pte_mkdirty (pte_t pte)
@@ -705,6 +711,12 @@ static inline pmd_t pmd_mkwrite_novma(pmd_t pmd)return pte_pmd (pte_mkwrite_novma (pmd_pte (pmd))); } +static inline pmd_t pmd_mkwrite_shstk (pmd_t pte) +{ +/* shadow stack on risc-v is XWR = 010. Clear everything and only set _PAGE_WRITE */ +return __pmd ((pmd_val (pte) & ~(_PAGE_LEAF)) | _PAGE_WRITE); +} +static inline pmd_t pmd_wrprotect (pmd_t pmd) {return pte_pmd (pte_wrprotect (pmd_pte (pmd)));
Signature · 1 line
2.43.0
RFC PATCH 13/28 riscv mmu: teach pte_mkwrite to manufacture shadow stack PTEs
In reply to [email protected]From: Deepak Gupta <[email protected]>
pte_mkwrite creates PTEs with WRITE encodings for underlying arch. Underlying arch can have two types of writeable mappings. One that can be written using regular store instructions. Another one that can only be written using specialized store instructions (like shadow stack stores). pte_mkwrite can select write PTE encoding based on VMA range.
On riscv, presence of only VM_WRITE in vma->vm_flags means it's a shadow stack.
rebase with a30f0ca0fa31cdb2ac3d24b7b5be9e3ae75f4175
Implementation of pte_mkwrite and pmd_mkwrite on riscv
--- arch/riscv/include/asm/pgtable.h | 7 +++++++ arch/riscv/mm/pgtable.c | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+)
arch/riscv/include/asm/pgtable.h +7 -0
@@ -403,6 +403,10 @@ static inline pte_t pte_wrprotect(pte_t pte)/* static inline pte_t pte_mkread(pte_t pte) */ +struct vm_area_struct ; +pte_t pte_mkwrite (pte_t pte,struct vm_area_struct *vma); +#define pte_mkwrite pte_mkwrite +static inline pte_t pte_mkwrite_novma (pte_t pte) {return __pte (pte_val (pte) | _PAGE_WRITE);
@@ -706,6 +710,9 @@ static inline pmd_t pmd_mkyoung(pmd_t pmd)return pte_pmd (pte_mkyoung (pmd_pte (pmd))); } +pmd_t pmd_mkwrite (pmd_t pmd,struct vm_area_struct *vma); +#define pmd_mkwrite pmd_mkwrite +static inline pmd_t pmd_mkwrite_novma (pmd_t pmd) {return pte_pmd (pte_mkwrite_novma (pmd_pte (pmd)));
arch/riscv/mm/pgtable.c +21 -0
@@ -101,3 +101,24 @@ pmd_t pmdp_collapse_flush(struct vm_area_struct *vma, return pmd; }#endif /* CONFIG_TRANSPARENT_HUGEPAGE */ + +pte_t pte_mkwrite (pte_t pte,struct vm_area_struct *vma) +{ +if (arch_is_shadow_stack (vma->vm_flags)) +return pte_mkwrite_shstk (pte); + + pte =pte_mkwrite_novma (pte); + +return pte; +} + +pmd_t pmd_mkwrite (pmd_t pmd,struct vm_area_struct *vma) +{ +if (arch_is_shadow_stack (vma->vm_flags)) +return pmd_mkwrite_shstk (pmd); + + pmd =pmd_mkwrite_novma (pmd); + +return pmd; +} +
Signature · 1 line
2.43.0
RFC PATCH 14/28 riscv mmu: write protect and shadow stack
In reply to [email protected]From: Deepak Gupta <[email protected]>
fork implements copy on write (COW) by making pages readonly in child and parent both.
ptep_set_wrprotect and pte_wrprotect clears _PAGE_WRITE in PTE. Assumption is that page is readable and on fault copy on write happens.
To implement COW on such pages, clearing up W bit makes them XWR = 000. This will result in wrong PTE setting which says no perms but V=1 and PFN field pointing to final page. Instead desired behavior is to turn it into a readable page, take an access (load/store) fault on sspush/sspop (shadow stack) and then perform COW on such pages. This way regular reads would still be allowed and not lead to COW maintaining current behavior of COW on non-shadow stack but writeable memory.
On the other hand it doesn't interfere with existing COW for read-write memory. Assumption is always that _PAGE_READ must have been set and thus setting _PAGE_READ is harmless.
--- arch/riscv/include/asm/pgtable.h | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
arch/riscv/include/asm/pgtable.h +10 -2
@@ -398,7 +398,7 @@ static inline int pte_special(pte_t pte)static inline pte_t pte_wrprotect (pte_t pte) { -return __pte (pte_val (pte) & ~(_PAGE_WRITE)); +return __pte ((pte_val (pte) & ~(_PAGE_WRITE)) | (_PAGE_READ)); }/* static inline pte_t pte_mkread(pte_t pte) */
@@ -594,7 +594,15 @@ static inline int ptep_test_and_clear_young(struct vm_area_struct *vma,static inline void ptep_set_wrprotect (struct mm_struct *mm,unsigned long address,pte_t *ptep) { -atomic_long_and (~(unsigned long )_PAGE_WRITE, (atomic_long_t *)ptep); +volatile pte_t read_pte = *ptep; +/* +* ptep_set_wrprotect can be called for shadow stack ranges too. +* shadow stack memory is XWR = 010 and thus clearing _PAGE_WRITE will lead to +* encoding 000b which is wrong encoding with V = 1. This should lead to page fault +* but we dont want this wrong configuration to be set in page tables. +*/ +atomic_long_set ((atomic_long_t *)ptep, + ((pte_val (read_pte) & ~(unsigned long )_PAGE_WRITE) | _PAGE_READ)); }#define __HAVE_ARCH_PTEP_CLEAR_YOUNG_FLUSH
Signature · 1 line
2.43.0
RFC PATCH 15/28 riscv/mm: Implement map_shadow_stack() syscall
In reply to [email protected]From: Deepak Gupta <[email protected]>
As discussed extensively in the changelog for the addition of this syscall on x86 ("x86/shstk: Introduce map_shadow_stack syscall") the existing mmap() and madvise() syscalls do not map entirely well onto the security requirements for guarded control stacks since they lead to windows where memory is allocated but not yet protected or stacks which are not properly and safely initialised. Instead a new syscall map_shadow_stack() has been defined which allocates and initialises a shadow stack page.
This patch implements this syscall for riscv. riscv doesn't require token to be setup by kernel because user mode can do that by itself. However to provide compatiblity and portability with other architectues, user mode can specify token set flag.
--- arch/riscv/kernel/Makefile | 2 + arch/riscv/kernel/usercfi.c | 150 ++++++++++++++++++++++++++++++++ include/uapi/asm-generic/mman.h | 1 + 3 files changed, 153 insertions(+) create mode 100644 arch/riscv/kernel/usercfi.c
arch/riscv/kernel/Makefile +2 -0
@@ -102,3 +102,5 @@ obj-$(CONFIG_COMPAT) += compat_vdso/ obj-$(CONFIG_64BIT) += pi/ obj-$(CONFIG_ACPI) += acpi.o + +obj-$(CONFIG_RISCV_USER_CFI) += usercfi.o
arch/riscv/kernel/usercfi.c new file +150 -0
150 lines not on this page · raw message
include/uapi/asm-generic/mman.h +1 -0
@@ -19,4 +19,5 @@#define MCL_FUTURE 2/* lock all future mappings */ #define MCL_ONFAULT 4/* lock all pages that are faulted in */ +#define SHADOW_STACK_SET_TOKEN (1ULL << 0)/* Set up a restore token in the shadow stack */ #endif /* __ASM_GENERIC_MMAN_H */
Signature · 1 line
2.43.0
RFC PATCH 16/28 riscv/shstk: If needed allocate a new shadow stack on clone
In reply to [email protected]From: Deepak Gupta <[email protected]>
Userspace specifies VM_CLONE to share address space and spawn new thread. clone allow userspace to specify a new stack for new thread. However there is no way to specify new shadow stack base address without changing API. This patch allocates a new shadow stack whenever VM_CLONE is given.
In case of VM_FORK, parent is suspended until child finishes and thus can child use parent shadow stack. In case of !VM_CLONE, COW kicks in because entire address space is copied from parent to child.
clone3 is extensible and can provide mechanisms using which shadow stack as an input parameter can be provided. This is not settled yet and being extensively discussed on mailing list. Once that's settled, this commit will adapt to that.
--- arch/riscv/include/asm/usercfi.h | 39 ++++++++++ arch/riscv/kernel/process.c | 10 +++ arch/riscv/kernel/usercfi.c | 121 +++++++++++++++++++++++++++++++ 3 files changed, 170 insertions(+)
arch/riscv/include/asm/usercfi.h +39 -0
@@ -8,6 +8,9 @@ #ifndef __ASSEMBLY__ #include <linux/types.h> +struct task_struct; +struct kernel_clone_args; + #ifdef CONFIG_RISCV_USER_CFI struct cfi_status { unsigned long ubcfi_en : 1; /* Enable for backward cfi. */
@@ -17,6 +20,42 @@ struct cfi_status {unsigned long shdw_stk_size;/* size of shadow stack */ }; +unsigned long shstk_alloc_thread_stack (struct task_struct *tsk, +const struct kernel_clone_args *args); +void shstk_release (struct task_struct *tsk); +void set_shstk_base (struct task_struct *task,unsigned long shstk_addr,unsigned long size); +void set_active_shstk (struct task_struct *task,unsigned long shstk_addr); +bool is_shstk_enabled (struct task_struct *task); + +#else + +static inline unsigned long shstk_alloc_thread_stack (struct task_struct *tsk, +const struct kernel_clone_args *args) +{ +return 0 ; +} + +static inline void shstk_release (struct task_struct *tsk) +{ + +} + +static inline void set_shstk_base (struct task_struct *task,unsigned long shstk_addr, +unsigned long size) +{ + +} + +static inline void set_active_shstk (struct task_struct *task,unsigned long shstk_addr) +{ + +} + +static inline bool is_shstk_enabled (struct task_struct *task) +{ +return false; +} +#endif /* CONFIG_RISCV_USER_CFI */ #endif /* __ASSEMBLY__ */
arch/riscv/kernel/process.c +10 -0
@@ -26,6 +26,7 @@#include <asm/cpuidle.h> #include <asm/vector.h> #include <asm/cpufeature.h> +#include <asm/usercfi.h> registerunsigned long gp_in_global __asm__("gp" );
@@ -194,6 +195,7 @@ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src)void exit_thread (struct task_struct *tsk) { +shstk_release (tsk);return ; }
@@ -202,6 +204,7 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)unsigned long clone_flags = args->flags;unsigned long usp = args->stack;unsigned long tls = args->tls; +unsigned long ssp =0 ;struct pt_regs *childregs =task_pt_regs (p);memset (&p->thread.s,0 ,sizeof (p->thread.s));
@@ -217,11 +220,18 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args) p->thread.s[0 ] = (unsigned long )args->fn; p->thread.s[1 ] = (unsigned long )args->fn_arg; }else { +/* allocate new shadow stack if needed. In case of CLONE_VM we have to */ + ssp =shstk_alloc_thread_stack (p, args); +if (IS_ERR_VALUE (ssp)) +return PTR_ERR ((void *)ssp); + *childregs = *(current_pt_regs ());/* Turn off status.VS */ riscv_v_vstate_off (childregs);if (usp)/* User fork */ childregs->sp = usp; +if (ssp)/* if needed, set new ssp */ +set_active_shstk (p, ssp);if (clone_flags &CLONE_SETTLS ) childregs->tp = tls; childregs->a0 =0 ;/* Return value of fork() */
arch/riscv/kernel/usercfi.c +121 -0
130 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 17/28 prctl: arch-agnostic prctl for shadow stack
In reply to [email protected]From: Mark Brown <[email protected]>
Three architectures (x86, aarch64, riscv) have announced support for shadow stacks with fairly similar functionality. While x86 is using arch_prctl() to control the functionality neither arm64 nor riscv uses that interface so this patch adds arch-agnostic prctl() support to get and set status of shadow stacks and lock the current configuation to prevent further changes, with support for turning on and off individual subfeatures so applications can limit their exposure to features that they do not need. The features are:
- PR_SHADOW_STACK_ENABLE: Tracking and enforcement of shadow stacks, including allocation of a shadow stack if one is not already allocated.
- PR_SHADOW_STACK_WRITE: Writes to specific addresses in the shadow stack.
- PR_SHADOW_STACK_PUSH: Push additional values onto the shadow stack.
- PR_SHADOW_STACK_DISABLE: Allow to disable shadow stack. Note once locked, disable must fail.
These features are expected to be inherited by new threads and cleared on exec(), unknown features should be rejected for enable but accepted for locking (in order to allow for future proofing).
This is based on a patch originally written by Deepak Gupta but later modified by Mark Brown for arm's GCS patch series.
--- include/linux/mm.h | 3 +++ include/uapi/linux/prctl.h | 22 ++++++++++++++++++++++ kernel/sys.c | 30 ++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+)
include/linux/mm.h +3 -0
@@ -4170,5 +4170,8 @@ static inline bool pfn_is_unaccepted_memory(unsigned long pfn) return range_contains_unaccepted_memory(paddr, paddr + PAGE_SIZE); } +int arch_get_shadow_stack_status (struct task_struct *t,unsigned long __user *status); +int arch_set_shadow_stack_status (struct task_struct *t,unsigned long status); +int arch_lock_shadow_stack_status (struct task_struct *t,unsigned long status);#endif /* _LINUX_MM_H */
include/uapi/linux/prctl.h +22 -0
@@ -306,4 +306,26 @@ struct prctl_mm_map {# define PR_RISCV_V_VSTATE_CTRL_NEXT_MASK 0xc# define PR_RISCV_V_VSTATE_CTRL_MASK 0x1f +/* +* Get the current shadow stack configuration for the current thread, +* this will be the value configured via PR_SET_SHADOW_STACK_STATUS. +*/ +#define PR_GET_SHADOW_STACK_STATUS 71 + +/* +* Set the current shadow stack configuration. Enabling the shadow +* stack will cause a shadow stack to be allocated for the thread. +*/ +#define PR_SET_SHADOW_STACK_STATUS 72 +# define PR_SHADOW_STACK_ENABLE (1UL << 0) +# define PR_SHADOW_STACK_WRITE (1UL << 1) +# define PR_SHADOW_STACK_PUSH (1UL << 2) + +/* +* Prevent further changes to the specified shadow stack +* configuration. All bits may be locked via this call, including +* undefined bits. +*/ +#define PR_LOCK_SHADOW_STACK_STATUS 73 +#endif /* _LINUX_PRCTL_H */
kernel/sys.c +30 -0
@@ -2301,6 +2301,21 @@ int __weak arch_prctl_spec_ctrl_set(struct task_struct *t, unsigned long which,return -EINVAL ; } +int __weak arch_get_shadow_stack_status (struct task_struct *t,unsigned long __user *status) +{ +return -EINVAL ; +} + +int __weak arch_set_shadow_stack_status (struct task_struct *t,unsigned long status) +{ +return -EINVAL ; +} + +int __weak arch_lock_shadow_stack_status (struct task_struct *t,unsigned long status) +{ +return -EINVAL ; +} +#define PR_IO_FLUSHER (PF_MEMALLOC_NOIO | PF_LOCAL_THROTTLE)#ifdef CONFIG_ANON_VMA_NAME
@@ -2743,6 +2758,21 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,case PR_RISCV_V_GET_CONTROL : error =RISCV_V_GET_CONTROL ();break ; +case PR_GET_SHADOW_STACK_STATUS : +if (arg3 || arg4 || arg5) +return -EINVAL ; + error =arch_get_shadow_stack_status (me, (unsigned long __user *) arg2); +break ; +case PR_SET_SHADOW_STACK_STATUS : +if (arg3 || arg4 || arg5) +return -EINVAL ; + error =arch_set_shadow_stack_status (me, arg2); +break ; +case PR_LOCK_SHADOW_STACK_STATUS : +if (arg3 || arg4 || arg5) +return -EINVAL ; + error =arch_lock_shadow_stack_status (me, arg2); +break ;default : error = -EINVAL ;break ;
Signature · 1 line
2.43.0
RFC PATCH 18/28 prctl: arch-agnostic prtcl for indirect branch tracking
In reply to [email protected]From: Deepak Gupta <[email protected]>
Three architectures (x86, aarch64, riscv) have support for indirect branch tracking feature in a very similar fashion. On a very high level, indirect branch tracking is a CPU feature where CPU tracks branches which uses memory operand to perform control transfer in program. As part of this tracking on indirect branches, CPU goes in a state where it expects a landing pad instr on target and if not found then CPU raises some fault (architecture dependent)
x86 landing pad instr - ENDBRANCH
aarch64 landing pad instr - BTI
riscv landing instr - lpad
Given that three major arches have support for indirect branch tracking, This patch makes prctl for indirect branch tracking arch agnostic.
To allow userspace to enable this feature for itself, following prtcls are defined:
- PR_GET_INDIR_BR_LP_STATUS: Gets current configured status for indirect branch tracking.
- PR_SET_INDIR_BR_LP_STATUS: Sets a configuration for indirect branch tracking Following status options are allowed
- PR_INDIR_BR_LP_ENABLE: Enables indirect branch tracking on user thread.
- PR_INDIR_BR_LP_DISABLE; Disables indirect branch tracking on user thread.
- PR_LOCK_INDIR_BR_LP_STATUS: Locks configured status for indirect branch tracking for user thread.
--- include/uapi/linux/prctl.h | 27 +++++++++++++++++++++++++++ kernel/sys.c | 30 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+)
include/uapi/linux/prctl.h +27 -0
@@ -328,4 +328,31 @@ struct prctl_mm_map {*/ #define PR_LOCK_SHADOW_STACK_STATUS 73 +/* +* Get the current indirect branch tracking configuration for the current +* thread, this will be the value configured via PR_SET_INDIR_BR_LP_STATUS. +*/ +#define PR_GET_INDIR_BR_LP_STATUS 74 + +/* +* Set the indirect branch tracking configuration. PR_INDIR_BR_LP_ENABLE will +* enable cpu feature for user thread, to track all indirect branches and ensure +* they land on arch defined landing pad instruction. +* x86 - If enabled, an indirect branch must land on `ENDBRANCH` instruction. +* arch64 - If enabled, an indirect branch must land on `BTI` instruction. +* riscv - If enabled, an indirect branch must land on `lpad` instruction. +* PR_INDIR_BR_LP_DISABLE will disable feature for user thread and indirect +* branches will no more be tracked by cpu to land on arch defined landing pad +* instruction. +*/ +#define PR_SET_INDIR_BR_LP_STATUS 75 +# define PR_INDIR_BR_LP_ENABLE (1UL << 0) + +/* +* Prevent further changes to the specified indirect branch tracking +* configuration. All bits may be locked via this call, including +* undefined bits. +*/ +#define PR_LOCK_INDIR_BR_LP_STATUS 76 +#endif /* _LINUX_PRCTL_H */
kernel/sys.c +30 -0
@@ -2316,6 +2316,21 @@ int __weak arch_lock_shadow_stack_status(struct task_struct *t, unsigned long streturn -EINVAL ; } +int __weak arch_get_indir_br_lp_status (struct task_struct *t,unsigned long __user *status) +{ +return -EINVAL ; +} + +int __weak arch_set_indir_br_lp_status (struct task_struct *t,unsigned long __user *status) +{ +return -EINVAL ; +} + +int __weak arch_lock_indir_br_lp_status (struct task_struct *t,unsigned long __user *status) +{ +return -EINVAL ; +} +#define PR_IO_FLUSHER (PF_MEMALLOC_NOIO | PF_LOCAL_THROTTLE)#ifdef CONFIG_ANON_VMA_NAME
@@ -2773,6 +2788,21 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,return -EINVAL ; error =arch_lock_shadow_stack_status (me, arg2);break ; +case PR_GET_INDIR_BR_LP_STATUS : +if (arg3 || arg4 || arg5) +return -EINVAL ; + error =arch_get_indir_br_lp_status (me, (unsigned long __user *) arg2); +break ; +case PR_SET_INDIR_BR_LP_STATUS : +if (arg3 || arg4 || arg5) +return -EINVAL ; + error =arch_set_indir_br_lp_status (me, (unsigned long __user *) arg2); +break ; +case PR_LOCK_INDIR_BR_LP_STATUS : +if (arg3 || arg4 || arg5) +return -EINVAL ; + error =arch_lock_indir_br_lp_status (me, (unsigned long __user *) arg2); +break ;default : error = -EINVAL ;break ;
Signature · 1 line
2.43.0
RFC PATCH 19/28 riscv: Implements arch agnostic shadow stack prctls
In reply to [email protected]From: Deepak Gupta <[email protected]>
Implement architecture agnostic prctls() interface for setting and getting shadow stack status.
prctls implemented are PR_GET_SHADOW_STACK_STATUS, PR_SET_SHADOW_STACK_STATUS and PR_LOCK_SHADOW_STACK_STATUS.
As part of PR_SET_SHADOW_STACK_STATUS/PR_GET_SHADOW_STACK_STATUS, only PR_SHADOW_STACK_ENABLE is implemented because RISCV allows each mode to write to their own shadow stack using sspush or ssamoswap.
PR_LOCK_SHADOW_STACK_STATUS locks current configuration of shadow stack enabling Following is not supported
"Enable shadow stack, then disable and enable again."
It's not sure whether providing such semantics are useful. It's better to return error code when such situation arises.
--- arch/riscv/include/asm/usercfi.h | 12 +++- arch/riscv/kernel/usercfi.c | 105 +++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +11 -1
@@ -7,6 +7,7 @@#ifndef __ASSEMBLY__#include <linux/types.h> +#include <linux/prctl.h> struct task_struct ;struct kernel_clone_args ;
@@ -14,7 +15,8 @@ struct kernel_clone_args; #ifdef CONFIG_RISCV_USER_CFI struct cfi_status { unsigned long ubcfi_en : 1; /* Enable for backward cfi. */ - unsigned long rsvd : ((sizeof(unsigned long)*8) - 1); + unsigned long ubcfi_locked : 1; + unsigned long rsvd : ((sizeof(unsigned long)*8) - 2); unsigned long user_shdw_stk; /* Current user shadow stack pointer */ unsigned long shdw_stk_base; /* Base address of shadow stack */ unsigned long shdw_stk_size; /* size of shadow stack */
@@ -26,6 +28,9 @@ void shstk_release(struct task_struct *tsk);void set_shstk_base (struct task_struct *task,unsigned long shstk_addr,unsigned long size);void set_active_shstk (struct task_struct *task,unsigned long shstk_addr);bool is_shstk_enabled (struct task_struct *task); +bool is_shstk_locked (struct task_struct *task); + +#define PR_SHADOW_STACK_SUPPORTED_STATUS_MASK (PR_SHADOW_STACK_ENABLE)#else
@@ -56,6 +61,11 @@ static inline bool is_shstk_enabled(struct task_struct *task)return false; } +static inline bool is_shstk_locked (struct task_struct *task) +{ +return false; +} +#endif /* CONFIG_RISCV_USER_CFI */ #endif /* __ASSEMBLY__ */
arch/riscv/kernel/usercfi.c +105 -0
120 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 20/28 riscv: Implements arch argnostic indirect branch tracking prctls
In reply to [email protected]From: Deepak Gupta <[email protected]>
prctls implemented are PR_SET_INDIR_BR_LP_STATUS / PR_GET_INDIR_BR_LP_STATUS and PR_LOCK_INDIR_BR_LP_STATUS.
--- arch/riscv/include/asm/usercfi.h | 17 +++++++- arch/riscv/kernel/usercfi.c | 74 ++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +16 -1
@@ -16,7 +16,9 @@ struct kernel_clone_args;struct cfi_status {unsigned long ubcfi_en :1 ;/* Enable for backward cfi. */ unsigned long ubcfi_locked :1 ; -unsigned long rsvd : ((sizeof (unsigned long )*8 ) -2 ); +unsigned long ufcfi_en :1 ;/* Enable for forward cfi. Note that ELP goes in sstatus */ +unsigned long ufcfi_locked :1 ; +unsigned long rsvd : ((sizeof (unsigned long )*8 ) -4 );unsigned long user_shdw_stk;/* Current user shadow stack pointer */ unsigned long shdw_stk_base;/* Base address of shadow stack */ unsigned long shdw_stk_size;/* size of shadow stack */
@@ -29,6 +31,8 @@ void set_shstk_base(struct task_struct *task, unsigned long shstk_addr, unsignedvoid set_active_shstk (struct task_struct *task,unsigned long shstk_addr);bool is_shstk_enabled (struct task_struct *task);bool is_shstk_locked (struct task_struct *task); +bool is_indir_lp_enabled (struct task_struct *task); +bool is_indir_lp_locked (struct task_struct *task);#define PR_SHADOW_STACK_SUPPORTED_STATUS_MASK (PR_SHADOW_STACK_ENABLE)
@@ -66,6 +70,17 @@ static inline bool is_shstk_locked(struct task_struct *task)return false; } +static inline bool is_indir_lp_enabled (struct task_struct *task) +{ +return false; +} + +static inline bool is_indir_lp_locked (struct task_struct *task) + +{ +return false; +} +#endif /* CONFIG_RISCV_USER_CFI */ #endif /* __ASSEMBLY__ */
arch/riscv/kernel/usercfi.c +74 -0
83 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 21/28 riscv/traps: Introduce software check exception
In reply to [email protected]From: Deepak Gupta <[email protected]>
zicfiss / zicfilp introduces a new exception to priv isa software check exception with cause code = 18. This patch implements software check exception.
Additionally it implements a cfi violation handler which checks for code in xtval If xtval=2, it means that sw check exception happened because of an indirect branch not landing on 4 byte aligned PC or not landing on lpad instruction or label value embedded in lpad not matching label value setup in x7. If xtval=3, it means that sw check exception happened because of mismatch between link register (x1 or x5) and top of shadow stack (on execution of sspopchk)
In case of cfi violation, SIGSEGV is raised with code=SEGV_CPERR. SEGV_CPERR was introduced by x86 shadow stack patches.
--- arch/riscv/include/asm/asm-prototypes.h | 1 + arch/riscv/kernel/entry.S | 3 ++ arch/riscv/kernel/traps.c | 38 +++++++++++++++++++++++++ 3 files changed, 42 insertions(+)
arch/riscv/include/asm/asm-prototypes.h +1 -0
@@ -24,6 +24,7 @@ DECLARE_DO_ERROR_INFO(do_trap_ecall_u);DECLARE_DO_ERROR_INFO (do_trap_ecall_s);DECLARE_DO_ERROR_INFO (do_trap_ecall_m);DECLARE_DO_ERROR_INFO (do_trap_break); +DECLARE_DO_ERROR_INFO (do_trap_software_check); asmlinkage void handle_bad_stack(struct pt_regs *regs); asmlinkage void do_page_fault(struct pt_regs *regs);
arch/riscv/kernel/entry.S +3 -0
@@ -369,6 +369,9 @@ SYM_DATA_START_LOCAL(excp_vect_table) RISCV_PTR do_page_fault /* load page fault */ RISCV_PTR do_trap_unknown RISCV_PTR do_page_fault /* store page fault */ + RISCV_PTR do_trap_unknown /* cause=16 */ + RISCV_PTR do_trap_unknown /* cause=17 */ + RISCV_PTR do_trap_software_check /* cause=18 is sw check exception */ SYM_DATA_END_LABEL(excp_vect_table, SYM_L_LOCAL, excp_vect_table_end) #ifndef CONFIG_MMU
arch/riscv/kernel/traps.c +38 -0
@@ -339,6 +339,44 @@ asmlinkage __visible __trap_section void do_trap_ecall_u(struct pt_regs *regs) } +#define CFI_TVAL_FCFI_CODE 2 +#define CFI_TVAL_BCFI_CODE 3 +/* handle cfi violations */ +bool handle_user_cfi_violation (struct pt_regs *regs) +{ +bool ret = false; +unsigned long tval =csr_read (CSR_TVAL ); + +if (((tval ==CFI_TVAL_FCFI_CODE ) &&cpu_supports_indirect_br_lp_instr ()) || + ((tval ==CFI_TVAL_BCFI_CODE ) &&cpu_supports_shadow_stack ())) { +do_trap_error (regs,SIGSEGV ,SEGV_CPERR , regs->epc, +"Oops - control flow violation" ); + ret = true; + } + +return ret; +} +/* +* software check exception is defined with risc-v cfi spec. Software check +* exception is raised when:- +* a) An indirect branch doesn't land on 4 byte aligned PC or `lpad` +* instruction or `label` value programmed in `lpad` instr doesn't +* match with value setup in `x7`. reported code in `xtval` is 2. +* b) `sspopchk` instruction finds a mismatch between top of shadow stack (ssp) +* and x1/x5. reported code in `xtval` is 3. +*/ +asmlinkage __visible __trap_section void do_trap_software_check(struct pt_regs *regs) +{ +if (user_mode (regs)) { +/* not a cfi violation, then merge into flow of unknown trap handler */ +if (!handle_user_cfi_violation (regs)) +do_trap_unknown (regs); + }else { +/* sw check exception coming from kernel is a bug in kernel */ +die (regs,"Kernel BUG" ); + } +} +#ifdef CONFIG_MMU asmlinkage __visible noinstr void do_page_fault(struct pt_regs *regs) {
Signature · 1 line
2.43.0
RFC PATCH 22/28 riscv sigcontext: adding cfi state field in sigcontext
In reply to [email protected]From: Deepak Gupta <[email protected]>
Shadow stack needs to be saved and restored on signal delivery and signal return.
sigcontext embedded in ucontext is extendible. Adding cfi state in there which can be used to save cfi state before signal delivery and restore cfi state on sigreturn
--- arch/riscv/include/uapi/asm/sigcontext.h | 5 +++++ 1 file changed, 5 insertions(+)
arch/riscv/include/uapi/asm/sigcontext.h +5 -0
@@ -21,6 +21,10 @@ struct __sc_riscv_v_state {struct __riscv_v_ext_state v_state; } __attribute__((aligned(16))); +struct __sc_riscv_cfi_state { +unsigned long ss_ptr;/* shadow stack pointer */ +unsigned long rsvd;/* keeping another word reserved in case we need it */ +};/* * Signal context structure *
@@ -29,6 +33,7 @@ struct __sc_riscv_v_state {*/ struct sigcontext {struct user_regs_struct sc_regs; +struct __sc_riscv_cfi_state sc_cfi_state;union {union __riscv_fp_state sc_fpregs;struct __riscv_extra_ext_header sc_extdesc;
Signature · 1 line
2.43.0
RFC PATCH 23/28 riscv signal: Save and restore of shadow stack for signal
In reply to [email protected]From: Deepak Gupta <[email protected]>
Save shadow stack pointer in sigcontext structure while delivering signal. Restore shadow stack pointer from sigcontext on sigreturn.
--- arch/riscv/include/asm/usercfi.h | 18 ++++++++++++ arch/riscv/kernel/signal.c | 45 ++++++++++++++++++++++++++++++ arch/riscv/kernel/usercfi.c | 47 ++++++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+)
arch/riscv/include/asm/usercfi.h +18 -0
@@ -33,6 +33,9 @@ bool is_shstk_enabled(struct task_struct *task);bool is_shstk_locked (struct task_struct *task);bool is_indir_lp_enabled (struct task_struct *task);bool is_indir_lp_locked (struct task_struct *task); +unsigned long get_active_shstk (struct task_struct *task); +int restore_user_shstk (struct task_struct *tsk,unsigned long shstk_ptr); +int save_user_shstk (struct task_struct *tsk,unsigned long *saved_shstk_ptr);#define PR_SHADOW_STACK_SUPPORTED_STATUS_MASK (PR_SHADOW_STACK_ENABLE)
@@ -70,6 +73,16 @@ static inline bool is_shstk_locked(struct task_struct *task)return false; } +int restore_user_shstk (struct task_struct *tsk,unsigned long shstk_ptr) +{ +return -EINVAL ; +} + +int save_user_shstk (struct task_struct *tsk,unsigned long *saved_shstk_ptr) +{ +return -EINVAL ; +} +static inline bool is_indir_lp_enabled (struct task_struct *task) {return false;
@@ -81,6 +94,11 @@ static inline bool is_indir_lp_locked(struct task_struct *task)return false; } +static inline unsigned long get_active_shstk (struct task_struct *task) +{ +return 0 ; +} +#endif /* CONFIG_RISCV_USER_CFI */ #endif /* __ASSEMBLY__ */
arch/riscv/kernel/signal.c +45 -0
81 lines not on this page · raw message
arch/riscv/kernel/usercfi.c +47 -0
59 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 24/28 riscv: select config for shadow stack and landing pad instr support
In reply to [email protected]From: Deepak Gupta <[email protected]>
This patch selects config shadow stack support and landing pad instr support. Shadow stack support and landing instr support is hidden behind CONFIG_RISCV_USER_CFI. Selecting CONFIG_RISCV_USER_CFI wires up path to enumerate CPU support and if cpu support exists, kernel will support cpu assisted user mode cfi.
--- arch/riscv/Kconfig | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
arch/riscv/Kconfig +15 -0
@@ -163,6 +163,7 @@ config RISCV select SYSCTL_EXCEPTION_TRACE select THREAD_INFO_IN_TASK select TRACE_IRQFLAGS_SUPPORT + select RISCV_USER_CFI select UACCESS_MEMCPY if !MMU select ZONE_DMA32 if 64BIT
@@ -182,6 +183,20 @@ config HAVE_SHADOW_CALL_STACK # https://github.com/riscv-non-isa/riscv-elf-psabi-doc/commit/a484e843e6eeb51f0cb7b8819e50da6d2444d769 depends on $(ld-option,--no-relax-gp) +config RISCV_USER_CFI + bool "riscv userspace control flow integrity" + help + Provides CPU assisted control flow integrity to userspace tasks. + Control flow integrity is provided by implementing shadow stack for + backward edge and indirect branch tracking for forward edge in program. + Shadow stack protection is a hardware feature that detects function + return address corruption. This helps mitigate ROP attacks. + Indirect branch tracking enforces that all indirect branches must land + on a landing pad instruction else CPU will fault. This mitigates against + JOP / COP attacks. Applications must be enabled to use it, and old user- + space does not get protection "for free". + default y + config ARCH_MMAP_RND_BITS_MIN default 18 if 64BIT default 8
Signature · 1 line
2.43.0
RFC PATCH 25/28 riscv/ptrace: riscv cfi status and state via ptrace and in core files
In reply to [email protected]From: Deepak Gupta <[email protected]>
Expose a new register type NT_RISCV_USER_CFI for risc-v cfi status and state. Intentionally both landing pad and shadow stack status and state are rolled into cfi state. Creating two different NT_RISCV_USER_XXX would not be useful and wastage of a note type. Enabling or disabling of feature is not allowed via ptrace set interface. However setting elp state or setting shadow stack pointer are allowed via ptrace set interface. It is expected gdb might have use to fixup elp state or shadow stack pointer.
--- arch/riscv/include/uapi/asm/ptrace.h | 18 ++++++ arch/riscv/kernel/ptrace.c | 83 ++++++++++++++++++++++++++++ include/uapi/linux/elf.h | 1 + 3 files changed, 102 insertions(+)
arch/riscv/include/uapi/asm/ptrace.h +18 -0
@@ -127,6 +127,24 @@ struct __riscv_v_regset_state {*/ #define RISCV_MAX_VLENB (8192) +struct __cfi_status { +/* indirect branch tracking state */ +__u64 lp_en :1 ; +__u64 lp_lock :1 ; +__u64 elp_state :1 ; + +/* shadow stack status */ +__u64 shstk_en :1 ; +__u64 shstk_lock :1 ; + +__u64 rsvd :sizeof (__u64) -5 ; +}; + +struct user_cfi_state { +struct __cfi_status cfi_status; +__u64 shstk_ptr; +}; +#endif /* __ASSEMBLY__ */ #endif /* _UAPI_ASM_RISCV_PTRACE_H */
arch/riscv/kernel/ptrace.c +83 -0
107 lines not on this page · raw message
include/uapi/linux/elf.h +1 -0
@@ -447,6 +447,7 @@ typedef struct elf64_shdr {#define NT_MIPS_MSA 0x802/* MIPS SIMD registers */ #define NT_RISCV_CSR 0x900/* RISC-V Control and Status Registers */ #define NT_RISCV_VECTOR 0x901/* RISC-V vector registers */ +#define NT_RISCV_USER_CFI 0x902/* RISC-V shadow stack state */ #define NT_LOONGARCH_CPUCFG 0xa00/* LoongArch CPU config registers */ #define NT_LOONGARCH_CSR 0xa01/* LoongArch control and status registers */ #define NT_LOONGARCH_LSX 0xa02/* LoongArch Loongson SIMD Extension registers */
Signature · 1 line
2.43.0
RFC PATCH 26/28 riscv: Documentation for landing pad / indirect branch tracking
In reply to [email protected]From: Deepak Gupta <[email protected]>
Adding documentation on landing pad aka indirect branch tracking on riscv and kernel interfaces exposed so that user tasks can enable it.
--- Documentation/arch/riscv/zicfilp.rst | 104 +++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 Documentation/arch/riscv/zicfilp.rst
Documentation/arch/riscv/zicfilp.rst new file +104 -0
@@ -0,0 +1,104 @@ +.. SPDX-License-Identifier: GPL-2.0 + +:Author: Deepak Gupta <[email protected]> +:Date: 12 January 2024 + +==================================================== +Tracking indirect control transfers on RISC-V Linux +==================================================== + +This document briefly describes the interface provided to userspace by Linux +to enable indirect branch tracking for user mode applications on RISV-V + +1. Feature Overview +-------------------- + +Memory corruption issues usually result in to crashes, however when in hands of +an adversary and if used creatively can result into variety security issues. + +One of those security issues can be code re-use attacks on program where adversary +can use corrupt function pointers and chain them together to perform jump oriented +programming (JOP) or call oriented programming (COP) and thus compromising control +flow integrity (CFI) of the program. + +Function pointers live in read-write memory and thus are susceptible to corruption +and allows an adversary to reach any program counter (PC) in address space. On +RISC-V zicfilp extension enforces a restriction on such indirect control transfers + + - indirect control transfers must land on a landing pad instruction `lpad`. + There are two exception to this rule + - rs1 = x1 or rs1 = x5, i.e. a return from a function and returns are + protected using shadow stack (see zicfiss.rst) + + - rs1 = x7. On RISC-V compiler usually does below to reach function + which is beyond the offset possible J-type instruction. + + "auipc x7, <imm>" + "jalr (x7)" + + Such form of indirect control transfer are still immutable and don't rely + on memory and thus rs1=x7 is exempted from tracking and considered software + guarded jumps. + +`lpad` instruction is pseudo of `auipc rd, <imm_20bit>` and is a HINT nop. `lpad` +instruction must be aligned on 4 byte boundary and compares 20 bit immediate with x7. +If `imm_20bit` == 0, CPU don't perform any comparision with x7. If `imm_20bit` != 0, +then `imm_20bit` must match x7 else CPU will raise `software check exception` +(cause=18)with `*tval = 2`. + +Compiler can generate a hash over function signatures and setup them (truncated +to 20bit) in x7 at callsites and function proglogs can have `lpad` with same +function hash. This further reduces number of program counters a call site can +reach. + +2. ELF and psABI +----------------- + +Toolchain sets up `GNU_PROPERTY_RISCV_FEATURE_1_FCFI` for property +`GNU_PROPERTY_RISCV_FEATURE_1_AND` in notes section of the object file. + +3. Linux enabling +------------------ + +User space programs can have multiple shared objects loaded in its address space +and it's a difficult task to make sure all the dependencies have been compiled +with support of indirect branch. Thus it's left to dynamic loader to enable +indirect branch tracking for the program. + +4. prctl() enabling +-------------------- + +`PR_SET_INDIR_BR_LP_STATUS` / `PR_GET_INDIR_BR_LP_STATUS` / +`PR_LOCK_INDIR_BR_LP_STATUS` are three prctls added to manage indirect branch +tracking. prctls are arch agnostic and returns -EINVAL on other arches. + +`PR_SET_INDIR_BR_LP_STATUS`: If arg1 `PR_INDIR_BR_LP_ENABLE` and if CPU supports +`zicfilp` then kernel will enabled indirect branch tracking for the task. +Dynamic loader can issue this `prctl` once it has determined that all the objects +loaded in address space support indirect branch tracking. Additionally if there is +a `dlopen` to an object which wasn't compiled with `zicfilp`, dynamic loader can +issue this prctl with arg1 set to 0 (i.e. `PR_INDIR_BR_LP_ENABLE` being clear) + +`PR_GET_INDIR_BR_LP_STATUS`: Returns current status of indirect branch tracking. +If enabled it'll return `PR_INDIR_BR_LP_ENABLE` + +`PR_LOCK_INDIR_BR_LP_STATUS`: Locks current status of indirect branch tracking on +the task. User space may want to run with strict security posture and wouldn't want +loading of objects without `zicfilp` support in it and thus would want to disallow +disabling of indirect branch tracking. In that case user space can use this prctl +to lock current settings. + +5. violations related to indirect branch tracking +-------------------------------------------------- + +Pertaining to indirect branch tracking, CPU raises software check exception in +following conditions + - missing `lpad` after indirect call / jmp + - `lpad` not on 4 byte boundary + - `imm_20bit` embedded in `lpad` instruction doesn't match with `x7` + +In all 3 cases, `*tval = 2` is captured and software check exception is raised +(cause=18) + +Linux kernel will treat this as `SIGSEV`` with code = `SEGV_CPERR` and follow +normal course of signal delivery.
Signature · 1 line
2.43.0
RFC PATCH 27/28 riscv: Documentation for shadow stack on riscv
In reply to [email protected]From: Deepak Gupta <[email protected]>
Adding documentation on shadow stack for user mode on riscv and kernel interfaces exposed so that user tasks can enable it.
--- Documentation/arch/riscv/zicfiss.rst | 169 +++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 Documentation/arch/riscv/zicfiss.rst
Documentation/arch/riscv/zicfiss.rst new file +169 -0
@@ -0,0 +1,169 @@ +.. SPDX-License-Identifier: GPL-2.0 + +:Author: Deepak Gupta <[email protected]> +:Date: 12 January 2024 + +========================================================= +Shadow stack to protect function returns on RISC-V Linux +========================================================= + +This document briefly describes the interface provided to userspace by Linux +to enable shadow stack for user mode applications on RISV-V + +1. Feature Overview +-------------------- + +Memory corruption issues usually result in to crashes, however when in hands of +an adversary and if used creatively can result into variety security issues. + +One of those security issues can be code re-use attacks on program where adversary +can use corrupt return addresses present on stack and chain them together to perform +return oriented programming (ROP) and thus compromising control flow integrity (CFI) +of the program. + +Return addresses live on stack and thus in read-write memory and thus are +susceptible to corruption and allows an adversary to reach any program counter +(PC) in address space. On RISC-V `zicfiss` extension provides an alternate stack +`shadow stack` on which return addresses can be safely placed in prolog of the +function and retrieved in epilog. `zicfiss` extension makes following changes + + - PTE encodings for shadow stack virtual memory + An earlier reserved encoding in first stage translation i.e. + PTE.R=0, PTE.W=1, PTE.X=0 becomes PTE encoding for shadow stack pages. + + - `sspush x1/x5` instruction pushes (stores) `x1/x5` to shadow stack. + + - `sspopchk x1/x5` instruction pops (loads) from shadow stack and compares + with `x1/x5` and if un-equal, CPU raises `software check exception` with + `*tval = 3` + +Compiler toolchain makes sure that function prologs have `sspush x1/x5` to save return +address on shadow stack in addition to regular stack. Similarly function epilogs have +`ld x5, offset(x2)`; `sspopchk x5` to ensure that popped value from regular stack +matches with popped value from shadow stack. + +2. Shadow stack protections and linux memory manager +----------------------------------------------------- + +As mentioned earlier, shadow stack get new page table encodings and thus have some +special properties assigned to them and instructions that operate on them as below + + - Regular stores to shadow stack memory raises access store faults. + This way shadow stack memory is protected from stray inadvertant + writes + + - Regular loads to shadow stack memory are allowed. + This allows stack trace utilities or backtrace functions to read + true callstack (not tampered) + + - Only shadow stack instructions can generate shadow stack load or + shadow stack store. + + - Shadow stack load / shadow stack store on read-only memory raises + AMO/store page fault. Thus both `sspush x1/x5` and `sspopchk x1/x5` + will raise AMO/store page fault. This simplies COW handling in kernel + During fork, kernel can convert shadow stack pages into read-only + memory (as it does for regular read-write memory) and as soon as + subsequent `sspush` or `sspopchk` in userspace is encountered, then + kernel can perform COW. + + - Shadow stack load / shadow stack store on read-write, read-write- + execute memory raises an access fault. This is a fatal condition + because shadow stack should never be operating on read-write, read- + write-execute memory. + +3. ELF and psABI +----------------- + +Toolchain sets up `GNU_PROPERTY_RISCV_FEATURE_1_BCFI` for property +`GNU_PROPERTY_RISCV_FEATURE_1_AND` in notes section of the object file. + +4. Linux enabling +------------------ + +User space programs can have multiple shared objects loaded in its address space +and it's a difficult task to make sure all the dependencies have been compiled +with support of shadow stack. Thus it's left to dynamic loader to enable +shadow stack for the program. + +5. prctl() enabling +-------------------- + +`PR_SET_SHADOW_STACK_STATUS` / `PR_GET_SHADOW_STACK_STATUS` / +`PR_LOCK_SHADOW_STACK_STATUS` are three prctls added to manage shadow stack +enabling for tasks. prctls are arch agnostic and returns -EINVAL on other arches. + +`PR_SET_SHADOW_STACK_STATUS`: If arg1 `PR_SHADOW_STACK_ENABLE` and if CPU supports +`zicfiss` then kernel will enable shadow stack for the task. Dynamic loader can +issue this `prctl` once it has determined that all the objects loaded in address +space have support for shadow stack. Additionally if there is a `dlopen` to an +object which wasn't compiled with `zicfiss`, dynamic loader can issue this prctl +with arg1 set to 0 (i.e. `PR_SHADOW_STACK_ENABLE` being clear) + +`PR_GET_SHADOW_STACK_STATUS`: Returns current status of indirect branch tracking. +If enabled it'll return `PR_SHADOW_STACK_ENABLE` + +`PR_LOCK_SHADOW_STACK_STATUS`: Locks current status of shadow stack enabling on the +task. User space may want to run with strict security posture and wouldn't want +loading of objects without `zicfiss` support in it and thus would want to disallow +disabling of shadow stack on current task. In that case user space can use this prctl +to lock current settings. + +5. violations related to returns with shadow stack enabled +----------------------------------------------------------- + +Pertaining to shadow stack, CPU raises software check exception in following +condition + + - On execution of `sspopchk x1/x5`, x1/x5 didn't match top of shadow stack. + If mismatch happens then cpu does `*tval = 3` and raise software check + exception + +Linux kernel will treat this as `SIGSEV`` with code = `SEGV_CPERR` and follow +normal course of signal delivery. + +6. Shadow stack tokens +----------------------- +Regular stores on shadow stacks are not allowed and thus can't be tampered with via +arbitrary stray writes due to bugs. Method of pivoting / switching to shadow stack +is simply writing to csr `CSR_SSP` changes active shadow stack. This can be problematic +because usually value to be written to `CSR_SSP` will be loaded somewhere in writeable +memory and thus allows an adversary to corruption bug in software to pivot to an any +address in shadow stack range. Shadow stack tokens can help mitigate this problem by +making sure that: + + - When software is switching away from a shadow stack, shadow stack pointer should be + saved on shadow stack itself and call it `shadow stack token` + + - When software is switching to a shadow stack, it should read the `shadow stack token` + from shadow stack pointer and verify that `shadow stack token` itself is pointer to + shadow stack itself. + + - Once the token verification is done, software can perform the write to `CSR_SSP` to + switch shadow stack. + +Here software can be user mode task runtime itself which is managing various contexts +as part of single thread. Software can be kernel as well when kernel has to deliver a +signal to user task and must save shadow stack pointer. Kernel can perform similar +procedure by saving a token on user shadow stack itself. This way whenever sigreturn +happens, kernel can read the token and verify the token and then switch to shadow stack. +Using this mechanism, kernel helps user task so that any corruption issue in user task +is not exploited by adversary by arbitrarily using `sigreturn`. Adversary will have to +make sure that there is a `shadow stack token` in addition to invoking `sigreturn` + +7. Signal shadow stack +----------------------- +Following structure has been added to sigcontext for RISC-V. `rsvd` field has been kept +in case we need some extra information in future for landing pads / indirect branch +tracking. It has been kept today in order to allow backward compatibility in future. + +struct __sc_riscv_cfi_state { + unsigned long ss_ptr; + unsigned long rsvd; +}; + +As part of signal delivery, shadow stack token is saved on current shadow stack itself and +updated pointer is saved away in `ss_ptr` field in `__sc_riscv_cfi_state` under `sigcontext` +Existing shadow stack allocation is used for signal delivery. During `sigreturn`, kernel will +obtain `ss_ptr` from `sigcontext` and verify the saved token on shadow stack itself and switch +shadow stack.
Signature · 1 line
2.43.0
RFC PATCH 28/28 kselftest/riscv: kselftest for user mode cfi
In reply to [email protected]From: Deepak Gupta <[email protected]>
Adds kselftest for RISC-V control flow integrity implementation for user mode. There is not a lot going on in kernel for enabling landing pad for user mode. Thus kselftest simply enables landing pad for the binary and a signal handler is registered for SIGSEGV. Any control flow violation are reported as SIGSEGV with si_code = SEGV_CPERR. Test will fail on recieving any SEGV_CPERR. Shadow stack part has more changes in kernel and thus there are separate tests for that
- enable and disable
- Exercise map_shadow_stack syscall
- fork test to make sure COW works for shadow stack pages
- gup tests
As of today kernel uses FOLL_FORCE when access happens to memory via /proc/<pid>/mem. Not breaking that for shadow stack
- signal test. Make sure signal delivery results in token creation on
shadow stack and consumes (and verifies) token on sigreturn
- shadow stack protection test. attempts to write using regular store instruction on shadow stack memory must result in access faults
--- tools/testing/selftests/riscv/Makefile | 2 +- tools/testing/selftests/riscv/cfi/Makefile | 10 + .../testing/selftests/riscv/cfi/cfi_rv_test.h | 85 ++++ .../selftests/riscv/cfi/riscv_cfi_test.c | 91 +++++ .../testing/selftests/riscv/cfi/shadowstack.c | 376 ++++++++++++++++++ .../testing/selftests/riscv/cfi/shadowstack.h | 39 ++ 6 files changed, 602 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/riscv/cfi/Makefile create mode 100644 tools/testing/selftests/riscv/cfi/cfi_rv_test.h create mode 100644 tools/testing/selftests/riscv/cfi/riscv_cfi_test.c create mode 100644 tools/testing/selftests/riscv/cfi/shadowstack.c create mode 100644 tools/testing/selftests/riscv/cfi/shadowstack.h
tools/testing/selftests/riscv/Makefile +1 -1
@@ -5,7 +5,7 @@ ARCH ?= $(shell uname -m 2>/dev/null || echo not) ifneq (,$(filter $(ARCH),riscv)) -RISCV_SUBTARGETS ?= hwprobe vector mm +RISCV_SUBTARGETS ?= hwprobe vector mm cfi else RISCV_SUBTARGETS := endif
tools/testing/selftests/riscv/cfi/Makefile new file +10 -0
@@ -0,0 +1,10 @@ +CFLAGS += -I$(top_srcdir)/tools/include + +CFLAGS += -march=rv64gc_zicfilp_zicfiss + +TEST_GEN_PROGS := cfitests + +include ../../lib.mk + +$(OUTPUT)/cfitests: riscv_cfi_test.c shadowstack.c + $(CC) -static -o$@ $(CFLAGS) $(LDFLAGS) $^
tools/testing/selftests/riscv/cfi/cfi_rv_test.h new file +85 -0
85 lines not on this page · raw message
tools/testing/selftests/riscv/cfi/riscv_cfi_test.c new file +91 -0
91 lines not on this page · raw message
tools/testing/selftests/riscv/cfi/shadowstack.c new file +376 -0
376 lines not on this page · raw message
tools/testing/selftests/riscv/cfi/shadowstack.h new file +39 -0
@@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#ifndef SELFTEST_SHADOWSTACK_TEST_H +#define SELFTEST_SHADOWSTACK_TEST_H +#include <stddef.h> +#include <linux/prctl.h> + +/* +* a cfi test returns true for success or false for fail +* takes a number for test number to index into array and void pointer. +*/ +typedef bool (*shstk_test_func )(unsigned long test_num,void *); + +struct shadow_stack_tests { +char *name; +shstk_test_func t_func; +}; + +bool enable_disable_check (unsigned long test_num,void *ctx); +bool shadow_stack_fork_test (unsigned long test_num,void *ctx); +bool shadow_stack_map_test (unsigned long test_num,void *ctx); +bool shadow_stack_protection_test (unsigned long test_num,void *ctx); +bool shadow_stack_gup_tests (unsigned long test_num,void *ctx); +bool shadow_stack_signal_test (unsigned long test_num,void *ctx); + +static struct shadow_stack_tests shstk_tests[] = { + {"enable disable\n" , enable_disable_check }, + {"shstk fork test\n" , shadow_stack_fork_test }, + {"map shadow stack syscall\n" , shadow_stack_map_test }, + {"shadow stack gup tests\n" , shadow_stack_gup_tests }, + {"shadow stack signal tests\n" , shadow_stack_signal_test}, + {"memory protections of shadow stack memory\n" , shadow_stack_protection_test } +}; + +#define RISCV_SHADOW_STACK_TESTS ARRAY_SIZE(shstk_tests) + +int execute_shadow_stack_tests (void ); + +#endif
Signature · 1 line
2.43.0
Re: [RFC PATCH v1 02/28] riscv: envcfg save and restore on trap entry/exit
In reply to [email protected]Quoted 10 lines · On Thu, Jan 25, 2024, at 1:21 AM, [email protected] wrote:
From: Deepak Gupta <[email protected]>
envcfg CSR defines enabling bits for cache management instructions and soon will control enabling for control flow integrity and pointer masking features.
Control flow integrity enabling for forward cfi and backward cfi is controlled via envcfg and thus need to be enabled on per thread basis.
This patch creates a place holder for envcfg CSR in
thread_infoand adds logic to save and restore on trap entry and exits.
Should only be "restore"? I don't see saving.
Quoted 39 lines
Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/asm-offsets.c | 1 + arch/riscv/kernel/entry.S | 4 ++++ 3 files changed, 6 insertions(+)arch/riscv/include/asm/thread_info.h +1
-0@@ -57,6 +57,7 @@ struct thread_info {long user_sp;/* User stack pointer */ int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ +unsigned long envcfg;#ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;arch/riscv/kernel/asm-offsets.c +1
-0@@ -39,6 +39,7 @@ void asm_offsets(void)OFFSET (TASK_TI_PREEMPT_COUNT , task_struct, thread_info.preempt_count);OFFSET (TASK_TI_KERNEL_SP , task_struct, thread_info.kernel_sp);OFFSET (TASK_TI_USER_SP , task_struct, thread_info.user_sp); +OFFSET (TASK_TI_ENVCFG , task_struct, thread_info.envcfg);#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif arch/riscv/kernel/entry.S +0
-0
arch/riscv/kernel/entry.S SYM_CODE_START_NOALIGN(ret_from_exception) · line 135
Quoted 7 lines
arch/riscv/kernel/entry.S +4
-0@@ -129,6 +129,10 @@ SYM_CODE_START_NOALIGN(ret_from_exception) addi s0, sp, PT_SIZE_ON_STACK REG_S s0, TASK_TI_KERNEL_SP(tp) + /* restore envcfg bits for current thread */ + REG_L s0, TASK_TI_ENVCFG(tp) + csrw CSR_ENVCFG, s0 +
This is redundant if we're repeatedly processing interrupts or exceptions within a single task. We should only be writing envcfg when switching between tasks or as part of the prctl.
We need to use an ALTERNATIVE for this since the oldest supported hardware does not have envcfg csrs.
-s
Quoted 11 lines
arch/riscv/kernel/entry.S +0
-0/* Save the kernel shadow call stack pointer */ scs_save_currentSignature · 7 lines
2.43.0 _______________________________________________ linux-riscv mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 07/28] riscv: kernel handling on trap entry/exit for user cfi
In reply to [email protected]Quoted 130 lines · On Thu, Jan 25, 2024, at 1:21 AM, [email protected] wrote:
From: Deepak Gupta <[email protected]>
Carves out space in arch specific thread struct for cfi status and shadow stack in usermode on riscv.
This patch does following
- defines a new structurecfi_statuswith status bit for cfi feature
- defines shadow stack pointer, base and size incfi_statusstructure
- defines offsets to new member fields in thread inasm-offsets.c
- Saves and restore shadow stack pointer on trap entry (U --> S) and exit (S --> U)Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/processor.h | 1 + arch/riscv/include/asm/thread_info.h | 3 +++ arch/riscv/include/asm/usercfi.h | 24 ++++++++++++++++++++++++ arch/riscv/kernel/asm-offsets.c | 5 ++++- arch/riscv/kernel/entry.S | 25 +++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 arch/riscv/include/asm/usercfi.harch/riscv/include/asm/processor.h +1
-0@@ -14,6 +14,7 @@#include <asm/ptrace.h> #include <asm/hwcap.h> +#include <asm/usercfi.h> #ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))arch/riscv/include/asm/thread_info.h +3
-0@@ -58,6 +58,9 @@ struct thread_info {int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ unsigned long envcfg; +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status user_cfi_state; +#endif #ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;arch/riscv/include/asm/usercfi.h new file +24
-0@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 +* Copyright (C) 2023 Rivos, Inc. +* Deepak Gupta <[email protected]> +*/ +#ifndef _ASM_RISCV_USERCFI_H +#define _ASM_RISCV_USERCFI_H + +#ifndef __ASSEMBLY__ +#include <linux/types.h> + +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status { +unsigned long ubcfi_en :1 ;/* Enable for backward cfi. */ +unsigned long rsvd : ((sizeof (unsigned long )*8 ) -1 ); +unsigned long user_shdw_stk;/* Current user shadow stack pointer */ +unsigned long shdw_stk_base;/* Base address of shadow stack */ +unsigned long shdw_stk_size;/* size of shadow stack */ +}; + +#endif /* CONFIG_RISCV_USER_CFI */ + +#endif /* __ASSEMBLY__ */ + +#endif /* _ASM_RISCV_USERCFI_H */ arch/riscv/kernel/asm-offsets.c +4
-1@@ -43,8 +43,11 @@ void asm_offsets(void)#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif -OFFSET (TASK_TI_CPU_NUM , task_struct, thread_info.cpu); +#ifdef CONFIG_RISCV_USER_CFI +OFFSET (TASK_TI_CFI_STATUS , task_struct, thread_info.user_cfi_state); +OFFSET (TASK_TI_USER_SSP , task_struct, thread_info.user_cfi_state.user_shdw_stk); +#endif OFFSET (TASK_THREAD_F0 , task_struct, thread.fstate.f[0 ]);OFFSET (TASK_THREAD_F1 , task_struct, thread.fstate.f[1 ]);arch/riscv/kernel/asm-offsets.c +0
-0OFFSET (TASK_THREAD_F2 , task_struct, thread.fstate.f[2 ]);arch/riscv/kernel/entry.S +15
-0@@ -49,6 +49,21 @@ SYM_CODE_START(handle_exception) REG_S x5, PT_T0(sp) save_from_x6_to_x31 +#ifdef CONFIG_RISCV_USER_CFI + /* + * we need to save cfi status only when previous mode was U + */ + csrr s2, CSR_STATUS + andi s2, s2, SR_SPP + bnez s2, skip_bcfi_save + /* load cfi status word */ + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_save + csrr s3, CSR_SSP + REG_S s3, TASK_TI_USER_SSP(tp) /* save user ssp in thread_info */ +skip_bcfi_save: +#endif /* * Disable user-mode memory access as it should only be set in the * actual user copy routines.@@ -141,6 +156,16 @@ SYM_CODE_START_NOALIGN(ret_from_exception) * structures again. */ csrw CSR_SCRATCH, tp
arch/riscv/kernel/entry.S SYM_CODE_START_NOALIGN(ret_from_exception) · line 168
Quoted 10 lines
arch/riscv/kernel/entry.S +10
-0+ +#ifdef CONFIG_RISCV_USER_CFI + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_resume + REG_L s3, TASK_TI_USER_SSP(tp) /* restore user ssp from thread struct */ + csrw CSR_SSP, s3 +skip_bcfi_resume: +#endif +
We shouldn't need any of this in the entry/exit code, at least as long as the kernel itself is not using Zicfiss. ssp can keep its value in the kernel and swap it on task switches. Our entry/exit code is rather short and I'd like to keep it that way.
-s
Quoted 11 lines
arch/riscv/kernel/entry.S +0
-01: REG_L a0, PT_STATUS(sp) /*Signature · 7 lines
2.43.0 _______________________________________________ linux-riscv mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 08/28] mm: Define VM_SHADOW_STACK for RISC-V
In reply to [email protected]Quoted 34 lines · On 25.01.24 07:21, [email protected] wrote:
From: Deepak Gupta <[email protected]>
VM_SHADOW_STACKis defined by x86 as vm flag to mark a shadow stack vma.x86 uses
VM_HIGH_ARCH_5bit but that limits shadow stack vma to 64bit only. arm64 follows same path
https://lore.kernel.org/lkml/[email protected]/#rOn RISC-V, write-only page table encodings are shadow stack pages. This patch re-defines
VM_WRITEonly to beVM_SHADOW_STACK.Next set of patches will set guard rail that no other mm flow can set
VM_WRITEonly in vma except when specifically creating shadow stack.Signed-off-by Deepak Gupta <[email protected]>--- include/linux/mm.h | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)include/linux/mm.h +6
-1@@ -352,7 +352,19 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 -#else +#endif + +#ifdef CONFIG_RISCV_USER_CFI +/* +* On RISC-V pte encodings for shadow stack is R=0, W=1, X=0 and thus RISCV +* choosing to use similar mechanism on vm_flags where VM_WRITE only means
include/linux/mm.h extern unsigned int kobjsize(const void *objp); · line 370
Quoted 10 lines
include/linux/mm.h +7
-0+* VM_SHADOW_STACK. RISCV as well doesn't support VM_SHADOW_STACK to be set +* with VM_SHARED. +*/ +#define VM_SHADOW_STACK VM_WRITE +#endif + +#ifndef VM_SHADOW_STACK # define VM_SHADOW_STACK VM_NONE#endif
That just screams for trouble. Can we find a less hacky way, please?
Maybe just start with 64bit support only and do it like the other archs. No need to be special.
When wanting to support 32bit, we'll just finally clean up this high flag mess and allow for more vm flags on 32bit as well.
Signature · 3 lines
Cheers, David / dhildenb
Re: [RFC PATCH v1 09/28] mm: abstract shadow stack vma behind `arch_is_shadow_stack`
In reply to [email protected]Quoted 37 lines · On 25.01.24 07:21, [email protected] wrote:
From: Deepak Gupta <[email protected]>
x86 has used
VM_SHADOW_STACK(alias toVM_HIGH_ARCH_5) to encode shadow stack VMA.VM_SHADOW_STACKis thus not possible on 32bit. Some arches may need a way to encode shadow stack on 32bit and 64bit both and they may encode this information differently in VMAs.This patch changes checks of
VM_SHADOW_STACKflag in generic code to call to a functionarch_is_shadow_stackwhich will return true if arch supports shadow stack and vma is shadow stack else stub returns false.There was a suggestion to name it as
vma_is_shadow_stack. I preferred to keeparchprefix in there because it's each arch specific.Signed-off-by Deepak Gupta <[email protected]>--- include/linux/mm.h | 18 +++++++++++++++++- mm/gup.c | 5 +++-- mm/internal.h | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-)include/linux/mm.h +4
-0@@ -352,6 +352,10 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return (vm_flags &VM_SHADOW_STACK ); +}#endif #ifdef CONFIG_RISCV_USER_CFI
include/linux/mm.h extern unsigned int kobjsize(const void *objp); · line 374
Quoted 9 lines
include/linux/mm.h +6
-0@@ -362,10 +366,22 @@ extern unsigned int kobjsize(const void *objp);* with VM_SHARED. */ #define VM_SHADOW_STACK VM_WRITE + +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return ((vm_flags & (VM_WRITE |VM_READ |VM_EXEC )) ==VM_WRITE ); +} +
Please no such hacks just to work around the 32bit vmflags limitation.
Signature · 3 lines
Cheers, David / dhildenb
Re: [RFC PATCH v1 08/28] mm: Define VM_SHADOW_STACK for RISC-V
In reply to David HildenbrandQuoted 47 lines · David Hildenbrand
Quoted 33 lines · On 25.01.24 07:21, [email protected] wrote:
From: Deepak Gupta <[email protected]>
VM_SHADOW_STACKis defined by x86 as vm flag to mark a shadow stack vma.x86 uses
VM_HIGH_ARCH_5bit but that limits shadow stack vma to 64bit only. arm64 follows same path
https://lore.kernel.org/lkml/[email protected]/#rOn RISC-V, write-only page table encodings are shadow stack pages. This patch re-defines
VM_WRITEonly to beVM_SHADOW_STACK.Next set of patches will set guard rail that no other mm flow can set
VM_WRITEonly in vma except when specifically creating shadow stack.Signed-off-by Deepak Gupta <[email protected]>--- include/linux/mm.h | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)include/linux/mm.h +5
-1@@ -352,7 +352,19 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 -#else +#endif + +#ifdef CONFIG_RISCV_USER_CFI +/* +* On RISC-V pte encodings for shadow stack is R=0, W=1, X=0 and thus RISCV include/linux/mm.h extern unsigned int kobjsize(const void *objp); · line 369
Quoted 10 lines
include/linux/mm.h +8
-0+* choosing to use similar mechanism on vm_flags where VM_WRITE only means +* VM_SHADOW_STACK. RISCV as well doesn't support VM_SHADOW_STACK to be set +* with VM_SHARED. +*/ +#define VM_SHADOW_STACK VM_WRITE +#endif + +#ifndef VM_SHADOW_STACK # define VM_SHADOW_STACK VM_NONE#endif That just screams for trouble. Can we find a less hacky way, please?
Quoted 3 lines
Maybe just start with 64bit support only and do it like the other archs. No need to be special.
When wanting to support 32bit, we'll just finally clean up this high flag mess and allow for more vm flags on 32bit as well.
Noted. I wanted to give a chance to anyone who cares about 32bit on riscv. Will fix it in next series.
Quoted 6 lines
Signature · 4 lines
-- Cheers, David / dhildenb
Re: [RFC PATCH v1 09/28] mm: abstract shadow stack vma behind `arch_is_shadow_stack`
In reply to David HildenbrandQuoted 40 lines · David Hildenbrand
Quoted 39 lines · On 25.01.24 07:21, [email protected] wrote:
From: Deepak Gupta <[email protected]>
x86 has used
VM_SHADOW_STACK(alias toVM_HIGH_ARCH_5) to encode shadow stack VMA.VM_SHADOW_STACKis thus not possible on 32bit. Some arches may need a way to encode shadow stack on 32bit and 64bit both and they may encode this information differently in VMAs.This patch changes checks of
VM_SHADOW_STACKflag in generic code to call to a functionarch_is_shadow_stackwhich will return true if arch supports shadow stack and vma is shadow stack else stub returns false.There was a suggestion to name it as
vma_is_shadow_stack. I preferred to keeparchprefix in there because it's each arch specific.Signed-off-by Deepak Gupta <[email protected]>--- include/linux/mm.h | 18 +++++++++++++++++- mm/gup.c | 5 +++-- mm/internal.h | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-)include/linux/mm.h +4
-0@@ -352,6 +352,10 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return (vm_flags &VM_SHADOW_STACK ); +}#endif #ifdef CONFIG_RISCV_USER_CFI @@ -362,10 +366,22 @@ extern unsigned int kobjsize(const void *objp);* with VM_SHARED. */ #define VM_SHADOW_STACK VM_WRITE
Quoted 8 lines
include/linux/mm.h extern unsigned int kobjsize(const void *objp); · line 374
Quoted 6 lines
include/linux/mm.h +6
-0+ +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return ((vm_flags & (VM_WRITE |VM_READ |VM_EXEC )) ==VM_WRITE ); +} +Please no such hacks just to work around the 32bit vmflags limitation.
As I said in another response. Noted.
And if there're no takers for 32bit on riscv (which highly likely is the case) This will go away in next version of patchsets.
Quoted 6 lines
Signature · 4 lines
-- Cheers, David / dhildenb
Re: [RFC PATCH v1 02/28] riscv: envcfg save and restore on trap entry/exit
In reply to Stefan O'RearQuoted 6 lines · Stefan O'Rear
Quoted 5 lines · On Thu, Jan 25, 2024, at 1:21 AM, [email protected] wrote:
From: Deepak Gupta <[email protected]>
envcfg CSR defines enabling bits for cache management instructions and soon will control enabling for control flow integrity and pointer masking features.
Quoted 7 lines
Quoted 5 lines
Control flow integrity enabling for forward cfi and backward cfi is controlled via envcfg and thus need to be enabled on per thread basis.
This patch creates a place holder for envcfg CSR in
thread_infoand adds logic to save and restore on trap entry and exits.Should only be "restore"? I don't see saving.
It's always saved in thread_info and user mode can't change it. So no point saving it.
Quoted 52 lines
Quoted 40 lines
Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/asm-offsets.c | 1 + arch/riscv/kernel/entry.S | 4 ++++ 3 files changed, 6 insertions(+)arch/riscv/include/asm/thread_info.h +1
-0@@ -57,6 +57,7 @@ struct thread_info {long user_sp;/* User stack pointer */ int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ +unsigned long envcfg;#ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;arch/riscv/kernel/asm-offsets.c +1
-0@@ -39,6 +39,7 @@ void asm_offsets(void)OFFSET (TASK_TI_PREEMPT_COUNT , task_struct, thread_info.preempt_count);OFFSET (TASK_TI_KERNEL_SP , task_struct, thread_info.kernel_sp);OFFSET (TASK_TI_USER_SP , task_struct, thread_info.user_sp); +OFFSET (TASK_TI_ENVCFG , task_struct, thread_info.envcfg);#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif arch/riscv/kernel/entry.S +0
-0arch/riscv/kernel/entry.S SYM_CODE_START_NOALIGN(ret_from_exception) · line 135
Quoted 7 lines
arch/riscv/kernel/entry.S +4
-0@@ -129,6 +129,10 @@ SYM_CODE_START_NOALIGN(ret_from_exception) addi s0, sp, PT_SIZE_ON_STACK REG_S s0, TASK_TI_KERNEL_SP(tp) + /* restore envcfg bits for current thread */ + REG_L s0, TASK_TI_ENVCFG(tp) + csrw CSR_ENVCFG, s0 +This is redundant if we're repeatedly processing interrupts or exceptions within a single task. We should only be writing envcfg when switching between tasks or as part of the prctl.
Quoted 2 lines
We need to use an ALTERNATIVE for this since the oldest supported hardware does not have envcfg csrs.
Yeah fixing that in next series. Thanks
Quoted 14 lines
-s
Quoted 11 lines
arch/riscv/kernel/entry.S +0
-1/* Save the kernel shadow call stack pointer */ scs_save_current --2.43.0
_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 07/28] riscv: kernel handling on trap entry/exit for user cfi
In reply to Stefan O'RearQuoted 138 lines · Stefan O'Rear
Quoted 137 lines · On Thu, Jan 25, 2024, at 1:21 AM, [email protected] wrote:
From: Deepak Gupta <[email protected]>
Carves out space in arch specific thread struct for cfi status and shadow stack in usermode on riscv.
This patch does following
- defines a new structurecfi_statuswith status bit for cfi feature
- defines shadow stack pointer, base and size incfi_statusstructure
- defines offsets to new member fields in thread inasm-offsets.c
- Saves and restore shadow stack pointer on trap entry (U --> S) and exit (S --> U)Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/processor.h | 1 + arch/riscv/include/asm/thread_info.h | 3 +++ arch/riscv/include/asm/usercfi.h | 24 ++++++++++++++++++++++++ arch/riscv/kernel/asm-offsets.c | 5 ++++- arch/riscv/kernel/entry.S | 25 +++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 arch/riscv/include/asm/usercfi.harch/riscv/include/asm/processor.h +1
-0@@ -14,6 +14,7 @@#include <asm/ptrace.h> #include <asm/hwcap.h> +#include <asm/usercfi.h> #ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))arch/riscv/include/asm/thread_info.h +3
-0@@ -58,6 +58,9 @@ struct thread_info {int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ unsigned long envcfg; +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status user_cfi_state; +#endif #ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;arch/riscv/include/asm/usercfi.h new file +24
-0@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 +* Copyright (C) 2023 Rivos, Inc. +* Deepak Gupta <[email protected]> +*/ +#ifndef _ASM_RISCV_USERCFI_H +#define _ASM_RISCV_USERCFI_H + +#ifndef __ASSEMBLY__ +#include <linux/types.h> + +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status { +unsigned long ubcfi_en :1 ;/* Enable for backward cfi. */ +unsigned long rsvd : ((sizeof (unsigned long )*8 ) -1 ); +unsigned long user_shdw_stk;/* Current user shadow stack pointer */ +unsigned long shdw_stk_base;/* Base address of shadow stack */ +unsigned long shdw_stk_size;/* size of shadow stack */ +}; + +#endif /* CONFIG_RISCV_USER_CFI */ + +#endif /* __ASSEMBLY__ */ + +#endif /* _ASM_RISCV_USERCFI_H */ arch/riscv/kernel/asm-offsets.c +4
-1@@ -43,8 +43,11 @@ void asm_offsets(void)#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif -OFFSET (TASK_TI_CPU_NUM , task_struct, thread_info.cpu); +#ifdef CONFIG_RISCV_USER_CFI +OFFSET (TASK_TI_CFI_STATUS , task_struct, thread_info.user_cfi_state); +OFFSET (TASK_TI_USER_SSP , task_struct, thread_info.user_cfi_state.user_shdw_stk); +#endif OFFSET (TASK_THREAD_F0 , task_struct, thread.fstate.f[0 ]);OFFSET (TASK_THREAD_F1 , task_struct, thread.fstate.f[1 ]);arch/riscv/kernel/asm-offsets.c +0
-0OFFSET (TASK_THREAD_F2 , task_struct, thread.fstate.f[2 ]);arch/riscv/kernel/entry.S +22
-0@@ -49,6 +49,21 @@ SYM_CODE_START(handle_exception) REG_S x5, PT_T0(sp) save_from_x6_to_x31 +#ifdef CONFIG_RISCV_USER_CFI + /* + * we need to save cfi status only when previous mode was U + */ + csrr s2, CSR_STATUS + andi s2, s2, SR_SPP + bnez s2, skip_bcfi_save + /* load cfi status word */ + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_save + csrr s3, CSR_SSP + REG_S s3, TASK_TI_USER_SSP(tp) /* save user ssp in thread_info */ +skip_bcfi_save: +#endif /* * Disable user-mode memory access as it should only be set in the * actual user copy routines.@@ -141,6 +156,16 @@ SYM_CODE_START_NOALIGN(ret_from_exception) * structures again. */ csrw CSR_SCRATCH, tp + +#ifdef CONFIG_RISCV_USER_CFI + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_resume + REG_L s3, TASK_TI_USER_SSP(tp) /* restore user ssp from thread struct */ + csrw CSR_SSP, s3
Quoted 8 lines
arch/riscv/kernel/entry.S SYM_CODE_START_NOALIGN(ret_from_exception) · line 168
Quoted 3 lines
arch/riscv/kernel/entry.S +3
-0+skip_bcfi_resume: +#endif +We shouldn't need any of this in the entry/exit code, at least as long as the kernel itself is not using Zicfiss. ssp can keep its value in the kernel and swap it on task switches. Our entry/exit code is rather short and I'd like to keep it that way.
I kept it here because sooner or later we will need to establish kernel shadow stack. Kernel shadow stack on riscv (compared to other arches) kernel actually will be easier to support and adopt because there is already support for shadow call stack (SCS, [1]). Difference between existing shadow call stack (SCS) and zicfiss based kernel shadow stack would be
- In prolog instead of using sd, we will be inserting sspush to save ret addr
- In epilog instead of using ld and compare, we will be inserting sspopchk
So a lot underlying work and functional testing for shadow kernel stack is already carried out with SCS patches. It would be easier and faster to re-use SCS patches to support zicfiss based shadow stack.
I don't have favorites here, if overwhelving opinion of community here is to take this logic into task switching and re-work this logic back into entry.S whenever shadow stack for kernel patches are posted, I can do that as well.
[1] - https://lore.kernel.org/all/[email protected]/
Quoted 14 lines
-s
Quoted 11 lines
arch/riscv/kernel/entry.S +0
-11: REG_L a0, PT_STATUS(sp) /* --2.43.0
_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 02/28] riscv: envcfg save and restore on trap entry/exit
In reply to Deepak GuptaQuoted 10 lines · Deepak Gupta
Quoted 9 lines · Stefan O'Rear
Quoted 8 lines · On Thu, Jan 25, 2024, at 1:21 AM, [email protected] wrote:
From: Deepak Gupta <[email protected]>
envcfg CSR defines enabling bits for cache management instructions and soon will control enabling for control flow integrity and pointer masking features.
Control flow integrity enabling for forward cfi and backward cfi is controlled via envcfg and thus need to be enabled on per thread basis.
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
This patch creates a place holder for envcfg CSR in
thread_infoand adds logic to save and restore on trap entry and exits.Should only be "restore"? I don't see saving.
It's always saved in
thread_infoand user mode can't change it. So no point saving it.
Also I'll fix the commit message. I think that's what you were pointing out.
Quoted 72 lines
Quoted 53 lines
Quoted 41 lines
Signed-off-by Deepak Gupta <[email protected]>---
arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/asm-offsets.c | 1 + arch/riscv/kernel/entry.S | 4 ++++ 3 files changed, 6 insertions(+)arch/riscv/include/asm/thread_info.h +1
-0@@ -57,6 +57,7 @@ struct thread_info {long user_sp;/* User stack pointer */ int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ +unsigned long envcfg;#ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;arch/riscv/kernel/asm-offsets.c +1
-0@@ -39,6 +39,7 @@ void asm_offsets(void)OFFSET (TASK_TI_PREEMPT_COUNT , task_struct, thread_info.preempt_count);OFFSET (TASK_TI_KERNEL_SP , task_struct, thread_info.kernel_sp);OFFSET (TASK_TI_USER_SP , task_struct, thread_info.user_sp); +OFFSET (TASK_TI_ENVCFG , task_struct, thread_info.envcfg);#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif arch/riscv/kernel/entry.S +0
-0arch/riscv/kernel/entry.S SYM_CODE_START_NOALIGN(ret_from_exception) · line 135
Quoted 7 lines
arch/riscv/kernel/entry.S +4
-0@@ -129,6 +129,10 @@ SYM_CODE_START_NOALIGN(ret_from_exception) addi s0, sp, PT_SIZE_ON_STACK REG_S s0, TASK_TI_KERNEL_SP(tp) + /* restore envcfg bits for current thread */ + REG_L s0, TASK_TI_ENVCFG(tp) + csrw CSR_ENVCFG, s0 +This is redundant if we're repeatedly processing interrupts or exceptions within a single task. We should only be writing envcfg when switching between tasks or as part of the prctl.
Quoted 2 lines
We need to use an ALTERNATIVE for this since the oldest supported hardware does not have envcfg csrs.
Yeah fixing that in next series. Thanks
Quoted 14 lines
-s
Quoted 11 lines
arch/riscv/kernel/entry.S +0
-1/* Save the kernel shadow call stack pointer */ scs_save_current --2.43.0
_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 05/28] riscv: zicfiss/zicfilp enumeration
In reply to [email protected]Yo,
Series is RFC, so not gonna review it in depth, just wanted to comment on this particular patch.
Quoted 24 lines · On Wed, Jan 24, 2024 at 10:21:30PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
This patch adds support for detecting zicfiss and zicfilp. zicfiss and zicfilp stands for unprivleged integer spec extension for shadow stack and branch tracking on indirect branches, respectively.
This patch looks for zicfiss and zicfilp in device tree and accordinlgy lights up bit in cpu feature bitmap. Furthermore this patch adds detection utility functions to return whether shadow stack or landing pads are supported by cpu.
Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/cpufeature.h | 18 ++++++++++++++++++ arch/riscv/include/asm/hwcap.h | 2 ++ arch/riscv/include/asm/processor.h | 1 + arch/riscv/kernel/cpufeature.c | 2 ++ 4 files changed, 23 insertions(+)arch/riscv/include/asm/cpufeature.h +0
-0
arch/riscv/include/asm/cpufeature.h static __always_inline bool riscv_cpu_has_extension_unlikely(int cpu, const unsi · line 138
Quoted 6 lines
arch/riscv/include/asm/cpufeature.h +3
-0@@ -133,4 +133,22 @@ static __always_inline bool riscv_cpu_has_extension_unlikely(int cpu, const unsireturn __riscv_isa_extension_available (hart_isa[cpu].isa, ext); } +static inline bool cpu_supports_shadow_stack (void ) +{ +#ifdef CONFIG_RISCV_USER_CFI
In passing, I don't see any reason for not using IS_ENABLED() here.
Quoted 46 lines
arch/riscv/include/asm/cpufeature.h +15
-0+return riscv_isa_extension_available (NULL ,ZICFISS ); +#else +return false; +#endif +} + +static inline bool cpu_supports_indirect_br_lp_instr (void ) +{ +#ifdef CONFIG_RISCV_USER_CFI +return riscv_isa_extension_available (NULL ,ZICFILP ); +#else +return false; +#endif +} +#endif arch/riscv/include/asm/hwcap.h +2
-0@@ -57,6 +57,8 @@#define RISCV_ISA_EXT_ZIHPM 42#define RISCV_ISA_EXT_SMSTATEEN 43#define RISCV_ISA_EXT_ZICOND 44 +#define RISCV_ISA_EXT_ZICFISS 45 +#define RISCV_ISA_EXT_ZICFILP 46#define RISCV_ISA_EXT_MAX 64arch/riscv/include/asm/processor.h +1
-0@@ -13,6 +13,7 @@#include <vdso/processor.h> #include <asm/ptrace.h> +#include <asm/hwcap.h> #ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))arch/riscv/kernel/cpufeature.c +0
-0
arch/riscv/kernel/cpufeature.c const struct riscv_isa_ext_data riscv_isa_ext[] = { · line 189
Quoted 5 lines
arch/riscv/kernel/cpufeature.c +2
-0@@ -185,6 +185,8 @@ const struct riscv_isa_ext_data riscv_isa_ext[] = {__RISCV_ISA_EXT_DATA (svinval,RISCV_ISA_EXT_SVINVAL ),__RISCV_ISA_EXT_DATA (svnapot,RISCV_ISA_EXT_SVNAPOT ),__RISCV_ISA_EXT_DATA (svpbmt,RISCV_ISA_EXT_SVPBMT ), +__RISCV_ISA_EXT_DATA (zicfiss,RISCV_ISA_EXT_ZICFISS ), + __RISCV_ISA_EXT_DATA(zicfilp, RISCV_ISA_EXT_ZICFILP),
Anything you add to this array, you need to document in a dt-binding. Also, you added these in the wrong place. There's a massive comment before the array describing the order entries must be in, please take a look.
Thanks,
Conor.
Quoted 11 lines
arch/riscv/kernel/cpufeature.c +0
-0};const size_t riscv_isa_ext_count =ARRAY_SIZE (riscv_isa_ext);Signature · 7 lines
2.43.0 _______________________________________________ linux-riscv mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 24/28] riscv: select config for shadow stack and landing pad instr support
In reply to [email protected]Quoted 18 lines · On Wed, Jan 24, 2024 at 10:21:49PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
This patch selects config shadow stack support and landing pad instr support. Shadow stack support and landing instr support is hidden behind
CONFIG_RISCV_USER_CFI. SelectingCONFIG_RISCV_USER_CFIwires up path to enumerate CPU support and if cpu support exists, kernel will support cpu assisted user mode cfi.Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/Kconfig | 15 +++++++++++++++ 1 file changed, 15 insertions(+)arch/riscv/Kconfig +0
-0
arch/riscv/Kconfig config RISCV · line 166
Quoted 4 lines
arch/riscv/Kconfig +1
-0@@ -163,6 +163,7 @@ config RISCV select SYSCTL_EXCEPTION_TRACE select THREAD_INFO_IN_TASK select TRACE_IRQFLAGS_SUPPORT + select RISCV_USER_CFI
This select makes no sense to me, it will unconditionally enable RISCV_USER_CFI. I don't think that that is your intent, since you have a detailed option below that allows the user to turn it on or off.
If you remove it, the commit message will need to change too FYI.
Thanks,
Conor.
Quoted 32 lines
arch/riscv/Kconfig +14
-0select UACCESS_MEMCPY if !MMU select ZONE_DMA32 if 64BIT@@ -182,6 +183,20 @@ config HAVE_SHADOW_CALL_STACK # https://github.com/riscv-non-isa/riscv-elf-psabi-doc/commit/a484e843e6eeb51f0cb7b8819e50da6d2444d769 depends on $(ld-option,--no-relax-gp) +config RISCV_USER_CFI + bool "riscv userspace control flow integrity" + help + Provides CPU assisted control flow integrity to userspace tasks. + Control flow integrity is provided by implementing shadow stack for + backward edge and indirect branch tracking for forward edge in program. + Shadow stack protection is a hardware feature that detects function + return address corruption. This helps mitigate ROP attacks. + Indirect branch tracking enforces that all indirect branches must land + on a landing pad instruction else CPU will fault. This mitigates against + JOP / COP attacks. Applications must be enabled to use it, and old user- + space does not get protection "for free". + default y + config ARCH_MMAP_RND_BITS_MIN default 18 if 64BIT default 8Signature · 7 lines
2.43.0 _______________________________________________ linux-riscv mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 24/28] riscv: select config for shadow stack and landing pad instr support
Quoted 28 lines · Conor Dooley
Quoted 18 lines · On Wed, Jan 24, 2024 at 10:21:49PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
This patch selects config shadow stack support and landing pad instr support. Shadow stack support and landing instr support is hidden behind
CONFIG_RISCV_USER_CFI. SelectingCONFIG_RISCV_USER_CFIwires up path to enumerate CPU support and if cpu support exists, kernel will support cpu assisted user mode cfi.Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/Kconfig | 15 +++++++++++++++ 1 file changed, 15 insertions(+)arch/riscv/Kconfig +0
-0arch/riscv/Kconfig config RISCV · line 166
Quoted 4 lines
arch/riscv/Kconfig +1
-0@@ -163,6 +163,7 @@ config RISCV select SYSCTL_EXCEPTION_TRACE select THREAD_INFO_IN_TASK select TRACE_IRQFLAGS_SUPPORT + select RISCV_USER_CFIThis select makes no sense to me, it will unconditionally enable
RISCV_USER_CFI. I don't think that that is your intent, since you have a detailed option below that allows the user to turn it on or off.
Quoted 2 lines
If you remove it, the commit message will need to change too FYI.
Selecting this config puts support in Kernel so that it can run tasks who wants to enable hardware assisted control flow integrity for themselves. But apps still always need to optin using prctls. Those prctls are stubs and return EINVAL when this config is not selected. Not selecting this config means, kernel will not support enabling this feature for user mode.
I'll edit commit message to better reflect this.
Quoted 35 lines
Thanks,
Conor.Quoted 32 lines
arch/riscv/Kconfig +14
-1select UACCESS_MEMCPY if !MMU select ZONE_DMA32 if 64BIT@@ -182,6 +183,20 @@ config HAVE_SHADOW_CALL_STACK # https://github.com/riscv-non-isa/riscv-elf-psabi-doc/commit/a484e843e6eeb51f0cb7b8819e50da6d2444d769 depends on $(ld-option,--no-relax-gp) +config RISCV_USER_CFI + bool "riscv userspace control flow integrity" + help + Provides CPU assisted control flow integrity to userspace tasks. + Control flow integrity is provided by implementing shadow stack for + backward edge and indirect branch tracking for forward edge in program. + Shadow stack protection is a hardware feature that detects function + return address corruption. This helps mitigate ROP attacks. + Indirect branch tracking enforces that all indirect branches must land + on a landing pad instruction else CPU will fault. This mitigates against + JOP / COP attacks. Applications must be enabled to use it, and old user- + space does not get protection "for free". + default y + config ARCH_MMAP_RND_BITS_MIN default 18 if 64BIT default 8 --2.43.0
_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 05/28] riscv: zicfiss/zicfilp enumeration
In reply to Conor DooleyQuoted 33 lines · Conor Dooley
Yo,
Series is RFC, so not gonna review it in depth, just wanted to comment on this particular patch.
Quoted 27 lines · On Wed, Jan 24, 2024 at 10:21:30PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
This patch adds support for detecting zicfiss and zicfilp. zicfiss and zicfilp stands for unprivleged integer spec extension for shadow stack and branch tracking on indirect branches, respectively.
This patch looks for zicfiss and zicfilp in device tree and accordinlgy lights up bit in cpu feature bitmap. Furthermore this patch adds detection utility functions to return whether shadow stack or landing pads are supported by cpu.
Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/cpufeature.h | 18 ++++++++++++++++++ arch/riscv/include/asm/hwcap.h | 2 ++ arch/riscv/include/asm/processor.h | 1 + arch/riscv/kernel/cpufeature.c | 2 ++ 4 files changed, 23 insertions(+)arch/riscv/include/asm/cpufeature.h +0
-0@@ -133,4 +133,22 @@ static __always_inline bool riscv_cpu_has_extension_unlikely(int cpu, const unsireturn __riscv_isa_extension_available (hart_isa[cpu].isa, ext); }
Quoted 5 lines
arch/riscv/include/asm/cpufeature.h static __always_inline bool riscv_cpu_has_extension_unlikely(int cpu, const unsi · line 138
Quoted 3 lines
arch/riscv/include/asm/cpufeature.h +3
-0+static inline bool cpu_supports_shadow_stack (void ) +{ +#ifdef CONFIG_RISCV_USER_CFI In passing, I don't see any reason for not using
IS_ENABLED()here.
No reason. I should probably do that. More readable. Thanks.
Quoted 40 lines
Quoted 40 lines
arch/riscv/include/asm/cpufeature.h +15
-0+return riscv_isa_extension_available (NULL ,ZICFISS ); +#else +return false; +#endif +} + +static inline bool cpu_supports_indirect_br_lp_instr (void ) +{ +#ifdef CONFIG_RISCV_USER_CFI +return riscv_isa_extension_available (NULL ,ZICFILP ); +#else +return false; +#endif +} +#endif arch/riscv/include/asm/hwcap.h +2
-0@@ -57,6 +57,8 @@#define RISCV_ISA_EXT_ZIHPM 42#define RISCV_ISA_EXT_SMSTATEEN 43#define RISCV_ISA_EXT_ZICOND 44 +#define RISCV_ISA_EXT_ZICFISS 45 +#define RISCV_ISA_EXT_ZICFILP 46#define RISCV_ISA_EXT_MAX 64arch/riscv/include/asm/processor.h +1
-0@@ -13,6 +13,7 @@#include <vdso/processor.h> #include <asm/ptrace.h> +#include <asm/hwcap.h>
Quoted 14 lines
arch/riscv/kernel/cpufeature.c const struct riscv_isa_ext_data riscv_isa_ext[] = { · line 189
Quoted 12 lines
arch/riscv/include/asm/processor.h +0
-0#ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))arch/riscv/kernel/cpufeature.c +2
-0@@ -185,6 +185,8 @@ const struct riscv_isa_ext_data riscv_isa_ext[] = {__RISCV_ISA_EXT_DATA (svinval,RISCV_ISA_EXT_SVINVAL ),__RISCV_ISA_EXT_DATA (svnapot,RISCV_ISA_EXT_SVNAPOT ),__RISCV_ISA_EXT_DATA (svpbmt,RISCV_ISA_EXT_SVPBMT ), +__RISCV_ISA_EXT_DATA (zicfiss,RISCV_ISA_EXT_ZICFISS ), + __RISCV_ISA_EXT_DATA(zicfilp, RISCV_ISA_EXT_ZICFILP),Anything you add to this array, you need to document in a dt-binding.
You mean Documentation/devicetree/bindings/riscv/extensions.yaml (or possibly any other yaml if needed?)
Quoted 3 lines
Also, you added these in the wrong place. There's a massive comment before the array describing the order entries must be in, please take a look.
I see the comment.
In my defense, looks like I missed it when I was rebasing.
Will fix it.
Quoted 16 lines
Thanks,
Conor.Quoted 11 lines
arch/riscv/kernel/cpufeature.c +0
-1};const size_t riscv_isa_ext_count =ARRAY_SIZE (riscv_isa_ext); --2.43.0
_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 24/28] riscv: select config for shadow stack and landing pad instr support
In reply to Deepak GuptaQuoted 29 lines · Deepak Gupta
Quoted 28 lines · Conor Dooley
Quoted 18 lines · On Wed, Jan 24, 2024 at 10:21:49PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
This patch selects config shadow stack support and landing pad instr support. Shadow stack support and landing instr support is hidden behind
CONFIG_RISCV_USER_CFI. SelectingCONFIG_RISCV_USER_CFIwires up path to enumerate CPU support and if cpu support exists, kernel will support cpu assisted user mode cfi.Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/Kconfig | 15 +++++++++++++++ 1 file changed, 15 insertions(+)arch/riscv/Kconfig +0
-0arch/riscv/Kconfig config RISCV · line 166
Quoted 4 lines
arch/riscv/Kconfig +1
-0@@ -163,6 +163,7 @@ config RISCV select SYSCTL_EXCEPTION_TRACE select THREAD_INFO_IN_TASK select TRACE_IRQFLAGS_SUPPORT + select RISCV_USER_CFIThis select makes no sense to me, it will unconditionally enable
RISCV_USER_CFI. I don't think that that is your intent, since you have a detailed option below that allows the user to turn it on or off.
Quoted 8 lines
Quoted 2 lines
If you remove it, the commit message will need to change too FYI.
Selecting this config puts support in Kernel so that it can run tasks who wants to enable hardware assisted control flow integrity for themselves. But apps still always need to optin using
prctls. Those prctls are stubs and return EINVAL when this config is not selected. Not selecting this config means, kernel will not support enabling this feature for user mode.
I don't think you understand me. "select RISCV_USER_CFI" will unconditionally build it into the kernel, making stubs etc useless. You're talking like (and the rest of your commit implements it!) that this feature can be enabled in menuconfig etc. Having this select will always enable the config option, rendering the choice below redundant. Try turning it off in menuconfig.
Oh and if it were valid to have here, you put it in out of order. That's an alphanumerically sorted list :)
Cheers,
Conor.
Re: [RFC PATCH v1 05/28] riscv: zicfiss/zicfilp enumeration
In reply to Deepak GuptaQuoted 4 lines · Deepak Gupta
Quoted 1 line
Anything you add to this array, you need to document in a dt-binding.
You mean
Documentation/devicetree/bindings/riscv/extensions.yaml(or possibly any other yaml if needed?)
That one alone should be okay.
Quoted 6 lines
Quoted 3 lines
Also, you added these in the wrong place. There's a massive comment before the array describing the order entries must be in, please take a look.
I see the comment.
In my defense, looks like I missed it when I was rebasing.
No worries.
Re: [RFC PATCH v1 24/28] riscv: select config for shadow stack and landing pad instr support
In reply to Conor DooleyQuoted 39 lines · Conor Dooley
Quoted 29 lines · Deepak Gupta
Quoted 28 lines · Conor Dooley
Quoted 18 lines · On Wed, Jan 24, 2024 at 10:21:49PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
This patch selects config shadow stack support and landing pad instr support. Shadow stack support and landing instr support is hidden behind
CONFIG_RISCV_USER_CFI. SelectingCONFIG_RISCV_USER_CFIwires up path to enumerate CPU support and if cpu support exists, kernel will support cpu assisted user mode cfi.Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/Kconfig | 15 +++++++++++++++ 1 file changed, 15 insertions(+)arch/riscv/Kconfig +0
-0arch/riscv/Kconfig config RISCV · line 166
Quoted 4 lines
arch/riscv/Kconfig +1
-0@@ -163,6 +163,7 @@ config RISCV select SYSCTL_EXCEPTION_TRACE select THREAD_INFO_IN_TASK select TRACE_IRQFLAGS_SUPPORT + select RISCV_USER_CFIThis select makes no sense to me, it will unconditionally enable
RISCV_USER_CFI. I don't think that that is your intent, since you have a detailed option below that allows the user to turn it on or off.Quoted 8 lines
Quoted 2 lines
If you remove it, the commit message will need to change too FYI.
Selecting this config puts support in Kernel so that it can run tasks who wants to enable hardware assisted control flow integrity for themselves. But apps still always need to optin using
prctls. Those prctls are stubs and return EINVAL when this config is not selected. Not selecting this config means, kernel will not support enabling this feature for user mode.
Quoted 6 lines
I don't think you understand me. "select
RISCV_USER_CFI" will unconditionally build it into the kernel, making stubs etc useless. You're talking like (and the rest of your commit implements it!) that this feature can be enabled in menuconfig etc. Having this select will always enable the config option, rendering the choice below redundant. Try turning it off in menuconfig.
Aah got it now. Thanks.
I'll fix this messaging and select in next version.
Quoted 3 lines
Oh and if it were valid to have here, you put it in out of order. That's an alphanumerically sorted list :)
Thanks for pointing that out. Will fix it.
Quoted 4 lines
Cheers,
Conor.
Re: [RFC PATCH v1 07/28] riscv: kernel handling on trap entry/exit for user cfi
In reply to Deepak GuptaQuoted 163 lines · Deepak Gupta
Quoted 138 lines · Stefan O'Rear
Quoted 137 lines · On Thu, Jan 25, 2024, at 1:21 AM, [email protected] wrote:
From: Deepak Gupta <[email protected]>
Carves out space in arch specific thread struct for cfi status and shadow stack in usermode on riscv.
This patch does following
- defines a new structurecfi_statuswith status bit for cfi feature
- defines shadow stack pointer, base and size incfi_statusstructure
- defines offsets to new member fields in thread inasm-offsets.c
- Saves and restore shadow stack pointer on trap entry (U --> S) and exit (S --> U)Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/processor.h | 1 + arch/riscv/include/asm/thread_info.h | 3 +++ arch/riscv/include/asm/usercfi.h | 24 ++++++++++++++++++++++++ arch/riscv/kernel/asm-offsets.c | 5 ++++- arch/riscv/kernel/entry.S | 25 +++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 arch/riscv/include/asm/usercfi.harch/riscv/include/asm/processor.h +1
-0@@ -14,6 +14,7 @@#include <asm/ptrace.h> #include <asm/hwcap.h> +#include <asm/usercfi.h> #ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))arch/riscv/include/asm/thread_info.h +3
-0@@ -58,6 +58,9 @@ struct thread_info {int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ unsigned long envcfg; +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status user_cfi_state; +#endif #ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;arch/riscv/include/asm/usercfi.h new file +24
-0@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 +* Copyright (C) 2023 Rivos, Inc. +* Deepak Gupta <[email protected]> +*/ +#ifndef _ASM_RISCV_USERCFI_H +#define _ASM_RISCV_USERCFI_H + +#ifndef __ASSEMBLY__ +#include <linux/types.h> + +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status { +unsigned long ubcfi_en :1 ;/* Enable for backward cfi. */ +unsigned long rsvd : ((sizeof (unsigned long )*8 ) -1 ); +unsigned long user_shdw_stk;/* Current user shadow stack pointer */ +unsigned long shdw_stk_base;/* Base address of shadow stack */ +unsigned long shdw_stk_size;/* size of shadow stack */ +}; + +#endif /* CONFIG_RISCV_USER_CFI */ + +#endif /* __ASSEMBLY__ */ + +#endif /* _ASM_RISCV_USERCFI_H */ arch/riscv/kernel/asm-offsets.c +4
-1@@ -43,8 +43,11 @@ void asm_offsets(void)#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif -OFFSET (TASK_TI_CPU_NUM , task_struct, thread_info.cpu); +#ifdef CONFIG_RISCV_USER_CFI +OFFSET (TASK_TI_CFI_STATUS , task_struct, thread_info.user_cfi_state); +OFFSET (TASK_TI_USER_SSP , task_struct, thread_info.user_cfi_state.user_shdw_stk); +#endif OFFSET (TASK_THREAD_F0 , task_struct, thread.fstate.f[0 ]);OFFSET (TASK_THREAD_F1 , task_struct, thread.fstate.f[1 ]);arch/riscv/kernel/asm-offsets.c +0
-0OFFSET (TASK_THREAD_F2 , task_struct, thread.fstate.f[2 ]);arch/riscv/kernel/entry.S +22
-0@@ -49,6 +49,21 @@ SYM_CODE_START(handle_exception) REG_S x5, PT_T0(sp) save_from_x6_to_x31 +#ifdef CONFIG_RISCV_USER_CFI + /* + * we need to save cfi status only when previous mode was U + */ + csrr s2, CSR_STATUS + andi s2, s2, SR_SPP + bnez s2, skip_bcfi_save + /* load cfi status word */ + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_save + csrr s3, CSR_SSP + REG_S s3, TASK_TI_USER_SSP(tp) /* save user ssp in thread_info */ +skip_bcfi_save: +#endif /* * Disable user-mode memory access as it should only be set in the * actual user copy routines.@@ -141,6 +156,16 @@ SYM_CODE_START_NOALIGN(ret_from_exception) * structures again. */ csrw CSR_SCRATCH, tp + +#ifdef CONFIG_RISCV_USER_CFI + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_resume + REG_L s3, TASK_TI_USER_SSP(tp) /* restore user ssp from thread struct */ + csrw CSR_SSP, s3Quoted 8 lines
arch/riscv/kernel/entry.S SYM_CODE_START_NOALIGN(ret_from_exception) · line 168
Quoted 3 lines
arch/riscv/kernel/entry.S +3
-0+skip_bcfi_resume: +#endif +We shouldn't need any of this in the entry/exit code, at least as long as the kernel itself is not using Zicfiss. ssp can keep its value in the kernel and swap it on task switches. Our entry/exit code is rather short and I'd like to keep it that way.
I kept it here because sooner or later we will need to establish kernel shadow
stack. Kernel shadow stack on riscv (compared to other arches) kernel actually will
be easier to support and adopt because there is already support for shadow call stack
(SCS, [1]). Difference between existing shadow call stack (SCS) andzicfissbased
kernel shadow stack would be- In prolog instead of using
sd, we will be insertingsspushto
save ret addr
- In epilog instead of usingldand compare, we will be insertingsspopchk
Quoted 5 lines
So a lot underlying work and functional testing for shadow kernel stack is already carried
out with SCS patches. It would be easier and faster to re-use SCS patches to supportzicfissbased shadow stack.
Do you think that realistically, after all the patches are merged, almost all kernel configurations that enable kernel Zicfiss will also enable userspace Zicfiss and vice versa?
If not - if Zicfiss exclusively in user mode is likely to be a common configuration - then the kernel should handle that case in task switch.
If kernel Zicfiss and user Zicfiss are overwhelmingly likely to be supported together, then I agree it makes sense to handle it in the same place in entry/exit, but I think what you have is more complicated than necessary. I'm picturing something like this:
arch/riscv/kernel/entry.S +20 -3
@@ -32,6 +32,13 @@ SYM_CODE_START(handle_exception) csrr tp, CSR_SCRATCH REG_S sp, TASK_TI_KERNEL_SP(tp) +#ifdef CONFIG_SHADOW_CALL_STACK + ALTERNATIVE("scs_save_current\n\tnop\n\tnop", + "csrr sp, ssp\n\t" + "REG_S sp, TASK_TI_SCS_SP(tp)\n\t" + "REG_L sp, TASK_TI_KERNEL_SP(tp)") +#endif + #ifdef CONFIG_VMAP_STACK addi sp, sp, -(PT_SIZE_ON_STACK) srli sp, sp, THREAD_SHIFT
@@ -80,8 +87,13 @@ SYM_CODE_START(handle_exception) /* Load the global pointer */ load_global_pointer - /* Load the kernel shadow call stack pointer if coming from userspace */ - scs_load_current_if_task_changed s5 + /* Load the kernel shadow call stack pointer (harmless if from kernel) */ +#ifdef CONFIG_SHADOW_CALL_STACK + ALTERNATIVE("scs_load_current\n\tnop\n\tnop", + "REG_L s0, TASK_TI_SCS_SP(tp)\n\t" + "csrrw s0, ssp, s0\n\t" + "REG_S s0, PT_SSP(sp)") +#endif move a0, sp /* pt_regs */ la ra, ret_from_exception
@@ -130,7 +142,12 @@ SYM_CODE_START_NOALIGN(ret_from_exception) REG_S s0, TASK_TI_KERNEL_SP(tp) /* Save the kernel shadow call stack pointer */ - scs_save_current +#ifdef CONFIG_SHADOW_CALL_STACK + ALTERNATIVE("scs_save_current\n\tnop\n\tnop", + "REG_L s0, PT_SSP(sp)\n\t" + "csrrw s0, ssp, s0\n\t" + "REG_S s0, TASK_TI_SCS_SP(tp)") +#endif /* * Save TP into the scratch register , so we can find the kernel data
I moved the shadow stack pointer into pt_regs because it's nearly a GPR and has a meaningfully different value on every trap; this allows us to talk about the ssp at the time of a trap in kernel mode.
Saving both the sp and ssp in Lrestore_kernel_tpsp avoids adding conditional logic to Lsave_context. I believe the current code also has a bug: if the U-mode tp is, by chance or intentional exploit, equal to the thread_info address, kernel code will be executed with whatever value U-mode left in gp.
I also notice that there is no check for overflow of the shadow stack. This may be intentional, since as long as the shadow stack is at least half the size of the main kernel stack the latter will always overflow first, barring deeper corruption of the control structures or assembly code issues. I expect that the result in that case would be an infinite loop of shadow stack overflows in handle_bad_stack and do_trap_software_check with occasional visits to handle_kernel_stack_overflow.
I believe that "Save unwound kernel stack pointer in thread_info" and "Save the kernel shadow call stack pointer" are both no-ops in all cases other than ret_from_fork, since the ABI requires the C trap handler to return with the same sp and ssp it was entered with. Optimizing that would be a separate issue.
-s
Quoted 29 lines
I don't have favorites here, if overwhelving opinion of community here is to take this
logic into task switching and re-work this logic back intoentry.Swhenever shadow stack for
kernel patches are posted, I can do that as well.[1] -
https://lore.kernel.org/all/[email protected]/Quoted 14 lines
-s
Quoted 11 lines
arch/riscv/kernel/entry.S +0
-11: REG_L a0, PT_STATUS(sp) /* --2.43.0
_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 15/28] riscv/mm: Implement map_shadow_stack() syscall
In reply to [email protected]Quoted 40 lines · On Wed, Jan 24, 2024 at 10:21:40PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
As discussed extensively in the changelog for the addition of this syscall on x86 ("x86/shstk: Introduce
map_shadow_stacksyscall") the existingmmap()andmadvise()syscalls do not map entirely well onto the security requirements for guarded control stacks since they lead to windows where memory is allocated but not yet protected or stacks which are not properly and safely initialised. Instead a new syscallmap_shadow_stack()has been defined which allocates and initialises a shadow stack page.This patch implements this syscall for riscv. riscv doesn't require token to be setup by kernel because user mode can do that by itself. However to provide compatiblity and portability with other architectues, user mode can specify token set flag.
Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/kernel/Makefile | 2 + arch/riscv/kernel/usercfi.c | 150 ++++++++++++++++++++++++++++++++ include/uapi/asm-generic/mman.h | 1 + 3 files changed, 153 insertions(+) create mode 100644 arch/riscv/kernel/usercfi.carch/riscv/kernel/Makefile +2
-0@@ -102,3 +102,5 @@ obj-$(CONFIG_COMPAT) += compat_vdso/ obj-$(CONFIG_64BIT) += pi/ obj-$(CONFIG_ACPI) += acpi.o + +obj-$(CONFIG_RISCV_USER_CFI) += usercfi.oarch/riscv/kernel/usercfi.c new file +0
-0
arch/riscv/kernel/usercfi.c line 3
Quoted 3 lines
arch/riscv/kernel/usercfi.c new file +3
-0@@ -0,0 +1,150 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Copyright (C) 2023 Rivos, Inc.
Nit: Should be updated to 2024
Quoted 30 lines
arch/riscv/kernel/usercfi.c new file +30
-0+* Deepak Gupta <[email protected]> +*/ + +#include <linux/sched.h> +#include <linux/bitops.h> +#include <linux/types.h> +#include <linux/mm.h> +#include <linux/mman.h> +#include <linux/uaccess.h> +#include <linux/sizes.h> +#include <linux/user.h> +#include <linux/syscalls.h> +#include <linux/prctl.h> +#include <asm/csr.h> +#include <asm/usercfi.h> + +#define SHSTK_ENTRY_SIZE sizeof(void *) + +/* +* Writes on shadow stack can either be `sspush` or `ssamoswap`. `sspush` can happen +* implicitly on current shadow stack pointed to by CSR_SSP. `ssamoswap` takes pointer to +* shadow stack. To keep it simple, we plan to use `ssamoswap` to perform writes on shadow +* stack. +*/ +static noinline unsigned long amo_user_shstk (unsigned long *addr,unsigned long val) +{ +/* +* In case ssamoswap faults, return -1. +* Never expect -1 on shadow stack. Expect return addresses and zero +*/
arch/riscv/kernel/usercfi.c line 43
Quoted 10 lines
arch/riscv/kernel/usercfi.c new file +10
-0+unsigned long swap =-1 ; + +__enable_user_access (); +asm_volatile_goto ( + ".option push\n" + ".option arch, +zicfiss\n" +#ifdef CONFIG_64BIT + "1: ssamoswap.d %0, %2, %1\n" +#else + "1: ssamoswap.w %0, %2, %1\n"
A SSAMOSWAP macro that conditionally defines this would be cleaner
arch/riscv/kernel/usercfi.c line 48
Quoted 5 lines
arch/riscv/kernel/usercfi.c new file +5
-0+#endif + _ASM_EXTABLE(1b, %l[fault]) + RISCV_ACQUIRE_BARRIER + ".option pop\n" + : "=r" (swap), "+A" (*addr)
I just ran into this on one of my patches that not every compiler supports output args in asm goto blocks. You need to guard this with the kconfig option CC_HAS_ASM_GOTO_TIED_OUTPUT. Unfortunately, that means that this code needs two versions, or you can choose to gate CFI behind this option, it's supported by recent versions of GCC/CLANG.
For readability it is also nice to use labels for the asm variables such as "=r" (swap) can be [swap] "=r" (swap) and then replace %0 with %[swap].
- Charlie
Quoted 115 lines
arch/riscv/kernel/usercfi.c new file +102
-0+ : "r" (val) + : "memory" + : fault + ); +__disable_user_access (); +return swap; +fault: +__disable_user_access (); +return -1 ; +} + +/* +* Create a restore token on the shadow stack. A token is always XLEN wide +* and aligned to XLEN. +*/ +static int create_rstor_token (unsigned long ssp,unsigned long *token_addr) +{ +unsigned long addr; + +/* Token must be aligned */ +if (!IS_ALIGNED (ssp,SHSTK_ENTRY_SIZE )) +return -EINVAL ; + +/* On RISC-V we're constructing token to be function of address itself */ + addr = ssp -SHSTK_ENTRY_SIZE ; + +if (amo_user_shstk ((unsigned long __user *)addr, (unsigned long ) ssp) ==-1 ) +return -EFAULT ; + +if (token_addr) + *token_addr = addr; + +return 0 ; +} + +static unsigned long allocate_shadow_stack (unsigned long addr,unsigned long size, +unsigned long token_offset, +bool set_tok) +{ +int flags =MAP_ANONYMOUS |MAP_PRIVATE ; +struct mm_struct *mm = current->mm; +unsigned long populate, tok_loc =0 ; + +if (addr) + flags |=MAP_FIXED_NOREPLACE ; + +mmap_write_lock (mm); + addr =do_mmap (NULL , addr, size,PROT_SHADOWSTACK , flags, +VM_SHADOW_STACK ,0 , &populate,NULL ); +mmap_write_unlock (mm); + +if (!set_tok ||IS_ERR_VALUE (addr)) + goto out; + +if (create_rstor_token (addr + token_offset, &tok_loc)) { +vm_munmap (addr, size); +return -EINVAL ; + } + + addr = tok_loc; + +out: +return addr; +} + +SYSCALL_DEFINE3(map_shadow_stack, unsigned long, addr, unsigned long, size, unsigned int, flags) +{ +bool set_tok = flags &SHADOW_STACK_SET_TOKEN ; +unsigned long aligned_size =0 ; + +if (!cpu_supports_shadow_stack ()) +return -EOPNOTSUPP ; + +/* Anything other than set token should result in invalid param */ +if (flags & ~SHADOW_STACK_SET_TOKEN ) +return -EINVAL ; + +/* +* Unlike other architectures, on RISC-V, SSP pointer is held in CSR_SSP and is available +* CSR in all modes. CSR accesses are performed using 12bit index programmed in instruction +* itself. This provides static property on register programming and writes to CSR can't +* be unintentional from programmer's perspective. As long as programmer has guarded areas +* which perform writes to CSR_SSP properly, shadow stack pivoting is not possible. Since +* CSR_SSP is writeable by user mode, it itself can setup a shadow stack token subsequent +* to allocation. Although in order to provide portablity with other architecture (because +* `map_shadow_stack` is arch agnostic syscall), RISC-V will follow expectation of a token +* flag in flags and if provided in flags, setup a token at the base. +*/ + +/* If there isn't space for a token */ +if (set_tok && size <SHSTK_ENTRY_SIZE ) +return -ENOSPC ; + +if (addr && (addr %PAGE_SIZE )) +return -EINVAL ; + + aligned_size =PAGE_ALIGN (size); +if (aligned_size < size) +return -EOVERFLOW ; + +return allocate_shadow_stack (addr, aligned_size, size, set_tok); +}include/uapi/asm-generic/mman.h +1
-0@@ -19,4 +19,5 @@#define MCL_FUTURE 2/* lock all future mappings */ #define MCL_ONFAULT 4/* lock all pages that are faulted in */ +#define SHADOW_STACK_SET_TOKEN (1ULL << 0)/* Set up a restore token in the shadow stack */ #endif /* __ASM_GENERIC_MMAN_H */ Signature · 1 line
2.43.0
Re: [RFC PATCH v1 07/28] riscv: kernel handling on trap entry/exit for user cfi
In reply to Stefan O'RearQuoted 174 lines · Stefan O'Rear
Quoted 163 lines · Deepak Gupta
Quoted 138 lines · Stefan O'Rear
Quoted 137 lines · On Thu, Jan 25, 2024, at 1:21 AM, [email protected] wrote:
From: Deepak Gupta <[email protected]>
Carves out space in arch specific thread struct for cfi status and shadow stack in usermode on riscv.
This patch does following
- defines a new structurecfi_statuswith status bit for cfi feature
- defines shadow stack pointer, base and size incfi_statusstructure
- defines offsets to new member fields in thread inasm-offsets.c
- Saves and restore shadow stack pointer on trap entry (U --> S) and exit (S --> U)Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/processor.h | 1 + arch/riscv/include/asm/thread_info.h | 3 +++ arch/riscv/include/asm/usercfi.h | 24 ++++++++++++++++++++++++ arch/riscv/kernel/asm-offsets.c | 5 ++++- arch/riscv/kernel/entry.S | 25 +++++++++++++++++++++++++ 5 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 arch/riscv/include/asm/usercfi.harch/riscv/include/asm/processor.h +1
-0@@ -14,6 +14,7 @@#include <asm/ptrace.h> #include <asm/hwcap.h> +#include <asm/usercfi.h> #ifdef CONFIG_64BIT #define DEFAULT_MAP_WINDOW (UL(1) << (MMAP_VA_BITS - 1))arch/riscv/include/asm/thread_info.h +3
-0@@ -58,6 +58,9 @@ struct thread_info {int cpu;unsigned long syscall_work;/* SYSCALL_WORK_ flags */ unsigned long envcfg; +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status user_cfi_state; +#endif #ifdef CONFIG_SHADOW_CALL_STACK void *scs_base;void *scs_sp;arch/riscv/include/asm/usercfi.h new file +24
-0@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0 +* Copyright (C) 2023 Rivos, Inc. +* Deepak Gupta <[email protected]> +*/ +#ifndef _ASM_RISCV_USERCFI_H +#define _ASM_RISCV_USERCFI_H + +#ifndef __ASSEMBLY__ +#include <linux/types.h> + +#ifdef CONFIG_RISCV_USER_CFI +struct cfi_status { +unsigned long ubcfi_en :1 ;/* Enable for backward cfi. */ +unsigned long rsvd : ((sizeof (unsigned long )*8 ) -1 ); +unsigned long user_shdw_stk;/* Current user shadow stack pointer */ +unsigned long shdw_stk_base;/* Base address of shadow stack */ +unsigned long shdw_stk_size;/* size of shadow stack */ +}; + +#endif /* CONFIG_RISCV_USER_CFI */ + +#endif /* __ASSEMBLY__ */ + +#endif /* _ASM_RISCV_USERCFI_H */ arch/riscv/kernel/asm-offsets.c +4
-1@@ -43,8 +43,11 @@ void asm_offsets(void)#ifdef CONFIG_SHADOW_CALL_STACK OFFSET (TASK_TI_SCS_SP , task_struct, thread_info.scs_sp);#endif -OFFSET (TASK_TI_CPU_NUM , task_struct, thread_info.cpu); +#ifdef CONFIG_RISCV_USER_CFI +OFFSET (TASK_TI_CFI_STATUS , task_struct, thread_info.user_cfi_state); +OFFSET (TASK_TI_USER_SSP , task_struct, thread_info.user_cfi_state.user_shdw_stk); +#endif OFFSET (TASK_THREAD_F0 , task_struct, thread.fstate.f[0 ]);OFFSET (TASK_THREAD_F1 , task_struct, thread.fstate.f[1 ]);arch/riscv/kernel/asm-offsets.c +0
-0OFFSET (TASK_THREAD_F2 , task_struct, thread.fstate.f[2 ]);arch/riscv/kernel/entry.S +22
-0@@ -49,6 +49,21 @@ SYM_CODE_START(handle_exception) REG_S x5, PT_T0(sp) save_from_x6_to_x31 +#ifdef CONFIG_RISCV_USER_CFI + /* + * we need to save cfi status only when previous mode was U + */ + csrr s2, CSR_STATUS + andi s2, s2, SR_SPP + bnez s2, skip_bcfi_save + /* load cfi status word */ + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_save + csrr s3, CSR_SSP + REG_S s3, TASK_TI_USER_SSP(tp) /* save user ssp in thread_info */ +skip_bcfi_save: +#endif /* * Disable user-mode memory access as it should only be set in the * actual user copy routines.@@ -141,6 +156,16 @@ SYM_CODE_START_NOALIGN(ret_from_exception) * structures again. */ csrw CSR_SCRATCH, tp + +#ifdef CONFIG_RISCV_USER_CFI + lw s3, TASK_TI_CFI_STATUS(tp) + andi s3, s3, 1 + beqz s3, skip_bcfi_resume + REG_L s3, TASK_TI_USER_SSP(tp) /* restore user ssp from thread struct */ + csrw CSR_SSP, s3Quoted 8 lines
arch/riscv/kernel/entry.S SYM_CODE_START(handle_exception) · line 41
Quoted 3 lines
arch/riscv/kernel/entry.S +3
-0+skip_bcfi_resume: +#endif +We shouldn't need any of this in the entry/exit code, at least as long as the kernel itself is not using Zicfiss. ssp can keep its value in the kernel and swap it on task switches. Our entry/exit code is rather short and I'd like to keep it that way.
I kept it here because sooner or later we will need to establish kernel shadow
stack. Kernel shadow stack on riscv (compared to other arches) kernel actually will
be easier to support and adopt because there is already support for shadow call stack
(SCS, [1]). Difference between existing shadow call stack (SCS) andzicfissbased
kernel shadow stack would be- In prolog instead of using
sd, we will be insertingsspushto
save ret addr
- In epilog instead of usingldand compare, we will be insertingsspopchkQuoted 5 lines
So a lot underlying work and functional testing for shadow kernel stack is already carried
out with SCS patches. It would be easier and faster to re-use SCS patches to supportzicfissbased shadow stack.Do you think that realistically, after all the patches are merged, almost all kernel configurations that enable kernel Zicfiss will also enable userspace Zicfiss and vice versa?
Quoted 7 lines
If not - if Zicfiss exclusively in user mode is likely to be a common configuration - then the kernel should handle that case in task switch.
If kernel Zicfiss and user Zicfiss are overwhelmingly likely to be supported together, then I agree it makes sense to handle it in the same place in entry/exit, but I think what you have is more complicated than necessary. I'm picturing something like this:
I expect user mode would be the first target and even if kernel shadow stacks are enabled, it may not be as pervasive in adoption as I expect for user mode.
I do expect it to be used in settings where both are enabled (if not overwhelmingly)
Since that has to be supported, it's better to have it organized where we are saving/ restoring in a way which serves both needs rather than have two ways to save/restore depending on how user shadow stacks and kernel shadow stacks are configured.
Quoted 34 lines
arch/riscv/kernel/entry.S +14
-2@@ -32,6 +32,13 @@ SYM_CODE_START(handle_exception) csrr tp, CSR_SCRATCH REG_S sp, TASK_TI_KERNEL_SP(tp) +#ifdef CONFIG_SHADOW_CALL_STACK + ALTERNATIVE("scs_save_current\n\tnop\n\tnop", + "csrr sp, ssp\n\t" + "REG_S sp, TASK_TI_SCS_SP(tp)\n\t" + "REG_L sp, TASK_TI_KERNEL_SP(tp)") +#endif + #ifdef CONFIG_VMAP_STACK addi sp, sp, -(PT_SIZE_ON_STACK) srli sp, sp, THREAD_SHIFT@@ -80,8 +87,13 @@ SYM_CODE_START(handle_exception) /* Load the global pointer */ load_global_pointer - /* Load the kernel shadow call stack pointer if coming from userspace */ - scs_load_current_if_task_changed s5 + /* Load the kernel shadow call stack pointer (harmless if from kernel) */ +#ifdef CONFIG_SHADOW_CALL_STACK + ALTERNATIVE("scs_load_current\n\tnop\n\tnop", + "REG_L s0, TASK_TI_SCS_SP(tp)\n\t" + "csrrw s0, ssp, s0\n\t" + "REG_S s0, PT_SSP(sp)") +#endif move a0, sp /* pt_regs */ la ra, ret_from_exception
arch/riscv/kernel/entry.S SYM_CODE_START_NOALIGN(ret_from_exception) · line 150
Quoted 10 lines
arch/riscv/kernel/entry.S +6
-1@@ -130,7 +142,12 @@ SYM_CODE_START_NOALIGN(ret_from_exception) REG_S s0, TASK_TI_KERNEL_SP(tp) /* Save the kernel shadow call stack pointer */ - scs_save_current +#ifdef CONFIG_SHADOW_CALL_STACK + ALTERNATIVE("scs_save_current\n\tnop\n\tnop", + "REG_L s0, PT_SSP(sp)\n\t" + "csrrw s0, ssp, s0\n\t" + "REG_S s0, TASK_TI_SCS_SP(tp)") +#endif
I've not used alternatives earlier. But yes along with kernel shadow stack this is much more appealing. Let me munch on it a bit.
Quoted 8 lines
arch/riscv/kernel/entry.S +0
-0/* * Save TP into the scratch register , so we can find the kernel dataI moved the shadow stack pointer into
pt_regsbecause it's nearly a GPR and has a meaningfully different value on every trap; this allows us to talk about the ssp at the time of a trap in kernel mode.
I had been under the impression that changing pt_regs is something that we don't do usually. If it doesn't require a high bar, I'll do that. Infact, one my earlier implementation had ssp in pt_regs.
Quoted 49 lines
Saving both the sp and ssp in
Lrestore_kernel_tpspavoids adding conditional logic toLsave_context. I believe the current code also has a bug: if the U-mode tp is, by chance or intentional exploit, equal to thethread_infoaddress, kernel code will be executed with whatever value U-mode left in gp.I also notice that there is no check for overflow of the shadow stack. This may be intentional, since as long as the shadow stack is at least half the size of the main kernel stack the latter will always overflow first, barring deeper corruption of the control structures or assembly code issues. I expect that the result in that case would be an infinite loop of shadow stack overflows in
handle_bad_stackanddo_trap_software_checkwith occasional visits tohandle_kernel_stack_overflow.I believe that "Save unwound kernel stack pointer in
thread_info" and "Save the kernel shadow call stack pointer" are both no-ops in all cases other thanret_from_fork, since the ABI requires the C trap handler to return with the same sp and ssp it was entered with. Optimizing that would be a separate issue.-s
Quoted 29 lines
I don't have favorites here, if overwhelving opinion of community here is to take this
logic into task switching and re-work this logic back intoentry.Swhenever shadow stack for
kernel patches are posted, I can do that as well.[1] -
https://lore.kernel.org/all/[email protected]/Quoted 14 lines
-s
Quoted 11 lines
arch/riscv/kernel/entry.S +0
-11: REG_L a0, PT_STATUS(sp) /* --2.43.0
_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv
Re: [RFC PATCH v1 15/28] riscv/mm: Implement map_shadow_stack() syscall
In reply to Charlie JenkinsQuoted 31 lines · Charlie Jenkins
Quoted 30 lines · On Wed, Jan 24, 2024 at 10:21:40PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
As discussed extensively in the changelog for the addition of this syscall on x86 ("x86/shstk: Introduce
map_shadow_stacksyscall") the existingmmap()andmadvise()syscalls do not map entirely well onto the security requirements for guarded control stacks since they lead to windows where memory is allocated but not yet protected or stacks which are not properly and safely initialised. Instead a new syscallmap_shadow_stack()has been defined which allocates and initialises a shadow stack page.This patch implements this syscall for riscv. riscv doesn't require token to be setup by kernel because user mode can do that by itself. However to provide compatiblity and portability with other architectues, user mode can specify token set flag.
Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/kernel/Makefile | 2 + arch/riscv/kernel/usercfi.c | 150 ++++++++++++++++++++++++++++++++ include/uapi/asm-generic/mman.h | 1 + 3 files changed, 153 insertions(+) create mode 100644 arch/riscv/kernel/usercfi.carch/riscv/kernel/Makefile +0
-0@@ -102,3 +102,5 @@ obj-$(CONFIG_COMPAT) += compat_vdso/
Quoted 14 lines
arch/riscv/kernel/usercfi.c line 3
Quoted 13 lines
arch/riscv/kernel/Makefile +2
-0obj-$(CONFIG_64BIT) += pi/ obj-$(CONFIG_ACPI) += acpi.o + +obj-$(CONFIG_RISCV_USER_CFI) += usercfi.oarch/riscv/kernel/usercfi.c new file +3
-0@@ -0,0 +1,150 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Copyright (C) 2023 Rivos, Inc. Nit: Should be updated to 2024
noted
Quoted 34 lines
Quoted 34 lines
arch/riscv/kernel/usercfi.c new file +34
-0+* Deepak Gupta <[email protected]> +*/ + +#include <linux/sched.h> +#include <linux/bitops.h> +#include <linux/types.h> +#include <linux/mm.h> +#include <linux/mman.h> +#include <linux/uaccess.h> +#include <linux/sizes.h> +#include <linux/user.h> +#include <linux/syscalls.h> +#include <linux/prctl.h> +#include <asm/csr.h> +#include <asm/usercfi.h> + +#define SHSTK_ENTRY_SIZE sizeof(void *) + +/* +* Writes on shadow stack can either be `sspush` or `ssamoswap`. `sspush` can happen +* implicitly on current shadow stack pointed to by CSR_SSP. `ssamoswap` takes pointer to +* shadow stack. To keep it simple, we plan to use `ssamoswap` to perform writes on shadow +* stack. +*/ +static noinline unsigned long amo_user_shstk (unsigned long *addr,unsigned long val) +{ +/* +* In case ssamoswap faults, return -1. +* Never expect -1 on shadow stack. Expect return addresses and zero +*/ +unsigned long swap =-1 ; + +__enable_user_access (); + asm_volatile_goto(
Quoted 8 lines
arch/riscv/kernel/usercfi.c line 43
Quoted 6 lines
arch/riscv/kernel/usercfi.c new file +6
-0+ ".option push\n" + ".option arch, +zicfiss\n" +#ifdef CONFIG_64BIT + "1: ssamoswap.d %0, %2, %1\n" +#else +"1: ssamoswap.w %0, %2, %1\n" A SSAMOSWAP macro that conditionally defines this would be cleaner
Yes I need to do that. Infact I need to gate CONFIG_RISCV_USER_CFI behind some riscv-gnu toolchain version as well. Becuase not all toolchain versions will recognize this.
Quoted 12 lines
arch/riscv/kernel/usercfi.c line 48
Quoted 6 lines
arch/riscv/kernel/usercfi.c new file +5
-0+#endif + _ASM_EXTABLE(1b, %l[fault]) + RISCV_ACQUIRE_BARRIER + ".option pop\n" + : "=r" (swap), "+A" (*addr)I just ran into this on one of my patches that not every compiler supports output args in asm goto blocks. You need to guard this with the kconfig option
CC_HAS_ASM_GOTO_TIED_OUTPUT. Unfortunately, that means that this code needs two versions, or you can choose to gate CFI behind this option, it's supported by recent versions of GCC/CLANG.
Thanks.
I'll gate behind CC_HAS_ASM_GOTO_TIED_OUTPUT. Earlier versions of GCC/CLANG won't have CFI support in them anyways.
Quoted 4 lines
For readability it is also nice to use labels for the asm variables such as
"=r" (swap)can be[swap] "=r" (swap)and then replace %0 with %[swap].
noted, will do that. I copied it from gcc asm snippet amoswap somewhere in kernel. Goes without saying, I am terrible with gcc asm syntax.
Quoted 6 lines
- Charlie
Quoted 3 lines
arch/riscv/kernel/usercfi.c new file +3
-0+ : "r" (val) + : "memory" + : fault
Re: [RFC PATCH v1 15/28] riscv/mm: Implement map_shadow_stack() syscall
In reply to [email protected]Quoted 8 lines · On Wed, Jan 24, 2024 at 10:21:40PM -0800, [email protected] wrote:
As discussed extensively in the changelog for the addition of this syscall on x86 ("x86/shstk: Introduce
map_shadow_stacksyscall") the existingmmap()andmadvise()syscalls do not map entirely well onto the security requirements for guarded control stacks since they lead to windows where memory is allocated but not yet protected or stacks which are not properly and safely initialised. Instead a new syscallmap_shadow_stack()has been defined which allocates and initialises a shadow stack page.
While I agree that this is very well written you probably want to update the references to guarded control stacks to whatever the RISC-V term is :P
include/uapi/asm-generic/mman.h line 23
Quoted 8 lines
include/uapi/asm-generic/mman.h +1
-0@@ -19,4 +19,5 @@#define MCL_FUTURE 2/* lock all future mappings */ #define MCL_ONFAULT 4/* lock all pages that are faulted in */ +#define SHADOW_STACK_SET_TOKEN (1ULL << 0)/* Set up a restore token in the shadow stack */ #endif /* __ASM_GENERIC_MMAN_H */
For arm64 I also added a SHADOW_STACK_SET_MARKER for adding a top of stack marker, did you have any thoughts on that for RISC-V? I think x86 were considering adding it too, it'd be good if we could get things consistent.
Re: [RFC PATCH v1 18/28] prctl: arch-agnostic prtcl for indirect branch tracking
In reply to [email protected]Quoted 4 lines · On Wed, Jan 24, 2024 at 10:21:43PM -0800, [email protected] wrote:
To allow userspace to enable this feature for itself, following prtcls are defined:
-PR_GET_INDIR_BR_LP_STATUS: Gets current configured status for indirect branch tracking.
Quoted 8 lines
-
PR_SET_INDIR_BR_LP_STATUS: Sets a configuration for indirect branch tracking Following status options are allowed
-PR_INDIR_BR_LP_ENABLE: Enables indirect branch tracking on user thread.
-PR_INDIR_BR_LP_DISABLE; Disables indirect branch tracking on user thread.
-PR_LOCK_INDIR_BR_LP_STATUS: Locks configured status for indirect branch tracking for user thread.
FWIW the arm64 BTI feature is enabled per page of executable memory rather than in CPU state so it'd be hard for us to adopt this interface. I don't think that's a blocker, just noting it.
Re: [RFC PATCH v1 11/28] riscv: Implementing "PROT_SHADOWSTACK" on riscv
In reply to [email protected]Quoted 11 lines · On Wed, 2024-01-24 at 22:21 -0800, [email protected] wrote:
+ /*
+ *PROT_SHADOWSTACKis a kernel only protection flag on risc- v.
+ * mmap doesn't expectPROT_SHADOWSTACKto be set by user space.
+ * User space can rely onmap_shadow_stacksyscall to create
+ * shadow stack pages.
+ */
+ if (unlikely(prot & PROT_SHADOWSTACK))
+ return-EINVAL;
Are you sure you need PROT_SHADOWSTACK? Since you are passing VM_SHADOW_STACK into do_mmap() directly.
Re: [RFC PATCH v1 15/28] riscv/mm: Implement map_shadow_stack() syscall
In reply to [email protected]Quoted 13 lines · On Wed, 2024-01-24 at 22:21 -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
As discussed extensively in the changelog for the addition of this syscall on x86 ("x86/shstk: Introduce
map_shadow_stacksyscall") the existingmmap()andmadvise()syscalls do not map entirely well onto the
security requirements for guarded control stacks since they lead to windows where memory is allocated but not yet protected or stacks which
are not properly and safely initialised. Instead a new syscallmap_shadow_stack()has been defined which allocates and initialises a shadow stack page.
Quoted 7 lines
This patch implements this syscall for riscv. riscv doesn't require token
to be setup by kernel because user mode can do that by itself. However to
provide compatiblity and portability with other architectues, user mode can
specify token set flag.
A lot of this code look very familiar. We'll have to think about at what point we could pull some of it into the code kernel.
I think if we had an arch write_user_shstk(), most of the code could be shared here.
Re: [RFC PATCH v1 01/28] riscv: abstract envcfg CSR
In reply to [email protected]Quoted 51 lines · On Wed, Jan 24, 2024 at 10:21:26PM -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
This patch abstracts envcfg CSR in kernel (as is done for other homonyn CSRs).
CSR_ENVCFGis used as alias forCSR_SENVCFGorCSR_MENVCFGdepending on how kernel is compiled.Additionally it changes CBZE enabling to start using
CSR_ENVCFGinstead ofCSR_SENVCFG.Signed-off-by Deepak Gupta <[email protected]>--- arch/riscv/include/asm/csr.h | 2 ++ arch/riscv/kernel/cpufeature.c | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-)arch/riscv/include/asm/csr.h +2
-0@@ -415,6 +415,7 @@# define CSR_STATUS CSR_MSTATUS# define CSR_IE CSR_MIE# define CSR_TVEC CSR_MTVEC +# define CSR_ENVCFG CSR_MENVCFG# define CSR_SCRATCH CSR_MSCRATCH# define CSR_EPC CSR_MEPC# define CSR_CAUSE CSR_MCAUSE@@ -439,6 +440,7 @@# define CSR_STATUS CSR_SSTATUS# define CSR_IE CSR_SIE# define CSR_TVEC CSR_STVEC +# define CSR_ENVCFG CSR_SENVCFG# define CSR_SCRATCH CSR_SSCRATCH# define CSR_EPC CSR_SEPC# define CSR_CAUSE CSR_SCAUSEarch/riscv/kernel/cpufeature.c +1
-1@@ -725,7 +725,7 @@ arch_initcall(check_unaligned_access_all_cpus);void riscv_user_isa_enable (void ) {if (riscv_cpu_has_extension_unlikely (smp_processor_id (),RISCV_ISA_EXT_ZICBOZ )) -csr_set (CSR_SENVCFG ,ENVCFG_CBZE ); +csr_set (CSR_ENVCFG ,ENVCFG_CBZE ); }#ifdef CONFIG_RISCV_ALTERNATIVE Signature · 1 line
2.43.0
Re: [RFC PATCH v1 09/28] mm: abstract shadow stack vma behind `arch_is_shadow_stack`
In reply to Deepak GuptaQuoted 50 lines · Deepak Gupta
Quoted 40 lines · David Hildenbrand
Quoted 39 lines · On 25.01.24 07:21, [email protected] wrote:
From: Deepak Gupta <[email protected]>
x86 has used
VM_SHADOW_STACK(alias toVM_HIGH_ARCH_5) to encode shadow stack VMA.VM_SHADOW_STACKis thus not possible on 32bit. Some arches may need a way to encode shadow stack on 32bit and 64bit both and they may encode this information differently in VMAs.This patch changes checks of
VM_SHADOW_STACKflag in generic code to call to a functionarch_is_shadow_stackwhich will return true if arch supports shadow stack and vma is shadow stack else stub returns false.There was a suggestion to name it as
vma_is_shadow_stack. I preferred to keeparchprefix in there because it's each arch specific.Signed-off-by Deepak Gupta <[email protected]>--- include/linux/mm.h | 18 +++++++++++++++++- mm/gup.c | 5 +++-- mm/internal.h | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-)include/linux/mm.h +4
-0@@ -352,6 +352,10 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return (vm_flags &VM_SHADOW_STACK ); +}#endif #ifdef CONFIG_RISCV_USER_CFI @@ -362,10 +366,22 @@ extern unsigned int kobjsize(const void *objp);* with VM_SHARED. */ #define VM_SHADOW_STACK VM_WRITEQuoted 8 lines
include/linux/mm.h extern unsigned int kobjsize(const void *objp); · line 374
Quoted 6 lines
include/linux/mm.h +6
-0+ +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return ((vm_flags & (VM_WRITE |VM_READ |VM_EXEC )) ==VM_WRITE ); +} +Please no such hacks just to work around the 32bit vmflags limitation.
Quoted 3 lines
As I said in another response. Noted.
And if there're no takers for 32bit on riscv (which highly likely is the case) This will go away in next version of patchsets.
Sorry for the (unusually for me) late reply. Simplifying to riscv64 sounds great.
Alternatively, maybe VM_SHADOW_STACK is not even required at all on riscv if we can teach all code to only stare at arch_is_shadow_stack() instead.
... but, just using the same VM_SHADOW_STACK will it all much cleaner. Eventually, we can just stop playing arch-specific games with arch_is_shadow_stack and VM_SHADOW_STACK.
Signature · 3 lines
Cheers, David / dhildenb
Re: [RFC PATCH v1 11/28] riscv: Implementing "PROT_SHADOWSTACK" on riscv
In reply to Edgecombe, Rick PQuoted 13 lines · Rick P
Quoted 11 lines · On Wed, 2024-01-24 at 22:21 -0800, [email protected] wrote:
+ /*
+ *PROT_SHADOWSTACKis a kernel only protection flag on risc- v.
+ * mmap doesn't expectPROT_SHADOWSTACKto be set by user space.
+ * User space can rely onmap_shadow_stacksyscall to create
+ * shadow stack pages.
+ */
+ if (unlikely(prot & PROT_SHADOWSTACK))
+ return-EINVAL;
Quoted 2 lines
Are you sure you need
PROT_SHADOWSTACK? Since you are passingVM_SHADOW_STACKintodo_mmap()directly.
Sorry for (very) late response.
In this patch series since VM_SHADOW_STACK was an alias to VM_WRITE. And that's why I needed PROT_SHADOWSTACK to disambiguate.
I am updating my patches and going with ARCH_5 bit (and thus only 64bit support). So x86, aarch64 and risc-v will be using same bit position.
Re: [RFC PATCH v1 18/28] prctl: arch-agnostic prtcl for indirect branch tracking
In reply to Mark BrownQuoted 15 lines · Mark Brown
Quoted 4 lines · On Wed, Jan 24, 2024 at 10:21:43PM -0800, [email protected] wrote:
To allow userspace to enable this feature for itself, following prtcls are defined:
-PR_GET_INDIR_BR_LP_STATUS: Gets current configured status for indirect branch tracking.Quoted 8 lines
-
PR_SET_INDIR_BR_LP_STATUS: Sets a configuration for indirect branch tracking Following status options are allowed
-PR_INDIR_BR_LP_ENABLE: Enables indirect branch tracking on user thread.
-PR_INDIR_BR_LP_DISABLE; Disables indirect branch tracking on user thread.
-PR_LOCK_INDIR_BR_LP_STATUS: Locks configured status for indirect branch tracking for user thread.
Quoted 3 lines
FWIW the arm64 BTI feature is enabled per page of executable memory rather than in CPU state so it'd be hard for us to adopt this interface. I don't think that's a blocker, just noting it.
Got it, makes sense.
Re: [RFC PATCH v1 15/28] riscv/mm: Implement map_shadow_stack() syscall
In reply to Mark BrownQuoted 11 lines · Mark Brown
Quoted 8 lines · On Wed, Jan 24, 2024 at 10:21:40PM -0800, [email protected] wrote:
As discussed extensively in the changelog for the addition of this syscall on x86 ("x86/shstk: Introduce
map_shadow_stacksyscall") the existingmmap()andmadvise()syscalls do not map entirely well onto the security requirements for guarded control stacks since they lead to windows where memory is allocated but not yet protected or stacks which are not properly and safely initialised. Instead a new syscallmap_shadow_stack()has been defined which allocates and initialises a shadow stack page.
Quoted 2 lines
While I agree that this is very well written you probably want to update the references to guarded control stacks to whatever the RISC-V term is :P
Noted. I'll do that in next patchset.
Quoted 7 lines
Quoted 7 lines
include/uapi/asm-generic/mman.h +0
-0@@ -19,4 +19,5 @@#define MCL_FUTURE 2/* lock all future mappings */ #define MCL_ONFAULT 4/* lock all pages that are faulted in */
Quoted 7 lines
include/uapi/asm-generic/mman.h line 23
Quoted 2 lines
include/uapi/asm-generic/mman.h +1
-0+#define SHADOW_STACK_SET_TOKEN (1ULL << 0)/* Set up a restore token in the shadow stack */ #endif /* __ASM_GENERIC_MMAN_H */ For arm64 I also added a
SHADOW_STACK_SET_MARKERfor adding a top of stack marker, did you have any thoughts on that for RISC-V? I think x86 were considering adding it too, it'd be good if we could get things consistent.
Please correct me on this. A token at the top which can't be consumed to restore but *just* purely as marker, right?
It's a good design basic with not a lot of cost.
I think risc-v should be able to converge on that.
Re: [RFC PATCH v1 15/28] riscv/mm: Implement map_shadow_stack() syscall
In reply to Edgecombe, Rick PQuoted 22 lines · Rick P
Quoted 13 lines · On Wed, 2024-01-24 at 22:21 -0800, [email protected] wrote:
From: Deepak Gupta <[email protected]>
As discussed extensively in the changelog for the addition of this syscall on x86 ("x86/shstk: Introduce
map_shadow_stacksyscall") the existingmmap()andmadvise()syscalls do not map entirely well onto the
security requirements for guarded control stacks since they lead to windows where memory is allocated but not yet protected or stacks which
are not properly and safely initialised. Instead a new syscallmap_shadow_stack()has been defined which allocates and initialises a shadow stack page.Quoted 7 lines
This patch implements this syscall for riscv. riscv doesn't require token
to be setup by kernel because user mode can do that by itself. However to
provide compatiblity and portability with other architectues, user mode can
specify token set flag.
Quoted 5 lines
A lot of this code look very familiar. We'll have to think about at what point we could pull some of it into the code kernel.
I think if we had an arch
write_user_shstk(), most of the code could be shared here.
Yes it is. I'll think a little bit more on this on next set of patchsets when I send.
Re: [RFC PATCH v1 09/28] mm: abstract shadow stack vma behind `arch_is_shadow_stack`
In reply to David HildenbrandQuoted 51 lines · David Hildenbrand
Quoted 50 lines · Deepak Gupta
Quoted 48 lines · David Hildenbrand
Quoted 36 lines · On 25.01.24 07:21, [email protected] wrote:
From: Deepak Gupta <[email protected]>
x86 has used
VM_SHADOW_STACK(alias toVM_HIGH_ARCH_5) to encode shadow stack VMA.VM_SHADOW_STACKis thus not possible on 32bit. Some arches may need a way to encode shadow stack on 32bit and 64bit both and they may encode this information differently in VMAs.This patch changes checks of
VM_SHADOW_STACKflag in generic code to call to a functionarch_is_shadow_stackwhich will return true if arch supports shadow stack and vma is shadow stack else stub returns false.There was a suggestion to name it as
vma_is_shadow_stack. I preferred to keeparchprefix in there because it's each arch specific.Signed-off-by Deepak Gupta <[email protected]>--- include/linux/mm.h | 18 +++++++++++++++++- mm/gup.c | 5 +++-- mm/internal.h | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-)include/linux/mm.h +4
-0@@ -352,6 +352,10 @@ extern unsigned int kobjsize(const void *objp);* for more details on the guard size. */ # define VM_SHADOW_STACK VM_HIGH_ARCH_5 +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return (vm_flags &VM_SHADOW_STACK ); +}#endif #ifdef CONFIG_RISCV_USER_CFI include/linux/mm.h extern unsigned int kobjsize(const void *objp); · line 374
Quoted 9 lines
include/linux/mm.h +6
-0@@ -362,10 +366,22 @@ extern unsigned int kobjsize(const void *objp);* with VM_SHARED. */ #define VM_SHADOW_STACK VM_WRITE + +static inline bool arch_is_shadow_stack (vm_flags_t vm_flags) +{ +return ((vm_flags & (VM_WRITE |VM_READ |VM_EXEC )) ==VM_WRITE ); +} +Please no such hacks just to work around the 32bit vmflags limitation.
Quoted 7 lines
Quoted 3 lines
As I said in another response. Noted.
And if there're no takers for 32bit on riscv (which highly likely is the case) This will go away in next version of patchsets.Sorry for the (unusually for me) late reply. Simplifying to riscv64 sounds great.
Alternatively, maybe
VM_SHADOW_STACKis not even required at all on riscv if we can teach all code to only stare atarch_is_shadow_stack()instead.
Sorry for late reply.
I think for risc-v this can be done, if done in following way
static inline bool arch_is_shadow_stack(struct vm_flags_t vm_flags)
{
return (vm_get_page_prot(vm_flags) == PAGE_SHADOWSTACK);
}But doing above will require following
- Inventing a new PROT_XXX type (let's call it PROT_SHADOWSTACK) that is only exposed to kernel. PROT_SHADOWSTACK protection flag would allow do_mmap to do right thing and setup appropriate protection perms. We wouldn't want to expose this protection type to user mode (because map_shadow_stack already exists for that).
Current patch series uses PROT_SHADOWSTACK because VM_SHADOW_STACK was aliased to VM_WRITE.
- As you said teach all the generic code as well to use arch_is_shadow_stack which might become complicated (can't say for sure)
Quoted 2 lines
... but, just using the same
VM_SHADOW_STACKwill it all much cleaner. Eventually, we can just stop playing arch-specific games witharch_is_shadow_stackandVM_SHADOW_STACK.
Yeah for now, looks like easier thing to do.
Quoted 6 lines
Signature · 4 lines
-- Cheers, David / dhildenb
Re: [RFC PATCH v1 15/28] riscv/mm: Implement map_shadow_stack() syscall
In reply to Deepak GuptaQuoted 11 lines · Deepak Gupta
Quoted 6 lines · Mark Brown
Quoted 1 line
+#define
SHADOW_STACK_SET_TOKEN(1ULL << 0) /* Set up a restore token in the shadow stack */For arm64 I also added a
SHADOW_STACK_SET_MARKERfor adding a top of stack marker, did you have any thoughts on that for RISC-V? I think x86 were considering adding it too, it'd be good if we could get things consistent.Please correct me on this. A token at the top which can't be consumed to restore but *just* purely as marker, right?
Yes, for arm64 we just leave a zero word (which can't be a valid token) above the stack switch token, that does mean you can't exactly tell that the top of stack marker is there unless there's also a stack switch token below it.
Quoted 3 lines
It's a good design basic with not a lot of cost.
I think risc-v should be able to converge on that.
Great.