Skip to contentSkip to conversation

riscv control-flow integrity for usermode

PATCH Superseded Deepak Gupta 8 participants 46 messages Sep 12, 2024 – Sep 17, 2024

Subsystems (15)

v4 of 16 Superseded Latest is v16 →

lore
Share & tools
lore
#0 lore raw

v4 cover riscv control-flow integrity for usermode

v4 for cpu assisted riscv user mode control flow integrity. zicfiss and zicfilp [1] are ratified riscv CPU extensions.

v3 [2] was sent in April this year for riscv usermode control flow integrity enabling.

To get more information on zicfilp and zicfiss riscv CPU extensions, patch series adds documentation for zicfilp and zicfiss Documentation/arch/riscv/zicfiss.rst Documentation/arch/riscv/zicfilp.rst

Additionally, spec can be obtained from [1].

How to test this series
=======================

Toolchain
---------

$ git clone [email protected]:sifive/riscv-gnu-toolchain.git -b cfi-dev
$ riscv-gnu-toolchain/configure --prefix=<path-to-where-to-build> --with-arch=rv64gc_zicfilp_zicfiss --enable-linux --disable-gdb  --with-extra-multilib-test="rv64gc_zicfilp_zicfiss-lp64d:-static"
$ make -j$(nproc)

Qemu
----

$ git clone [email protected]:deepak0414/qemu.git -b zicfilp_zicfiss_ratified_master_july11
$ cd qemu
$ mkdir build
$ cd build
$ ../configure --target-list=riscv64-softmmu
$ make -j$(nproc)

Opensbi
-------

$ git clone [email protected]:deepak0414/opensbi.git -b cfi_spec_split_opensbi
$ make CROSS_COMPILE=<your riscv toolchain> -j$(nproc) PLATFORM=generic

Linux
-----
Running defconfig is fine. CFI is enabled by default if the toolchain supports it.

$ make ARCH=riscv CROSS_COMPILE=<path-to-cfi-riscv-gnu-toolchain>/build/bin/riscv64-unknown-linux-gnu- -j$(nproc) defconfig
$ make ARCH=riscv CROSS_COMPILE=<path-to-cfi-riscv-gnu-toolchain>/build/bin/riscv64-unknown-linux-gnu- -j$(nproc)

Running
-------

Modify your qemu command to have:
-bios <path-to-cfi-opensbi>/build/platform/generic/firmware/fw_dynamic.bin -cpu rv64,zicfilp=true,zicfiss=true,zimop=true,zcmop=true

vDSO related Opens (in the flux)
=================================

I am listing these opens for laying out plan and what to expect in future patch sets. And of course for the sake of discussion.

Shadow stack and landing pad enabling in vDSO
----------------------------------------------
vDSO must have shadow stack and landing pad support compiled in for task to have shadow stack and landing pad support. This patch series doesn't enable that (yet). Enabling shadow stack support in vDSO should be straight forward (intend to do that in next versions of patch set). Enabling landing pad support in vDSO requires some collaboration with toolchain folks to follow a single label scheme for all object binaries. This is necessary to ensure that all indirect call-sites are setting correct label and target landing pads are decorated with same label scheme.

How many vDSOs
---------------
Shadow stack instructions are carved out of zimop (may be operations) and if CPU doesn't implement zimop, they're illegal instructions. Kernel could be running on a CPU which may or may not implement zimop. And thus kernel will have to carry 2 different vDSOs and expose the appropriate one depending on whether CPU implements zimop or not.

[1] - https://github.com/riscv/riscv-cfi
[2] - https://lore.kernel.org/lkml/[email protected]/

---
changelog
---------

v4
--
- rebased on 6.11-rc6
- envcfg: Converged with Samuel Holland's patches for envcfg management on per- thread basis.
- vma_is_shadow_stack is renamed to is_vma_shadow_stack
- picked up Mark Brown's ARCH_HAS_USER_SHADOW_STACK patch
- signal context: using extended context management to maintain compatibility.
- fixed -Wmissing-prototypes compiler warnings for prctl functions
- Documentation fixes and amending typos.

v3
--
envcfg:
logic to pick up base envcfg had a bug where ENVCFG_CBZE could have been picked on per task basis, even though CPU didn't implement it. Fixed in this series.

dt-bindings:
As suggested, split into separate commit. fixed the messaging that spec is in public review

arch_is_shadow_stack change:
arch_is_shadow_stack changed to vma_is_shadow_stack

hwprobe:
zicfiss / zicfilp if present will get enumerated in hwprobe

selftests:
As suggested, added object and binary filenames to .gitignore Selftest binary anyways need to be compiled with cfi enabled compiler which will make sure that landing pad and shadow stack are enabled. Thus removed separate enable/disable tests. Cleaned up tests a bit.

v2
--

- 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

- This patch series introduces arch agnostic prctls to enable shadow stack and indirect branch tracking. And implements them on riscv.

Deepak Gupta (25):
mm: helper is_shadow_stack_vma to check shadow stack vma riscv/Kconfig: enable HAVE_EXIT_THREAD for riscv
riscv: zicfilp / zicfiss in dt-bindings (extensions.yaml)
riscv: zicfiss / zicfilp enumeration
riscv: zicfiss / zicfilp extension csr and bit definitions
riscv: usercfi state for task and save/restore of CSR_SSP on trap
entry/exit
riscv/mm : ensure PROT_WRITE leads to VM_READ | VM_WRITE 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 prctl for indirect branch tracking
riscv: Implements arch agnostic shadow stack prctls
riscv: Implements arch agnostic indirect branch tracking prctls riscv/traps: Introduce software check exception
riscv sigcontext: cfi state struct definition for sigcontext riscv signal: save and restore of shadow stack for signal riscv/kernel: update __show_regs to print shadow stack register riscv/ptrace: riscv cfi status and state via ptrace and in core files riscv/hwprobe: zicfilp / zicfiss enumeration in hwprobe
riscv: create a config for shadow stack and landing pad instr support
riscv: Documentation for landing pad / indirect branch tracking
riscv: Documentation for shadow stack on riscv kselftest/riscv: kselftest for user mode cfi

Mark Brown (2):
mm: Introduce ARCH_HAS_USER_SHADOW_STACK
prctl: arch-agnostic prctl for shadow stack

Samuel Holland (3):
riscv: Enable cbo.zero only when all harts support Zicboz
riscv: Add support for per-thread envcfg CSR values
riscv: Call riscv_user_isa_enable() only on the boot hart

 Documentation/arch/riscv/zicfilp.rst          | 104 ++++
 Documentation/arch/riscv/zicfiss.rst          | 169 ++++++
 .../devicetree/bindings/riscv/extensions.yaml |  12 +
 arch/riscv/Kconfig                            |  20 +
 arch/riscv/include/asm/asm-prototypes.h       |   1 +
 arch/riscv/include/asm/cpufeature.h           |  15 +-
 arch/riscv/include/asm/csr.h                  |  16 +
 arch/riscv/include/asm/entry-common.h         |   2 +
 arch/riscv/include/asm/hwcap.h                |   2 +
 arch/riscv/include/asm/mman.h                 |  24 +
 arch/riscv/include/asm/pgtable.h              |  30 +-
 arch/riscv/include/asm/processor.h            |   2 +
 arch/riscv/include/asm/switch_to.h            |   8 +
 arch/riscv/include/asm/thread_info.h          |   4 +
 arch/riscv/include/asm/usercfi.h              | 142 +++++
 arch/riscv/include/uapi/asm/hwprobe.h         |   2 +
 arch/riscv/include/uapi/asm/ptrace.h          |  18 +
 arch/riscv/include/uapi/asm/sigcontext.h      |   3 +
 arch/riscv/kernel/Makefile                    |   2 +
 arch/riscv/kernel/asm-offsets.c               |   4 +
 arch/riscv/kernel/cpufeature.c                |  13 +-
 arch/riscv/kernel/entry.S                     |  29 +
 arch/riscv/kernel/process.c                   |  32 +-
 arch/riscv/kernel/ptrace.c                    |  83 +++
 arch/riscv/kernel/signal.c                    |  62 ++-
 arch/riscv/kernel/smpboot.c                   |   2 -
 arch/riscv/kernel/suspend.c                   |   4 +-
 arch/riscv/kernel/sys_hwprobe.c               |   2 +
 arch/riscv/kernel/sys_riscv.c                 |  10 +
 arch/riscv/kernel/traps.c                     |  38 ++
 arch/riscv/kernel/usercfi.c                   | 506 ++++++++++++++++++
 arch/riscv/mm/init.c                          |   2 +-
 arch/riscv/mm/pgtable.c                       |  17 +
 arch/x86/Kconfig                              |   1 +
 fs/proc/task_mmu.c                            |   2 +-
 include/linux/cpu.h                           |   4 +
 include/linux/mm.h                            |  12 +-
 include/uapi/asm-generic/mman.h               |   1 +
 include/uapi/linux/elf.h                      |   1 +
 include/uapi/linux/prctl.h                    |  48 ++
 kernel/sys.c                                  |  60 +++
 mm/Kconfig                                    |   6 +
 mm/gup.c                                      |   2 +-
 mm/internal.h                                 |   2 +-
 mm/mmap.c                                     |   1 +
 tools/testing/selftests/riscv/Makefile        |   2 +-
 tools/testing/selftests/riscv/cfi/.gitignore  |   3 +
 tools/testing/selftests/riscv/cfi/Makefile    |  10 +
 .../testing/selftests/riscv/cfi/cfi_rv_test.h |  83 +++
 .../selftests/riscv/cfi/riscv_cfi_test.c      |  82 +++
 .../testing/selftests/riscv/cfi/shadowstack.c | 362 +++++++++++++
 .../testing/selftests/riscv/cfi/shadowstack.h |  37 ++
 52 files changed, 2079 insertions(+), 20 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/.gitignore
 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.45.0
#1 lore raw

PATCH v4 1/30 mm: Introduce ARCH_HAS_USER_SHADOW_STACK

From: Mark Brown <[email protected]>

Since multiple architectures have support for shadow stacks and we need to select support for this feature in several places in the generic code provide a generic config option that the architectures can select.

---
 arch/x86/Kconfig   | 1 +
 fs/proc/task_mmu.c | 2 +-
 include/linux/mm.h | 2 +-
 mm/Kconfig         | 6 ++++++
 4 files changed, 9 insertions(+), 2 deletions(-)
arch/x86/Kconfig +1 -0
index 007bab9f2a0e..320e1f411163 100644
@@ -1957,6 +1957,7 @@ config X86_USER_SHADOW_STACK
 	depends on AS_WRUSS
 	depends on X86_64
 	select ARCH_USES_HIGH_VMA_FLAGS
+	select ARCH_HAS_USER_SHADOW_STACK
 	select X86_CET
 	help
 	  Shadow stack protection is a hardware feature that detects function
fs/proc/task_mmu.c +1 -1
index 5f171ad7b436..0ea49725f524 100644
@@ -984,7 +984,7 @@ static void show_smap_vma_flags(struct seq_file *m, struct vm_area_struct *vma)
 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
 		[ilog2(VM_UFFD_MINOR)]	= "ui",
 #endif /* CONFIG_HAVE_ARCH_USERFAULTFD_MINOR */
-#ifdef CONFIG_X86_USER_SHADOW_STACK
+#ifdef CONFIG_ARCH_HAS_USER_SHADOW_STACK
 		[ilog2(VM_SHADOW_STACK)] = "ss",
 #endif
 #ifdef CONFIG_64BIT
include/linux/mm.h +1 -1
index 147073601716..e39796ea17db 100644
@@ -346,7 +346,7 @@ extern unsigned int kobjsize(const void *objp);
 #endif
 #endif /* CONFIG_ARCH_HAS_PKEYS */
 
-#ifdef CONFIG_X86_USER_SHADOW_STACK
+#ifdef CONFIG_ARCH_HAS_USER_SHADOW_STACK
 /*
  * VM_SHADOW_STACK should not be set with VM_SHARED because of lack of
  * support core mm.
mm/Kconfig +6 -0
index b72e7d040f78..3167be663bca 100644
@@ -1263,6 +1263,12 @@ config IOMMU_MM_DATA
 config EXECMEM
 	bool
 
+config ARCH_HAS_USER_SHADOW_STACK
+	bool
+	help
+	  The architecture has hardware support for userspace shadow call
+          stacks (eg, x86 CET, arm64 GCS or RISC-V Zicfiss).
+
 source "mm/damon/Kconfig"
 
 endmenu
Signature · 1 line
2.45.0
#3 lore raw

PATCH v4 2/30 mm: helper `is_shadow_stack_vma` to check shadow stack vma

In reply to Deepak Gupta

VM_SHADOW_STACK (alias to VM_HIGH_ARCH_5) is used to encode shadow stack VMA on three architectures (x86 shadow stack, arm GCS and RISC-V shadow stack). In case architecture doesn't implement shadow stack, it's VM_NONE Introducing a helper is_shadow_stack_vma to determine shadow stack vma or not.

---
 include/linux/mm.h | 7 ++++++-
 mm/gup.c           | 2 +-
 mm/internal.h      | 2 +-
 3 files changed, 8 insertions(+), 3 deletions(-)
include/linux/mm.h +6 -1
index e39796ea17db..f0dc94fb782a 100644
@@ -361,6 +361,11 @@ extern unsigned int kobjsize(const void *objp);
 # define VM_SHADOW_STACK	VM_NONE
 #endif
 
+static inline bool is_shadow_stack_vma(vm_flags_t vm_flags)
+{
+	return !!(vm_flags & VM_SHADOW_STACK);
+}
+
 #if defined(CONFIG_X86)
 # define VM_PAT		VM_ARCH_1	/* PAT reserves whole VMA at once (x86) */
 #elif defined(CONFIG_PPC)
@@ -3504,7 +3509,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 (is_shadow_stack_vma(vma->vm_flags))
 		return PAGE_SIZE;
 
 	return 0;
mm/gup.c +1 -1
index 54d0dc3831fb..2f84a0a80cfe 100644
@@ -1289,7 +1289,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) || is_shadow_stack_vma(vm_flags)) {
 			if (!(gup_flags & FOLL_FORCE))
 				return -EFAULT;
 			/* hugetlb does not support FOLL_FORCE|FOLL_WRITE. */
mm/internal.h +1 -1
index b4d86436565b..f7732c793f3f 100644
@@ -798,7 +798,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) || is_shadow_stack_vma(flags);
 }
 
 /*
Signature · 1 line
2.45.0
#4 lore raw

PATCH v4 3/30 riscv: Enable cbo.zero only when all harts support Zicboz

In reply to Deepak Gupta

From: Samuel Holland <[email protected]>

Currently, we enable cbo.zero for usermode on each hart that supports the Zicboz extension. This means that the [ms]envcfg CSR value may differ between harts. Other features, such as pointer masking and CFI, require setting [ms]envcfg bits on a per-thread basis. The combination of these two adds quite some complexity and overhead to context switching, as we would need to maintain two separate masks for the per-hart and per-thread bits. Andrew Jones, who originally added Zicboz support, writes[1][2]:

I've approached Zicboz the same way I would approach all extensions, which is to be per-hart. I'm not currently aware of a platform that is / will be composed of harts where some have Zicboz and others don't, but there's nothing stopping a platform like that from being built.

So, how about we add code that confirms Zicboz is on all harts. If any hart does not have it, then we complain loudly and disable it on all the other harts. If it was just a hardware description bug, then it'll get fixed. If there's actually a platform which doesn't have Zicboz on all harts, then, when the issue is reported, we can decide to not support it, support it with defconfig, or support it under a Kconfig guard which must be enabled by the user.

Let's follow his suggested solution and require the extension to be available on all harts, so the envcfg CSR value does not need to change when a thread migrates between harts. Since we are doing this for all extensions with fields in envcfg, the CSR itself only needs to be saved/ restored when it is present on all harts.

This should not be a regression as no known hardware has asymmetric Zicboz support, but if anyone reports seeing the warning, we will re-evaluate our solution.

---
 arch/riscv/kernel/cpufeature.c | 7 ++++++-
 arch/riscv/kernel/suspend.c    | 4 ++--
 2 files changed, 8 insertions(+), 3 deletions(-)
arch/riscv/kernel/cpufeature.c +6 -1
index b427188b28fc..0139d4ea8426 100644
@@ -28,6 +28,8 @@
 
 #define NUM_ALPHA_EXTS ('z' - 'a' + 1)
 
+static bool any_cpu_has_zicboz;
+
 unsigned long elf_hwcap __read_mostly;
 
 /* Host ISA bitmap */
@@ -98,6 +100,7 @@ static int riscv_ext_zicboz_validate(const struct riscv_isa_ext_data *data,
 		pr_err("Zicboz disabled as cboz-block-size present, but is not a power-of-2\n");
 		return -EINVAL;
 	}
+	any_cpu_has_zicboz = true;
 	return 0;
 }
 
@@ -918,8 +921,10 @@ unsigned long riscv_get_elf_hwcap(void)
 
 void riscv_user_isa_enable(void)
 {
-	if (riscv_cpu_has_extension_unlikely(smp_processor_id(), RISCV_ISA_EXT_ZICBOZ))
+	if (riscv_has_extension_unlikely(RISCV_ISA_EXT_ZICBOZ))
 		csr_set(CSR_ENVCFG, ENVCFG_CBZE);
+	else if (any_cpu_has_zicboz)
+		pr_warn_once("Zicboz disabled as it is unavailable on some harts\n");
 }
 
 #ifdef CONFIG_RISCV_ALTERNATIVE
