Merge branch 'work.lookup' of git://git.kernel.org/pub/scm/linux/kernel/git/viro/vfs
[sfrench/cifs-2.6.git] / arch / x86 / mm / pti.c
1 /*
2  * Copyright(c) 2017 Intel Corporation. All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of version 2 of the GNU General Public License as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * This code is based in part on work published here:
14  *
15  *      https://github.com/IAIK/KAISER
16  *
17  * The original work was written by and and signed off by for the Linux
18  * kernel by:
19  *
20  *   Signed-off-by: Richard Fellner <richard.fellner@student.tugraz.at>
21  *   Signed-off-by: Moritz Lipp <moritz.lipp@iaik.tugraz.at>
22  *   Signed-off-by: Daniel Gruss <daniel.gruss@iaik.tugraz.at>
23  *   Signed-off-by: Michael Schwarz <michael.schwarz@iaik.tugraz.at>
24  *
25  * Major changes to the original code by: Dave Hansen <dave.hansen@intel.com>
26  * Mostly rewritten by Thomas Gleixner <tglx@linutronix.de> and
27  *                     Andy Lutomirsky <luto@amacapital.net>
28  */
29 #include <linux/kernel.h>
30 #include <linux/errno.h>
31 #include <linux/string.h>
32 #include <linux/types.h>
33 #include <linux/bug.h>
34 #include <linux/init.h>
35 #include <linux/spinlock.h>
36 #include <linux/mm.h>
37 #include <linux/uaccess.h>
38
39 #include <asm/cpufeature.h>
40 #include <asm/hypervisor.h>
41 #include <asm/vsyscall.h>
42 #include <asm/cmdline.h>
43 #include <asm/pti.h>
44 #include <asm/pgtable.h>
45 #include <asm/pgalloc.h>
46 #include <asm/tlbflush.h>
47 #include <asm/desc.h>
48
49 #undef pr_fmt
50 #define pr_fmt(fmt)     "Kernel/User page tables isolation: " fmt
51
52 /* Backporting helper */
53 #ifndef __GFP_NOTRACK
54 #define __GFP_NOTRACK   0
55 #endif
56
57 /*
58  * Define the page-table levels we clone for user-space on 32
59  * and 64 bit.
60  */
61 #ifdef CONFIG_X86_64
62 #define PTI_LEVEL_KERNEL_IMAGE  PTI_CLONE_PMD
63 #else
64 #define PTI_LEVEL_KERNEL_IMAGE  PTI_CLONE_PTE
65 #endif
66
67 static void __init pti_print_if_insecure(const char *reason)
68 {
69         if (boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
70                 pr_info("%s\n", reason);
71 }
72
73 static void __init pti_print_if_secure(const char *reason)
74 {
75         if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
76                 pr_info("%s\n", reason);
77 }
78
79 enum pti_mode {
80         PTI_AUTO = 0,
81         PTI_FORCE_OFF,
82         PTI_FORCE_ON
83 } pti_mode;
84
85 void __init pti_check_boottime_disable(void)
86 {
87         char arg[5];
88         int ret;
89
90         /* Assume mode is auto unless overridden. */
91         pti_mode = PTI_AUTO;
92
93         if (hypervisor_is_type(X86_HYPER_XEN_PV)) {
94                 pti_mode = PTI_FORCE_OFF;
95                 pti_print_if_insecure("disabled on XEN PV.");
96                 return;
97         }
98
99         ret = cmdline_find_option(boot_command_line, "pti", arg, sizeof(arg));
100         if (ret > 0)  {
101                 if (ret == 3 && !strncmp(arg, "off", 3)) {
102                         pti_mode = PTI_FORCE_OFF;
103                         pti_print_if_insecure("disabled on command line.");
104                         return;
105                 }
106                 if (ret == 2 && !strncmp(arg, "on", 2)) {
107                         pti_mode = PTI_FORCE_ON;
108                         pti_print_if_secure("force enabled on command line.");
109                         goto enable;
110                 }
111                 if (ret == 4 && !strncmp(arg, "auto", 4)) {
112                         pti_mode = PTI_AUTO;
113                         goto autosel;
114                 }
115         }
116
117         if (cmdline_find_option_bool(boot_command_line, "nopti")) {
118                 pti_mode = PTI_FORCE_OFF;
119                 pti_print_if_insecure("disabled on command line.");
120                 return;
121         }
122
123 autosel:
124         if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
125                 return;
126 enable:
127         setup_force_cpu_cap(X86_FEATURE_PTI);
128 }
129
130 pgd_t __pti_set_user_pgtbl(pgd_t *pgdp, pgd_t pgd)
131 {
132         /*
133          * Changes to the high (kernel) portion of the kernelmode page
134          * tables are not automatically propagated to the usermode tables.
135          *
136          * Users should keep in mind that, unlike the kernelmode tables,
137          * there is no vmalloc_fault equivalent for the usermode tables.
138          * Top-level entries added to init_mm's usermode pgd after boot
139          * will not be automatically propagated to other mms.
140          */
141         if (!pgdp_maps_userspace(pgdp))
142                 return pgd;
143
144         /*
145          * The user page tables get the full PGD, accessible from
146          * userspace:
147          */
148         kernel_to_user_pgdp(pgdp)->pgd = pgd.pgd;
149
150         /*
151          * If this is normal user memory, make it NX in the kernel
152          * pagetables so that, if we somehow screw up and return to
153          * usermode with the kernel CR3 loaded, we'll get a page fault
154          * instead of allowing user code to execute with the wrong CR3.
155          *
156          * As exceptions, we don't set NX if:
157          *  - _PAGE_USER is not set.  This could be an executable
158          *     EFI runtime mapping or something similar, and the kernel
159          *     may execute from it
160          *  - we don't have NX support
161          *  - we're clearing the PGD (i.e. the new pgd is not present).
162          */
163         if ((pgd.pgd & (_PAGE_USER|_PAGE_PRESENT)) == (_PAGE_USER|_PAGE_PRESENT) &&
164             (__supported_pte_mask & _PAGE_NX))
165                 pgd.pgd |= _PAGE_NX;
166
167         /* return the copy of the PGD we want the kernel to use: */
168         return pgd;
169 }
170
171 /*
172  * Walk the user copy of the page tables (optionally) trying to allocate
173  * page table pages on the way down.
174  *
175  * Returns a pointer to a P4D on success, or NULL on failure.
176  */
177 static p4d_t *pti_user_pagetable_walk_p4d(unsigned long address)
178 {
179         pgd_t *pgd = kernel_to_user_pgdp(pgd_offset_k(address));
180         gfp_t gfp = (GFP_KERNEL | __GFP_NOTRACK | __GFP_ZERO);
181
182         if (address < PAGE_OFFSET) {
183                 WARN_ONCE(1, "attempt to walk user address\n");
184                 return NULL;
185         }
186
187         if (pgd_none(*pgd)) {
188                 unsigned long new_p4d_page = __get_free_page(gfp);
189                 if (WARN_ON_ONCE(!new_p4d_page))
190                         return NULL;
191
192                 set_pgd(pgd, __pgd(_KERNPG_TABLE | __pa(new_p4d_page)));
193         }
194         BUILD_BUG_ON(pgd_large(*pgd) != 0);
195
196         return p4d_offset(pgd, address);
197 }
198
199 /*
200  * Walk the user copy of the page tables (optionally) trying to allocate
201  * page table pages on the way down.
202  *
203  * Returns a pointer to a PMD on success, or NULL on failure.
204  */
205 static pmd_t *pti_user_pagetable_walk_pmd(unsigned long address)
206 {
207         gfp_t gfp = (GFP_KERNEL | __GFP_NOTRACK | __GFP_ZERO);
208         p4d_t *p4d;
209         pud_t *pud;
210
211         p4d = pti_user_pagetable_walk_p4d(address);
212         if (!p4d)
213                 return NULL;
214
215         BUILD_BUG_ON(p4d_large(*p4d) != 0);
216         if (p4d_none(*p4d)) {
217                 unsigned long new_pud_page = __get_free_page(gfp);
218                 if (WARN_ON_ONCE(!new_pud_page))
219                         return NULL;
220
221                 set_p4d(p4d, __p4d(_KERNPG_TABLE | __pa(new_pud_page)));
222         }
223
224         pud = pud_offset(p4d, address);
225         /* The user page tables do not use large mappings: */
226         if (pud_large(*pud)) {
227                 WARN_ON(1);
228                 return NULL;
229         }
230         if (pud_none(*pud)) {
231                 unsigned long new_pmd_page = __get_free_page(gfp);
232                 if (WARN_ON_ONCE(!new_pmd_page))
233                         return NULL;
234
235                 set_pud(pud, __pud(_KERNPG_TABLE | __pa(new_pmd_page)));
236         }
237
238         return pmd_offset(pud, address);
239 }
240
241 /*
242  * Walk the shadow copy of the page tables (optionally) trying to allocate
243  * page table pages on the way down.  Does not support large pages.
244  *
245  * Note: this is only used when mapping *new* kernel data into the
246  * user/shadow page tables.  It is never used for userspace data.
247  *
248  * Returns a pointer to a PTE on success, or NULL on failure.
249  */
250 static __init pte_t *pti_user_pagetable_walk_pte(unsigned long address)
251 {
252         gfp_t gfp = (GFP_KERNEL | __GFP_NOTRACK | __GFP_ZERO);
253         pmd_t *pmd;
254         pte_t *pte;
255
256         pmd = pti_user_pagetable_walk_pmd(address);
257         if (!pmd)
258                 return NULL;
259
260         /* We can't do anything sensible if we hit a large mapping. */
261         if (pmd_large(*pmd)) {
262                 WARN_ON(1);
263                 return NULL;
264         }
265
266         if (pmd_none(*pmd)) {
267                 unsigned long new_pte_page = __get_free_page(gfp);
268                 if (!new_pte_page)
269                         return NULL;
270
271                 set_pmd(pmd, __pmd(_KERNPG_TABLE | __pa(new_pte_page)));
272         }
273
274         pte = pte_offset_kernel(pmd, address);
275         if (pte_flags(*pte) & _PAGE_USER) {
276                 WARN_ONCE(1, "attempt to walk to user pte\n");
277                 return NULL;
278         }
279         return pte;
280 }
281
282 #ifdef CONFIG_X86_VSYSCALL_EMULATION
283 static void __init pti_setup_vsyscall(void)
284 {
285         pte_t *pte, *target_pte;
286         unsigned int level;
287
288         pte = lookup_address(VSYSCALL_ADDR, &level);
289         if (!pte || WARN_ON(level != PG_LEVEL_4K) || pte_none(*pte))
290                 return;
291
292         target_pte = pti_user_pagetable_walk_pte(VSYSCALL_ADDR);
293         if (WARN_ON(!target_pte))
294                 return;
295
296         *target_pte = *pte;
297         set_vsyscall_pgtable_user_bits(kernel_to_user_pgdp(swapper_pg_dir));
298 }
299 #else
300 static void __init pti_setup_vsyscall(void) { }
301 #endif
302
303 enum pti_clone_level {
304         PTI_CLONE_PMD,
305         PTI_CLONE_PTE,
306 };
307
308 static void
309 pti_clone_pgtable(unsigned long start, unsigned long end,
310                   enum pti_clone_level level)
311 {
312         unsigned long addr;
313
314         /*
315          * Clone the populated PMDs which cover start to end. These PMD areas
316          * can have holes.
317          */
318         for (addr = start; addr < end;) {
319                 pte_t *pte, *target_pte;
320                 pmd_t *pmd, *target_pmd;
321                 pgd_t *pgd;
322                 p4d_t *p4d;
323                 pud_t *pud;
324
325                 /* Overflow check */
326                 if (addr < start)
327                         break;
328
329                 pgd = pgd_offset_k(addr);
330                 if (WARN_ON(pgd_none(*pgd)))
331                         return;
332                 p4d = p4d_offset(pgd, addr);
333                 if (WARN_ON(p4d_none(*p4d)))
334                         return;
335
336                 pud = pud_offset(p4d, addr);
337                 if (pud_none(*pud)) {
338                         addr += PUD_SIZE;
339                         continue;
340                 }
341
342                 pmd = pmd_offset(pud, addr);
343                 if (pmd_none(*pmd)) {
344                         addr += PMD_SIZE;
345                         continue;
346                 }
347
348                 if (pmd_large(*pmd) || level == PTI_CLONE_PMD) {
349                         target_pmd = pti_user_pagetable_walk_pmd(addr);
350                         if (WARN_ON(!target_pmd))
351                                 return;
352
353                         /*
354                          * Only clone present PMDs.  This ensures only setting
355                          * _PAGE_GLOBAL on present PMDs.  This should only be
356                          * called on well-known addresses anyway, so a non-
357                          * present PMD would be a surprise.
358                          */
359                         if (WARN_ON(!(pmd_flags(*pmd) & _PAGE_PRESENT)))
360                                 return;
361
362                         /*
363                          * Setting 'target_pmd' below creates a mapping in both
364                          * the user and kernel page tables.  It is effectively
365                          * global, so set it as global in both copies.  Note:
366                          * the X86_FEATURE_PGE check is not _required_ because
367                          * the CPU ignores _PAGE_GLOBAL when PGE is not
368                          * supported.  The check keeps consistentency with
369                          * code that only set this bit when supported.
370                          */
371                         if (boot_cpu_has(X86_FEATURE_PGE))
372                                 *pmd = pmd_set_flags(*pmd, _PAGE_GLOBAL);
373
374                         /*
375                          * Copy the PMD.  That is, the kernelmode and usermode
376                          * tables will share the last-level page tables of this
377                          * address range
378                          */
379                         *target_pmd = *pmd;
380
381                         addr += PMD_SIZE;
382
383                 } else if (level == PTI_CLONE_PTE) {
384
385                         /* Walk the page-table down to the pte level */
386                         pte = pte_offset_kernel(pmd, addr);
387                         if (pte_none(*pte)) {
388                                 addr += PAGE_SIZE;
389                                 continue;
390                         }
391
392                         /* Only clone present PTEs */
393                         if (WARN_ON(!(pte_flags(*pte) & _PAGE_PRESENT)))
394                                 return;
395
396                         /* Allocate PTE in the user page-table */
397                         target_pte = pti_user_pagetable_walk_pte(addr);
398                         if (WARN_ON(!target_pte))
399                                 return;
400
401                         /* Set GLOBAL bit in both PTEs */
402                         if (boot_cpu_has(X86_FEATURE_PGE))
403                                 *pte = pte_set_flags(*pte, _PAGE_GLOBAL);
404
405                         /* Clone the PTE */
406                         *target_pte = *pte;
407
408                         addr += PAGE_SIZE;
409
410                 } else {
411                         BUG();
412                 }
413         }
414 }
415
416 #ifdef CONFIG_X86_64
417 /*
418  * Clone a single p4d (i.e. a top-level entry on 4-level systems and a
419  * next-level entry on 5-level systems.
420  */
421 static void __init pti_clone_p4d(unsigned long addr)
422 {
423         p4d_t *kernel_p4d, *user_p4d;
424         pgd_t *kernel_pgd;
425
426         user_p4d = pti_user_pagetable_walk_p4d(addr);
427         if (!user_p4d)
428                 return;
429
430         kernel_pgd = pgd_offset_k(addr);
431         kernel_p4d = p4d_offset(kernel_pgd, addr);
432         *user_p4d = *kernel_p4d;
433 }
434
435 /*
436  * Clone the CPU_ENTRY_AREA into the user space visible page table.
437  */
438 static void __init pti_clone_user_shared(void)
439 {
440         pti_clone_p4d(CPU_ENTRY_AREA_BASE);
441 }
442
443 #else /* CONFIG_X86_64 */
444
445 /*
446  * On 32 bit PAE systems with 1GB of Kernel address space there is only
447  * one pgd/p4d for the whole kernel. Cloning that would map the whole
448  * address space into the user page-tables, making PTI useless. So clone
449  * the page-table on the PMD level to prevent that.
450  */
451 static void __init pti_clone_user_shared(void)
452 {
453         unsigned long start, end;
454
455         start = CPU_ENTRY_AREA_BASE;
456         end   = start + (PAGE_SIZE * CPU_ENTRY_AREA_PAGES);
457
458         pti_clone_pgtable(start, end, PTI_CLONE_PMD);
459 }
460 #endif /* CONFIG_X86_64 */
461
462 /*
463  * Clone the ESPFIX P4D into the user space visible page table
464  */
465 static void __init pti_setup_espfix64(void)
466 {
467 #ifdef CONFIG_X86_ESPFIX64
468         pti_clone_p4d(ESPFIX_BASE_ADDR);
469 #endif
470 }
471
472 /*
473  * Clone the populated PMDs of the entry and irqentry text and force it RO.
474  */
475 static void pti_clone_entry_text(void)
476 {
477         pti_clone_pgtable((unsigned long) __entry_text_start,
478                           (unsigned long) __irqentry_text_end,
479                           PTI_CLONE_PMD);
480 }
481
482 /*
483  * Global pages and PCIDs are both ways to make kernel TLB entries
484  * live longer, reduce TLB misses and improve kernel performance.
485  * But, leaving all kernel text Global makes it potentially accessible
486  * to Meltdown-style attacks which make it trivial to find gadgets or
487  * defeat KASLR.
488  *
489  * Only use global pages when it is really worth it.
490  */
491 static inline bool pti_kernel_image_global_ok(void)
492 {
493         /*
494          * Systems with PCIDs get litlle benefit from global
495          * kernel text and are not worth the downsides.
496          */
497         if (cpu_feature_enabled(X86_FEATURE_PCID))
498                 return false;
499
500         /*
501          * Only do global kernel image for pti=auto.  Do the most
502          * secure thing (not global) if pti=on specified.
503          */
504         if (pti_mode != PTI_AUTO)
505                 return false;
506
507         /*
508          * K8 may not tolerate the cleared _PAGE_RW on the userspace
509          * global kernel image pages.  Do the safe thing (disable
510          * global kernel image).  This is unlikely to ever be
511          * noticed because PTI is disabled by default on AMD CPUs.
512          */
513         if (boot_cpu_has(X86_FEATURE_K8))
514                 return false;
515
516         /*
517          * RANDSTRUCT derives its hardening benefits from the
518          * attacker's lack of knowledge about the layout of kernel
519          * data structures.  Keep the kernel image non-global in
520          * cases where RANDSTRUCT is in use to help keep the layout a
521          * secret.
522          */
523         if (IS_ENABLED(CONFIG_GCC_PLUGIN_RANDSTRUCT))
524                 return false;
525
526         return true;
527 }
528
529 /*
530  * This is the only user for these and it is not arch-generic
531  * like the other set_memory.h functions.  Just extern them.
532  */
533 extern int set_memory_nonglobal(unsigned long addr, int numpages);
534 extern int set_memory_global(unsigned long addr, int numpages);
535
536 /*
537  * For some configurations, map all of kernel text into the user page
538  * tables.  This reduces TLB misses, especially on non-PCID systems.
539  */
540 static void pti_clone_kernel_text(void)
541 {
542         /*
543          * rodata is part of the kernel image and is normally
544          * readable on the filesystem or on the web.  But, do not
545          * clone the areas past rodata, they might contain secrets.
546          */
547         unsigned long start = PFN_ALIGN(_text);
548         unsigned long end_clone  = (unsigned long)__end_rodata_aligned;
549         unsigned long end_global = PFN_ALIGN((unsigned long)__stop___ex_table);
550
551         if (!pti_kernel_image_global_ok())
552                 return;
553
554         pr_debug("mapping partial kernel image into user address space\n");
555
556         /*
557          * Note that this will undo _some_ of the work that
558          * pti_set_kernel_image_nonglobal() did to clear the
559          * global bit.
560          */
561         pti_clone_pgtable(start, end_clone, PTI_LEVEL_KERNEL_IMAGE);
562
563         /*
564          * pti_clone_pgtable() will set the global bit in any PMDs
565          * that it clones, but we also need to get any PTEs in
566          * the last level for areas that are not huge-page-aligned.
567          */
568
569         /* Set the global bit for normal non-__init kernel text: */
570         set_memory_global(start, (end_global - start) >> PAGE_SHIFT);
571 }
572
573 void pti_set_kernel_image_nonglobal(void)
574 {
575         /*
576          * The identity map is created with PMDs, regardless of the
577          * actual length of the kernel.  We need to clear
578          * _PAGE_GLOBAL up to a PMD boundary, not just to the end
579          * of the image.
580          */
581         unsigned long start = PFN_ALIGN(_text);
582         unsigned long end = ALIGN((unsigned long)_end, PMD_PAGE_SIZE);
583
584         /*
585          * This clears _PAGE_GLOBAL from the entire kernel image.
586          * pti_clone_kernel_text() map put _PAGE_GLOBAL back for
587          * areas that are mapped to userspace.
588          */
589         set_memory_nonglobal(start, (end - start) >> PAGE_SHIFT);
590 }
591
592 /*
593  * Initialize kernel page table isolation
594  */
595 void __init pti_init(void)
596 {
597         if (!static_cpu_has(X86_FEATURE_PTI))
598                 return;
599
600         pr_info("enabled\n");
601
602 #ifdef CONFIG_X86_32
603         /*
604          * We check for X86_FEATURE_PCID here. But the init-code will
605          * clear the feature flag on 32 bit because the feature is not
606          * supported on 32 bit anyway. To print the warning we need to
607          * check with cpuid directly again.
608          */
609         if (cpuid_ecx(0x1) & BIT(17)) {
610                 /* Use printk to work around pr_fmt() */
611                 printk(KERN_WARNING "\n");
612                 printk(KERN_WARNING "************************************************************\n");
613                 printk(KERN_WARNING "** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!  **\n");
614                 printk(KERN_WARNING "**                                                        **\n");
615                 printk(KERN_WARNING "** You are using 32-bit PTI on a 64-bit PCID-capable CPU. **\n");
616                 printk(KERN_WARNING "** Your performance will increase dramatically if you     **\n");
617                 printk(KERN_WARNING "** switch to a 64-bit kernel!                             **\n");
618                 printk(KERN_WARNING "**                                                        **\n");
619                 printk(KERN_WARNING "** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!  **\n");
620                 printk(KERN_WARNING "************************************************************\n");
621         }
622 #endif
623
624         pti_clone_user_shared();
625
626         /* Undo all global bits from the init pagetables in head_64.S: */
627         pti_set_kernel_image_nonglobal();
628         /* Replace some of the global bits just for shared entry text: */
629         pti_clone_entry_text();
630         pti_setup_espfix64();
631         pti_setup_vsyscall();
632 }
633
634 /*
635  * Finalize the kernel mappings in the userspace page-table. Some of the
636  * mappings for the kernel image might have changed since pti_init()
637  * cloned them. This is because parts of the kernel image have been
638  * mapped RO and/or NX.  These changes need to be cloned again to the
639  * userspace page-table.
640  */
641 void pti_finalize(void)
642 {
643         /*
644          * We need to clone everything (again) that maps parts of the
645          * kernel image.
646          */
647         pti_clone_entry_text();
648         pti_clone_kernel_text();
649
650         debug_checkwx_user();
651 }