GNU Linux-libre 4.19.286-gnu1
[releases.git] / mm / usercopy.c
1 /*
2  * This implements the various checks for CONFIG_HARDENED_USERCOPY*,
3  * which are designed to protect kernel memory from needless exposure
4  * and overwrite under many unintended conditions. This code is based
5  * on PAX_USERCOPY, which is:
6  *
7  * Copyright (C) 2001-2016 PaX Team, Bradley Spengler, Open Source
8  * Security Inc.
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License version 2 as
12  * published by the Free Software Foundation.
13  *
14  */
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16
17 #include <linux/mm.h>
18 #include <linux/highmem.h>
19 #include <linux/slab.h>
20 #include <linux/sched.h>
21 #include <linux/sched/task.h>
22 #include <linux/sched/task_stack.h>
23 #include <linux/thread_info.h>
24 #include <linux/atomic.h>
25 #include <linux/jump_label.h>
26 #include <asm/sections.h>
27
28 /*
29  * Checks if a given pointer and length is contained by the current
30  * stack frame (if possible).
31  *
32  * Returns:
33  *      NOT_STACK: not at all on the stack
34  *      GOOD_FRAME: fully within a valid stack frame
35  *      GOOD_STACK: fully on the stack (when can't do frame-checking)
36  *      BAD_STACK: error condition (invalid stack position or bad stack frame)
37  */
38 static noinline int check_stack_object(const void *obj, unsigned long len)
39 {
40         const void * const stack = task_stack_page(current);
41         const void * const stackend = stack + THREAD_SIZE;
42         int ret;
43
44         /* Object is not on the stack at all. */
45         if (obj + len <= stack || stackend <= obj)
46                 return NOT_STACK;
47
48         /*
49          * Reject: object partially overlaps the stack (passing the
50          * the check above means at least one end is within the stack,
51          * so if this check fails, the other end is outside the stack).
52          */
53         if (obj < stack || stackend < obj + len)
54                 return BAD_STACK;
55
56         /* Check if object is safely within a valid frame. */
57         ret = arch_within_stack_frames(stack, stackend, obj, len);
58         if (ret)
59                 return ret;
60
61         return GOOD_STACK;
62 }
63
64 /*
65  * If these functions are reached, then CONFIG_HARDENED_USERCOPY has found
66  * an unexpected state during a copy_from_user() or copy_to_user() call.
67  * There are several checks being performed on the buffer by the
68  * __check_object_size() function. Normal stack buffer usage should never
69  * trip the checks, and kernel text addressing will always trip the check.
70  * For cache objects, it is checking that only the whitelisted range of
71  * bytes for a given cache is being accessed (via the cache's usersize and
72  * useroffset fields). To adjust a cache whitelist, use the usercopy-aware
73  * kmem_cache_create_usercopy() function to create the cache (and
74  * carefully audit the whitelist range).
75  */
76 void usercopy_warn(const char *name, const char *detail, bool to_user,
77                    unsigned long offset, unsigned long len)
78 {
79         WARN_ONCE(1, "Bad or missing usercopy whitelist? Kernel memory %s attempt detected %s %s%s%s%s (offset %lu, size %lu)!\n",
80                  to_user ? "exposure" : "overwrite",
81                  to_user ? "from" : "to",
82                  name ? : "unknown?!",
83                  detail ? " '" : "", detail ? : "", detail ? "'" : "",
84                  offset, len);
85 }
86
87 void __noreturn usercopy_abort(const char *name, const char *detail,
88                                bool to_user, unsigned long offset,
89                                unsigned long len)
90 {
91         pr_emerg("Kernel memory %s attempt detected %s %s%s%s%s (offset %lu, size %lu)!\n",
92                  to_user ? "exposure" : "overwrite",
93                  to_user ? "from" : "to",
94                  name ? : "unknown?!",
95                  detail ? " '" : "", detail ? : "", detail ? "'" : "",
96                  offset, len);
97
98         /*
99          * For greater effect, it would be nice to do do_group_exit(),
100          * but BUG() actually hooks all the lock-breaking and per-arch
101          * Oops code, so that is used here instead.
102          */
103         BUG();
104 }
105
106 /* Returns true if any portion of [ptr,ptr+n) over laps with [low,high). */
107 static bool overlaps(const unsigned long ptr, unsigned long n,
108                      unsigned long low, unsigned long high)
109 {
110         const unsigned long check_low = ptr;
111         unsigned long check_high = check_low + n;
112
113         /* Does not overlap if entirely above or entirely below. */
114         if (check_low >= high || check_high <= low)
115                 return false;
116
117         return true;
118 }
119
120 /* Is this address range in the kernel text area? */
121 static inline void check_kernel_text_object(const unsigned long ptr,
122                                             unsigned long n, bool to_user)
123 {
124         unsigned long textlow = (unsigned long)_stext;
125         unsigned long texthigh = (unsigned long)_etext;
126         unsigned long textlow_linear, texthigh_linear;
127
128         if (overlaps(ptr, n, textlow, texthigh))
129                 usercopy_abort("kernel text", NULL, to_user, ptr - textlow, n);
130
131         /*
132          * Some architectures have virtual memory mappings with a secondary
133          * mapping of the kernel text, i.e. there is more than one virtual
134          * kernel address that points to the kernel image. It is usually
135          * when there is a separate linear physical memory mapping, in that
136          * __pa() is not just the reverse of __va(). This can be detected
137          * and checked:
138          */
139         textlow_linear = (unsigned long)lm_alias(textlow);
140         /* No different mapping: we're done. */
141         if (textlow_linear == textlow)
142                 return;
143
144         /* Check the secondary mapping... */
145         texthigh_linear = (unsigned long)lm_alias(texthigh);
146         if (overlaps(ptr, n, textlow_linear, texthigh_linear))
147                 usercopy_abort("linear kernel text", NULL, to_user,
148                                ptr - textlow_linear, n);
149 }
150
151 static inline void check_bogus_address(const unsigned long ptr, unsigned long n,
152                                        bool to_user)
153 {
154         /* Reject if object wraps past end of memory. */
155         if (ptr + (n - 1) < ptr)
156                 usercopy_abort("wrapped address", NULL, to_user, 0, ptr + n);
157
158         /* Reject if NULL or ZERO-allocation. */
159         if (ZERO_OR_NULL_PTR(ptr))
160                 usercopy_abort("null address", NULL, to_user, ptr, n);
161 }
162
163 /* Checks for allocs that are marked in some way as spanning multiple pages. */
164 static inline void check_page_span(const void *ptr, unsigned long n,
165                                    struct page *page, bool to_user)
166 {
167 #ifdef CONFIG_HARDENED_USERCOPY_PAGESPAN
168         const void *end = ptr + n - 1;
169         struct page *endpage;
170         bool is_reserved, is_cma;
171
172         /*
173          * Sometimes the kernel data regions are not marked Reserved (see
174          * check below). And sometimes [_sdata,_edata) does not cover
175          * rodata and/or bss, so check each range explicitly.
176          */
177
178         /* Allow reads of kernel rodata region (if not marked as Reserved). */
179         if (ptr >= (const void *)__start_rodata &&
180             end <= (const void *)__end_rodata) {
181                 if (!to_user)
182                         usercopy_abort("rodata", NULL, to_user, 0, n);
183                 return;
184         }
185
186         /* Allow kernel data region (if not marked as Reserved). */
187         if (ptr >= (const void *)_sdata && end <= (const void *)_edata)
188                 return;
189
190         /* Allow kernel bss region (if not marked as Reserved). */
191         if (ptr >= (const void *)__bss_start &&
192             end <= (const void *)__bss_stop)
193                 return;
194
195         /* Is the object wholly within one base page? */
196         if (likely(((unsigned long)ptr & (unsigned long)PAGE_MASK) ==
197                    ((unsigned long)end & (unsigned long)PAGE_MASK)))
198                 return;
199
200         /* Allow if fully inside the same compound (__GFP_COMP) page. */
201         endpage = virt_to_head_page(end);
202         if (likely(endpage == page))
203                 return;
204
205         /*
206          * Reject if range is entirely either Reserved (i.e. special or
207          * device memory), or CMA. Otherwise, reject since the object spans
208          * several independently allocated pages.
209          */
210         is_reserved = PageReserved(page);
211         is_cma = is_migrate_cma_page(page);
212         if (!is_reserved && !is_cma)
213                 usercopy_abort("spans multiple pages", NULL, to_user, 0, n);
214
215         for (ptr += PAGE_SIZE; ptr <= end; ptr += PAGE_SIZE) {
216                 page = virt_to_head_page(ptr);
217                 if (is_reserved && !PageReserved(page))
218                         usercopy_abort("spans Reserved and non-Reserved pages",
219                                        NULL, to_user, 0, n);
220                 if (is_cma && !is_migrate_cma_page(page))
221                         usercopy_abort("spans CMA and non-CMA pages", NULL,
222                                        to_user, 0, n);
223         }
224 #endif
225 }
226
227 static inline void check_heap_object(const void *ptr, unsigned long n,
228                                      bool to_user)
229 {
230         struct page *page;
231
232         if (!virt_addr_valid(ptr))
233                 return;
234
235         /*
236          * When CONFIG_HIGHMEM=y, kmap_to_page() will give either the
237          * highmem page or fallback to virt_to_page(). The following
238          * is effectively a highmem-aware virt_to_head_page().
239          */
240         page = compound_head(kmap_to_page((void *)ptr));
241
242         if (PageSlab(page)) {
243                 /* Check slab allocator for flags and size. */
244                 __check_heap_object(ptr, n, page, to_user);
245         } else {
246                 /* Verify object does not incorrectly span multiple pages. */
247                 check_page_span(ptr, n, page, to_user);
248         }
249 }
250
251 static DEFINE_STATIC_KEY_FALSE_RO(bypass_usercopy_checks);
252
253 /*
254  * Validates that the given object is:
255  * - not bogus address
256  * - fully contained by stack (or stack frame, when available)
257  * - fully within SLAB object (or object whitelist area, when available)
258  * - not in kernel text
259  */
260 void __check_object_size(const void *ptr, unsigned long n, bool to_user)
261 {
262         if (static_branch_unlikely(&bypass_usercopy_checks))
263                 return;
264
265         /* Skip all tests if size is zero. */
266         if (!n)
267                 return;
268
269         /* Check for invalid addresses. */
270         check_bogus_address((const unsigned long)ptr, n, to_user);
271
272         /* Check for bad stack object. */
273         switch (check_stack_object(ptr, n)) {
274         case NOT_STACK:
275                 /* Object is not touching the current process stack. */
276                 break;
277         case GOOD_FRAME:
278         case GOOD_STACK:
279                 /*
280                  * Object is either in the correct frame (when it
281                  * is possible to check) or just generally on the
282                  * process stack (when frame checking not available).
283                  */
284                 return;
285         default:
286                 usercopy_abort("process stack", NULL, to_user, 0, n);
287         }
288
289         /* Check for bad heap object. */
290         check_heap_object(ptr, n, to_user);
291
292         /* Check for object in kernel to avoid text exposure. */
293         check_kernel_text_object((const unsigned long)ptr, n, to_user);
294 }
295 EXPORT_SYMBOL(__check_object_size);
296
297 static bool enable_checks __initdata = true;
298
299 static int __init parse_hardened_usercopy(char *str)
300 {
301         if (strtobool(str, &enable_checks))
302                 pr_warn("Invalid option string for hardened_usercopy: '%s'\n",
303                         str);
304         return 1;
305 }
306
307 __setup("hardened_usercopy=", parse_hardened_usercopy);
308
309 static int __init set_hardened_usercopy(void)
310 {
311         if (enable_checks == false)
312                 static_branch_enable(&bypass_usercopy_checks);
313         return 1;
314 }
315
316 late_initcall(set_hardened_usercopy);