arch/riscv/kernel/suspend.c +2 -2
index c8cec0cc5833..9a8a0dc035b2 100644
@@ -14,7 +14,7 @@
 
 void suspend_save_csrs(struct suspend_context *context)
 {
-	if (riscv_cpu_has_extension_unlikely(smp_processor_id(), RISCV_ISA_EXT_XLINUXENVCFG))
+	if (riscv_has_extension_unlikely(RISCV_ISA_EXT_XLINUXENVCFG))
 		context->envcfg = csr_read(CSR_ENVCFG);
 	context->tvec = csr_read(CSR_TVEC);
 	context->ie = csr_read(CSR_IE);
@@ -37,7 +37,7 @@ void suspend_save_csrs(struct suspend_context *context)
 void suspend_restore_csrs(struct suspend_context *context)
 {
 	csr_write(CSR_SCRATCH, 0);
-	if (riscv_cpu_has_extension_unlikely(smp_processor_id(), RISCV_ISA_EXT_XLINUXENVCFG))
+	if (riscv_has_extension_unlikely(RISCV_ISA_EXT_XLINUXENVCFG))
 		csr_write(CSR_ENVCFG, context->envcfg);
 	csr_write(CSR_TVEC, context->tvec);
 	csr_write(CSR_IE, context->ie);
Signature · 1 line
2.45.0
#5 lore raw

PATCH v4 4/30 riscv: Add support for per-thread envcfg CSR values

In reply to Deepak Gupta

From: Samuel Holland <[email protected]>

Some bits in the [ms]envcfg CSR, such as the CFI state and pointer masking mode, need to be controlled on a per-thread basis. Support this by keeping a copy of the CSR value in struct thread_struct and writing it during context switches. It is safe to discard the old CSR value during the context switch because the CSR is modified only by software, so the CSR will remain in sync with the copy in thread_struct.

Use ALTERNATIVE directly instead of riscv_has_extension_unlikely() to minimize branchiness in the context switching code.

Since thread_struct is copied during fork(), setting the value for the init task sets the default value for all other threads.

---
 arch/riscv/include/asm/switch_to.h   | 8 ++++++++
 arch/riscv/include/asm/thread_info.h | 1 +
 arch/riscv/kernel/cpufeature.c       | 2 +-
 3 files changed, 10 insertions(+), 1 deletion(-)
arch/riscv/include/asm/switch_to.h +8 -0
index 7594df37cc9f..dd4a36ff4356 100644
@@ -70,6 +70,13 @@ static __always_inline bool has_fpu(void) { return false; }
 #define __switch_to_fpu(__prev, __next) do { } while (0)
 #endif
 
+static inline void __switch_to_envcfg(struct task_struct *next)
+{
+	asm volatile (ALTERNATIVE("nop", "csrw " __stringify(CSR_ENVCFG) ", %0",
+				  0, RISCV_ISA_EXT_XLINUXENVCFG, 1)
+			:: "r" (next->thread_info.envcfg) : "memory");
+}
+
 extern struct task_struct *__switch_to(struct task_struct *,
 				       struct task_struct *);
 
@@ -103,6 +110,7 @@ do {							\
 		__switch_to_vector(__prev, __next);	\
 	if (switch_to_should_flush_icache(__next))	\
 		local_flush_icache_all();		\
+	__switch_to_envcfg(__next);			\
 	((last) = __switch_to(__prev, __next));		\
 } while (0)
 
arch/riscv/include/asm/thread_info.h +1 -0
index fca5c6be2b81..c74536194626 100644
@@ -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/cpufeature.c +1 -1
index 0139d4ea8426..f7fcd23d55de 100644
@@ -922,7 +922,7 @@ unsigned long riscv_get_elf_hwcap(void)
 void riscv_user_isa_enable(void)
 {
 	if (riscv_has_extension_unlikely(RISCV_ISA_EXT_ZICBOZ))
-		csr_set(CSR_ENVCFG, ENVCFG_CBZE);
+		current->thread_info.envcfg |= ENVCFG_CBZE;
 	else if (any_cpu_has_zicboz)
 		pr_warn_once("Zicboz disabled as it is unavailable on some harts\n");
 }
Signature · 1 line
2.45.0
#6 lore raw

PATCH v4 5/30 riscv: Call riscv_user_isa_enable() only on the boot hart

In reply to Deepak Gupta

From: Samuel Holland <[email protected]>

Now that the [ms]envcfg CSR value is maintained per thread, not per hart, riscv_user_isa_enable() only needs to be called once during boot, to set the value for the init task. This also allows it to be marked as __init.

---
 arch/riscv/include/asm/cpufeature.h | 2 +-
 arch/riscv/kernel/cpufeature.c      | 4 ++--
 arch/riscv/kernel/smpboot.c         | 2 --
 3 files changed, 3 insertions(+), 5 deletions(-)
arch/riscv/include/asm/cpufeature.h +1 -1
index 45f9c1171a48..ce9a995730c1 100644
@@ -31,7 +31,7 @@ DECLARE_PER_CPU(struct riscv_cpuinfo, riscv_cpuinfo);
 /* Per-cpu ISA extensions. */
 extern struct riscv_isainfo hart_isa[NR_CPUS];
 
-void riscv_user_isa_enable(void);
+void __init riscv_user_isa_enable(void);
 
 #define _RISCV_ISA_EXT_DATA(_name, _id, _subset_exts, _subset_exts_size, _validate) {	\
 	.name = #_name,									\
arch/riscv/kernel/cpufeature.c +2 -2
index f7fcd23d55de..41fd0be25bd8 100644
@@ -919,12 +919,12 @@ unsigned long riscv_get_elf_hwcap(void)
 	return hwcap;
 }
 
-void riscv_user_isa_enable(void)
+void __init riscv_user_isa_enable(void)
 {
 	if (riscv_has_extension_unlikely(RISCV_ISA_EXT_ZICBOZ))
 		current->thread_info.envcfg |= ENVCFG_CBZE;
 	else if (any_cpu_has_zicboz)
-		pr_warn_once("Zicboz disabled as it is unavailable on some harts\n");
+		pr_warn("Zicboz disabled as it is unavailable on some harts\n");
 }
 
 #ifdef CONFIG_RISCV_ALTERNATIVE
arch/riscv/kernel/smpboot.c +0 -2
index 0f8f1c95ac38..e36d20205bd7 100644
@@ -233,8 +233,6 @@ asmlinkage __visible void smp_callin(void)
 	numa_add_cpu(curr_cpuid);
 	set_cpu_online(curr_cpuid, true);
 
-	riscv_user_isa_enable();
-
 	/*
 	 * Remote cache and TLB flushes are ignored while the CPU is offline,
 	 * so flush them both right now just in case.
Signature · 1 line
2.45.0
#7 lore raw

PATCH v4 6/30 riscv/Kconfig: enable HAVE_EXIT_THREAD for riscv

In reply to Deepak Gupta

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
index 0f3cd7c3a436..d1d629a3eb91 100644
@@ -177,6 +177,7 @@ config RISCV
 	select HAVE_SAMPLE_FTRACE_DIRECT_MULTI
 	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
index e4bc61c4e58a..9b66dc07c3d2 100644
@@ -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)
+{
+
+}
+
 int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
 {
 	unsigned long clone_flags = args->flags;
Signature · 1 line
2.45.0
#8 lore raw

PATCH v4 7/30 riscv: zicfilp / zicfiss in dt-bindings (extensions.yaml)

In reply to Deepak Gupta

Make an entry for cfi extensions in extensions.yaml.

---
 .../devicetree/bindings/riscv/extensions.yaml        | 12 ++++++++++++
 1 file changed, 12 insertions(+)
Documentation/devicetree/bindings/riscv/extensions.yaml +12 -0
index a06dbc6b4928..b7c86fb91984 100644
@@ -361,6 +361,18 @@ properties:
             The standard Zicboz extension for cache-block zeroing as ratified
             in commit 3dd606f ("Create cmobase-v1.0.pdf") of riscv-CMOs.
 
+        - const: zicfilp
+          description:
+            The standard Zicfilp extension for enforcing forward edge control-flow
+            integrity as ratified in commit 3f8e450 ("merge pull request #227 from
+            ved-rivos/0709") of riscv-cfi github repo.
+
+        - const: zicfiss
+          description:
+            The standard Zicfilp extension for enforcing forward edge control-flow
+            integrity as ratified in commit 3f8e450 ("merge pull request #227 from
+            ved-rivos/0709") of riscv-cfi github repo.
+
         - const: zicntr
           description:
             The standard Zicntr extension for base counters and timers, as
Signature · 1 line
2.45.0
#11 lore raw

PATCH v4 8/30 riscv: zicfiss / zicfilp enumeration

In reply to Deepak Gupta

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 | 13 +++++++++++++
 arch/riscv/include/asm/hwcap.h      |  2 ++
 arch/riscv/include/asm/processor.h  |  1 +
 arch/riscv/kernel/cpufeature.c      |  2 ++
 4 files changed, 18 insertions(+)
arch/riscv/include/asm/cpufeature.h +13 -0
index ce9a995730c1..344b8e8cd3e8 100644
@@ -8,6 +8,7 @@
 
 #include <linux/bitmap.h>
 #include <linux/jump_label.h>
+#include <linux/smp.h>
 #include <asm/hwcap.h>
 #include <asm/alternative-macros.h>
 #include <asm/errno.h>
@@ -180,4 +181,16 @@ 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)
+{
+	return (IS_ENABLED(CONFIG_RISCV_USER_CFI) &&
+		    riscv_cpu_has_extension_unlikely(smp_processor_id(), RISCV_ISA_EXT_ZICFISS));
+}
+
+static inline bool cpu_supports_indirect_br_lp_instr(void)
+{
+	return (IS_ENABLED(CONFIG_RISCV_USER_CFI) &&
+		    riscv_cpu_has_extension_unlikely(smp_processor_id(), RISCV_ISA_EXT_ZICFILP));
+}
+
 #endif
arch/riscv/include/asm/hwcap.h +2 -0
index 5a0bd27fd11a..04425476526a 100644
@@ -92,6 +92,8 @@
 #define RISCV_ISA_EXT_ZCF		83
 #define RISCV_ISA_EXT_ZCMOP		84
 #define RISCV_ISA_EXT_ZAWRS		85
+#define RISCV_ISA_EXT_ZICFILP		86
+#define RISCV_ISA_EXT_ZICFISS		87
 
 #define RISCV_ISA_EXT_XLINUXENVCFG	127
 
arch/riscv/include/asm/processor.h +1 -0
index 8702b8721a27..d61587964bd7 100644
@@ -13,6 +13,7 @@
 #include <vdso/processor.h>
 
 #include <asm/ptrace.h>
+#include <asm/hwcap.h>
 
 /*
  * addr is a hint to the maximum userspace address that mmap should provide, so
arch/riscv/kernel/cpufeature.c +2 -0
index 41fd0be25bd8..ae6ea2f1d1db 100644
@@ -317,6 +317,8 @@ const struct riscv_isa_ext_data riscv_isa_ext[] = {
 					  riscv_ext_zicbom_validate),
 	__RISCV_ISA_EXT_SUPERSET_VALIDATE(zicboz, RISCV_ISA_EXT_ZICBOZ, riscv_xlinuxenvcfg_exts,
 					  riscv_ext_zicboz_validate),
+	__RISCV_ISA_EXT_SUPERSET(zicfilp, RISCV_ISA_EXT_ZICFILP, riscv_xlinuxenvcfg_exts),
+	__RISCV_ISA_EXT_SUPERSET(zicfiss, RISCV_ISA_EXT_ZICFISS, riscv_xlinuxenvcfg_exts),
 	__RISCV_ISA_EXT_DATA(zicntr, RISCV_ISA_EXT_ZICNTR),
 	__RISCV_ISA_EXT_DATA(zicond, RISCV_ISA_EXT_ZICOND),
 	__RISCV_ISA_EXT_DATA(zicsr, RISCV_ISA_EXT_ZICSR),
Signature · 1 line
2.45.0
#12 lore raw

PATCH v4 9/30 riscv: zicfiss / zicfilp extension csr and bit definitions

In reply to Deepak Gupta

zicfiss and zicfilp extension gets enabled via b3 and b2 in *envcfg CSR. menvcfg controls enabling for S/HS mode. henvcfg control enabling for VS while senvcfg controls enabling for U/VU mode.

zicfilp extension extends *status 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
index 25966995da04..af7ed9bedaee 100644
@@ -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)
@@ -197,6 +206,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)
@@ -215,6 +226,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.45.0
#13 lore raw

PATCH v4 10/30 riscv: usercfi state for task and save/restore of CSR_SSP on trap entry/exit

In reply to Deepak Gupta

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)

Shadow stack save/restore is gated on feature availiblity and implemented using alternative. CSR can be context switched in switch_to as well but soon as kernel shadow stack support gets rolled in, shadow stack pointer will need to be switched at trap entry/exit point (much like sp). It can be argued that kernel using shadow stack deployment scenario may not be as prevalant as user mode using this feature. But even if there is some minimal deployment of kernel shadow stack, that means that it needs to be supported. And thus save/restore of shadow stack pointer in entry.S instead of in switch_to.h.

---
 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      |  4 ++++
 arch/riscv/kernel/entry.S            | 26 ++++++++++++++++++++++++++
 5 files changed, 58 insertions(+)
 create mode 100644 arch/riscv/include/asm/usercfi.h
arch/riscv/include/asm/processor.h +1 -0
index d61587964bd7..83d6ca4e0bba 100644
@@ -14,6 +14,7 @@
 
 #include <asm/ptrace.h>
 #include <asm/hwcap.h>
+#include <asm/usercfi.h>
 
 /*
  * addr is a hint to the maximum userspace address that mmap should provide, so
arch/riscv/include/asm/thread_info.h +3 -0
index c74536194626..cb694aef337d 100644
@@ -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
new file mode 100644
index 000000000000..4fa201b4fc4e
@@ -0,0 +1,24 @@
+/* SPDX-License-Identifier: GPL-2.0
+ * Copyright (C) 2024 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 -0
index b09ca5f944f7..5457f9070cff 100644
@@ -45,6 +45,10 @@ void asm_offsets(void)
 #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 +26 -0
index ac2e908d4418..ca9203e6d76d 100644
@@ -60,6 +60,20 @@ SYM_CODE_START(handle_exception)
 
 	REG_L s0, TASK_TI_USER_SP(tp)
 	csrrc s1, CSR_STATUS, t0
+	/*
+	 * If previous mode was U, capture shadow stack pointer and save it away
+	 * Zero CSR_SSP at the same time for sanitization.
+	 */
+	ALTERNATIVE("nop; nop; nop; nop",
+				__stringify(			\
+				andi s2, s1, SR_SPP;	\
+				bnez s2, skip_ssp_save;	\
+				csrrw s2, CSR_SSP, x0;	\
+				REG_S s2, TASK_TI_USER_SSP(tp); \
+				skip_ssp_save:),
+				0,
+				RISCV_ISA_EXT_ZICFISS,
+				CONFIG_RISCV_USER_CFI)
 	csrr s2, CSR_EPC
 	csrr s3, CSR_TVAL
 	csrr s4, CSR_CAUSE
@@ -149,6 +163,18 @@ SYM_CODE_START_NOALIGN(ret_from_exception)
 	 * structures again.
 	 */
 	csrw CSR_SCRATCH, tp
+
+	/*
+	 * Going back to U mode, restore shadow stack pointer
+	 */
+	ALTERNATIVE("nop; nop",
+				__stringify(					\
+				REG_L s3, TASK_TI_USER_SSP(tp); \
+				csrw CSR_SSP, s3),
+				0,
+				RISCV_ISA_EXT_ZICFISS,
+				CONFIG_RISCV_USER_CFI)
+
 1:
 #ifdef CONFIG_RISCV_ISA_V_PREEMPTIVE
 	move a0, sp
Signature · 1 line
2.45.0
#14 lore raw

PATCH v4 11/30 riscv/mm : ensure PROT_WRITE leads to VM_READ | VM_WRITE

In reply to Deepak Gupta

arch_calc_vm_prot_bits is implemented on risc-v to return VM_READ | VM_WRITE if PROT_WRITE is specified. Similarly riscv_sys_mmap is updated to convert all incoming PROT_WRITE to (PROT_WRITE | PROT_READ). This is to make sure that any existing apps using PROT_WRITE still work.

Earlier protection_map[VM_WRITE] used to pick read-write PTE encodings. Now protection_map[VM_WRITE] will always pick PAGE_SHADOWSTACK PTE encodings for shadow stack. Above changes ensure that existing apps continue to work because underneath kernel will be picking protection_map[VM_WRITE|VM_READ] PTE encodings.

---
 arch/riscv/include/asm/mman.h    | 24 ++++++++++++++++++++++++
 arch/riscv/include/asm/pgtable.h |  1 +
 arch/riscv/kernel/sys_riscv.c    | 10 ++++++++++
 arch/riscv/mm/init.c             |  2 +-
 mm/mmap.c                        |  1 +
 5 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 arch/riscv/include/asm/mman.h
arch/riscv/include/asm/mman.h new file +24 -0
new file mode 100644
index 000000000000..ef9fedf32546
@@ -0,0 +1,24 @@
+/* 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>
+
+static inline unsigned long arch_calc_vm_prot_bits(unsigned long prot,
+	unsigned long pkey __always_unused)
+{
+	unsigned long ret = 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
index 089f3c9f56a3..af4337774fe5 100644
@@ -181,6 +181,7 @@ extern struct pt_alloc_ops pt_ops __meminitdata;
 #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 +10 -0
index d77afe05578f..43a448bf254b 100644
@@ -7,6 +7,7 @@
 
 #include <linux/syscalls.h>
 #include <asm/cacheflush.h>
+#include <asm-generic/mman-common.h>
 
 static long riscv_sys_mmap(unsigned long addr, unsigned long len,
 			   unsigned long prot, unsigned long flags,
@@ -16,6 +17,15 @@ static long riscv_sys_mmap(unsigned long addr, unsigned long len,
 	if (unlikely(offset & (~PAGE_MASK >> page_shift_offset)))
 		return -EINVAL;
 
+	/*
+	 * If 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;
+
 	return ksys_mmap_pgoff(addr, len, prot, flags, fd,
 			       offset >> (PAGE_SHIFT - page_shift_offset));
 }
arch/riscv/mm/init.c +1 -1
index eb0649a61b4c..000b51c26943 100644
@@ -324,7 +324,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,
mm/mmap.c +1 -0
index d0dfc85b209b..04023a464fac 100644
@@ -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.45.0
#15 lore raw

PATCH v4 12/30 riscv mm: manufacture shadow stack pte

In reply to Deepak Gupta

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 | 10 ++++++++++
 1 file changed, 10 insertions(+)
arch/riscv/include/asm/pgtable.h +10 -0
index af4337774fe5..0b6c66fb853a 100644
@@ -425,6 +425,11 @@ 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)
+{
+	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)
@@ -732,6 +737,11 @@ 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)
+{
+	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.45.0
#16 lore raw

PATCH v4 13/30 riscv mmu: teach pte_mkwrite to manufacture shadow stack PTEs

In reply to Deepak Gupta

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 (i.e. VM_SHADOW_STACK)

---
 arch/riscv/include/asm/pgtable.h |  7 +++++++
 arch/riscv/mm/pgtable.c          | 17 +++++++++++++++++
 2 files changed, 24 insertions(+)
arch/riscv/include/asm/pgtable.h +7 -0
index 0b6c66fb853a..30fd4874e871 100644
@@ -420,6 +420,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);
@@ -732,6 +736,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 +17 -0
index 533ec9055fa0..0dd6104a35ac 100644
@@ -142,3 +142,20 @@ 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 (vma->vm_flags & VM_SHADOW_STACK)
+		return pte_mkwrite_shstk(pte);
+
+	return pte_mkwrite_novma(pte);
+}
+
+pmd_t pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma)
+{
+	if (vma->vm_flags & VM_SHADOW_STACK)
+		return pmd_mkwrite_shstk(pmd);
+
+	return pmd_mkwrite_novma(pmd);
+}
+
Signature · 1 line
2.45.0
#17 lore raw

PATCH v4 14/30 riscv mmu: write protect and shadow stack

In reply to Deepak Gupta

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 shadow stack 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.

Alexandre Ghiti <[email protected]>

---
 arch/riscv/include/asm/pgtable.h | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
arch/riscv/include/asm/pgtable.h +10 -2
index 30fd4874e871..3e05fedb871c 100644
@@ -415,7 +415,7 @@ static inline int pte_devmap(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) */
@@ -606,7 +606,15 @@ static inline pte_t ptep_get_and_clear(struct mm_struct *mm,
 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);
+	pte_t read_pte = READ_ONCE(*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.45.0
#18 lore raw

PATCH v4 15/30 riscv/mm: Implement map_shadow_stack() syscall

In reply to Deepak Gupta

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 shadow stack memory 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 compatibility and portability with other architectues, user mode can specify token set flag.

---
 arch/riscv/kernel/Makefile      |   2 +
 arch/riscv/kernel/usercfi.c     | 145 ++++++++++++++++++++++++++++++++
 include/uapi/asm-generic/mman.h |   1 +
 3 files changed, 148 insertions(+)
 create mode 100644 arch/riscv/kernel/usercfi.c
arch/riscv/kernel/Makefile +2 -0
index 06d407f1b30b..7d673b2f5f3e 100644
@@ -113,3 +113,5 @@ obj-$(CONFIG_COMPAT)		+= compat_vdso/
 obj-$(CONFIG_64BIT)		+= pi/
 obj-$(CONFIG_ACPI)		+= acpi.o
 obj-$(CONFIG_ACPI_NUMA)	+= acpi_numa.o
+
+obj-$(CONFIG_RISCV_USER_CFI) += usercfi.o
arch/riscv/kernel/usercfi.c new file +145 -0

145 lines not on this page · raw message

include/uapi/asm-generic/mman.h +1 -0
index 57e8195d0b53..0c0ac6214de6 100644
@@ -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.45.0
#20 lore raw

PATCH v4 16/30 riscv/shstk: If needed allocate a new shadow stack on clone

In reply to Deepak Gupta

Userspace specifies CLONE_VM 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 CLONE_VM is given.

In case of CLONE_VFORK, parent is suspended until child finishes and thus can child use parent shadow stack. In case of !CLONE_VM, 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 |  45 ++++++++++++
 arch/riscv/kernel/process.c      |  12 ++-
 arch/riscv/kernel/usercfi.c      | 121 +++++++++++++++++++++++++++++++
 3 files changed, 177 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +45 -0
index 4fa201b4fc4e..a6974307ca6c 100644
@@ -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,48 @@ 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);
+unsigned long get_shstk_base(struct task_struct *task, 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)
+{
+
+}
+
+unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
+{
+	return 0;
+}
+
+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 +11 -1
index 9b66dc07c3d2..6747db72435a 100644
@@ -26,6 +26,7 @@
 #include <asm/cpuidle.h>
 #include <asm/vector.h>
 #include <asm/cpufeature.h>
+#include <asm/usercfi.h>
 
 #if defined(CONFIG_STACKPROTECTOR) && !defined(CONFIG_STACKPROTECTOR_PER_TASK)
 #include <linux/stackprotector.h>
@@ -194,7 +195,8 @@ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src)
 
 void exit_thread(struct task_struct *tsk)
 {
-
+	if (IS_ENABLED(CONFIG_RISCV_USER_CFI))
+		shstk_release(tsk);
 }
 
 int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
