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.
16 #include <generated/compile.h>
17 #include <linux/module.h>
18 #include <linux/uts.h>
19 #include <linux/utsname.h>
20 #include <generated/utsrelease.h>
22 /* Simplified build-specific string for starting entropy. */
23 static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
24 LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;
26 static unsigned long rotate_xor(unsigned long hash, const void *area,
30 unsigned long *ptr = (unsigned long *)area;
32 for (i = 0; i < size / sizeof(hash); i++) {
33 /* Rotate by odd number of bits and XOR. */
34 hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
41 /* Attempt to create a simple but unpredictable starting entropy. */
42 static unsigned long get_boot_seed(void)
44 unsigned long hash = 0;
46 hash = rotate_xor(hash, build_str, sizeof(build_str));
47 hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
52 #define KASLR_COMPRESSED_BOOT
53 #include "../../lib/kaslr.c"
56 unsigned long long start;
57 unsigned long long size;
60 /* Only supporting at most 4 unusable memmap regions with kaslr */
61 #define MAX_MEMMAP_REGIONS 4
63 static bool memmap_too_large;
65 enum mem_avoid_index {
66 MEM_AVOID_ZO_RANGE = 0,
70 MEM_AVOID_MEMMAP_BEGIN,
71 MEM_AVOID_MEMMAP_END = MEM_AVOID_MEMMAP_BEGIN + MAX_MEMMAP_REGIONS - 1,
75 static struct mem_vector mem_avoid[MEM_AVOID_MAX];
77 static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
79 /* Item one is entirely before item two. */
80 if (one->start + one->size <= two->start)
82 /* Item one is entirely after item two. */
83 if (one->start >= two->start + two->size)
89 * _memparse - Parse a string with mem suffixes into a number
90 * @ptr: Where parse begins
91 * @retptr: (output) Optional pointer to next char after parse completes
93 * Parses a string into a number. The number stored at @ptr is
94 * potentially suffixed with K, M, G, T, P, E.
96 static unsigned long long _memparse(const char *ptr, char **retptr)
98 char *endptr; /* Local pointer to end of parsed string */
100 unsigned long long ret = simple_strtoull(ptr, &endptr, 0);
133 parse_memmap(char *p, unsigned long long *start, unsigned long long *size)
140 /* We don't care about this option here */
141 if (!strncmp(p, "exactmap", 8))
145 *size = _memparse(p, &p);
151 /* Skip this region, usable */
158 *start = _memparse(p + 1, &p);
165 static void mem_avoid_memmap(void)
172 /* See if we have any memmap areas */
173 rc = cmdline_find_option("memmap", arg, sizeof(arg));
179 while (str && (i < MAX_MEMMAP_REGIONS)) {
181 unsigned long long start, size;
182 char *k = strchr(str, ',');
187 rc = parse_memmap(str, &start, &size);
191 /* A usable region that should not be skipped */
195 mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].start = start;
196 mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].size = size;
200 /* More than 4 memmaps, fail kaslr */
201 if ((i >= MAX_MEMMAP_REGIONS) && str)
202 memmap_too_large = true;
206 * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
207 * The mem_avoid array is used to store the ranges that need to be avoided
208 * when KASLR searches for an appropriate random address. We must avoid any
209 * regions that are unsafe to overlap with during decompression, and other
210 * things like the initrd, cmdline and boot_params. This comment seeks to
211 * explain mem_avoid as clearly as possible since incorrect mem_avoid
212 * memory ranges lead to really hard to debug boot failures.
214 * The initrd, cmdline, and boot_params are trivial to identify for
215 * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
216 * MEM_AVOID_BOOTPARAMS respectively below.
218 * What is not obvious how to avoid is the range of memory that is used
219 * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
220 * the compressed kernel (ZO) and its run space, which is used to extract
221 * the uncompressed kernel (VO) and relocs.
223 * ZO's full run size sits against the end of the decompression buffer, so
224 * we can calculate where text, data, bss, etc of ZO are positioned more
227 * For additional background, the decompression calculations can be found
228 * in header.S, and the memory diagram is based on the one found in misc.c.
230 * The following conditions are already enforced by the image layouts and
232 * - input + input_size >= output + output_size
233 * - kernel_total_size <= init_size
234 * - kernel_total_size <= output_size (see Note below)
235 * - output + init_size >= output + output_size
237 * (Note that kernel_total_size and output_size have no fundamental
238 * relationship, but output_size is passed to choose_random_location
239 * as a maximum of the two. The diagram is showing a case where
240 * kernel_total_size is larger than output_size, but this case is
241 * handled by bumping output_size.)
243 * The above conditions can be illustrated by a diagram:
245 * 0 output input input+input_size output+init_size
248 * |-----|--------|--------|--------------|-----------|--|-------------|
251 * output+init_size-ZO_INIT_SIZE output+output_size output+kernel_total_size
253 * [output, output+init_size) is the entire memory range used for
254 * extracting the compressed image.
256 * [output, output+kernel_total_size) is the range needed for the
257 * uncompressed kernel (VO) and its run size (bss, brk, etc).
259 * [output, output+output_size) is VO plus relocs (i.e. the entire
260 * uncompressed payload contained by ZO). This is the area of the buffer
261 * written to during decompression.
263 * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
264 * range of the copied ZO and decompression code. (i.e. the range
265 * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
267 * [input, input+input_size) is the original copied compressed image (ZO)
268 * (i.e. it does not include its run size). This range must be avoided
269 * because it contains the data used for decompression.
271 * [input+input_size, output+init_size) is [_text, _end) for ZO. This
272 * range includes ZO's heap and stack, and must be avoided since it
273 * performs the decompression.
275 * Since the above two ranges need to be avoided and they are adjacent,
276 * they can be merged, resulting in: [input, output+init_size) which
277 * becomes the MEM_AVOID_ZO_RANGE below.
279 static void mem_avoid_init(unsigned long input, unsigned long input_size,
280 unsigned long output)
282 unsigned long init_size = boot_params->hdr.init_size;
283 u64 initrd_start, initrd_size;
284 u64 cmd_line, cmd_line_size;
288 * Avoid the region that is unsafe to overlap during
291 mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
292 mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
293 add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
294 mem_avoid[MEM_AVOID_ZO_RANGE].size);
297 initrd_start = (u64)boot_params->ext_ramdisk_image << 32;
298 initrd_start |= boot_params->hdr.ramdisk_image;
299 initrd_size = (u64)boot_params->ext_ramdisk_size << 32;
300 initrd_size |= boot_params->hdr.ramdisk_size;
301 mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
302 mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
303 /* No need to set mapping for initrd, it will be handled in VO. */
305 /* Avoid kernel command line. */
306 cmd_line = (u64)boot_params->ext_cmd_line_ptr << 32;
307 cmd_line |= boot_params->hdr.cmd_line_ptr;
308 /* Calculate size of cmd_line. */
309 ptr = (char *)(unsigned long)cmd_line;
310 for (cmd_line_size = 0; ptr[cmd_line_size++]; )
312 mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
313 mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
314 add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
315 mem_avoid[MEM_AVOID_CMDLINE].size);
317 /* Avoid boot parameters. */
318 mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
319 mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
320 add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
321 mem_avoid[MEM_AVOID_BOOTPARAMS].size);
323 /* We don't need to set a mapping for setup_data. */
325 /* Mark the memmap regions we need to avoid */
328 #ifdef CONFIG_X86_VERBOSE_BOOTUP
329 /* Make sure video RAM can be used. */
330 add_identity_map(0, PMD_SIZE);
335 * Does this memory vector overlap a known avoided area? If so, record the
336 * overlap region with the lowest address.
338 static bool mem_avoid_overlap(struct mem_vector *img,
339 struct mem_vector *overlap)
342 struct setup_data *ptr;
343 unsigned long earliest = img->start + img->size;
344 bool is_overlapping = false;
346 for (i = 0; i < MEM_AVOID_MAX; i++) {
347 if (mem_overlaps(img, &mem_avoid[i]) &&
348 mem_avoid[i].start < earliest) {
349 *overlap = mem_avoid[i];
350 earliest = overlap->start;
351 is_overlapping = true;
355 /* Avoid all entries in the setup_data linked list. */
356 ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
358 struct mem_vector avoid;
360 avoid.start = (unsigned long)ptr;
361 avoid.size = sizeof(*ptr) + ptr->len;
363 if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
365 earliest = overlap->start;
366 is_overlapping = true;
369 ptr = (struct setup_data *)(unsigned long)ptr->next;
372 return is_overlapping;
380 #define MAX_SLOT_AREA 100
382 static struct slot_area slot_areas[MAX_SLOT_AREA];
384 static unsigned long slot_max;
386 static unsigned long slot_area_index;
388 static void store_slot_info(struct mem_vector *region, unsigned long image_size)
390 struct slot_area slot_area;
392 if (slot_area_index == MAX_SLOT_AREA)
395 slot_area.addr = region->start;
396 slot_area.num = (region->size - image_size) /
397 CONFIG_PHYSICAL_ALIGN + 1;
399 if (slot_area.num > 0) {
400 slot_areas[slot_area_index++] = slot_area;
401 slot_max += slot_area.num;
405 static unsigned long slots_fetch_random(void)
410 /* Handle case of no slots stored. */
414 slot = kaslr_get_random_long("Physical") % slot_max;
416 for (i = 0; i < slot_area_index; i++) {
417 if (slot >= slot_areas[i].num) {
418 slot -= slot_areas[i].num;
421 return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
424 if (i == slot_area_index)
425 debug_putstr("slots_fetch_random() failed!?\n");
429 static void process_e820_entry(struct e820entry *entry,
430 unsigned long minimum,
431 unsigned long image_size)
433 struct mem_vector region, overlap;
434 struct slot_area slot_area;
435 unsigned long start_orig;
437 /* Skip non-RAM entries. */
438 if (entry->type != E820_RAM)
441 /* On 32-bit, ignore entries entirely above our maximum. */
442 if (IS_ENABLED(CONFIG_X86_32) && entry->addr >= KERNEL_IMAGE_SIZE)
445 /* Ignore entries entirely below our minimum. */
446 if (entry->addr + entry->size < minimum)
449 region.start = entry->addr;
450 region.size = entry->size;
452 /* Give up if slot area array is full. */
453 while (slot_area_index < MAX_SLOT_AREA) {
454 start_orig = region.start;
456 /* Potentially raise address to minimum location. */
457 if (region.start < minimum)
458 region.start = minimum;
460 /* Potentially raise address to meet alignment needs. */
461 region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
463 /* Did we raise the address above this e820 region? */
464 if (region.start > entry->addr + entry->size)
467 /* Reduce size by any delta from the original address. */
468 region.size -= region.start - start_orig;
470 /* On 32-bit, reduce region size to fit within max size. */
471 if (IS_ENABLED(CONFIG_X86_32) &&
472 region.start + region.size > KERNEL_IMAGE_SIZE)
473 region.size = KERNEL_IMAGE_SIZE - region.start;
475 /* Return if region can't contain decompressed kernel */
476 if (region.size < image_size)
479 /* If nothing overlaps, store the region and return. */
480 if (!mem_avoid_overlap(®ion, &overlap)) {
481 store_slot_info(®ion, image_size);
485 /* Store beginning of region if holds at least image_size. */
486 if (overlap.start > region.start + image_size) {
487 struct mem_vector beginning;
489 beginning.start = region.start;
490 beginning.size = overlap.start - region.start;
491 store_slot_info(&beginning, image_size);
494 /* Return if overlap extends to or past end of region. */
495 if (overlap.start + overlap.size >= region.start + region.size)
498 /* Clip off the overlapping region and start over. */
499 region.size -= overlap.start - region.start + overlap.size;
500 region.start = overlap.start + overlap.size;
504 static unsigned long find_random_phys_addr(unsigned long minimum,
505 unsigned long image_size)
510 /* Check if we had too many memmaps. */
511 if (memmap_too_large) {
512 debug_putstr("Aborted e820 scan (more than 4 memmap= args)!\n");
516 /* Make sure minimum is aligned. */
517 minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
519 /* Verify potential e820 positions, appending to slots list. */
520 for (i = 0; i < boot_params->e820_entries; i++) {
521 process_e820_entry(&boot_params->e820_map[i], minimum,
523 if (slot_area_index == MAX_SLOT_AREA) {
524 debug_putstr("Aborted e820 scan (slot_areas full)!\n");
529 return slots_fetch_random();
532 static unsigned long find_random_virt_addr(unsigned long minimum,
533 unsigned long image_size)
535 unsigned long slots, random_addr;
537 /* Make sure minimum is aligned. */
538 minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
539 /* Align image_size for easy slot calculations. */
540 image_size = ALIGN(image_size, CONFIG_PHYSICAL_ALIGN);
543 * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
544 * that can hold image_size within the range of minimum to
547 slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
548 CONFIG_PHYSICAL_ALIGN + 1;
550 random_addr = kaslr_get_random_long("Virtual") % slots;
552 return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
556 * Since this function examines addresses much more numerically,
557 * it takes the input and output pointers as 'unsigned long'.
559 void choose_random_location(unsigned long input,
560 unsigned long input_size,
561 unsigned long *output,
562 unsigned long output_size,
563 unsigned long *virt_addr)
565 unsigned long random_addr, min_addr;
567 /* By default, keep output position unchanged. */
568 *virt_addr = *output;
570 if (cmdline_find_option_bool("nokaslr")) {
571 warn("KASLR disabled: 'nokaslr' on cmdline.");
575 boot_params->hdr.loadflags |= KASLR_FLAG;
577 /* Prepare to add new identity pagetables on demand. */
578 initialize_identity_maps();
580 /* Record the various known unsafe memory ranges. */
581 mem_avoid_init(input, input_size, *output);
584 * Low end of the randomization range should be the
585 * smaller of 512M or the initial kernel image
588 min_addr = min(*output, 512UL << 20);
590 /* Walk e820 and find a random address. */
591 random_addr = find_random_phys_addr(min_addr, output_size);
593 warn("Physical KASLR disabled: no suitable memory region!");
595 /* Update the new physical address location. */
596 if (*output != random_addr) {
597 add_identity_map(random_addr, output_size);
598 *output = random_addr;
602 /* This actually loads the identity pagetable on x86_64. */
603 finalize_identity_maps();
605 /* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
606 if (IS_ENABLED(CONFIG_X86_64))
607 random_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, output_size);
608 *virt_addr = random_addr;