xref: /linux/arch/riscv/kernel/usercfi.c (revision 20bed0d6ff62d985fe8222958825504b8aad4e88)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2024 Rivos, Inc.
4  * Deepak Gupta <debug@rivosinc.com>
5  */
6 
7 #include <linux/sched.h>
8 #include <linux/bitops.h>
9 #include <linux/types.h>
10 #include <linux/mm.h>
11 #include <linux/mman.h>
12 #include <linux/uaccess.h>
13 #include <linux/sizes.h>
14 #include <linux/user.h>
15 #include <linux/syscalls.h>
16 #include <linux/prctl.h>
17 #include <asm/csr.h>
18 #include <asm/switch_to.h>
19 #include <asm/usercfi.h>
20 
21 unsigned long riscv_nousercfi __read_mostly;
22 
23 #define SHSTK_ENTRY_SIZE sizeof(void *)
24 
25 bool is_shstk_enabled(struct task_struct *task)
26 {
27 	return task->thread_info.user_cfi_state.ubcfi_en;
28 }
29 
30 bool is_shstk_allocated(struct task_struct *task)
31 {
32 	return task->thread_info.user_cfi_state.shdw_stk_base;
33 }
34 
35 bool is_shstk_locked(struct task_struct *task)
36 {
37 	return task->thread_info.user_cfi_state.ubcfi_locked;
38 }
39 
40 void set_shstk_base(struct task_struct *task, unsigned long shstk_addr, unsigned long size)
41 {
42 	task->thread_info.user_cfi_state.shdw_stk_base = shstk_addr;
43 	task->thread_info.user_cfi_state.shdw_stk_size = size;
44 }
45 
46 unsigned long get_shstk_base(struct task_struct *task, unsigned long *size)
47 {
48 	if (size)
49 		*size = task->thread_info.user_cfi_state.shdw_stk_size;
50 	return task->thread_info.user_cfi_state.shdw_stk_base;
51 }
52 
53 void set_active_shstk(struct task_struct *task, unsigned long shstk_addr)
54 {
55 	task->thread_info.user_cfi_state.user_shdw_stk = shstk_addr;
56 }
57 
58 unsigned long get_active_shstk(struct task_struct *task)
59 {
60 	return task->thread_info.user_cfi_state.user_shdw_stk;
61 }
62 
63 void set_shstk_status(struct task_struct *task, bool enable)
64 {
65 	if (!is_user_shstk_enabled())
66 		return;
67 
68 	task->thread_info.user_cfi_state.ubcfi_en = enable ? 1 : 0;
69 
70 	envcfg_update_bits(task, ENVCFG_SSE, enable ? ENVCFG_SSE : 0);
71 }
72 
73 void set_shstk_lock(struct task_struct *task, bool lock)
74 {
75 	task->thread_info.user_cfi_state.ubcfi_locked = lock;
76 }
77 
78 bool is_indir_lp_enabled(struct task_struct *task)
79 {
80 	return task->thread_info.user_cfi_state.ufcfi_en;
81 }
82 
83 bool is_indir_lp_locked(struct task_struct *task)
84 {
85 	return task->thread_info.user_cfi_state.ufcfi_locked;
86 }
87 
88 void set_indir_lp_status(struct task_struct *task, bool enable)
89 {
90 	if (!is_user_lpad_enabled())
91 		return;
92 
93 	task->thread_info.user_cfi_state.ufcfi_en = enable ? 1 : 0;
94 
95 	envcfg_update_bits(task, ENVCFG_LPE, enable ? ENVCFG_LPE : 0);
96 }
97 
98 void set_indir_lp_lock(struct task_struct *task, bool lock)
99 {
100 	task->thread_info.user_cfi_state.ufcfi_locked = lock;
101 }
102 /*
103  * The shadow stack only stores the return address and not any variables
104  * 512M should be more than sufficient for most applications.
105  * Else PAGE_ALIGN it and return back
106  */
107 static unsigned long calc_shstk_size(unsigned long size)
108 {
109 	if (size)
110 		return PAGE_ALIGN(size);
111 
112 	return PAGE_ALIGN(min(rlimit(RLIMIT_STACK) / 8, SZ_512M));
113 }
114 
115 /*
116  * Writes on shadow stack can either be `sspush` or `ssamoswap`. `sspush` can happen
117  * implicitly on current shadow stack pointed to by CSR_SSP. `ssamoswap` takes pointer to
118  * shadow stack. To keep it simple, we plan to use `ssamoswap` to perform writes on shadow
119  * stack.
120  */
121 static noinline unsigned long amo_user_shstk(unsigned long __user *addr, unsigned long val)
122 {
123 	/*
124 	 * Never expect -1 on shadow stack. Expect return addresses and zero
125 	 */
126 	unsigned long swap = -1;
127 
128 	__enable_user_access();
129 	asm goto(".option push\n"
130 		".option arch, +zicfiss\n"
131 		"1: ssamoswap.d %[swap], %[val], %[addr]\n"
132 		_ASM_EXTABLE(1b, %l[fault])
133 		".option pop\n"
134 		 : [swap] "=r" (swap), [addr] "+A" (*(__force unsigned long *)addr)
135 		: [val] "r" (val)
136 		: "memory"
137 		: fault
138 		);
139 	__disable_user_access();
140 	return swap;
141 fault:
142 	__disable_user_access();
143 	return -1;
144 }
145 
146 /*
147  * Create a restore token on the shadow stack.  A token is always XLEN wide
148  * and aligned to XLEN.
149  */
150 static int create_rstor_token(unsigned long ssp, unsigned long *token_addr)
151 {
152 	unsigned long addr;
153 
154 	/* Token must be aligned */
155 	if (!IS_ALIGNED(ssp, SHSTK_ENTRY_SIZE))
156 		return -EINVAL;
157 
158 	/* On RISC-V we're constructing token to be function of address itself */
159 	addr = ssp - SHSTK_ENTRY_SIZE;
160 
161 	if (amo_user_shstk((unsigned long __user *)addr, (unsigned long)ssp) == -1)
162 		return -EFAULT;
163 
164 	if (token_addr)
165 		*token_addr = addr;
166 
167 	return 0;
168 }
169 
170 /*
171  * Save user shadow stack pointer on the shadow stack itself and return a pointer to saved location.
172  * Returns -EFAULT if unsuccessful.
173  */
174 int save_user_shstk(struct task_struct *tsk, unsigned long *saved_shstk_ptr)
175 {
176 	unsigned long ss_ptr = 0;
177 	unsigned long token_loc = 0;
178 	int ret = 0;
179 
180 	if (!saved_shstk_ptr)
181 		return -EINVAL;
182 
183 	ss_ptr = get_active_shstk(tsk);
184 	ret = create_rstor_token(ss_ptr, &token_loc);
185 
186 	if (!ret) {
187 		*saved_shstk_ptr = token_loc;
188 		set_active_shstk(tsk, token_loc);
189 	}
190 
191 	return ret;
192 }
193 
194 /*
195  * Restores the user shadow stack pointer from the token on the shadow stack for task 'tsk'.
196  * Returns -EFAULT if unsuccessful.
197  */
198 int restore_user_shstk(struct task_struct *tsk, unsigned long shstk_ptr)
199 {
200 	unsigned long __user *token_ptr = (unsigned long __user *)shstk_ptr;
201 	unsigned long token = 0;
202 
203 	if (!access_ok(token_ptr, sizeof(token)))
204 		return -EFAULT;
205 
206 	token = amo_user_shstk(token_ptr, 0);
207 	if (token == -1)
208 		return -EFAULT;
209 
210 	/* invalid token, return EINVAL */
211 	if ((token - shstk_ptr) != SHSTK_ENTRY_SIZE) {
212 		pr_info_ratelimited("%s[%d]: bad restore token in %s: pc=%p sp=%p, token=%p, shstk_ptr=%p\n",
213 				    tsk->comm, task_pid_nr(tsk), __func__,
214 				    (void *)(task_pt_regs(tsk)->epc),
215 				    (void *)(task_pt_regs(tsk)->sp),
216 				    (void *)token, (void *)shstk_ptr);
217 		return -EINVAL;
218 	}
219 
220 	/* all checks passed, set active shstk and return success */
221 	set_active_shstk(tsk, token);
222 	return 0;
223 }
224 
225 static unsigned long allocate_shadow_stack(unsigned long addr, unsigned long size,
226 					   unsigned long token_offset, bool set_tok)
227 {
228 	addr = vm_mmap_shadow_stack(addr, size, 0);
229 
230 	if (!set_tok || IS_ERR_VALUE(addr))
231 		goto out;
232 
233 	if (create_rstor_token(addr + token_offset, NULL)) {
234 		vm_munmap(addr, size);
235 		return -EINVAL;
236 	}
237 
238 out:
239 	return addr;
240 }
241 
242 SYSCALL_DEFINE3(map_shadow_stack, unsigned long, addr, unsigned long, size, unsigned int, flags)
243 {
244 	bool set_tok = flags & SHADOW_STACK_SET_TOKEN;
245 	unsigned long aligned_size = 0;
246 
247 	if (!is_user_shstk_enabled())
248 		return -EOPNOTSUPP;
249 
250 	/* Anything other than set token should result in invalid param */
251 	if (flags & ~SHADOW_STACK_SET_TOKEN)
252 		return -EINVAL;
253 
254 	/*
255 	 * Unlike other architectures, on RISC-V, SSP pointer is held in CSR_SSP and is an available
256 	 * CSR in all modes. CSR accesses are performed using 12bit index programmed in instruction
257 	 * itself. This provides static property on register programming and writes to CSR can't
258 	 * be unintentional from programmer's perspective. As long as programmer has guarded areas
259 	 * which perform writes to CSR_SSP properly, shadow stack pivoting is not possible. Since
260 	 * CSR_SSP is writable by user mode, it itself can setup a shadow stack token subsequent
261 	 * to allocation. Although in order to provide portablity with other architectures (because
262 	 * `map_shadow_stack` is arch agnostic syscall), RISC-V will follow expectation of a token
263 	 * flag in flags and if provided in flags, will setup a token at the base.
264 	 */
265 
266 	/* If there isn't space for a token */
267 	if (set_tok && size < SHSTK_ENTRY_SIZE)
268 		return -ENOSPC;
269 
270 	if (addr && (addr & (PAGE_SIZE - 1)))
271 		return -EINVAL;
272 
273 	aligned_size = PAGE_ALIGN(size);
274 	if (aligned_size < size)
275 		return -EOVERFLOW;
276 
277 	return allocate_shadow_stack(addr, aligned_size, size, set_tok);
278 }
279 
280 /*
281  * This gets called during clone/clone3/fork. And is needed to allocate a shadow stack for
282  * cases where CLONE_VM is specified and thus a different stack is specified by user. We
283  * thus need a separate shadow stack too. How a separate shadow stack is specified by
284  * user is still being debated. Once that's settled, remove this part of the comment.
285  * This function simply returns 0 if shadow stacks are not supported or if separate shadow
286  * stack allocation is not needed (like in case of !CLONE_VM)
287  */
288 unsigned long shstk_alloc_thread_stack(struct task_struct *tsk,
289 				       const struct kernel_clone_args *args)
290 {
291 	unsigned long addr, size;
292 
293 	/* If shadow stack is not supported, return 0 */
294 	if (!is_user_shstk_enabled())
295 		return 0;
296 
297 	/*
298 	 * If shadow stack is not enabled on the new thread, skip any
299 	 * switch to a new shadow stack.
300 	 */
301 	if (!is_shstk_enabled(tsk))
302 		return 0;
303 
304 	/*
305 	 * For CLONE_VFORK the child will share the parents shadow stack.
306 	 * Set base = 0 and size = 0, this is special means to track this state
307 	 * so the freeing logic run for child knows to leave it alone.
308 	 */
309 	if (args->flags & CLONE_VFORK) {
310 		set_shstk_base(tsk, 0, 0);
311 		return 0;
312 	}
313 
314 	/*
315 	 * For !CLONE_VM the child will use a copy of the parents shadow
316 	 * stack.
317 	 */
318 	if (!(args->flags & CLONE_VM))
319 		return 0;
320 
321 	/*
322 	 * reaching here means, CLONE_VM was specified and thus a separate shadow
323 	 * stack is needed for new cloned thread. Note: below allocation is happening
324 	 * using current mm.
325 	 */
326 	size = calc_shstk_size(args->stack_size);
327 	addr = allocate_shadow_stack(0, size, 0, false);
328 	if (IS_ERR_VALUE(addr))
329 		return addr;
330 
331 	set_shstk_base(tsk, addr, size);
332 
333 	return addr + size;
334 }
335 
336 void shstk_release(struct task_struct *tsk)
337 {
338 	unsigned long base = 0, size = 0;
339 	/* If shadow stack is not supported or not enabled, nothing to release */
340 	if (!is_user_shstk_enabled() || !is_shstk_enabled(tsk))
341 		return;
342 
343 	/*
344 	 * When fork() with CLONE_VM fails, the child (tsk) already has a
345 	 * shadow stack allocated, and exit_thread() calls this function to
346 	 * free it.  In this case the parent (current) and the child share
347 	 * the same mm struct. Move forward only when they're same.
348 	 */
349 	if (!tsk->mm || tsk->mm != current->mm)
350 		return;
351 
352 	/*
353 	 * We know shadow stack is enabled but if base is NULL, then
354 	 * this task is not managing its own shadow stack (CLONE_VFORK). So
355 	 * skip freeing it.
356 	 */
357 	base = get_shstk_base(tsk, &size);
358 	if (!base)
359 		return;
360 
361 	vm_munmap(base, size);
362 	set_shstk_base(tsk, 0, 0);
363 }
364 
365 int arch_get_shadow_stack_status(struct task_struct *t, unsigned long __user *status)
366 {
367 	unsigned long bcfi_status = 0;
368 
369 	if (!is_user_shstk_enabled())
370 		return -EINVAL;
371 
372 	/* this means shadow stack is enabled on the task */
373 	bcfi_status |= (is_shstk_enabled(t) ? PR_SHADOW_STACK_ENABLE : 0);
374 
375 	return copy_to_user(status, &bcfi_status, sizeof(bcfi_status)) ? -EFAULT : 0;
376 }
377 
378 int arch_set_shadow_stack_status(struct task_struct *t, unsigned long status)
379 {
380 	unsigned long size = 0, addr = 0;
381 	bool enable_shstk = false;
382 
383 	if (!is_user_shstk_enabled())
384 		return -EINVAL;
385 
386 	/* Reject unknown flags */
387 	if (status & ~PR_SHADOW_STACK_SUPPORTED_STATUS_MASK)
388 		return -EINVAL;
389 
390 	/* bcfi status is locked and further can't be modified by user */
391 	if (is_shstk_locked(t))
392 		return -EINVAL;
393 
394 	enable_shstk = status & PR_SHADOW_STACK_ENABLE;
395 	/* Request is to enable shadow stack and shadow stack is not enabled already */
396 	if (enable_shstk && !is_shstk_enabled(t)) {
397 		/* shadow stack was allocated and enable request again
398 		 * no need to support such usecase and return EINVAL.
399 		 */
400 		if (is_shstk_allocated(t))
401 			return -EINVAL;
402 
403 		size = calc_shstk_size(0);
404 		addr = allocate_shadow_stack(0, size, 0, false);
405 		if (IS_ERR_VALUE(addr))
406 			return -ENOMEM;
407 		set_shstk_base(t, addr, size);
408 		set_active_shstk(t, addr + size);
409 	}
410 
411 	/*
412 	 * If a request to disable shadow stack happens, let's go ahead and release it
413 	 * Although, if CLONE_VFORKed child did this, then in that case we will end up
414 	 * not releasing the shadow stack (because it might be needed in parent). Although
415 	 * we will disable it for VFORKed child. And if VFORKed child tries to enable again
416 	 * then in that case, it'll get entirely new shadow stack because following condition
417 	 * are true
418 	 *  - shadow stack was not enabled for vforked child
419 	 *  - shadow stack base was anyways pointing to 0
420 	 * This shouldn't be a big issue because we want parent to have availability of shadow
421 	 * stack whenever VFORKed child releases resources via exit or exec but at the same
422 	 * time we want VFORKed child to break away and establish new shadow stack if it desires
423 	 *
424 	 */
425 	if (!enable_shstk)
426 		shstk_release(t);
427 
428 	set_shstk_status(t, enable_shstk);
429 	return 0;
430 }
431 
432 int arch_lock_shadow_stack_status(struct task_struct *task,
433 				  unsigned long arg)
434 {
435 	/* If shtstk not supported or not enabled on task, nothing to lock here */
436 	if (!is_user_shstk_enabled() ||
437 	    !is_shstk_enabled(task) || arg != 0)
438 		return -EINVAL;
439 
440 	set_shstk_lock(task, true);
441 
442 	return 0;
443 }
444 
445 int arch_prctl_get_branch_landing_pad_state(struct task_struct *t,
446 					    unsigned long __user *state)
447 {
448 	unsigned long fcfi_status = 0;
449 
450 	if (!is_user_lpad_enabled())
451 		return -EINVAL;
452 
453 	fcfi_status = (is_indir_lp_enabled(t) ? PR_CFI_ENABLE : PR_CFI_DISABLE);
454 	fcfi_status |= (is_indir_lp_locked(t) ? PR_CFI_LOCK : 0);
455 
456 	return copy_to_user(state, &fcfi_status, sizeof(fcfi_status)) ? -EFAULT : 0;
457 }
458 
459 int arch_prctl_set_branch_landing_pad_state(struct task_struct *t, unsigned long state)
460 {
461 	if (!is_user_lpad_enabled())
462 		return -EINVAL;
463 
464 	if (state & ~PR_CFI_SUPPORTED_STATUS_MASK)
465 		return -EINVAL;
466 
467 	/* indirect branch tracking is locked and further can't be modified by user */
468 	if (is_indir_lp_locked(t))
469 		return -EINVAL;
470 
471 	if (!(state & (PR_CFI_ENABLE | PR_CFI_DISABLE)))
472 		return -EINVAL;
473 
474 	if (state & PR_CFI_ENABLE && state & PR_CFI_DISABLE)
475 		return -EINVAL;
476 
477 	set_indir_lp_status(t, !!(state & PR_CFI_ENABLE));
478 
479 	return 0;
480 }
481 
482 int arch_prctl_lock_branch_landing_pad_state(struct task_struct *task)
483 {
484 	/*
485 	 * If indirect branch tracking is not supported or not enabled on task,
486 	 * nothing to lock here
487 	 */
488 	if (!is_user_lpad_enabled() ||
489 	    !is_indir_lp_enabled(task))
490 		return -EINVAL;
491 
492 	set_indir_lp_lock(task, true);
493 
494 	return 0;
495 }
496 
497 bool is_user_shstk_enabled(void)
498 {
499 	return (cpu_supports_shadow_stack() &&
500 		!(riscv_nousercfi & CMDLINE_DISABLE_RISCV_USERCFI_BCFI));
501 }
502 
503 bool is_user_lpad_enabled(void)
504 {
505 	return (cpu_supports_indirect_br_lp_instr() &&
506 		!(riscv_nousercfi & CMDLINE_DISABLE_RISCV_USERCFI_FCFI));
507 }
508 
509 static int __init setup_global_riscv_enable(char *str)
510 {
511 	if (strcmp(str, "all") == 0)
512 		riscv_nousercfi = CMDLINE_DISABLE_RISCV_USERCFI;
513 
514 	if (strcmp(str, "fcfi") == 0)
515 		riscv_nousercfi |= CMDLINE_DISABLE_RISCV_USERCFI_FCFI;
516 
517 	if (strcmp(str, "bcfi") == 0)
518 		riscv_nousercfi |= CMDLINE_DISABLE_RISCV_USERCFI_BCFI;
519 
520 	if (riscv_nousercfi)
521 		pr_info("RISC-V user CFI disabled via cmdline - shadow stack status : %s, landing pad status : %s\n",
522 			str_disabled_enabled(riscv_nousercfi & CMDLINE_DISABLE_RISCV_USERCFI_BCFI),
523 			str_disabled_enabled(riscv_nousercfi & CMDLINE_DISABLE_RISCV_USERCFI_FCFI));
524 
525 	return 1;
526 }
527 
528 __setup("riscv_nousercfi=", setup_global_riscv_enable);
529