@@ -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));
@@ -216,11 +219,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.45.0
#24 lore raw

PATCH v4 17/30 prctl: arch-agnostic prctl for shadow stack

In reply to Deepak Gupta

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 configuration 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 | 21 +++++++++++++++++++++
 kernel/sys.c               | 30 ++++++++++++++++++++++++++++++
 3 files changed, 54 insertions(+)
include/linux/mm.h +3 -0
index f0dc94fb782a..e3acb4297877 100644
@@ -4215,6 +4215,9 @@ 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);
 
 void vma_pgtable_walk_begin(struct vm_area_struct *vma);
 void vma_pgtable_walk_end(struct vm_area_struct *vma);
include/uapi/linux/prctl.h +21 -0
index 35791791a879..b8d7b6361754 100644
@@ -327,5 +327,26 @@ struct prctl_mm_map {
 # define PR_PPC_DEXCR_CTRL_SET_ONEXEC	 0x8 /* Set the aspect on exec */
 # define PR_PPC_DEXCR_CTRL_CLEAR_ONEXEC	0x10 /* Clear the aspect on exec */
 # define PR_PPC_DEXCR_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      74
+
+/*
+ * 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      75
+# 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      76
 
 #endif /* _LINUX_PRCTL_H */
kernel/sys.c +30 -0
index 3a2df1bd9f64..7e0c10e867cf 100644
@@ -2324,6 +2324,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
@@ -2782,6 +2797,21 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 	case PR_RISCV_SET_ICACHE_FLUSH_CTX:
 		error = RISCV_SET_ICACHE_FLUSH_CTX(arg2, arg3);
 		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.45.0
#25 lore raw

PATCH v4 18/30 prctl: arch-agnostic prctl for indirect branch tracking

In reply to Deepak Gupta

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/linux/cpu.h        |  4 ++++
 include/uapi/linux/prctl.h | 27 +++++++++++++++++++++++++++
 kernel/sys.c               | 30 ++++++++++++++++++++++++++++++
 3 files changed, 61 insertions(+)
include/linux/cpu.h +4 -0
index bdcec1732445..eff56aae05d7 100644
@@ -203,4 +203,8 @@ static inline bool cpu_mitigations_auto_nosmt(void)
 }
 #endif
 
+int arch_get_indir_br_lp_status(struct task_struct *t, unsigned long __user *status);
+int arch_set_indir_br_lp_status(struct task_struct *t, unsigned long status);
+int arch_lock_indir_br_lp_status(struct task_struct *t, unsigned long status);
+
 #endif /* _LINUX_CPU_H_ */
include/uapi/linux/prctl.h +27 -0
index b8d7b6361754..41ffb53490a4 100644
@@ -349,4 +349,31 @@ struct prctl_mm_map {
  */
 #define PR_LOCK_SHADOW_STACK_STATUS      76
 
+/*
+ * 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      77
+
+/*
+ * 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      78
+# 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      79
+
 #endif /* _LINUX_PRCTL_H */
kernel/sys.c +30 -0
index 7e0c10e867cf..5f88d358066d 100644
@@ -2339,6 +2339,21 @@ int __weak arch_lock_shadow_stack_status(struct task_struct *t, unsigned long st
 	return -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 status)
+{
+	return -EINVAL;
+}
+
+int __weak arch_lock_indir_br_lp_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
@@ -2812,6 +2827,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, arg2);
+		break;
+	case PR_LOCK_INDIR_BR_LP_STATUS:
+		if (arg3 || arg4 || arg5)
+			return -EINVAL;
+		error = arch_lock_indir_br_lp_status(me, arg2);
+		break;
 	default:
 		error = -EINVAL;
 		break;
Signature · 1 line
2.45.0
#26 lore raw

PATCH v4 19/30 riscv: Implements arch agnostic shadow stack prctls

In reply to Deepak Gupta

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.

---
 arch/riscv/include/asm/usercfi.h |  30 ++++++++-
 arch/riscv/kernel/process.c      |   8 +++
 arch/riscv/kernel/usercfi.c      | 107 +++++++++++++++++++++++++++++++
 3 files changed, 144 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +29 -1
index a6974307ca6c..6d806fbb283d 100644
@@ -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 */
@@ -27,6 +29,12 @@ void set_shstk_base(struct task_struct *task, unsigned long shstk_addr, unsigned
 unsigned long get_shstk_base(struct task_struct *task, 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);
+bool is_shstk_allocated(struct task_struct *task);
+void set_shstk_lock(struct task_struct *task);
+void set_shstk_status(struct task_struct *task, bool enable);
+
+#define PR_SHADOW_STACK_SUPPORTED_STATUS_MASK (PR_SHADOW_STACK_ENABLE)
 
 #else
 
@@ -62,6 +70,26 @@ static inline bool is_shstk_enabled(struct task_struct *task)
 	return false;
 }
 
+static inline bool is_shstk_locked(struct task_struct *task)
+{
+	return false;
+}
+
+bool is_shstk_allocated(struct task_struct *task)
+{
+	return false;
+}
+
+void set_shstk_lock(struct task_struct *task)
+{
+
+}
+
+static inline void set_shstk_status(struct task_struct *task, bool enable)
+{
+
+}
+
 #endif /* CONFIG_RISCV_USER_CFI */
 
 #endif /* __ASSEMBLY__ */
arch/riscv/kernel/process.c +8 -0
index 6747db72435a..b64baa0235ea 100644
@@ -143,6 +143,14 @@ void start_thread(struct pt_regs *regs, unsigned long pc,
 	regs->epc = pc;
 	regs->sp = sp;
 
+	/*
+	 * clear shadow stack state on exec.
+	 * libc will set it later via prctl.
+	 */
+	set_shstk_status(current, false);
+	set_shstk_base(current, 0, 0);
+	set_active_shstk(current, 0);
+
 #ifdef CONFIG_64BIT
 	regs->status &= ~SR_UXL;
 
arch/riscv/kernel/usercfi.c +107 -0

122 lines not on this page · raw message

Signature · 1 line
2.45.0
#27 lore raw

PATCH v4 20/30 riscv: Implements arch agnostic indirect branch tracking prctls

In reply to Deepak Gupta

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 | 28 +++++++++++-
 arch/riscv/kernel/process.c      |  5 +++
 arch/riscv/kernel/usercfi.c      | 76 ++++++++++++++++++++++++++++++++
 3 files changed, 108 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +27 -1
index 6d806fbb283d..20a9102cce51 100644
@@ -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 */
@@ -33,6 +35,10 @@ bool is_shstk_locked(struct task_struct *task);
 bool is_shstk_allocated(struct task_struct *task);
 void set_shstk_lock(struct task_struct *task);
 void set_shstk_status(struct task_struct *task, bool enable);
+bool is_indir_lp_enabled(struct task_struct *task);
+bool is_indir_lp_locked(struct task_struct *task);
+void set_indir_lp_status(struct task_struct *task, bool enable);
+void set_indir_lp_lock(struct task_struct *task);
 
 #define PR_SHADOW_STACK_SUPPORTED_STATUS_MASK (PR_SHADOW_STACK_ENABLE)
 
@@ -90,6 +96,26 @@ static inline void set_shstk_status(struct task_struct *task, bool enable)
 
 }
 
+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;
+}
+
+static inline void set_indir_lp_status(struct task_struct *task, bool enable)
+{
+
+}
+
+void set_indir_lp_lock(struct task_struct *task)
+{
+
+}
+
 #endif /* CONFIG_RISCV_USER_CFI */
 
 #endif /* __ASSEMBLY__ */
arch/riscv/kernel/process.c +5 -0
index b64baa0235ea..f3c5b8f2c869 100644
@@ -150,6 +150,11 @@ void start_thread(struct pt_regs *regs, unsigned long pc,
 	set_shstk_status(current, false);
 	set_shstk_base(current, 0, 0);
 	set_active_shstk(current, 0);
+	/*
+	 * disable indirect branch tracking on exec.
+	 * libc will enable it later via prctl.
+	 */
+	set_indir_lp_status(current, false);
 
 #ifdef CONFIG_64BIT
 	regs->status &= ~SR_UXL;
arch/riscv/kernel/usercfi.c +76 -0

85 lines not on this page · raw message

Signature · 1 line
2.45.0
#28 lore raw

PATCH v4 21/30 riscv/traps: Introduce software check exception

In reply to Deepak Gupta

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/include/asm/entry-common.h   |  2 ++
 arch/riscv/kernel/entry.S               |  3 ++
 arch/riscv/kernel/traps.c               | 38 +++++++++++++++++++++++++
 4 files changed, 44 insertions(+)
arch/riscv/include/asm/asm-prototypes.h +1 -0
index cd627ec289f1..5a27cefd7805 100644
@@ -51,6 +51,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/include/asm/entry-common.h +2 -0
index 2293e535f865..4068c7e5452a 100644
@@ -39,4 +39,6 @@ static inline int handle_misaligned_store(struct pt_regs *regs)
 }
 #endif
 
+bool handle_user_cfi_violation(struct pt_regs *regs);
+
 #endif /* _ASM_RISCV_ENTRY_COMMON_H */
arch/riscv/kernel/entry.S +3 -0
index ca9203e6d76d..2ec75ba864a8 100644
@@ -384,6 +384,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
index 51ebfd23e007..32d1453bed72 100644
@@ -354,6 +354,44 @@ 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.45.0
#31 lore raw

PATCH v4 22/30 riscv sigcontext: cfi state struct definition for sigcontext

In reply to Deepak Gupta

Shadow stack needs to be saved and restored on signal delivery and signal return.

sigcontext embedded in ucontext is extendible. Defining 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 | 3 +++
 1 file changed, 3 insertions(+)
