8ef1186f792a7ec53fa6c8add7b2240c2e3f1a8d
[cascardo/linux.git] / arch / x86 / boot / compressed / kaslr.c
1 /*
2  * kaslr.c
3  *
4  * This contains the routines needed to generate a reasonable level of
5  * entropy to choose a randomized kernel base address offset in support
6  * of Kernel Address Space Layout Randomization (KASLR). Additionally
7  * handles walking the physical memory maps (and tracking memory regions
8  * to avoid) in order to select a physical memory location that can
9  * contain the entire properly aligned running kernel image.
10  *
11  */
12 #include "misc.h"
13 #include "error.h"
14
15 #include <asm/msr.h>
16 #include <asm/archrandom.h>
17 #include <asm/e820.h>
18
19 #include <generated/compile.h>
20 #include <linux/module.h>
21 #include <linux/uts.h>
22 #include <linux/utsname.h>
23 #include <generated/utsrelease.h>
24
25 /* Simplified build-specific string for starting entropy. */
26 static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
27                 LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;
28
29 #define I8254_PORT_CONTROL      0x43
30 #define I8254_PORT_COUNTER0     0x40
31 #define I8254_CMD_READBACK      0xC0
32 #define I8254_SELECT_COUNTER0   0x02
33 #define I8254_STATUS_NOTREADY   0x40
34 static inline u16 i8254(void)
35 {
36         u16 status, timer;
37
38         do {
39                 outb(I8254_PORT_CONTROL,
40                      I8254_CMD_READBACK | I8254_SELECT_COUNTER0);
41                 status = inb(I8254_PORT_COUNTER0);
42                 timer  = inb(I8254_PORT_COUNTER0);
43                 timer |= inb(I8254_PORT_COUNTER0) << 8;
44         } while (status & I8254_STATUS_NOTREADY);
45
46         return timer;
47 }
48
49 static unsigned long rotate_xor(unsigned long hash, const void *area,
50                                 size_t size)
51 {
52         size_t i;
53         unsigned long *ptr = (unsigned long *)area;
54
55         for (i = 0; i < size / sizeof(hash); i++) {
56                 /* Rotate by odd number of bits and XOR. */
57                 hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
58                 hash ^= ptr[i];
59         }
60
61         return hash;
62 }
63
64 /* Attempt to create a simple but unpredictable starting entropy. */
65 static unsigned long get_random_boot(void)
66 {
67         unsigned long hash = 0;
68
69         hash = rotate_xor(hash, build_str, sizeof(build_str));
70         hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
71
72         return hash;
73 }
74
75 static unsigned long get_random_long(void)
76 {
77 #ifdef CONFIG_X86_64
78         const unsigned long mix_const = 0x5d6008cbf3848dd3UL;
79 #else
80         const unsigned long mix_const = 0x3f39e593UL;
81 #endif
82         unsigned long raw, random = get_random_boot();
83         bool use_i8254 = true;
84
85         debug_putstr("KASLR using");
86
87         if (has_cpuflag(X86_FEATURE_RDRAND)) {
88                 debug_putstr(" RDRAND");
89                 if (rdrand_long(&raw)) {
90                         random ^= raw;
91                         use_i8254 = false;
92                 }
93         }
94
95         if (has_cpuflag(X86_FEATURE_TSC)) {
96                 debug_putstr(" RDTSC");
97                 raw = rdtsc();
98
99                 random ^= raw;
100                 use_i8254 = false;
101         }
102
103         if (use_i8254) {
104                 debug_putstr(" i8254");
105                 random ^= i8254();
106         }
107
108         /* Circular multiply for better bit diffusion */
109         asm("mul %3"
110             : "=a" (random), "=d" (raw)
111             : "a" (random), "rm" (mix_const));
112         random += raw;
113
114         debug_putstr("...\n");
115
116         return random;
117 }
118
119 struct mem_vector {
120         unsigned long start;
121         unsigned long size;
122 };
123
124 enum mem_avoid_index {
125         MEM_AVOID_ZO_RANGE = 0,
126         MEM_AVOID_INITRD,
127         MEM_AVOID_CMDLINE,
128         MEM_AVOID_BOOTPARAMS,
129         MEM_AVOID_MAX,
130 };
131
132 static struct mem_vector mem_avoid[MEM_AVOID_MAX];
133
134 static bool mem_contains(struct mem_vector *region, struct mem_vector *item)
135 {
136         /* Item at least partially before region. */
137         if (item->start < region->start)
138                 return false;
139         /* Item at least partially after region. */
140         if (item->start + item->size > region->start + region->size)
141                 return false;
142         return true;
143 }
144
145 static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
146 {
147         /* Item one is entirely before item two. */
148         if (one->start + one->size <= two->start)
149                 return false;
150         /* Item one is entirely after item two. */
151         if (one->start >= two->start + two->size)
152                 return false;
153         return true;
154 }
155
156 /*
157  * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
158  * The mem_avoid array is used to store the ranges that need to be avoided
159  * when KASLR searches for an appropriate random address. We must avoid any
160  * regions that are unsafe to overlap with during decompression, and other
161  * things like the initrd, cmdline and boot_params. This comment seeks to
162  * explain mem_avoid as clearly as possible since incorrect mem_avoid
163  * memory ranges lead to really hard to debug boot failures.
164  *
165  * The initrd, cmdline, and boot_params are trivial to identify for
166  * avoiding. The are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
167  * MEM_AVOID_BOOTPARAMS respectively below.
168  *
169  * What is not obvious how to avoid is the range of memory that is used
170  * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
171  * the compressed kernel (ZO) and its run space, which is used to extract
172  * the uncompressed kernel (VO) and relocs.
173  *
174  * ZO's full run size sits against the end of the decompression buffer, so
175  * we can calculate where text, data, bss, etc of ZO are positioned more
176  * easily.
177  *
178  * For additional background, the decompression calculations can be found
179  * in header.S, and the memory diagram is based on the one found in misc.c.
180  *
181  * The following conditions are already enforced by the image layouts and
182  * associated code:
183  *  - input + input_size >= output + output_size
184  *  - kernel_total_size <= init_size
185  *  - kernel_total_size <= output_size (see Note below)
186  *  - output + init_size >= output + output_size
187  *
188  * (Note that kernel_total_size and output_size have no fundamental
189  * relationship, but output_size is passed to choose_random_location
190  * as a maximum of the two. The diagram is showing a case where
191  * kernel_total_size is larger than output_size, but this case is
192  * handled by bumping output_size.)
193  *
194  * The above conditions can be illustrated by a diagram:
195  *
196  * 0   output            input            input+input_size    output+init_size
197  * |     |                 |                             |             |
198  * |     |                 |                             |             |
199  * |-----|--------|--------|--------------|-----------|--|-------------|
200  *                |                       |           |
201  *                |                       |           |
202  * output+init_size-ZO_INIT_SIZE  output+output_size  output+kernel_total_size
203  *
204  * [output, output+init_size) is the entire memory range used for
205  * extracting the compressed image.
206  *
207  * [output, output+kernel_total_size) is the range needed for the
208  * uncompressed kernel (VO) and its run size (bss, brk, etc).
209  *
210  * [output, output+output_size) is VO plus relocs (i.e. the entire
211  * uncompressed payload contained by ZO). This is the area of the buffer
212  * written to during decompression.
213  *
214  * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
215  * range of the copied ZO and decompression code. (i.e. the range
216  * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
217  *
218  * [input, input+input_size) is the original copied compressed image (ZO)
219  * (i.e. it does not include its run size). This range must be avoided
220  * because it contains the data used for decompression.
221  *
222  * [input+input_size, output+init_size) is [_text, _end) for ZO. This
223  * range includes ZO's heap and stack, and must be avoided since it
224  * performs the decompression.
225  *
226  * Since the above two ranges need to be avoided and they are adjacent,
227  * they can be merged, resulting in: [input, output+init_size) which
228  * becomes the MEM_AVOID_ZO_RANGE below.
229  */
230 static void mem_avoid_init(unsigned long input, unsigned long input_size,
231                            unsigned long output)
232 {
233         unsigned long init_size = boot_params->hdr.init_size;
234         u64 initrd_start, initrd_size;
235         u64 cmd_line, cmd_line_size;
236         char *ptr;
237
238         /*
239          * Avoid the region that is unsafe to overlap during
240          * decompression.
241          */
242         mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
243         mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
244
245         /* Avoid initrd. */
246         initrd_start  = (u64)boot_params->ext_ramdisk_image << 32;
247         initrd_start |= boot_params->hdr.ramdisk_image;
248         initrd_size  = (u64)boot_params->ext_ramdisk_size << 32;
249         initrd_size |= boot_params->hdr.ramdisk_size;
250         mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
251         mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
252
253         /* Avoid kernel command line. */
254         cmd_line  = (u64)boot_params->ext_cmd_line_ptr << 32;
255         cmd_line |= boot_params->hdr.cmd_line_ptr;
256         /* Calculate size of cmd_line. */
257         ptr = (char *)(unsigned long)cmd_line;
258         for (cmd_line_size = 0; ptr[cmd_line_size++]; )
259                 ;
260         mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
261         mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
262
263         /* Avoid boot parameters. */
264         mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
265         mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
266 }
267
268 /* Does this memory vector overlap a known avoided area? */
269 static bool mem_avoid_overlap(struct mem_vector *img)
270 {
271         int i;
272         struct setup_data *ptr;
273
274         for (i = 0; i < MEM_AVOID_MAX; i++) {
275                 if (mem_overlaps(img, &mem_avoid[i]))
276                         return true;
277         }
278
279         /* Avoid all entries in the setup_data linked list. */
280         ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
281         while (ptr) {
282                 struct mem_vector avoid;
283
284                 avoid.start = (unsigned long)ptr;
285                 avoid.size = sizeof(*ptr) + ptr->len;
286
287                 if (mem_overlaps(img, &avoid))
288                         return true;
289
290                 ptr = (struct setup_data *)(unsigned long)ptr->next;
291         }
292
293         return false;
294 }
295
296 static unsigned long slots[KERNEL_IMAGE_SIZE / CONFIG_PHYSICAL_ALIGN];
297 static unsigned long slot_max;
298
299 static void slots_append(unsigned long addr)
300 {
301         /* Overflowing the slots list should be impossible. */
302         if (slot_max >= KERNEL_IMAGE_SIZE / CONFIG_PHYSICAL_ALIGN)
303                 return;
304
305         slots[slot_max++] = addr;
306 }
307
308 static unsigned long slots_fetch_random(void)
309 {
310         /* Handle case of no slots stored. */
311         if (slot_max == 0)
312                 return 0;
313
314         return slots[get_random_long() % slot_max];
315 }
316
317 static void process_e820_entry(struct e820entry *entry,
318                                unsigned long minimum,
319                                unsigned long image_size)
320 {
321         struct mem_vector region, img;
322
323         /* Skip non-RAM entries. */
324         if (entry->type != E820_RAM)
325                 return;
326
327         /* Ignore entries entirely above our maximum. */
328         if (entry->addr >= KERNEL_IMAGE_SIZE)
329                 return;
330
331         /* Ignore entries entirely below our minimum. */
332         if (entry->addr + entry->size < minimum)
333                 return;
334
335         region.start = entry->addr;
336         region.size = entry->size;
337
338         /* Potentially raise address to minimum location. */
339         if (region.start < minimum)
340                 region.start = minimum;
341
342         /* Potentially raise address to meet alignment requirements. */
343         region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
344
345         /* Did we raise the address above the bounds of this e820 region? */
346         if (region.start > entry->addr + entry->size)
347                 return;
348
349         /* Reduce size by any delta from the original address. */
350         region.size -= region.start - entry->addr;
351
352         /* Reduce maximum size to fit end of image within maximum limit. */
353         if (region.start + region.size > KERNEL_IMAGE_SIZE)
354                 region.size = KERNEL_IMAGE_SIZE - region.start;
355
356         /* Walk each aligned slot and check for avoided areas. */
357         for (img.start = region.start, img.size = image_size ;
358              mem_contains(&region, &img) ;
359              img.start += CONFIG_PHYSICAL_ALIGN) {
360                 if (mem_avoid_overlap(&img))
361                         continue;
362                 slots_append(img.start);
363         }
364 }
365
366 static unsigned long find_random_addr(unsigned long minimum,
367                                       unsigned long size)
368 {
369         int i;
370         unsigned long addr;
371
372         /* Make sure minimum is aligned. */
373         minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
374
375         /* Verify potential e820 positions, appending to slots list. */
376         for (i = 0; i < boot_params->e820_entries; i++) {
377                 process_e820_entry(&boot_params->e820_map[i], minimum, size);
378         }
379
380         return slots_fetch_random();
381 }
382
383 /*
384  * Since this function examines addresses much more numerically,
385  * it takes the input and output pointers as 'unsigned long'.
386  */
387 unsigned char *choose_random_location(unsigned long input,
388                                       unsigned long input_size,
389                                       unsigned long output,
390                                       unsigned long output_size)
391 {
392         unsigned long choice = output;
393         unsigned long random_addr;
394
395 #ifdef CONFIG_HIBERNATION
396         if (!cmdline_find_option_bool("kaslr")) {
397                 warn("KASLR disabled: 'kaslr' not on cmdline (hibernation selected).");
398                 goto out;
399         }
400 #else
401         if (cmdline_find_option_bool("nokaslr")) {
402                 warn("KASLR disabled: 'nokaslr' on cmdline.");
403                 goto out;
404         }
405 #endif
406
407         boot_params->hdr.loadflags |= KASLR_FLAG;
408
409         /* Record the various known unsafe memory ranges. */
410         mem_avoid_init(input, input_size, output);
411
412         /* Walk e820 and find a random address. */
413         random_addr = find_random_addr(output, output_size);
414         if (!random_addr) {
415                 warn("KASLR disabled: could not find suitable E820 region!");
416                 goto out;
417         }
418
419         /* Always enforce the minimum. */
420         if (random_addr < choice)
421                 goto out;
422
423         choice = random_addr;
424 out:
425         return (unsigned char *)choice;
426 }