1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This implements the various checks for CONFIG_HARDENED_USERCOPY*,
4  * which are designed to protect kernel memory from needless exposure
5  * and overwrite under many unintended conditions. This code is based
6  * on PAX_USERCOPY, which is:
7  *
8  * Copyright (C) 2001-2016 PaX Team, Bradley Spengler, Open Source
9  * Security Inc.
10  */
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/mm.h>
14 #include <linux/highmem.h>
15 #include <linux/slab.h>
16 #include <linux/sched.h>
17 #include <linux/sched/task.h>
18 #include <linux/sched/task_stack.h>
19 #include <linux/thread_info.h>
20 #include <linux/vmalloc.h>
21 #include <linux/atomic.h>
22 #include <linux/jump_label.h>
23 #include <asm/sections.h>
24 #include "slab.h"
25 
26 /*
27  * Checks if a given pointer and length is contained by the current
28  * stack frame (if possible).
29  *
30  * Returns:
31  *	NOT_STACK: not at all on the stack
32  *	GOOD_FRAME: fully within a valid stack frame
33  *	GOOD_STACK: within the current stack (when can't frame-check exactly)
34  *	BAD_STACK: error condition (invalid stack position or bad stack frame)
35  */
check_stack_object(const void * obj,unsigned long len)36 static noinline int check_stack_object(const void *obj, unsigned long len)
37 {
38 	const void * const stack = task_stack_page(current);
39 	const void * const stackend = stack + THREAD_SIZE;
40 	int ret;
41 
42 	/* Object is not on the stack at all. */
43 	if (obj + len <= stack || stackend <= obj)
44 		return NOT_STACK;
45 
46 	/*
47 	 * Reject: object partially overlaps the stack (passing the
48 	 * check above means at least one end is within the stack,
49 	 * so if this check fails, the other end is outside the stack).
50 	 */
51 	if (obj < stack || stackend < obj + len)
52 		return BAD_STACK;
53 
54 	/* Check if object is safely within a valid frame. */
55 	ret = arch_within_stack_frames(stack, stackend, obj, len);
56 	if (ret)
57 		return ret;
58 
59 	/* Finally, check stack depth if possible. */
60 #ifdef CONFIG_ARCH_HAS_CURRENT_STACK_POINTER
61 	if (IS_ENABLED(CONFIG_STACK_GROWSUP)) {
62 		if ((void *)current_stack_pointer < obj + len)
63 			return BAD_STACK;
64 	} else {
65 		if (obj < (void *)current_stack_pointer)
66 			return BAD_STACK;
67 	}
68 #endif
69 
70 	return GOOD_STACK;
71 }
72 
73 /*
74  * If these functions are reached, then CONFIG_HARDENED_USERCOPY has found
75  * an unexpected state during a copy_from_user() or copy_to_user() call.
76  * There are several checks being performed on the buffer by the
77  * __check_object_size() function. Normal stack buffer usage should never
78  * trip the checks, and kernel text addressing will always trip the check.
79  * For cache objects, it is checking that only the whitelisted range of
80  * bytes for a given cache is being accessed (via the cache's usersize and
81  * useroffset fields). To adjust a cache whitelist, use the usercopy-aware
82  * kmem_cache_create_usercopy() function to create the cache (and
83  * carefully audit the whitelist range).
84  */
usercopy_abort(const char * name,const char * detail,bool to_user,unsigned long offset,unsigned long len)85 void __noreturn usercopy_abort(const char *name, const char *detail,
86 			       bool to_user, unsigned long offset,
87 			       unsigned long len)
88 {
89 	pr_emerg("Kernel memory %s attempt detected %s %s%s%s%s (offset %lu, size %lu)!\n",
90 		 to_user ? "exposure" : "overwrite",
91 		 to_user ? "from" : "to",
92 		 name ? : "unknown?!",
93 		 detail ? " '" : "", detail ? : "", detail ? "'" : "",
94 		 offset, len);
95 
96 	/*
97 	 * For greater effect, it would be nice to do do_group_exit(),
98 	 * but BUG() actually hooks all the lock-breaking and per-arch
99 	 * Oops code, so that is used here instead.
100 	 */
101 	BUG();
102 }
103 
104 /* Returns true if any portion of [ptr,ptr+n) over laps with [low,high). */
overlaps(const unsigned long ptr,unsigned long n,unsigned long low,unsigned long high)105 static bool overlaps(const unsigned long ptr, unsigned long n,
106 		     unsigned long low, unsigned long high)
107 {
108 	const unsigned long check_low = ptr;
109 	unsigned long check_high = check_low + n;
110 
111 	/* Does not overlap if entirely above or entirely below. */
112 	if (check_low >= high || check_high <= low)
113 		return false;
114 
115 	return true;
116 }
117 
118 /* Is this address range in the kernel text area? */
check_kernel_text_object(const unsigned long ptr,unsigned long n,bool to_user)119 static inline void check_kernel_text_object(const unsigned long ptr,
120 					    unsigned long n, bool to_user)
121 {
122 	unsigned long textlow = (unsigned long)_stext;
123 	unsigned long texthigh = (unsigned long)_etext;
124 	unsigned long textlow_linear, texthigh_linear;
125 
126 	if (overlaps(ptr, n, textlow, texthigh))
127 		usercopy_abort("kernel text", NULL, to_user, ptr - textlow, n);
128 
129 	/*
130 	 * Some architectures have virtual memory mappings with a secondary
131 	 * mapping of the kernel text, i.e. there is more than one virtual
132 	 * kernel address that points to the kernel image. It is usually
133 	 * when there is a separate linear physical memory mapping, in that
134 	 * __pa() is not just the reverse of __va(). This can be detected
135 	 * and checked:
136 	 */
137 	textlow_linear = (unsigned long)lm_alias(textlow);
138 	/* No different mapping: we're done. */
139 	if (textlow_linear == textlow)
140 		return;
141 
142 	/* Check the secondary mapping... */
143 	texthigh_linear = (unsigned long)lm_alias(texthigh);
144 	if (overlaps(ptr, n, textlow_linear, texthigh_linear))
145 		usercopy_abort("linear kernel text", NULL, to_user,
146 			       ptr - textlow_linear, n);
147 }
148 
check_bogus_address(const unsigned long ptr,unsigned long n,bool to_user)149 static inline void check_bogus_address(const unsigned long ptr, unsigned long n,
150 				       bool to_user)
151 {
152 	/* Reject if object wraps past end of memory. */
153 	if (ptr + (n - 1) < ptr)
154 		usercopy_abort("wrapped address", NULL, to_user, 0, ptr + n);
155 
156 	/* Reject if NULL or ZERO-allocation. */
157 	if (ZERO_OR_NULL_PTR(ptr))
158 		usercopy_abort("null address", NULL, to_user, ptr, n);
159 }
160 
check_heap_object(const void * ptr,unsigned long n,bool to_user)161 static inline void check_heap_object(const void *ptr, unsigned long n,
162 				     bool to_user)
163 {
164 	uintptr_t addr = (uintptr_t)ptr;
165 	unsigned long offset;
166 	struct folio *folio;
167 
168 	if (is_kmap_addr(ptr)) {
169 		offset = offset_in_page(ptr);
170 		if (n > PAGE_SIZE - offset)
171 			usercopy_abort("kmap", NULL, to_user, offset, n);
172 		return;
173 	}
174 
175 	if (is_vmalloc_addr(ptr)) {
176 		struct vmap_area *area = find_vmap_area(addr);
177 
178 		if (!area)
179 			usercopy_abort("vmalloc", "no area", to_user, 0, n);
180 
181 		if (n > area->va_end - addr) {
182 			offset = addr - area->va_start;
183 			usercopy_abort("vmalloc", NULL, to_user, offset, n);
184 		}
185 		return;
186 	}
187 
188 	if (!virt_addr_valid(ptr))
189 		return;
190 
191 	folio = virt_to_folio(ptr);
192 
193 	if (folio_test_slab(folio)) {
194 		/* Check slab allocator for flags and size. */
195 		__check_heap_object(ptr, n, folio_slab(folio), to_user);
196 	} else if (folio_test_large(folio)) {
197 		offset = ptr - folio_address(folio);
198 		if (n > folio_size(folio) - offset)
199 			usercopy_abort("page alloc", NULL, to_user, offset, n);
200 	}
201 }
202 
203 static DEFINE_STATIC_KEY_FALSE_RO(bypass_usercopy_checks);
204 
205 /*
206  * Validates that the given object is:
207  * - not bogus address
208  * - fully contained by stack (or stack frame, when available)
209  * - fully within SLAB object (or object whitelist area, when available)
210  * - not in kernel text
211  */
__check_object_size(const void * ptr,unsigned long n,bool to_user)212 void __check_object_size(const void *ptr, unsigned long n, bool to_user)
213 {
214 	if (static_branch_unlikely(&bypass_usercopy_checks))
215 		return;
216 
217 	/* Skip all tests if size is zero. */
218 	if (!n)
219 		return;
220 
221 	/* Check for invalid addresses. */
222 	check_bogus_address((const unsigned long)ptr, n, to_user);
223 
224 	/* Check for bad stack object. */
225 	switch (check_stack_object(ptr, n)) {
226 	case NOT_STACK:
227 		/* Object is not touching the current process stack. */
228 		break;
229 	case GOOD_FRAME:
230 	case GOOD_STACK:
231 		/*
232 		 * Object is either in the correct frame (when it
233 		 * is possible to check) or just generally on the
234 		 * process stack (when frame checking not available).
235 		 */
236 		return;
237 	default:
238 		usercopy_abort("process stack", NULL, to_user,
239 #ifdef CONFIG_ARCH_HAS_CURRENT_STACK_POINTER
240 			IS_ENABLED(CONFIG_STACK_GROWSUP) ?
241 				ptr - (void *)current_stack_pointer :
242 				(void *)current_stack_pointer - ptr,
243 #else
244 			0,
245 #endif
246 			n);
247 	}
248 
249 	/* Check for bad heap object. */
250 	check_heap_object(ptr, n, to_user);
251 
252 	/* Check for object in kernel to avoid text exposure. */
253 	check_kernel_text_object((const unsigned long)ptr, n, to_user);
254 }
255 EXPORT_SYMBOL(__check_object_size);
256 
257 static bool enable_checks __initdata = true;
258 
parse_hardened_usercopy(char * str)259 static int __init parse_hardened_usercopy(char *str)
260 {
261 	if (strtobool(str, &enable_checks))
262 		pr_warn("Invalid option string for hardened_usercopy: '%s'\n",
263 			str);
264 	return 1;
265 }
266 
267 __setup("hardened_usercopy=", parse_hardened_usercopy);
268 
set_hardened_usercopy(void)269 static int __init set_hardened_usercopy(void)
270 {
271 	if (enable_checks == false)
272 		static_branch_enable(&bypass_usercopy_checks);
273 	return 1;
274 }
275 
276 late_initcall(set_hardened_usercopy);
277