arch/riscv/include/uapi/asm/sigcontext.h +3 -0
index cd4f175dc837..c4d19a10651d 100644
@@ -21,6 +21,9 @@ 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 */
+};
 /*
  * Signal context structure
  *
Signature · 1 line
2.45.0
#32 lore raw

PATCH v4 23/30 riscv signal: save and restore of shadow stack for signal

In reply to Deepak Gupta

Save shadow stack pointer in sigcontext structure while delivering signal. Restore shadow stack pointer from sigcontext on sigreturn.

As part of save operation, kernel uses ssamoswap to save snapshot of current shadow stack on shadow stack itself (can be called as a save token). During restore on sigreturn, kernel retrieves token from top of shadow stack and validates it. This allows that user mode can't arbitrary pivot to any shadow stack address without having a token and thus provide strong security assurance between signaly delivery and sigreturn window.

---
 arch/riscv/include/asm/usercfi.h | 19 ++++++++++
 arch/riscv/kernel/signal.c       | 62 +++++++++++++++++++++++++++++++-
 arch/riscv/kernel/usercfi.c      | 57 +++++++++++++++++++++++++++++
 3 files changed, 137 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +19 -0
index 20a9102cce51..d5050a5df26c 100644
@@ -8,6 +8,7 @@
 #ifndef __ASSEMBLY__
 #include <linux/types.h>
 #include <linux/prctl.h>
+#include <linux/errno.h>
 
 struct task_struct;
 struct kernel_clone_args;
@@ -35,6 +36,9 @@ bool is_shstk_locked(struct task_struct *task);
 bool is_shstk_allocated(struct task_struct *task);
 void set_shstk_lock(struct task_struct *task);
 void set_shstk_status(struct task_struct *task, bool enable);
+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);
 bool is_indir_lp_enabled(struct task_struct *task);
 bool is_indir_lp_locked(struct task_struct *task);
 void set_indir_lp_status(struct task_struct *task, bool enable);
@@ -96,6 +100,21 @@ static inline void set_shstk_status(struct task_struct *task, bool enable)
 
 }
 
+static inline int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+	return -EINVAL;
+}
+
+static inline int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+	return -EINVAL;
+}
+
+static inline unsigned long get_active_shstk(struct task_struct *task)
+{
+	return 0;
+}
+
 static inline bool is_indir_lp_enabled(struct task_struct *task)
 {
 	return false;
arch/riscv/kernel/signal.c +61 -1

109 lines not on this page · raw message

arch/riscv/kernel/usercfi.c +57 -0

69 lines not on this page · raw message

Signature · 1 line
2.45.0
#37 lore raw

PATCH v4 24/30 riscv/kernel: update __show_regs to print shadow stack register

In reply to Deepak Gupta

Updating __show_regs to print captured shadow stack pointer as well. On tasks where shadow stack is disabled, it'll simply print 0.

---
 arch/riscv/kernel/process.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/riscv/kernel/process.c +2 -2
index f3c5b8f2c869..1a5d70977e5a 100644
@@ -87,8 +87,8 @@ void __show_regs(struct pt_regs *regs)
 		regs->s8, regs->s9, regs->s10);
 	pr_cont(" s11: " REG_FMT " t3 : " REG_FMT " t4 : " REG_FMT "\n",
 		regs->s11, regs->t3, regs->t4);
-	pr_cont(" t5 : " REG_FMT " t6 : " REG_FMT "\n",
-		regs->t5, regs->t6);
+	pr_cont(" t5 : " REG_FMT " t6 : " REG_FMT " ssp : " REG_FMT "\n",
+		regs->t5, regs->t6, get_active_shstk(current));
 
 	pr_cont("status: " REG_FMT " badaddr: " REG_FMT " cause: " REG_FMT "\n",
 		regs->status, regs->badaddr, regs->cause);
Signature · 1 line
2.45.0
#38 lore raw

PATCH v4 25/30 riscv/ptrace: riscv cfi status and state via ptrace and in core files

In reply to Deepak Gupta

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
index a38268b19c3d..512be06a8661 100644
@@ -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
index b54b313bcf07..390732883fd7 100644
@@ -448,6 +448,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.45.0
#39 lore raw

PATCH v4 26/30 riscv/hwprobe: zicfilp / zicfiss enumeration in hwprobe

In reply to Deepak Gupta

Adding enumeration of zicfilp and zicfiss extensions in hwprobe syscall.

---
 arch/riscv/include/uapi/asm/hwprobe.h | 2 ++
 arch/riscv/kernel/sys_hwprobe.c       | 2 ++
 2 files changed, 4 insertions(+)
arch/riscv/include/uapi/asm/hwprobe.h +2 -0
index 1e153cda57db..d5c5dec9ae6c 100644
@@ -72,6 +72,8 @@ struct riscv_hwprobe {
 #define		RISCV_HWPROBE_EXT_ZCF		(1ULL << 46)
 #define		RISCV_HWPROBE_EXT_ZCMOP		(1ULL << 47)
 #define		RISCV_HWPROBE_EXT_ZAWRS		(1ULL << 48)
+#define		RISCV_HWPROBE_EXT_ZICFILP	(1ULL << 49)
+#define		RISCV_HWPROBE_EXT_ZICFISS	(1ULL << 50)
 #define RISCV_HWPROBE_KEY_CPUPERF_0	5
 #define		RISCV_HWPROBE_MISALIGNED_UNKNOWN	(0 << 0)
 #define		RISCV_HWPROBE_MISALIGNED_EMULATED	(1 << 0)
arch/riscv/kernel/sys_hwprobe.c +2 -0
index cea0ca2bf2a2..98f72ad7124f 100644
@@ -107,6 +107,8 @@ static void hwprobe_isa_ext0(struct riscv_hwprobe *pair,
 		EXT_KEY(ZCB);
 		EXT_KEY(ZCMOP);
 		EXT_KEY(ZICBOZ);
+		EXT_KEY(ZICFILP);
+		EXT_KEY(ZICFISS);
 		EXT_KEY(ZICOND);
 		EXT_KEY(ZIHINTNTL);
 		EXT_KEY(ZIHINTPAUSE);
Signature · 1 line
2.45.0
#40 lore raw

PATCH v4 27/30 riscv: create a config for shadow stack and landing pad instr support

In reply to Deepak Gupta

This patch creates a config for shadow stack support and landing pad instr support. Shadow stack support and landing instr support can be enabled by selecting 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.

If CONFIG_RISCV_USER_CFI is selected, select ARCH_USES_HIGH_VMA_FLAGS and ARCH_HAS_USER_SHADOW_STACK for riscv.

---
 arch/riscv/Kconfig | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
arch/riscv/Kconfig +19 -0
index d1d629a3eb91..24bf08c905d2 100644
@@ -231,6 +231,25 @@ config ARCH_HAS_BROKEN_DWARF5
 	# https://github.com/llvm/llvm-project/commit/7ffabb61a5569444b5ac9322e22e5471cc5e4a77
 	depends on LD_IS_LLD && LLD_VERSION < 180000
 
+config RISCV_USER_CFI
+	def_bool y
+	bool "riscv userspace control flow integrity"
+	depends on 64BIT && $(cc-option,-mabi=lp64 -march=rv64ima_zicfiss)
+	depends on RISCV_ALTERNATIVE
+	select ARCH_HAS_USER_SHADOW_STACK
+	select ARCH_USES_HIGH_VMA_FLAGS
+	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.45.0
#41 lore raw

PATCH v4 28/30 riscv: Documentation for landing pad / indirect branch tracking

In reply to Deepak Gupta

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
new file mode 100644
index 000000000000..23013ee711ac
@@ -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>` with `rd=x0`` and is a HINT
+nop. `lpad` instruction must be aligned on 4 byte boundary and compares 20 bit
+immediate withx7. 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 prologues 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.45.0
#43 lore raw

PATCH v4 29/30 riscv: Documentation for shadow stack on riscv

In reply to Deepak Gupta

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
new file mode 100644
index 000000000000..f133b6af9c15
@@ -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.45.0
#45 lore raw

PATCH v4 30/30 kselftest/riscv: kselftest for user mode cfi

In reply to Deepak Gupta

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. cfi selftest are intended to be compiled with zicfilp and zicfiss enabled compiler. Thus kselftest simply checks if landing pad and shadow stack for the binary and process are enabled or not. selftest then register a signal handler for SIGSEGV. Any control flow violation are reported as SIGSEGV with si_code = SEGV_CPERR. Test will fail on receiving any SEGV_CPERR. Shadow stack part has more changes in kernel and thus there are separate tests for that
- 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/.gitignore  |   3 +
 tools/testing/selftests/riscv/cfi/Makefile    |  10 +
 .../testing/selftests/riscv/cfi/cfi_rv_test.h |  83 ++++
 .../selftests/riscv/cfi/riscv_cfi_test.c      |  82 ++++
 .../testing/selftests/riscv/cfi/shadowstack.c | 362 ++++++++++++++++++
 .../testing/selftests/riscv/cfi/shadowstack.h |  37 ++
 7 files changed, 578 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/riscv/cfi/.gitignore
 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
index 7ce03d832b64..6e142fe004ab 100644
@@ -5,7 +5,7 @@
 ARCH ?= $(shell uname -m 2>/dev/null || echo not)
 
 ifneq (,$(filter $(ARCH),riscv))
-RISCV_SUBTARGETS ?= hwprobe vector mm sigreturn
+RISCV_SUBTARGETS ?= hwprobe vector mm sigreturn cfi
 else
 RISCV_SUBTARGETS :=
 endif
tools/testing/selftests/riscv/cfi/.gitignore new file +3 -0
new file mode 100644
index 000000000000..ce7623f9da28
@@ -0,0 +1,3 @@
+cfitests
+riscv_cfi_test
+shadowstack
\ No newline at end of file
tools/testing/selftests/riscv/cfi/Makefile new file +10 -0
new file mode 100644
index 000000000000..b65f7ff38a32
@@ -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) -o$@ $(CFLAGS) $(LDFLAGS) $^
tools/testing/selftests/riscv/cfi/cfi_rv_test.h new file +83 -0

83 lines not on this page · raw message

tools/testing/selftests/riscv/cfi/riscv_cfi_test.c new file +82 -0

82 lines not on this page · raw message

tools/testing/selftests/riscv/cfi/shadowstack.c new file +362 -0

362 lines not on this page · raw message

tools/testing/selftests/riscv/cfi/shadowstack.h new file +37 -0
new file mode 100644
index 000000000000..b43e74136a26
@@ -0,0 +1,37 @@
+/* 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 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[] = {
+	{ "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.45.0
#9 lore raw

Re: [PATCH v4 07/30] riscv: zicfilp / zicfiss in dt-bindings (extensions.yaml)

In reply to Deepak Gupta
Quoted 7 lines · Deepak Gupta

Make an entry for cfi extensions in extensions.yaml.

---
 .../devicetree/bindings/riscv/extensions.yaml        | 12 ++++++++++++
 1 file changed, 12 insertions(+)

My bot found errors running 'make dt_binding_check' on your patch:

yamllint warnings/errors:
./Documentation/devicetree/bindings/riscv/extensions.yaml:367:75: [error] missing starting space in comment (comments) ./Documentation/devicetree/bindings/riscv/extensions.yaml:368:13: [error] syntax error: expected <block end>, but found '<scalar>' (syntax) ./Documentation/devicetree/bindings/riscv/extensions.yaml:373:75: [error] missing starting space in comment (comments) ./Documentation/devicetree/bindings/riscv/extensions.yaml:374:13: [warning] wrong indentation: expected 10 but found 12 (indentation)

dtschema/dtc warnings/errors:
/builds/robherring/dt-review-ci/linux/Documentation/devicetree/bindings/riscv/extensions.yaml: ignoring, error parsing file
make[2]: *** Deleting file 'Documentation/devicetree/bindings/riscv/extensions.example.dts'
Documentation/devicetree/bindings/riscv/extensions.yaml:368:13: did not find expected key
make[2]: *** [Documentation/devicetree/bindings/Makefile:26: Documentation/devicetree/bindings/riscv/extensions.example.dts] Error 1
make[2]: *** Waiting for unfinished jobs....
/builds/robherring/dt-review-ci/linux/Documentation/devicetree/bindings/riscv/cpus.example.dtb: cpu@0: False schema does not allow {'clock-frequency': 0, 'compatible': ['sifive,rocket0', 'riscv'], 'device_type': ['cpu'], 'i-cache-block-size': 64, 'i-cache-sets': 128, 'i-cache-size': 16384, 'reg': [[0]], 'riscv,isa-base': ['rv64i'], 'riscv,isa-extensions': [1761635584, 1627415296], 'interrupt-controller': {'#interrupt-cells': 1, 'compatible': ['riscv,cpu-intc'], 'interrupt-controller': True}, '$nodename': ['cpu@0']}
from schema $id: http://devicetree.org/schemas/riscv/cpus.yaml#
/builds/robherring/dt-review-ci/linux/Documentation/devicetree/bindings/riscv/cpus.example.dtb: cpu@0: Unevaluated properties are not allowed ('riscv,isa-base', 'riscv,isa-extensions' were unexpected)
from schema $id: http://devicetree.org/schemas/riscv/cpus.yaml#
/builds/robherring/dt-review-ci/linux/Documentation/devicetree/bindings/riscv/cpus.example.dtb: cpu@1: False schema does not allow {'clock-frequency': 0, 'compatible': ['sifive,rocket0', 'riscv'], 'd-cache-block-size': 64, 'd-cache-sets': 64, 'd-cache-size': 32768, 'd-tlb-sets': 1, 'd-tlb-size': 32, 'device_type': ['cpu'], 'i-cache-block-size': 64, 'i-cache-sets': 64, 'i-cache-size': 32768, 'i-tlb-sets': 1, 'i-tlb-size': 32, 'mmu-type': ['riscv,sv39'], 'reg': [[1]], 'tlb-split': True, 'riscv,isa-base': ['rv64i'], 'riscv,isa-extensions': [1761635584, 1627416064, 1677746944], 'interrupt-controller': {'#interrupt-cells': 1, 'compatible': ['riscv,cpu-intc'], 'interrupt-controller': True}, '$nodename': ['cpu@1']}
from schema $id: http://devicetree.org/schemas/riscv/cpus.yaml#
/builds/robherring/dt-review-ci/linux/Documentation/devicetree/bindings/riscv/cpus.example.dtb: cpu@1: Unevaluated properties are not allowed ('riscv,isa-base', 'riscv,isa-extensions' were unexpected)
from schema $id: http://devicetree.org/schemas/riscv/cpus.yaml#
/builds/robherring/dt-review-ci/linux/Documentation/devicetree/bindings/riscv/cpus.example.dtb: cpu@0: False schema does not allow {'device_type': ['cpu'], 'reg': [[0]], 'compatible': ['riscv'], 'mmu-type': ['riscv,sv48'], 'riscv,isa-base': ['rv64i'], 'riscv,isa-extensions': [1761635584, 1627416064, 1677746944], 'interrupt-controller': {'#interrupt-cells': 1, 'interrupt-controller': True, 'compatible': ['riscv,cpu-intc']}, '$nodename': ['cpu@0']}
from schema $id: http://devicetree.org/schemas/riscv/cpus.yaml#
/builds/robherring/dt-review-ci/linux/Documentation/devicetree/bindings/riscv/cpus.example.dtb: cpu@0: Unevaluated properties are not allowed ('riscv,isa-base', 'riscv,isa-extensions' were unexpected)
from schema $id: http://devicetree.org/schemas/riscv/cpus.yaml#
./Documentation/devicetree/bindings/riscv/extensions.yaml:368:13: did not find expected key
make[1]: *** [/builds/robherring/dt-review-ci/linux/Makefile:1432: dt_binding_check] Error 2
make: *** [Makefile:224: __sub-make] Error 2

doc reference errors (make refcheckdocs):

See https://patchwork.ozlabs.org/project/devicetree-bindings/patch/[email protected]

The base for the series is generally the latest rc1. A different dependency should be noted in *this* patch.

If you already ran 'make dt_binding_check' and didn't see the above error(s), then make sure 'yamllint' is installed and dt-schema is up to date:

pip3 install dtschema --upgrade

Please check and re-submit after running the above command yourself. Note that DT_SCHEMA_FILES can be set to your schema file to speed up checking your schema. However, it must be unset to test all examples with your schema.

#19 lore raw

Re: [PATCH v4 15/30] riscv/mm: Implement map_shadow_stack() syscall

In reply to Deepak Gupta
Quoted 4 lines · Deepak Gupta

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 compatibility and portability with other architectues, user mode can specify token set flag.

The arm64 series also adds SHADOW_STACK_SET_MARKER for a top of stack marker, if this is only being done for compatibility it might be good to pick that up as well. I don't know what the thoughts are on using them for RISC-V. On arm64 the top of stack marker is just all bits 0.

Reviewed-by on v4 1/30
#2 lore raw

Re: [PATCH v4 01/30] mm: Introduce ARCH_HAS_USER_SHADOW_STACK

In reply to Deepak Gupta
Quoted 62 lines · Deepak Gupta

From: Mark Brown <[email protected]>

Since multiple architectures have support for shadow stacks and we need to select support for this feature in several places in the generic code provide a generic config option that the architectures can select.

---
 arch/x86/Kconfig   | 1 +
 fs/proc/task_mmu.c | 2 +-
 include/linux/mm.h | 2 +-
 mm/Kconfig         | 6 ++++++
 4 files changed, 9 insertions(+), 2 deletions(-)
arch/x86/Kconfig +1 -0
index 007bab9f2a0e..320e1f411163 100644
@@ -1957,6 +1957,7 @@ config X86_USER_SHADOW_STACK
 	depends on AS_WRUSS
 	depends on X86_64
 	select ARCH_USES_HIGH_VMA_FLAGS
+	select ARCH_HAS_USER_SHADOW_STACK
 	select X86_CET
 	help
 	  Shadow stack protection is a hardware feature that detects function
fs/proc/task_mmu.c +1 -1
index 5f171ad7b436..0ea49725f524 100644
@@ -984,7 +984,7 @@ static void show_smap_vma_flags(struct seq_file *m, struct vm_area_struct *vma)
 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
 		[ilog2(VM_UFFD_MINOR)]	= "ui",
 #endif /* CONFIG_HAVE_ARCH_USERFAULTFD_MINOR */
-#ifdef CONFIG_X86_USER_SHADOW_STACK
+#ifdef CONFIG_ARCH_HAS_USER_SHADOW_STACK
 		[ilog2(VM_SHADOW_STACK)] = "ss",
 #endif
 #ifdef CONFIG_64BIT
include/linux/mm.h +1 -1
index 147073601716..e39796ea17db 100644
@@ -346,7 +346,7 @@ extern unsigned int kobjsize(const void *objp);
 #endif
 #endif /* CONFIG_ARCH_HAS_PKEYS */
 
-#ifdef CONFIG_X86_USER_SHADOW_STACK
+#ifdef CONFIG_ARCH_HAS_USER_SHADOW_STACK
 /*
  * VM_SHADOW_STACK should not be set with VM_SHARED because of lack of
  * support core mm.
mm/Kconfig +0 -0
index b72e7d040f78..3167be663bca 100644

mm/Kconfig config IOMMU_MM_DATA · line 1272

Quoted 10 lines
mm/Kconfig +6 -0
@@ -1263,6 +1263,12 @@ config IOMMU_MM_DATA
 config EXECMEM
 	bool
 
+config ARCH_HAS_USER_SHADOW_STACK
+	bool
+	help
+	  The architecture has hardware support for userspace shadow call
+          stacks (eg, x86 CET, arm64 GCS or RISC-V Zicfiss).
+
 source "mm/damon/Kconfig"

mm/Kconfig config IOMMU_MM_DATA · line 1273

Quoted 2 lines
mm/Kconfig +0 -0
 endmenu

Thanks, Carlos

#10 lore raw

Re: [PATCH v4 07/30] riscv: zicfilp / zicfiss in dt-bindings (extensions.yaml)

In reply to Deepak Gupta
Quoted 16 lines · Deepak Gupta

Make an entry for cfi extensions in extensions.yaml.

---
 .../devicetree/bindings/riscv/extensions.yaml        | 12 ++++++++++++
 1 file changed, 12 insertions(+)
Documentation/devicetree/bindings/riscv/extensions.yaml +1 -0
index a06dbc6b4928..b7c86fb91984 100644
@@ -361,6 +361,18 @@ properties:
             The standard Zicboz extension for cache-block zeroing as ratified
             in commit 3dd606f ("Create cmobase-v1.0.pdf") of riscv-CMOs.
 
+        - const: zicfilp

Documentation/devicetree/bindings/riscv/extensions.yaml properties: · line 374

Quoted 10 lines
Documentation/devicetree/bindings/riscv/extensions.yaml +10 -0
+          description:
+            The standard Zicfilp extension for enforcing forward edge control-flow
+            integrity as ratified in commit 3f8e450 ("merge pull request #227 from
+            ved-rivos/0709") of riscv-cfi github repo.
+
+        - const: zicfiss
+          description:
+            The standard Zicfilp extension for enforcing forward edge control-flow
+            integrity as ratified in commit 3f8e450 ("merge pull request #227 from
+            ved-rivos/0709") of riscv-cfi github repo.

Because both of these have a # in them you need to have a | after description:. Please run dt_binding_check :)

Quoted 7 lines
Documentation/devicetree/bindings/riscv/extensions.yaml +1 -0
+
         - const: zicntr
           description:
             The standard Zicntr extension for base counters and timers, as
Signature · 1 line
2.45.0
#33 lore raw

Re: [PATCH v4 23/30] riscv signal: save and restore of shadow stack for signal

In reply to Deepak Gupta

Hi Deepak,

Deepak Gupta <[email protected]> 於 2024年9月13日 週五 上午1:20寫道:

Quoted 129 lines

Save shadow stack pointer in sigcontext structure while delivering signal. Restore shadow stack pointer from sigcontext on sigreturn.

As part of save operation, kernel uses ssamoswap to save snapshot of current shadow stack on shadow stack itself (can be called as a save token). During restore on sigreturn, kernel retrieves token from top of shadow stack and validates it. This allows that user mode can't arbitrary pivot to any shadow stack address without having a token and thus provide strong security assurance between signaly delivery and sigreturn window.

---
 arch/riscv/include/asm/usercfi.h | 19 ++++++++++
 arch/riscv/kernel/signal.c       | 62 +++++++++++++++++++++++++++++++-
 arch/riscv/kernel/usercfi.c      | 57 +++++++++++++++++++++++++++++
 3 files changed, 137 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +19 -0
index 20a9102cce51..d5050a5df26c 100644
@@ -8,6 +8,7 @@
 #ifndef __ASSEMBLY__
 #include <linux/types.h>
 #include <linux/prctl.h>
+#include <linux/errno.h>
 
 struct task_struct;
 struct kernel_clone_args;
@@ -35,6 +36,9 @@ bool is_shstk_locked(struct task_struct *task);
 bool is_shstk_allocated(struct task_struct *task);
 void set_shstk_lock(struct task_struct *task);
 void set_shstk_status(struct task_struct *task, bool enable);
+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);
 bool is_indir_lp_enabled(struct task_struct *task);
 bool is_indir_lp_locked(struct task_struct *task);
 void set_indir_lp_status(struct task_struct *task, bool enable);
@@ -96,6 +100,21 @@ static inline void set_shstk_status(struct task_struct *task, bool enable)
 
 }
 
+static inline int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline unsigned long get_active_shstk(struct task_struct *task)
+{
+       return 0;
+}
+
 static inline bool is_indir_lp_enabled(struct task_struct *task)
 {
        return false;
arch/riscv/kernel/signal.c +33 -0
index dcd282419456..7d5c1825650f 100644
@@ -22,6 +22,7 @@
 #include <asm/vector.h>
 #include <asm/csr.h>
 #include <asm/cacheflush.h>
+#include <asm/usercfi.h>
 
 unsigned long signal_minsigstksz __ro_after_init;
 
@@ -153,6 +154,16 @@ static long restore_sigcontext(struct pt_regs *regs,
        void __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
        __u32 rsvd;
        long err;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
+
+       sc_cfi = (struct __sc_riscv_cfi_state *)
+                ((unsigned long) sc_ext_ptr + sizeof(struct __riscv_ctx_hdr));
+
+       if (has_vector() && riscv_v_vstate_query(regs))
+               sc_cfi = (struct __sc_riscv_cfi_state *)
+                        ((unsigned long) sc_cfi + riscv_v_sc_size);
+
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_from_user(regs, &sc->sc_regs, sizeof(sc->sc_regs));
        if (unlikely(err))
@@ -172,6 +183,24 @@ static long restore_sigcontext(struct pt_regs *regs,
        if (unlikely(rsvd))
                return -EINVAL;
 
+       /*
+        * Restore shadow stack as a form of token stored on shadow stack itself as a safe
+        * way to restore.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments.
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= __copy_from_user(&ss_ptr, &sc_cfi->ss_ptr, sizeof(unsigned long));
+               err |= restore_user_shstk(current, ss_ptr);
+       }
+
        while (!err) {
                __u32 magic, size;
                struct __riscv_ctx_hdr __user *head = sc_ext_ptr;
@@ -215,6 +244,10 @@ static size_t get_rt_frame_size(bool cal_all)
                if (cal_all || riscv_v_vstate_query(task_pt_regs(current)))
                        total_context_size += riscv_v_sc_size;
        }
+
+       if (is_shstk_enabled(current))
+               total_context_size += sizeof(struct __sc_riscv_cfi_state);
+
        /*
         * Preserved a __riscv_ctx_hdr for END signal context header if an
         * extension uses __riscv_extra_ext_header

arch/riscv/kernel/signal.c static long setup_sigcontext(struct rt_sigframe __user *frame, · line 317

Quoted 9 lines
arch/riscv/kernel/signal.c +4 -0
@@ -276,18 +309,40 @@ static long setup_sigcontext(struct rt_sigframe __user *frame,
 {
        struct sigcontext __user *sc = &frame->uc.uc_mcontext;
        struct __riscv_ctx_hdr __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
        long err;
 
+       sc_cfi = (struct __sc_riscv_cfi_state *) (sc_ext_ptr + 1);
+

Is it intended that cfi sigcontext does not follow the sigcontext rule setup by Vector? It seems like there is no extension header (struct __riscv_ctx_hdr) defined for cfi sigcontext here. If the sigcontext is directly appended to the signal stack, the user may not be able to recognize the meaning without defining a new ABI.

BTW, I have sent a patch[1] that refactor setup_sigcontext so it'd be easier for future extensions to expand on the signal stack.

Quoted 123 lines
arch/riscv/kernel/signal.c +24 -1
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_to_user(&sc->sc_regs, regs, sizeof(sc->sc_regs));
        /* Save the floating-point state. */
        if (has_fpu())
                err |= save_fp_state(regs, &sc->sc_fpregs);
        /* Save the vector state. */
-       if (has_vector() && riscv_v_vstate_query(regs))
+       if (has_vector() && riscv_v_vstate_query(regs)) {
                err |= save_v_state(regs, (void __user **)&sc_ext_ptr);
+               sc_cfi = (struct __sc_riscv_cfi_state *) ((unsigned long) sc_cfi + riscv_v_sc_size);
+       }
        /* Write zero to fp-reserved space and check it on restore_sigcontext */
        err |= __put_user(0, &sc->sc_extdesc.reserved);
+       /*
+        * Save a pointer to shadow stack itself on shadow stack as a form of token.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments. Any
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= save_user_shstk(current, &ss_ptr);
+               err |= __put_user(ss_ptr, &sc_cfi->ss_ptr);
+       }
        /* And put END __riscv_ctx_hdr at the end. */
        err |= __put_user(END_MAGIC, &sc_ext_ptr->magic);
        err |= __put_user(END_HDR_SIZE, &sc_ext_ptr->size);
@@ -345,6 +400,11 @@ static int setup_rt_frame(struct ksignal *ksig, sigset_t *set,
 #ifdef CONFIG_MMU
        regs->ra = (unsigned long)VDSO_SYMBOL(
                current->mm->context.vdso, rt_sigreturn);
+
+       /* if bcfi is enabled x1 (ra) and x5 (t0) must match. not sure if we need this? */
+       if (is_shstk_enabled(current))
+               regs->t0 = regs->ra;
+
 #else
        /*
         * For the nommu case we don't have a VDSO.  Instead we push two
arch/riscv/kernel/usercfi.c +57 -1
index 8da509afdbe9..40c32258b6ec 100644
@@ -52,6 +52,11 @@ void set_active_shstk(struct task_struct *task, unsigned long shstk_addr)
        task->thread_info.user_cfi_state.user_shdw_stk = shstk_addr;
 }
 
+unsigned long get_active_shstk(struct task_struct *task)
+{
+       return task->thread_info.user_cfi_state.user_shdw_stk;
+}
+
 void set_shstk_status(struct task_struct *task, bool enable)
 {
        task->thread_info.user_cfi_state.ubcfi_en = enable ? 1 : 0;
@@ -164,6 +169,58 @@ static int create_rstor_token(unsigned long ssp, unsigned long *token_addr)
        return 0;
 }
 
+/*
+ * Save user shadow stack pointer on shadow stack itself and return pointer to saved location
+ * returns -EFAULT if operation was unsuccessful
+ */
+int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       unsigned long ss_ptr = 0;
+       unsigned long token_loc = 0;
+       int ret = 0;
+
+       if (saved_shstk_ptr == NULL)
+               return -EINVAL;
+
+       ss_ptr = get_active_shstk(tsk);
+       ret = create_rstor_token(ss_ptr, &token_loc);
+
+       if (!ret) {
+               *saved_shstk_ptr = token_loc;
+               set_active_shstk(tsk, token_loc);
+       }
+
+       return ret;
+}
+
+/*
+ * Restores user shadow stack pointer from token on shadow stack for task `tsk`
+ * returns -EFAULT if operation was unsuccessful
+ */
+int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       unsigned long token = 0;
+
+       token = amo_user_shstk((unsigned long __user *)shstk_ptr, 0);
+
+       if (token == -1)
+               return -EFAULT;
+
+       /* invalid token, return EINVAL */
+       if ((token - shstk_ptr) != SHSTK_ENTRY_SIZE) {
+               pr_info_ratelimited(
+                               "%s[%d]: bad restore token in %s: pc=%p sp=%p, token=%p, shstk_ptr=%p\n",
+                               tsk->comm, task_pid_nr(tsk), __func__,
+                               (void *)(task_pt_regs(tsk)->epc), (void *)(task_pt_regs(tsk)->sp),
+                               (void *)token, (void *)shstk_ptr);
+               return -EINVAL;
+       }
+
+       /* all checks passed, set active shstk and return success */
+       set_active_shstk(tsk, token);
+       return 0;
+}
+
 static unsigned long allocate_shadow_stack(unsigned long addr, unsigned long size,
                                unsigned long token_offset,
                                bool set_tok)
--

2.45.0

Quoted 4 lines

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

- [1]: https://lore.kernel.org/all/[email protected]/

Thanks,
Andy

#29 lore raw

Re: [PATCH v4 21/30] riscv/traps: Introduce software check exception

In reply to Deepak Gupta

Hi Deepak

Deepak Gupta <[email protected]> 於 2024年9月13日 週五 上午2:32寫道:

Quoted 85 lines

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/include/asm/entry-common.h   |  2 ++
 arch/riscv/kernel/entry.S               |  3 ++
 arch/riscv/kernel/traps.c               | 38 +++++++++++++++++++++++++
 4 files changed, 44 insertions(+)
arch/riscv/include/asm/asm-prototypes.h +1 -0
index cd627ec289f1..5a27cefd7805 100644
@@ -51,6 +51,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/include/asm/entry-common.h +2 -0
index 2293e535f865..4068c7e5452a 100644
@@ -39,4 +39,6 @@ static inline int handle_misaligned_store(struct pt_regs *regs)
 }
 #endif
 
+bool handle_user_cfi_violation(struct pt_regs *regs);
+
 #endif /* _ASM_RISCV_ENTRY_COMMON_H */
arch/riscv/kernel/entry.S +3 -0
index ca9203e6d76d..2ec75ba864a8 100644
@@ -384,6 +384,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 +16 -0
index 51ebfd23e007..32d1453bed72 100644
@@ -354,6 +354,44 @@ 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;

arch/riscv/kernel/traps.c void do_trap_ecall_u(struct pt_regs *regs) · line 382

Quoted 10 lines
arch/riscv/kernel/traps.c +10 -0
+}
+/*
+ * 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.
+ */

It seems like this trap handler does not follow generic entry. This can cause problems as signal delivery is done in irqentry_exit_to_user_mode(). Please reference the commit f0bddf50586d ("riscv: entry: Convert to generic entry") for more information.

Quoted 19 lines
arch/riscv/kernel/traps.c +12 -1
+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)
 {
--

2.45.0

Quoted 4 lines

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

Cheers,
Andy

#21 lore raw

Re: [PATCH v4 16/30] riscv/shstk: If needed allocate a new shadow stack on clone

In reply to Deepak Gupta
kernel test robot noticed the following build warnings:

Hi Deepak,

kernel test robot noticed the following build warnings:

[auto build test WARNING on shuah-kselftest/next]
[also build test WARNING on shuah-kselftest/fixes tip/x86/core robh/for-next tip/smp/core kees/for-next/execve linus/master v6.11-rc7] [cannot apply to akpm-mm/mm-everything next-20240913]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Deepak-Gupta/mm-Introduce-ARCH_HAS_USER_SHADOW_STACK/20240913-072124
base:   https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git next
patch link:    https://lore.kernel.org/r/20240912231650.3740732-17-debug%40rivosinc.com
patch subject: [PATCH v4 16/30] riscv/shstk: If needed allocate a new shadow stack on clone
config: riscv-defconfig (https://download.01.org/0day-ci/archive/20240914/[email protected]/config)
compiler: clang version 20.0.0git (https://github.com/llvm/llvm-project bf684034844c660b778f0eba103582f582b710c9)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240914/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

In file included from arch/riscv/kernel/asm-offsets.c:10:
In file included from include/linux/mm.h:7:
In file included from include/linux/gfp.h:7:
In file included from include/linux/mmzone.h:8:
In file included from include/linux/spinlock.h:56:
In file included from include/linux/preempt.h:79:
In file included from ./arch/riscv/include/generated/asm/preempt.h:1:
In file included from include/asm-generic/preempt.h:5:
In file included from include/linux/thread_info.h:60:
In file included from arch/riscv/include/asm/thread_info.h:37:
In file included from arch/riscv/include/asm/processor.h:17:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for function 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^
   arch/riscv/include/asm/usercfi.h:44:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         | ^
         | static 
   In file included from arch/riscv/kernel/asm-offsets.c:10:
   In file included from include/linux/mm.h:2233:
   include/linux/vmstat.h:514:36: warning: arithmetic between different enumeration types ('enum node_stat_item' and 'enum lru_list') [-Wenum-enum-conversion]
     514 |         return node_stat_name(NR_LRU_BASE + lru) + 3; // skip "nr_"
         |                               ~~~~~~~~~~~ ^ ~~~

2 warnings generated.
--
In file included from arch/riscv/kernel/soc.c:7:
In file included from include/linux/pgtable.h:6:
In file included from arch/riscv/include/asm/pgtable.h:9:
In file included from include/linux/mmzone.h:8:
In file included from include/linux/spinlock.h:56:
In file included from include/linux/preempt.h:79:
In file included from ./arch/riscv/include/generated/asm/preempt.h:1:
In file included from include/asm-generic/preempt.h:5:
In file included from include/linux/thread_info.h:60:
In file included from arch/riscv/include/asm/thread_info.h:37:
In file included from arch/riscv/include/asm/processor.h:17:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for function 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^
   arch/riscv/include/asm/usercfi.h:44:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         | ^
         | static 

1 warning generated.
--
In file included from arch/riscv/kernel/asm-offsets.c:10:
In file included from include/linux/mm.h:7:
In file included from include/linux/gfp.h:7:
In file included from include/linux/mmzone.h:8:
In file included from include/linux/spinlock.h:56:
In file included from include/linux/preempt.h:79:
In file included from ./arch/riscv/include/generated/asm/preempt.h:1:
In file included from include/asm-generic/preempt.h:5:
In file included from include/linux/thread_info.h:60:
In file included from arch/riscv/include/asm/thread_info.h:37:
In file included from arch/riscv/include/asm/processor.h:17:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for function 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^
   arch/riscv/include/asm/usercfi.h:44:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         | ^
         | static 
   In file included from arch/riscv/kernel/asm-offsets.c:10:
   In file included from include/linux/mm.h:2233:
   include/linux/vmstat.h:514:36: warning: arithmetic between different enumeration types ('enum node_stat_item' and 'enum lru_list') [-Wenum-enum-conversion]
     514 |         return node_stat_name(NR_LRU_BASE + lru) + 3; // skip "nr_"
         |                               ~~~~~~~~~~~ ^ ~~~

2 warnings generated.

vim +/get_shstk_base +44 arch/riscv/include/asm/usercfi.h

    43	
  > 44	unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
    45	{
    46		return 0;
    47	}
    48	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#22 lore raw

Re: [PATCH v4 16/30] riscv/shstk: If needed allocate a new shadow stack on clone

In reply to Deepak Gupta
kernel test robot noticed the following build errors:

Hi Deepak,

kernel test robot noticed the following build errors:

[auto build test ERROR on shuah-kselftest/next]
[also build test ERROR on shuah-kselftest/fixes tip/x86/core robh/for-next arnd-asm-generic/master tip/smp/core kees/for-next/execve linus/master v6.11-rc7] [cannot apply to akpm-mm/mm-everything next-20240913]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Deepak-Gupta/mm-Introduce-ARCH_HAS_USER_SHADOW_STACK/20240913-072124
base:   https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git next
patch link:    https://lore.kernel.org/r/20240912231650.3740732-17-debug%40rivosinc.com
patch subject: [PATCH v4 16/30] riscv/shstk: If needed allocate a new shadow stack on clone
config: riscv-randconfig-001-20240914 (https://download.01.org/0day-ci/archive/20240914/[email protected]/config)
compiler: clang version 14.0.6 (https://github.com/llvm/llvm-project f28c006a5895fc0e329fe15fead81e37457cb1d1)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240914/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All error/warnings (new ones prefixed by >>):

>> clang diag: arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for function 'get_shstk_base' [-Wmissing-prototypes]

--
In file included from drivers/gpu/drm/drm_plane.c:23:
In file included from include/linux/slab.h:16:
In file included from include/linux/gfp.h:7:
In file included from include/linux/mmzone.h:8:
In file included from include/linux/spinlock.h:56:
In file included from include/linux/preempt.h:79:
In file included from ./arch/riscv/include/generated/asm/preempt.h:1:
In file included from include/asm-generic/preempt.h:5:
In file included from include/linux/thread_info.h:60:
In file included from arch/riscv/include/asm/thread_info.h:37:
In file included from arch/riscv/include/asm/processor.h:17:

>> arch/riscv/include/asm/usercfi.h:44:15: error: no previous prototype for function 'get_shstk_base' [-Werror,-Wmissing-prototypes]
   unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
                 ^

arch/riscv/include/asm/usercfi.h:44:1: note: declare 'static' if the function is not intended to be used outside of this translation unit unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
^
static
1 error generated.
--
In file included from arch/riscv/kernel/asm-offsets.c:10:
In file included from include/linux/mm.h:7:
In file included from include/linux/gfp.h:7:
In file included from include/linux/mmzone.h:8:
In file included from include/linux/spinlock.h:56:
In file included from include/linux/preempt.h:79:
In file included from ./arch/riscv/include/generated/asm/preempt.h:1:
In file included from include/asm-generic/preempt.h:5:
In file included from include/linux/thread_info.h:60:
In file included from arch/riscv/include/asm/thread_info.h:37:
In file included from arch/riscv/include/asm/processor.h:17:
arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for function 'get_shstk_base' [-Wmissing-prototypes] unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)

                 ^
   arch/riscv/include/asm/usercfi.h:44:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
   unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
   ^
   static 
   1 warning generated.
>> clang diag: arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for function 'get_shstk_base' [-Wmissing-prototypes]
>> clang diag: arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for function 'get_shstk_base' [-Wmissing-prototypes]

vim +/get_shstk_base +44 arch/riscv/include/asm/usercfi.h

    43	
  > 44	unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
    45	{
    46		return 0;
    47	}
    48	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#23 lore raw

Re: [PATCH v4 16/30] riscv/shstk: If needed allocate a new shadow stack on clone

In reply to Deepak Gupta
kernel test robot noticed the following build errors:

Hi Deepak,

kernel test robot noticed the following build errors:

[auto build test ERROR on shuah-kselftest/next]
[also build test ERROR on shuah-kselftest/fixes tip/x86/core robh/for-next arnd-asm-generic/master tip/smp/core kees/for-next/execve linus/master v6.11-rc7] [cannot apply to akpm-mm/mm-everything next-20240913]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Deepak-Gupta/mm-Introduce-ARCH_HAS_USER_SHADOW_STACK/20240913-072124
base:   https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git next
patch link:    https://lore.kernel.org/r/20240912231650.3740732-17-debug%40rivosinc.com
patch subject: [PATCH v4 16/30] riscv/shstk: If needed allocate a new shadow stack on clone
config: riscv-randconfig-r071-20240914 (https://download.01.org/0day-ci/archive/20240914/[email protected]/config)
compiler: riscv64-linux-gcc (GCC) 14.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240914/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All error/warnings (new ones prefixed by >>):

In file included from arch/riscv/include/asm/processor.h:17,
from arch/riscv/include/asm/thread_info.h:37, from include/linux/thread_info.h:60, from include/asm-generic/preempt.h:5, from ./arch/riscv/include/generated/asm/preempt.h:1, from include/linux/preempt.h:79,
from include/linux/spinlock.h:56,
from include/linux/mmzone.h:8,
from include/linux/gfp.h:7,
from include/linux/mm.h:7,
from arch/riscv/kernel/asm-offsets.c:10:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]

44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
| ^~~~~~~~~~~~~~
--
In file included from arch/riscv/include/asm/processor.h:17,
from include/linux/sched.h:13,
from kernel/ptrace.c:13:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^~~~~~~~~~~~~~
   In file included from include/linux/string.h:374,
                    from include/linux/bitmap.h:13,
                    from include/linux/cpumask.h:12,
                    from arch/riscv/include/asm/processor.h:79:
   In function 'fortify_memcpy_chk',
       inlined from 'syscall_get_arguments.isra' at arch/riscv/include/asm/syscall.h:66:2:
   include/linux/fortify-string.h:580:25: warning: call to '__read_overflow2_field' declared with attribute warning: detected read beyond size of field (2nd parameter); maybe use struct_group()? [-Wattribute-warning]
     580 |                         __read_overflow2_field(q_size_field, size);
         |                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
   In file included from arch/riscv/include/asm/processor.h:17,
                    from include/linux/mutex.h:19,
                    from include/linux/notifier.h:14,
                    from include/linux/clk.h:14,
                    from lib/vsprintf.c:22:
>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^~~~~~~~~~~~~~
   lib/vsprintf.c: In function 'va_format':
   lib/vsprintf.c:1683:9: warning: function 'va_format' might be a candidate for 'gnu_printf' format attribute [-Wsuggest-attribute=format]
    1683 |         buf += vsnprintf(buf, end > buf ? end - buf : 0, va_fmt->fmt, va);
         |         ^~~

--
In file included from arch/riscv/include/asm/processor.h:17,
from include/linux/sched.h:13, from include/linux/ratelimit.h:6, from include/linux/dev_printk.h:16, from include/linux/device.h:15, from lib/string_helpers.c:13:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^~~~~~~~~~~~~~
   lib/string_helpers.c: In function 'string_get_size':
   lib/string_helpers.c:124:46: warning: '%03u' directive output may be truncated writing between 3 and 10 bytes into a region of size 7 [-Wformat-truncation=]
     124 |                 snprintf(tmp, sizeof(tmp), ".%03u", remainder);
         |                                              ^~~~
   lib/string_helpers.c:124:44: note: directive argument in the range [0, 4294966295]
     124 |                 snprintf(tmp, sizeof(tmp), ".%03u", remainder);
         |                                            ^~~~~~~
   lib/string_helpers.c:124:17: note: 'snprintf' output between 5 and 12 bytes into a destination of size 8
     124 |                 snprintf(tmp, sizeof(tmp), ".%03u", remainder);
         |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
   In file included from arch/riscv/include/asm/processor.h:17,
                    from arch/riscv/include/asm/thread_info.h:37,
                    from include/linux/thread_info.h:60,
                    from include/asm-generic/preempt.h:5,
                    from ./arch/riscv/include/generated/asm/preempt.h:1,
                    from include/linux/preempt.h:79,
                    from include/linux/spinlock.h:56,
                    from include/linux/mmzone.h:8,
                    from include/linux/gfp.h:7,
                    from include/linux/umh.h:4,
                    from include/linux/kmod.h:9,
                    from include/linux/module.h:17,
                    from lib/test_bitops.c:10:
>> arch/riscv/include/asm/usercfi.h:44:15: error: no previous prototype for 'get_shstk_base' [-Werror=missing-prototypes]

44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
| ^~~~~~~~~~~~~~
cc1: all warnings being treated as errors
--
In file included from arch/riscv/include/asm/processor.h:17,
from include/linux/mutex.h:19,
from kernel/locking/lockdep.c:30:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]

44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
| ^~~~~~~~~~~~~~
In file included from kernel/locking/lockdep.c:62:
kernel/locking/lockdep_internals.h:69:28: warning: 'LOCKF_USED_IN_IRQ_READ' defined but not used [-Wunused-const-variable=]
69 | static const unsigned long LOCKF_USED_IN_IRQ_READ =
| ^~~~~~~~~~~~~~~~~~~~~~
kernel/locking/lockdep_internals.h:63:28: warning: 'LOCKF_ENABLED_IRQ_READ' defined but not used [-Wunused-const-variable=]
63 | static const unsigned long LOCKF_ENABLED_IRQ_READ =
| ^~~~~~~~~~~~~~~~~~~~~~
kernel/locking/lockdep_internals.h:57:28: warning: 'LOCKF_USED_IN_IRQ' defined but not used [-Wunused-const-variable=]
57 | static const unsigned long LOCKF_USED_IN_IRQ =
| ^~~~~~~~~~~~~~~~~
kernel/locking/lockdep_internals.h:51:28: warning: 'LOCKF_ENABLED_IRQ' defined but not used [-Wunused-const-variable=]
51 | static const unsigned long LOCKF_ENABLED_IRQ =
| ^~~~~~~~~~~~~~~~~
--
In file included from arch/riscv/include/asm/processor.h:17,

                    from arch/riscv/include/asm/thread_info.h:37,
                    from include/linux/thread_info.h:60,
                    from include/asm-generic/preempt.h:5,
                    from ./arch/riscv/include/generated/asm/preempt.h:1,
                    from include/linux/preempt.h:79,
                    from include/linux/spinlock.h:56,
                    from include/linux/mmzone.h:8,
                    from include/linux/gfp.h:7,
                    from include/linux/umh.h:4,
                    from include/linux/kmod.h:9,
                    from include/linux/module.h:17,
                    from net/sunrpc/clnt.c:22:
>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^~~~~~~~~~~~~~
   net/sunrpc/clnt.c: In function 'rpc_create':
   net/sunrpc/clnt.c:582:75: warning: '%s' directive output may be truncated writing up to 107 bytes into a region of size 48 [-Wformat-truncation=]
     582 |                                 snprintf(servername, sizeof(servername), "%s",
         |                                                                           ^~
   net/sunrpc/clnt.c:582:33: note: 'snprintf' output between 1 and 108 bytes into a destination of size 48
     582 |                                 snprintf(servername, sizeof(servername), "%s",
         |                                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     583 |                                          sun->sun_path);
         |                                          ~~~~~~~~~~~~~~

--
In file included from arch/riscv/include/asm/processor.h:17,
from arch/riscv/include/asm/thread_info.h:37, from include/linux/thread_info.h:60, from include/asm-generic/preempt.h:5, from ./arch/riscv/include/generated/asm/preempt.h:1, from include/linux/preempt.h:79,
from include/linux/spinlock.h:56,
from include/linux/mmzone.h:8,
from include/linux/gfp.h:7,
from include/linux/umh.h:4,
from include/linux/kmod.h:9,
from include/linux/module.h:17,
from drivers/clk/clkdev.c:9:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^~~~~~~~~~~~~~
   drivers/clk/clkdev.c: In function 'vclkdev_alloc':
   drivers/clk/clkdev.c:185:17: warning: function 'vclkdev_alloc' might be a candidate for 'gnu_printf' format attribute [-Wsuggest-attribute=format]
     185 |                 res = vsnprintf(cla->dev_id, sizeof(cla->dev_id), dev_fmt, ap);
         |                 ^~~
--
   riscv64-linux-ld: net/dns_resolver/dns_query.o: in function `get_shstk_base':
>> arch/riscv/include/asm/usercfi.h:45: multiple definition of `get_shstk_base'; net/dns_resolver/dns_key.o:arch/riscv/include/asm/usercfi.h:45: first defined here

--
In file included from arch/riscv/include/asm/processor.h:17,
from include/linux/sched.h:13, from include/linux/ratelimit.h:6, from include/linux/dev_printk.h:16, from include/linux/device.h:15, from include/linux/miscdevice.h:7, from drivers/misc/xilinx_sdfec.c:13:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]
      44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
         |               ^~~~~~~~~~~~~~
   drivers/misc/xilinx_sdfec.c: In function 'xsdfec_probe':
   drivers/misc/xilinx_sdfec.c:1404:57: warning: '%d' directive output may be truncated writing between 1 and 10 bytes into a region of size 6 [-Wformat-truncation=]
    1404 |         snprintf(xsdfec->dev_name, DEV_NAME_LEN, "xsdfec%d", xsdfec->dev_id);
         |                                                         ^~
   drivers/misc/xilinx_sdfec.c:1404:50: note: directive argument in the range [0, 2147483647]
    1404 |         snprintf(xsdfec->dev_name, DEV_NAME_LEN, "xsdfec%d", xsdfec->dev_id);
         |                                                  ^~~~~~~~~~
   drivers/misc/xilinx_sdfec.c:1404:9: note: 'snprintf' output between 8 and 17 bytes into a destination of size 12
    1404 |         snprintf(xsdfec->dev_name, DEV_NAME_LEN, "xsdfec%d", xsdfec->dev_id);
         |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--
In file included from arch/riscv/include/asm/processor.h:17,
from include/linux/sched.h:13, from include/linux/ratelimit.h:6, from include/linux/dev_printk.h:16, from include/linux/device.h:15, from include/linux/node.h:18, from include/linux/cpu.h:17,
from kernel/time/hrtimer.c:25:

>> arch/riscv/include/asm/usercfi.h:44:15: warning: no previous prototype for 'get_shstk_base' [-Wmissing-prototypes]

44 | unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
| ^~~~~~~~~~~~~~
kernel/time/hrtimer.c:121:35: warning: initialized field overwritten [-Woverride-init]
121 | [CLOCK_REALTIME] = HRTIMER_BASE_REALTIME,
| ^~~~~~~~~~~~~~~~~~~~~
kernel/time/hrtimer.c:121:35: note: (near initialization for 'hrtimer_clock_to_base_table[0]') kernel/time/hrtimer.c:122:35: warning: initialized field overwritten [-Woverride-init]
122 | [CLOCK_MONOTONIC] = HRTIMER_BASE_MONOTONIC,
| ^~~~~~~~~~~~~~~~~~~~~~
kernel/time/hrtimer.c:122:35: note: (near initialization for 'hrtimer_clock_to_base_table[1]') kernel/time/hrtimer.c:123:35: warning: initialized field overwritten [-Woverride-init]
123 | [CLOCK_BOOTTIME] = HRTIMER_BASE_BOOTTIME,
| ^~~~~~~~~~~~~~~~~~~~~
kernel/time/hrtimer.c:123:35: note: (near initialization for 'hrtimer_clock_to_base_table[7]') kernel/time/hrtimer.c:124:35: warning: initialized field overwritten [-Woverride-init]
124 | [CLOCK_TAI] = HRTIMER_BASE_TAI,
| ^~~~~~~~~~~~~~~~
kernel/time/hrtimer.c:124:35: note: (near initialization for 'hrtimer_clock_to_base_table[11]')
..

vim +/get_shstk_base +44 arch/riscv/include/asm/usercfi.h

    43	
  > 44	unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
  > 45	{
    46		return 0;
    47	}
    48	
Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#42 lore raw

Re: [PATCH v4 28/30] riscv: Documentation for landing pad / indirect branch tracking

In reply to Deepak Gupta
Quoted 8 lines · Deepak Gupta

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

Don't forget to add toctree entry:

---- >8 ----

Documentation/arch/riscv/index.rst +1 -0
index eecf347ce84944..be7237b6968213 100644
@@ -14,6 +14,7 @@ RISC-V architecture
     uabi
     vector
     cmodx
+    zicfilp
 
     features
 
Quoted 8 lines
(quoted diff) +8 -0
+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)

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+		- 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.

Sphinx reports new htmldocs warnings:

Documentation/arch/riscv/zicfilp.rst:30: ERROR: Unexpected indentation. Documentation/arch/riscv/zicfilp.rst:96: ERROR: Unexpected indentation.

I have to fix up the lists:

---- >8 ----

Documentation/arch/riscv/zicfilp.rst +19 -16
index 23013ee711ac2c..c0fad1b5caa3d8 100644
@@ -23,22 +23,24 @@ 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
+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)
+- indirect control transfers must land on a landing pad instruction `lpad`.
+  There are two exception to this rule:
 
-		- rs1 = x7. On RISC-V compiler usually does below to reach function
-		  which is beyond the offset possible J-type instruction.
+  - rs1 = x1 or rs1 = x5, i.e. a return from a function and returns are
+    protected using shadow stack (see zicfiss.rst)
 
-			"auipc x7, <imm>"
-			"jalr (x7)"
+  - rs1 = x7. On RISC-V compiler usually does below to reach function
+    which is beyond the offset possible J-type instruction.
 
-		  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.
+      "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>` with `rd=x0`` and is a HINT
 nop. `lpad` instruction must be aligned on 4 byte boundary and compares 20 bit
@@ -92,10 +94,11 @@ to lock current settings.
 --------------------------------------------------
 
 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`
+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)

Review

Quoted 7 lines
(quoted diff) +7 -0
+
+`lpad` instruction is pseudo of `auipc rd, <imm_20bit>` with `rd=x0`` and is a HINT
+nop. `lpad` instruction must be aligned on 4 byte boundary and compares 20 bit
+immediate withx7. 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`.
+

Also inline identifiers/keywords to be consistent with rest of riscv docs:

---- >8 ----

Documentation/arch/riscv/zicfilp.rst +33 -32

108 lines not on this page · raw message

Thanks.

Signature · 1 line
An old man doll... just what I always wanted! - Clara
#44 lore raw

Re: [PATCH v4 29/30] riscv: Documentation for shadow stack on riscv

In reply to Deepak Gupta
Quoted 8 lines · Deepak Gupta

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

Add the toctree entry:

---- >8 ----

Documentation/arch/riscv/index.rst +1 -0
index be7237b6968213..e240eb0ceb70c4 100644
@@ -15,6 +15,7 @@ RISC-V architecture
     vector
     cmodx
     zicfilp
+    zicfiss
 
     features
 

Review

Quoted 8 lines
(quoted diff) +8 -0
+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;
+};

Sphinx reports indentation warning again:

Documentation/arch/riscv/zicfiss.rst:163: WARNING: Definition list ends without a blank line; unexpected unindent.

I have to wrap __sc_riscv_cfi_state struct definition as a literal code block:

---- >8 ----

Documentation/arch/riscv/zicfiss.rst +3 -3
index f133b6af9c1525..96d85ed352b146 100644
@@ -155,12 +155,12 @@ make sure that there is a `shadow stack token` in addition to invoking `sigretur
 -----------------------
 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.
+tracking. It has been kept today in order to allow backward compatibility in future::
 
-struct __sc_riscv_cfi_state {
+  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`

Review

Quoted 6 lines
(quoted diff) +6 -0
+
+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.

Also inline the code identifiers (keywords):

---- >8 ----

Documentation/arch/riscv/zicfiss.rst +63 -60

190 lines not on this page · raw message

Thanks.

Signature · 1 line
An old man doll... just what I always wanted! - Clara
#34 lore raw

Re: [PATCH v4 23/30] riscv signal: save and restore of shadow stack for signal

In reply to Andy Chiu
Quoted 139 lines · Andy Chiu

Hi Deepak,

Deepak Gupta <[email protected]> 於 2024年9月13日 週五 上午1:20寫道:

Quoted 136 lines

Save shadow stack pointer in sigcontext structure while delivering signal. Restore shadow stack pointer from sigcontext on sigreturn.

As part of save operation, kernel uses ssamoswap to save snapshot of current shadow stack on shadow stack itself (can be called as a save token). During restore on sigreturn, kernel retrieves token from top of shadow stack and validates it. This allows that user mode can't arbitrary pivot to any shadow stack address without having a token and thus provide strong security assurance between signaly delivery and sigreturn window.

---
 arch/riscv/include/asm/usercfi.h | 19 ++++++++++
 arch/riscv/kernel/signal.c       | 62 +++++++++++++++++++++++++++++++-
 arch/riscv/kernel/usercfi.c      | 57 +++++++++++++++++++++++++++++
 3 files changed, 137 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +19 -0
index 20a9102cce51..d5050a5df26c 100644
@@ -8,6 +8,7 @@
 #ifndef __ASSEMBLY__
 #include <linux/types.h>
 #include <linux/prctl.h>
+#include <linux/errno.h>
 
 struct task_struct;
 struct kernel_clone_args;
@@ -35,6 +36,9 @@ bool is_shstk_locked(struct task_struct *task);
 bool is_shstk_allocated(struct task_struct *task);
 void set_shstk_lock(struct task_struct *task);
 void set_shstk_status(struct task_struct *task, bool enable);
+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);
 bool is_indir_lp_enabled(struct task_struct *task);
 bool is_indir_lp_locked(struct task_struct *task);
 void set_indir_lp_status(struct task_struct *task, bool enable);
@@ -96,6 +100,21 @@ static inline void set_shstk_status(struct task_struct *task, bool enable)
 
 }
 
+static inline int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline unsigned long get_active_shstk(struct task_struct *task)
+{
+       return 0;
+}
+
 static inline bool is_indir_lp_enabled(struct task_struct *task)
 {
        return false;
arch/riscv/kernel/signal.c +35 -0
index dcd282419456..7d5c1825650f 100644
@@ -22,6 +22,7 @@
 #include <asm/vector.h>
 #include <asm/csr.h>
 #include <asm/cacheflush.h>
+#include <asm/usercfi.h>
 
 unsigned long signal_minsigstksz __ro_after_init;
 
@@ -153,6 +154,16 @@ static long restore_sigcontext(struct pt_regs *regs,
        void __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
        __u32 rsvd;
        long err;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
+
+       sc_cfi = (struct __sc_riscv_cfi_state *)
+                ((unsigned long) sc_ext_ptr + sizeof(struct __riscv_ctx_hdr));
+
+       if (has_vector() && riscv_v_vstate_query(regs))
+               sc_cfi = (struct __sc_riscv_cfi_state *)
+                        ((unsigned long) sc_cfi + riscv_v_sc_size);
+
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_from_user(regs, &sc->sc_regs, sizeof(sc->sc_regs));
        if (unlikely(err))
@@ -172,6 +183,24 @@ static long restore_sigcontext(struct pt_regs *regs,
        if (unlikely(rsvd))
                return -EINVAL;
 
+       /*
+        * Restore shadow stack as a form of token stored on shadow stack itself as a safe
+        * way to restore.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments.
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= __copy_from_user(&ss_ptr, &sc_cfi->ss_ptr, sizeof(unsigned long));
+               err |= restore_user_shstk(current, ss_ptr);
+       }
+
        while (!err) {
                __u32 magic, size;
                struct __riscv_ctx_hdr __user *head = sc_ext_ptr;
@@ -215,6 +244,10 @@ static size_t get_rt_frame_size(bool cal_all)
                if (cal_all || riscv_v_vstate_query(task_pt_regs(current)))
                        total_context_size += riscv_v_sc_size;
        }
+
+       if (is_shstk_enabled(current))
+               total_context_size += sizeof(struct __sc_riscv_cfi_state);
+
        /*
         * Preserved a __riscv_ctx_hdr for END signal context header if an
         * extension uses __riscv_extra_ext_header
@@ -276,18 +309,40 @@ static long setup_sigcontext(struct rt_sigframe __user *frame,
 {
        struct sigcontext __user *sc = &frame->uc.uc_mcontext;
        struct __riscv_ctx_hdr __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
        long err;
 
Quoted 8 lines

arch/riscv/kernel/signal.c static long setup_sigcontext(struct rt_sigframe __user *frame, · line 317

Quoted 2 lines
arch/riscv/kernel/signal.c +2 -0
+       sc_cfi = (struct __sc_riscv_cfi_state *) (sc_ext_ptr + 1);
+

Is it intended that cfi sigcontext does not follow the sigcontext rule setup by Vector? It seems like there is no extension header (struct __riscv_ctx_hdr) defined for cfi sigcontext here. If the sigcontext is directly appended to the signal stack, the user may not be able to recognize the meaning without defining a new ABI.

Hmm... I didn't realize that struct struct __riscv_ctx_hdr is strongly tied to vector state. I was under the impression that any new extended state addition would require this header to be present.

cfi sigcontenxt doesn't need any ABI between user and kernel here. We need this space so that kernel can save a pointer to shadow stack token on signal delivery. Once sigreturn happens, kernel will use the same pointer, verify the token saved on shadow stack and restore shadow stack for user mode. At no point in this scheme, user mode is required to perform any action.

All that is needed is that user mode doesn't accidenly trample at this offset.

Since I was under the impression that struct __riscv_ctx_hdr is there for context extension and must be present for any state beyond sc_regs, I assumed that I must make space for this header (even if vector state is not present).

Quoted 3 lines

BTW, I have sent a patch[1] that refactor setup_sigcontext so it'd be easier for future extensions to expand on the signal stack.

I can adopt to this, although its orthogonal to what we are discussing here.

Quoted 133 lines
Quoted 124 lines
arch/riscv/kernel/signal.c +24 -1
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_to_user(&sc->sc_regs, regs, sizeof(sc->sc_regs));
        /* Save the floating-point state. */
        if (has_fpu())
                err |= save_fp_state(regs, &sc->sc_fpregs);
        /* Save the vector state. */
-       if (has_vector() && riscv_v_vstate_query(regs))
+       if (has_vector() && riscv_v_vstate_query(regs)) {
                err |= save_v_state(regs, (void __user **)&sc_ext_ptr);
+               sc_cfi = (struct __sc_riscv_cfi_state *) ((unsigned long) sc_cfi + riscv_v_sc_size);
+       }
        /* Write zero to fp-reserved space and check it on restore_sigcontext */
        err |= __put_user(0, &sc->sc_extdesc.reserved);
+       /*
+        * Save a pointer to shadow stack itself on shadow stack as a form of token.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments. Any
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= save_user_shstk(current, &ss_ptr);
+               err |= __put_user(ss_ptr, &sc_cfi->ss_ptr);
+       }
        /* And put END __riscv_ctx_hdr at the end. */
        err |= __put_user(END_MAGIC, &sc_ext_ptr->magic);
        err |= __put_user(END_HDR_SIZE, &sc_ext_ptr->size);
@@ -345,6 +400,11 @@ static int setup_rt_frame(struct ksignal *ksig, sigset_t *set,
 #ifdef CONFIG_MMU
        regs->ra = (unsigned long)VDSO_SYMBOL(
                current->mm->context.vdso, rt_sigreturn);
+
+       /* if bcfi is enabled x1 (ra) and x5 (t0) must match. not sure if we need this? */
+       if (is_shstk_enabled(current))
+               regs->t0 = regs->ra;
+
 #else
        /*
         * For the nommu case we don't have a VDSO.  Instead we push two
arch/riscv/kernel/usercfi.c +57 -1
index 8da509afdbe9..40c32258b6ec 100644
@@ -52,6 +52,11 @@ void set_active_shstk(struct task_struct *task, unsigned long shstk_addr)
        task->thread_info.user_cfi_state.user_shdw_stk = shstk_addr;
 }
 
+unsigned long get_active_shstk(struct task_struct *task)
+{
+       return task->thread_info.user_cfi_state.user_shdw_stk;
+}
+
 void set_shstk_status(struct task_struct *task, bool enable)
 {
        task->thread_info.user_cfi_state.ubcfi_en = enable ? 1 : 0;
@@ -164,6 +169,58 @@ static int create_rstor_token(unsigned long ssp, unsigned long *token_addr)
        return 0;
 }
 
+/*
+ * Save user shadow stack pointer on shadow stack itself and return pointer to saved location
+ * returns -EFAULT if operation was unsuccessful
+ */
+int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       unsigned long ss_ptr = 0;
+       unsigned long token_loc = 0;
+       int ret = 0;
+
+       if (saved_shstk_ptr == NULL)
+               return -EINVAL;
+
+       ss_ptr = get_active_shstk(tsk);
+       ret = create_rstor_token(ss_ptr, &token_loc);
+
+       if (!ret) {
+               *saved_shstk_ptr = token_loc;
+               set_active_shstk(tsk, token_loc);
+       }
+
+       return ret;
+}
+
+/*
+ * Restores user shadow stack pointer from token on shadow stack for task `tsk`
+ * returns -EFAULT if operation was unsuccessful
+ */
+int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       unsigned long token = 0;
+
+       token = amo_user_shstk((unsigned long __user *)shstk_ptr, 0);
+
+       if (token == -1)
+               return -EFAULT;
+
+       /* invalid token, return EINVAL */
+       if ((token - shstk_ptr) != SHSTK_ENTRY_SIZE) {
+               pr_info_ratelimited(
+                               "%s[%d]: bad restore token in %s: pc=%p sp=%p, token=%p, shstk_ptr=%p\n",
+                               tsk->comm, task_pid_nr(tsk), __func__,
+                               (void *)(task_pt_regs(tsk)->epc), (void *)(task_pt_regs(tsk)->sp),
+                               (void *)token, (void *)shstk_ptr);
+               return -EINVAL;
+       }
+
+       /* all checks passed, set active shstk and return success */
+       set_active_shstk(tsk, token);
+       return 0;
+}
+
 static unsigned long allocate_shadow_stack(unsigned long addr, unsigned long size,
                                unsigned long token_offset,
                                bool set_tok)
--

2.45.0

Quoted 4 lines

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

- [1]: https://lore.kernel.org/all/[email protected]/

Thanks,
Andy

#30 lore raw

Re: [PATCH v4 21/30] riscv/traps: Introduce software check exception

In reply to Andy Chiu
Quoted 95 lines · Andy Chiu

Hi Deepak

Deepak Gupta <[email protected]> 於 2024年9月13日 週五 上午2:32寫道:

Quoted 92 lines

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/include/asm/entry-common.h   |  2 ++
 arch/riscv/kernel/entry.S               |  3 ++
 arch/riscv/kernel/traps.c               | 38 +++++++++++++++++++++++++
 4 files changed, 44 insertions(+)
arch/riscv/include/asm/asm-prototypes.h +1 -0
index cd627ec289f1..5a27cefd7805 100644
@@ -51,6 +51,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/include/asm/entry-common.h +2 -0
index 2293e535f865..4068c7e5452a 100644
@@ -39,4 +39,6 @@ static inline int handle_misaligned_store(struct pt_regs *regs)
 }
 #endif
 
+bool handle_user_cfi_violation(struct pt_regs *regs);
+
 #endif /* _ASM_RISCV_ENTRY_COMMON_H */
arch/riscv/kernel/entry.S +3 -0
index ca9203e6d76d..2ec75ba864a8 100644
@@ -384,6 +384,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 +23 -0
index 51ebfd23e007..32d1453bed72 100644
@@ -354,6 +354,44 @@ 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.
Quoted 8 lines

arch/riscv/kernel/traps.c void do_trap_ecall_u(struct pt_regs *regs) · line 382

Quoted 3 lines
arch/riscv/kernel/traps.c +3 -0
+ * b) `sspopchk` instruction finds a mismatch between top of shadow stack (ssp)
+ *    and x1/x5. reported code in `xtval` is 3.
+ */

It seems like this trap handler does not follow generic entry. This can cause problems as signal delivery is done in irqentry_exit_to_user_mode(). Please reference the commit f0bddf50586d ("riscv: entry: Convert to generic entry") for more information.

Ack. will fix it.

Quoted 27 lines
Quoted 20 lines
arch/riscv/kernel/traps.c +12 -1
+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)
 {
--

2.45.0

Quoted 4 lines

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

Cheers,
Andy

#35 lore raw

Re: [PATCH v4 23/30] riscv signal: save and restore of shadow stack for signal

In reply to Deepak Gupta

Deepak Gupta <[email protected]> 於 2024年9月17日 週二 上午12:03寫道:

Quoted 150 lines · Andy Chiu
Quoted 139 lines

Hi Deepak,

Deepak Gupta <[email protected]> 於 2024年9月13日 週五 上午1:20寫道:

Quoted 136 lines

Save shadow stack pointer in sigcontext structure while delivering signal. Restore shadow stack pointer from sigcontext on sigreturn.

As part of save operation, kernel uses ssamoswap to save snapshot of current shadow stack on shadow stack itself (can be called as a save token). During restore on sigreturn, kernel retrieves token from top of shadow stack and validates it. This allows that user mode can't arbitrary pivot to any shadow stack address without having a token and thus provide strong security assurance between signaly delivery and sigreturn window.

---
 arch/riscv/include/asm/usercfi.h | 19 ++++++++++
 arch/riscv/kernel/signal.c       | 62 +++++++++++++++++++++++++++++++-
 arch/riscv/kernel/usercfi.c      | 57 +++++++++++++++++++++++++++++
 3 files changed, 137 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +19 -0
index 20a9102cce51..d5050a5df26c 100644
@@ -8,6 +8,7 @@
 #ifndef __ASSEMBLY__
 #include <linux/types.h>
 #include <linux/prctl.h>
+#include <linux/errno.h>
 
 struct task_struct;
 struct kernel_clone_args;
@@ -35,6 +36,9 @@ bool is_shstk_locked(struct task_struct *task);
 bool is_shstk_allocated(struct task_struct *task);
 void set_shstk_lock(struct task_struct *task);
 void set_shstk_status(struct task_struct *task, bool enable);
+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);
 bool is_indir_lp_enabled(struct task_struct *task);
 bool is_indir_lp_locked(struct task_struct *task);
 void set_indir_lp_status(struct task_struct *task, bool enable);
@@ -96,6 +100,21 @@ static inline void set_shstk_status(struct task_struct *task, bool enable)
 
 }
 
+static inline int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline unsigned long get_active_shstk(struct task_struct *task)
+{
+       return 0;
+}
+
 static inline bool is_indir_lp_enabled(struct task_struct *task)
 {
        return false;
arch/riscv/kernel/signal.c +35 -0
index dcd282419456..7d5c1825650f 100644
@@ -22,6 +22,7 @@
 #include <asm/vector.h>
 #include <asm/csr.h>
 #include <asm/cacheflush.h>
+#include <asm/usercfi.h>
 
 unsigned long signal_minsigstksz __ro_after_init;
 
@@ -153,6 +154,16 @@ static long restore_sigcontext(struct pt_regs *regs,
        void __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
        __u32 rsvd;
        long err;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
+
+       sc_cfi = (struct __sc_riscv_cfi_state *)
+                ((unsigned long) sc_ext_ptr + sizeof(struct __riscv_ctx_hdr));
+
+       if (has_vector() && riscv_v_vstate_query(regs))
+               sc_cfi = (struct __sc_riscv_cfi_state *)
+                        ((unsigned long) sc_cfi + riscv_v_sc_size);
+
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_from_user(regs, &sc->sc_regs, sizeof(sc->sc_regs));
        if (unlikely(err))
@@ -172,6 +183,24 @@ static long restore_sigcontext(struct pt_regs *regs,
        if (unlikely(rsvd))
                return -EINVAL;
 
+       /*
+        * Restore shadow stack as a form of token stored on shadow stack itself as a safe
+        * way to restore.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments.
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= __copy_from_user(&ss_ptr, &sc_cfi->ss_ptr, sizeof(unsigned long));
+               err |= restore_user_shstk(current, ss_ptr);
+       }
+
        while (!err) {
                __u32 magic, size;
                struct __riscv_ctx_hdr __user *head = sc_ext_ptr;
@@ -215,6 +244,10 @@ static size_t get_rt_frame_size(bool cal_all)
                if (cal_all || riscv_v_vstate_query(task_pt_regs(current)))
                        total_context_size += riscv_v_sc_size;
        }
+
+       if (is_shstk_enabled(current))
+               total_context_size += sizeof(struct __sc_riscv_cfi_state);
+
        /*
         * Preserved a __riscv_ctx_hdr for END signal context header if an
         * extension uses __riscv_extra_ext_header
@@ -276,18 +309,40 @@ static long setup_sigcontext(struct rt_sigframe __user *frame,
 {
        struct sigcontext __user *sc = &frame->uc.uc_mcontext;
        struct __riscv_ctx_hdr __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
        long err;
 
Quoted 8 lines

arch/riscv/kernel/signal.c static long setup_sigcontext(struct rt_sigframe __user *frame, · line 317

Quoted 2 lines
arch/riscv/kernel/signal.c +2 -0
+       sc_cfi = (struct __sc_riscv_cfi_state *) (sc_ext_ptr + 1);
+

Is it intended that cfi sigcontext does not follow the sigcontext rule setup by Vector? It seems like there is no extension header (struct __riscv_ctx_hdr) defined for cfi sigcontext here. If the sigcontext is directly appended to the signal stack, the user may not be able to recognize the meaning without defining a new ABI.

Quoted 3 lines

Hmm... I didn't realize that struct struct __riscv_ctx_hdr is strongly tied to vector state. I was under the impression that any new extended state addition would require this header to be present.

__riscv_ctx_hdr is not tied to vector state. Your impression is not wrong. When sigcontext for Vector was designed, it is intended that every new extension should define its header, please check RISCV_V_MAGIC. The magic value and the size of the extension added to the sigcontext are written into each hdr->magic and hdr->size. However, I did not find the corresponding code in this patch. Or, maybe I am missing something obvious. Could you help point me out it?

Quoted 14 lines

cfi sigcontenxt doesn't need any ABI between user and kernel here. We need this space so that kernel can save a pointer to shadow stack token on signal delivery. Once sigreturn happens, kernel will use the same pointer, verify the token saved on shadow stack and restore shadow stack for user mode. At no point in this scheme, user mode is required to perform any action.

All that is needed is that user mode doesn't accidenly trample at this offset.

Since I was under the impression that struct __riscv_ctx_hdr is there for context extension and must be present for any state beyond sc_regs, I assumed that I must make space for this header (even if vector state is not present).

Quoted 1 line
Quoted 138 lines
Quoted 2 lines

BTW, I have sent a patch[1] that refactor setup_sigcontext so it'd be easier for future extensions to expand on the signal stack.

I can adopt to this, although its orthogonal to what we are discussing here.

Quoted 133 lines
Quoted 124 lines
arch/riscv/kernel/signal.c +24 -1
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_to_user(&sc->sc_regs, regs, sizeof(sc->sc_regs));
        /* Save the floating-point state. */
        if (has_fpu())
                err |= save_fp_state(regs, &sc->sc_fpregs);
        /* Save the vector state. */
-       if (has_vector() && riscv_v_vstate_query(regs))
+       if (has_vector() && riscv_v_vstate_query(regs)) {
                err |= save_v_state(regs, (void __user **)&sc_ext_ptr);
+               sc_cfi = (struct __sc_riscv_cfi_state *) ((unsigned long) sc_cfi + riscv_v_sc_size);
+       }
        /* Write zero to fp-reserved space and check it on restore_sigcontext */
        err |= __put_user(0, &sc->sc_extdesc.reserved);
+       /*
+        * Save a pointer to shadow stack itself on shadow stack as a form of token.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments. Any
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= save_user_shstk(current, &ss_ptr);
+               err |= __put_user(ss_ptr, &sc_cfi->ss_ptr);
+       }
        /* And put END __riscv_ctx_hdr at the end. */
        err |= __put_user(END_MAGIC, &sc_ext_ptr->magic);
        err |= __put_user(END_HDR_SIZE, &sc_ext_ptr->size);
@@ -345,6 +400,11 @@ static int setup_rt_frame(struct ksignal *ksig, sigset_t *set,
 #ifdef CONFIG_MMU
        regs->ra = (unsigned long)VDSO_SYMBOL(
                current->mm->context.vdso, rt_sigreturn);
+
+       /* if bcfi is enabled x1 (ra) and x5 (t0) must match. not sure if we need this? */
+       if (is_shstk_enabled(current))
+               regs->t0 = regs->ra;
+
 #else
        /*
         * For the nommu case we don't have a VDSO.  Instead we push two
arch/riscv/kernel/usercfi.c +57 -1
index 8da509afdbe9..40c32258b6ec 100644
@@ -52,6 +52,11 @@ void set_active_shstk(struct task_struct *task, unsigned long shstk_addr)
        task->thread_info.user_cfi_state.user_shdw_stk = shstk_addr;
 }
 
+unsigned long get_active_shstk(struct task_struct *task)
+{
+       return task->thread_info.user_cfi_state.user_shdw_stk;
+}
+
 void set_shstk_status(struct task_struct *task, bool enable)
 {
        task->thread_info.user_cfi_state.ubcfi_en = enable ? 1 : 0;
@@ -164,6 +169,58 @@ static int create_rstor_token(unsigned long ssp, unsigned long *token_addr)
        return 0;
 }
 
+/*
+ * Save user shadow stack pointer on shadow stack itself and return pointer to saved location
+ * returns -EFAULT if operation was unsuccessful
+ */
+int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       unsigned long ss_ptr = 0;
+       unsigned long token_loc = 0;
+       int ret = 0;
+
+       if (saved_shstk_ptr == NULL)
+               return -EINVAL;
+
+       ss_ptr = get_active_shstk(tsk);
+       ret = create_rstor_token(ss_ptr, &token_loc);
+
+       if (!ret) {
+               *saved_shstk_ptr = token_loc;
+               set_active_shstk(tsk, token_loc);
+       }
+
+       return ret;
+}
+
+/*
+ * Restores user shadow stack pointer from token on shadow stack for task `tsk`
+ * returns -EFAULT if operation was unsuccessful
+ */
+int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       unsigned long token = 0;
+
+       token = amo_user_shstk((unsigned long __user *)shstk_ptr, 0);
+
+       if (token == -1)
+               return -EFAULT;
+
+       /* invalid token, return EINVAL */
+       if ((token - shstk_ptr) != SHSTK_ENTRY_SIZE) {
+               pr_info_ratelimited(
+                               "%s[%d]: bad restore token in %s: pc=%p sp=%p, token=%p, shstk_ptr=%p\n",
+                               tsk->comm, task_pid_nr(tsk), __func__,
+                               (void *)(task_pt_regs(tsk)->epc), (void *)(task_pt_regs(tsk)->sp),
+                               (void *)token, (void *)shstk_ptr);
+               return -EINVAL;
+       }
+
+       /* all checks passed, set active shstk and return success */
+       set_active_shstk(tsk, token);
+       return 0;
+}
+
 static unsigned long allocate_shadow_stack(unsigned long addr, unsigned long size,
                                unsigned long token_offset,
                                bool set_tok)
--

2.45.0

Quoted 4 lines

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

- [1]: https://lore.kernel.org/all/[email protected]/

Thanks,
Andy

Regards,
Andy

#36 lore raw

Re: [PATCH v4 23/30] riscv signal: save and restore of shadow stack for signal

Quoted 155 lines · Andy Chiu

Deepak Gupta <[email protected]> 於 2024年9月17日 週二 上午12:03寫道:

Quoted 150 lines · Andy Chiu
Quoted 139 lines

Hi Deepak,

Deepak Gupta <[email protected]> 於 2024年9月13日 週五 上午1:20寫道:

Quoted 136 lines

Save shadow stack pointer in sigcontext structure while delivering signal. Restore shadow stack pointer from sigcontext on sigreturn.

As part of save operation, kernel uses ssamoswap to save snapshot of current shadow stack on shadow stack itself (can be called as a save token). During restore on sigreturn, kernel retrieves token from top of shadow stack and validates it. This allows that user mode can't arbitrary pivot to any shadow stack address without having a token and thus provide strong security assurance between signaly delivery and sigreturn window.

---
 arch/riscv/include/asm/usercfi.h | 19 ++++++++++
 arch/riscv/kernel/signal.c       | 62 +++++++++++++++++++++++++++++++-
 arch/riscv/kernel/usercfi.c      | 57 +++++++++++++++++++++++++++++
 3 files changed, 137 insertions(+), 1 deletion(-)
arch/riscv/include/asm/usercfi.h +19 -0
index 20a9102cce51..d5050a5df26c 100644
@@ -8,6 +8,7 @@
 #ifndef __ASSEMBLY__
 #include <linux/types.h>
 #include <linux/prctl.h>
+#include <linux/errno.h>
 
 struct task_struct;
 struct kernel_clone_args;
@@ -35,6 +36,9 @@ bool is_shstk_locked(struct task_struct *task);
 bool is_shstk_allocated(struct task_struct *task);
 void set_shstk_lock(struct task_struct *task);
 void set_shstk_status(struct task_struct *task, bool enable);
+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);
 bool is_indir_lp_enabled(struct task_struct *task);
 bool is_indir_lp_locked(struct task_struct *task);
 void set_indir_lp_status(struct task_struct *task, bool enable);
@@ -96,6 +100,21 @@ static inline void set_shstk_status(struct task_struct *task, bool enable)
 
 }
 
+static inline int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       return -EINVAL;
+}
+
+static inline unsigned long get_active_shstk(struct task_struct *task)
+{
+       return 0;
+}
+
 static inline bool is_indir_lp_enabled(struct task_struct *task)
 {
        return false;
arch/riscv/kernel/signal.c +35 -0
index dcd282419456..7d5c1825650f 100644
@@ -22,6 +22,7 @@
 #include <asm/vector.h>
 #include <asm/csr.h>
 #include <asm/cacheflush.h>
+#include <asm/usercfi.h>
 
 unsigned long signal_minsigstksz __ro_after_init;
 
@@ -153,6 +154,16 @@ static long restore_sigcontext(struct pt_regs *regs,
        void __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
        __u32 rsvd;
        long err;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
+
+       sc_cfi = (struct __sc_riscv_cfi_state *)
+                ((unsigned long) sc_ext_ptr + sizeof(struct __riscv_ctx_hdr));
+
+       if (has_vector() && riscv_v_vstate_query(regs))
+               sc_cfi = (struct __sc_riscv_cfi_state *)
+                        ((unsigned long) sc_cfi + riscv_v_sc_size);
+
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_from_user(regs, &sc->sc_regs, sizeof(sc->sc_regs));
        if (unlikely(err))
@@ -172,6 +183,24 @@ static long restore_sigcontext(struct pt_regs *regs,
        if (unlikely(rsvd))
                return -EINVAL;
 
+       /*
+        * Restore shadow stack as a form of token stored on shadow stack itself as a safe
+        * way to restore.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments.
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= __copy_from_user(&ss_ptr, &sc_cfi->ss_ptr, sizeof(unsigned long));
+               err |= restore_user_shstk(current, ss_ptr);
+       }
+
        while (!err) {
                __u32 magic, size;
                struct __riscv_ctx_hdr __user *head = sc_ext_ptr;
@@ -215,6 +244,10 @@ static size_t get_rt_frame_size(bool cal_all)
                if (cal_all || riscv_v_vstate_query(task_pt_regs(current)))
                        total_context_size += riscv_v_sc_size;
        }
+
+       if (is_shstk_enabled(current))
+               total_context_size += sizeof(struct __sc_riscv_cfi_state);
+
        /*
         * Preserved a __riscv_ctx_hdr for END signal context header if an
         * extension uses __riscv_extra_ext_header
@@ -276,18 +309,40 @@ static long setup_sigcontext(struct rt_sigframe __user *frame,
 {
        struct sigcontext __user *sc = &frame->uc.uc_mcontext;
        struct __riscv_ctx_hdr __user *sc_ext_ptr = &sc->sc_extdesc.hdr;
+       unsigned long ss_ptr = 0;
+       struct __sc_riscv_cfi_state __user *sc_cfi = NULL;
        long err;
 
Quoted 8 lines

arch/riscv/kernel/signal.c static long setup_sigcontext(struct rt_sigframe __user *frame, · line 317

Quoted 2 lines
arch/riscv/kernel/signal.c +2 -0
+       sc_cfi = (struct __sc_riscv_cfi_state *) (sc_ext_ptr + 1);
+

Is it intended that cfi sigcontext does not follow the sigcontext rule setup by Vector? It seems like there is no extension header (struct __riscv_ctx_hdr) defined for cfi sigcontext here. If the sigcontext is directly appended to the signal stack, the user may not be able to recognize the meaning without defining a new ABI.

Quoted 3 lines

Hmm... I didn't realize that struct struct __riscv_ctx_hdr is strongly tied to vector state. I was under the impression that any new extended state addition would require this header to be present.

Quoted 7 lines

__riscv_ctx_hdr is not tied to vector state. Your impression is not wrong. When sigcontext for Vector was designed, it is intended that every new extension should define its header, please check RISCV_V_MAGIC. The magic value and the size of the extension added to the sigcontext are written into each hdr->magic and hdr->size. However, I did not find the corresponding code in this patch. Or, maybe I am missing something obvious. Could you help point me out it?

Sorry I was under the impression that there is only one ctx header for all extended state. It seems like from this conversation, any new state must declare it's own header, magic word and size.

Now that I am having this conversation, it seems like that the idea for having ctx header is to ensure that any software (user space or kernel) must parse sigcontext beyong pt_regs iteratively and start poking only when it sees relevant data structure (based on magic word?)

Hopefully, I got it right this time. I'll fix it, if that's the intention here.

Quoted 156 lines
Quoted 15 lines

cfi sigcontenxt doesn't need any ABI between user and kernel here. We need this space so that kernel can save a pointer to shadow stack token on signal delivery. Once sigreturn happens, kernel will use the same pointer, verify the token saved on shadow stack and restore shadow stack for user mode. At no point in this scheme, user mode is required to perform any action.

All that is needed is that user mode doesn't accidenly trample at this offset.

Since I was under the impression that struct __riscv_ctx_hdr is there for context extension and must be present for any state beyond sc_regs, I assumed that I must make space for this header (even if vector state is not present).

Quoted 1 line
Quoted 138 lines
Quoted 2 lines

BTW, I have sent a patch[1] that refactor setup_sigcontext so it'd be easier for future extensions to expand on the signal stack.

I can adopt to this, although its orthogonal to what we are discussing here.

Quoted 133 lines
Quoted 124 lines
arch/riscv/kernel/signal.c +24 -1
        /* sc_regs is structured the same as the start of pt_regs */
        err = __copy_to_user(&sc->sc_regs, regs, sizeof(sc->sc_regs));
        /* Save the floating-point state. */
        if (has_fpu())
                err |= save_fp_state(regs, &sc->sc_fpregs);
        /* Save the vector state. */
-       if (has_vector() && riscv_v_vstate_query(regs))
+       if (has_vector() && riscv_v_vstate_query(regs)) {
                err |= save_v_state(regs, (void __user **)&sc_ext_ptr);
+               sc_cfi = (struct __sc_riscv_cfi_state *) ((unsigned long) sc_cfi + riscv_v_sc_size);
+       }
        /* Write zero to fp-reserved space and check it on restore_sigcontext */
        err |= __put_user(0, &sc->sc_extdesc.reserved);
+       /*
+        * Save a pointer to shadow stack itself on shadow stack as a form of token.
+        * A token on shadow gives following properties
+        *      - Safe save and restore for shadow stack switching. Any save of shadow stack
+        *        must have had saved a token on shadow stack. Similarly any restore of shadow
+        *        stack must check the token before restore. Since writing to shadow stack with
+        *        address of shadow stack itself is not easily allowed. A restore without a save
+        *        is quite difficult for an attacker to perform.
+        *      - A natural break. A token in shadow stack provides a natural break in shadow stack
+        *        So a single linear range can be bucketed into different shadow stack segments. Any
+        *        sspopchk will detect the condition and fault to kernel as sw check exception.
+        */
+       if (is_shstk_enabled(current)) {
+               err |= save_user_shstk(current, &ss_ptr);
+               err |= __put_user(ss_ptr, &sc_cfi->ss_ptr);
+       }
        /* And put END __riscv_ctx_hdr at the end. */
        err |= __put_user(END_MAGIC, &sc_ext_ptr->magic);
        err |= __put_user(END_HDR_SIZE, &sc_ext_ptr->size);
@@ -345,6 +400,11 @@ static int setup_rt_frame(struct ksignal *ksig, sigset_t *set,
 #ifdef CONFIG_MMU
        regs->ra = (unsigned long)VDSO_SYMBOL(
                current->mm->context.vdso, rt_sigreturn);
+
+       /* if bcfi is enabled x1 (ra) and x5 (t0) must match. not sure if we need this? */
+       if (is_shstk_enabled(current))
+               regs->t0 = regs->ra;
+
 #else
        /*
         * For the nommu case we don't have a VDSO.  Instead we push two
arch/riscv/kernel/usercfi.c +57 -1
index 8da509afdbe9..40c32258b6ec 100644
@@ -52,6 +52,11 @@ void set_active_shstk(struct task_struct *task, unsigned long shstk_addr)
        task->thread_info.user_cfi_state.user_shdw_stk = shstk_addr;
 }
 
+unsigned long get_active_shstk(struct task_struct *task)
+{
+       return task->thread_info.user_cfi_state.user_shdw_stk;
+}
+
 void set_shstk_status(struct task_struct *task, bool enable)
 {
        task->thread_info.user_cfi_state.ubcfi_en = enable ? 1 : 0;
@@ -164,6 +169,58 @@ static int create_rstor_token(unsigned long ssp, unsigned long *token_addr)
        return 0;
 }
 
+/*
+ * Save user shadow stack pointer on shadow stack itself and return pointer to saved location
+ * returns -EFAULT if operation was unsuccessful
+ */
+int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
+{
+       unsigned long ss_ptr = 0;
+       unsigned long token_loc = 0;
+       int ret = 0;
+
+       if (saved_shstk_ptr == NULL)
+               return -EINVAL;
+
+       ss_ptr = get_active_shstk(tsk);
+       ret = create_rstor_token(ss_ptr, &token_loc);
+
+       if (!ret) {
+               *saved_shstk_ptr = token_loc;
+               set_active_shstk(tsk, token_loc);
+       }
+
+       return ret;
+}
+
+/*
+ * Restores user shadow stack pointer from token on shadow stack for task `tsk`
+ * returns -EFAULT if operation was unsuccessful
+ */
+int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
+{
+       unsigned long token = 0;
+
+       token = amo_user_shstk((unsigned long __user *)shstk_ptr, 0);
+
+       if (token == -1)
+               return -EFAULT;
+
+       /* invalid token, return EINVAL */
+       if ((token - shstk_ptr) != SHSTK_ENTRY_SIZE) {
+               pr_info_ratelimited(
+                               "%s[%d]: bad restore token in %s: pc=%p sp=%p, token=%p, shstk_ptr=%p\n",
+                               tsk->comm, task_pid_nr(tsk), __func__,
+                               (void *)(task_pt_regs(tsk)->epc), (void *)(task_pt_regs(tsk)->sp),
+                               (void *)token, (void *)shstk_ptr);
+               return -EINVAL;
+       }
+
+       /* all checks passed, set active shstk and return success */
+       set_active_shstk(tsk, token);
+       return 0;
+}
+
 static unsigned long allocate_shadow_stack(unsigned long addr, unsigned long size,
                                unsigned long token_offset,
                                bool set_tok)
--

2.45.0

Quoted 4 lines

_______________________________________________
linux-riscv mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-riscv

- [1]: https://lore.kernel.org/all/[email protected]/

Thanks,
Andy

Regards,
Andy