1 // SPDX-License-Identifier: GPL-2.0
5 * This contains the routines needed to generate a reasonable level of
6 * entropy to choose a randomized kernel base address offset in support
7 * of Kernel Address Space Layout Randomization (KASLR). Additionally
8 * handles walking the physical memory maps (and tracking memory regions
9 * to avoid) in order to select a physical memory location that can
10 * contain the entire properly aligned running kernel image.
15 * isspace() in linux/ctype.h is expected by next_args() to filter
16 * out "space/lf/tab". While boot/ctype.h conflicts with linux/ctype.h,
17 * since isdigit() is implemented in both of them. Hence disable it
23 * _ctype[] in lib/ctype.c is needed by isspace() of linux/ctype.h.
24 * While both lib/ctype.c and lib/cmdline.c will bring EXPORT_SYMBOL
25 * which is meaningless and will cause compiling error in some cases.
26 * So do not include linux/export.h and define EXPORT_SYMBOL(sym)
29 #define _LINUX_EXPORT_H
30 #define EXPORT_SYMBOL(sym)
34 #include "../string.h"
36 #include <generated/compile.h>
37 #include <linux/module.h>
38 #include <linux/uts.h>
39 #include <linux/utsname.h>
40 #include <linux/ctype.h>
41 #include <linux/efi.h>
42 #include <generated/utsrelease.h>
45 /* Macros used by the included decompressor code below. */
47 #include <linux/decompress/mm.h>
49 extern unsigned long get_cmd_line_ptr(void);
51 /* Simplified build-specific string for starting entropy. */
52 static const char build_str
[] = UTS_RELEASE
" (" LINUX_COMPILE_BY
"@"
53 LINUX_COMPILE_HOST
") (" LINUX_COMPILER
") " UTS_VERSION
;
55 static unsigned long rotate_xor(unsigned long hash
, const void *area
,
59 unsigned long *ptr
= (unsigned long *)area
;
61 for (i
= 0; i
< size
/ sizeof(hash
); i
++) {
62 /* Rotate by odd number of bits and XOR. */
63 hash
= (hash
<< ((sizeof(hash
) * 8) - 7)) | (hash
>> 7);
70 /* Attempt to create a simple but unpredictable starting entropy. */
71 static unsigned long get_boot_seed(void)
73 unsigned long hash
= 0;
75 hash
= rotate_xor(hash
, build_str
, sizeof(build_str
));
76 hash
= rotate_xor(hash
, boot_params
, sizeof(*boot_params
));
81 #define KASLR_COMPRESSED_BOOT
82 #include "../../lib/kaslr.c"
85 unsigned long long start
;
86 unsigned long long size
;
89 /* Only supporting at most 4 unusable memmap regions with kaslr */
90 #define MAX_MEMMAP_REGIONS 4
92 static bool memmap_too_large
;
95 /* Store memory limit specified by "mem=nn[KMG]" or "memmap=nn[KMG]" */
96 unsigned long long mem_limit
= ULLONG_MAX
;
99 enum mem_avoid_index
{
100 MEM_AVOID_ZO_RANGE
= 0,
103 MEM_AVOID_BOOTPARAMS
,
104 MEM_AVOID_MEMMAP_BEGIN
,
105 MEM_AVOID_MEMMAP_END
= MEM_AVOID_MEMMAP_BEGIN
+ MAX_MEMMAP_REGIONS
- 1,
109 static struct mem_vector mem_avoid
[MEM_AVOID_MAX
];
111 static bool mem_overlaps(struct mem_vector
*one
, struct mem_vector
*two
)
113 /* Item one is entirely before item two. */
114 if (one
->start
+ one
->size
<= two
->start
)
116 /* Item one is entirely after item two. */
117 if (one
->start
>= two
->start
+ two
->size
)
122 char *skip_spaces(const char *str
)
124 while (isspace(*str
))
128 #include "../../../../lib/ctype.c"
129 #include "../../../../lib/cmdline.c"
132 parse_memmap(char *p
, unsigned long long *start
, unsigned long long *size
)
139 /* We don't care about this option here */
140 if (!strncmp(p
, "exactmap", 8))
144 *size
= memparse(p
, &p
);
152 *start
= memparse(p
+ 1, &p
);
155 /* memmap=nn@ss specifies usable region, should be skipped */
160 * If w/o offset, only size specified, memmap=nn[KMG] has the
161 * same behaviour as mem=nn[KMG]. It limits the max address
162 * system can use. Region above the limit should be avoided.
171 static void mem_avoid_memmap(char *str
)
175 if (i
>= MAX_MEMMAP_REGIONS
)
178 while (str
&& (i
< MAX_MEMMAP_REGIONS
)) {
180 unsigned long long start
, size
;
181 char *k
= strchr(str
, ',');
186 rc
= parse_memmap(str
, &start
, &size
);
192 /* Store the specified memory limit if size > 0 */
199 mem_avoid
[MEM_AVOID_MEMMAP_BEGIN
+ i
].start
= start
;
200 mem_avoid
[MEM_AVOID_MEMMAP_BEGIN
+ i
].size
= size
;
204 /* More than 4 memmaps, fail kaslr */
205 if ((i
>= MAX_MEMMAP_REGIONS
) && str
)
206 memmap_too_large
= true;
209 static int handle_mem_memmap(void)
211 char *args
= (char *)get_cmd_line_ptr();
212 size_t len
= strlen((char *)args
);
217 if (!strstr(args
, "memmap=") && !strstr(args
, "mem="))
220 tmp_cmdline
= malloc(len
+ 1);
222 error("Failed to allocate space for tmp_cmdline");
224 memcpy(tmp_cmdline
, args
, len
);
225 tmp_cmdline
[len
] = 0;
228 /* Chew leading spaces */
229 args
= skip_spaces(args
);
232 args
= next_arg(args
, ¶m
, &val
);
234 if (!val
&& strcmp(param
, "--") == 0) {
235 warn("Only '--' specified in cmdline");
240 if (!strcmp(param
, "memmap")) {
241 mem_avoid_memmap(val
);
242 } else if (!strcmp(param
, "mem")) {
245 if (!strcmp(p
, "nopentium"))
247 mem_size
= memparse(p
, &p
);
252 mem_limit
= mem_size
;
261 * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
262 * The mem_avoid array is used to store the ranges that need to be avoided
263 * when KASLR searches for an appropriate random address. We must avoid any
264 * regions that are unsafe to overlap with during decompression, and other
265 * things like the initrd, cmdline and boot_params. This comment seeks to
266 * explain mem_avoid as clearly as possible since incorrect mem_avoid
267 * memory ranges lead to really hard to debug boot failures.
269 * The initrd, cmdline, and boot_params are trivial to identify for
270 * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
271 * MEM_AVOID_BOOTPARAMS respectively below.
273 * What is not obvious how to avoid is the range of memory that is used
274 * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
275 * the compressed kernel (ZO) and its run space, which is used to extract
276 * the uncompressed kernel (VO) and relocs.
278 * ZO's full run size sits against the end of the decompression buffer, so
279 * we can calculate where text, data, bss, etc of ZO are positioned more
282 * For additional background, the decompression calculations can be found
283 * in header.S, and the memory diagram is based on the one found in misc.c.
285 * The following conditions are already enforced by the image layouts and
287 * - input + input_size >= output + output_size
288 * - kernel_total_size <= init_size
289 * - kernel_total_size <= output_size (see Note below)
290 * - output + init_size >= output + output_size
292 * (Note that kernel_total_size and output_size have no fundamental
293 * relationship, but output_size is passed to choose_random_location
294 * as a maximum of the two. The diagram is showing a case where
295 * kernel_total_size is larger than output_size, but this case is
296 * handled by bumping output_size.)
298 * The above conditions can be illustrated by a diagram:
300 * 0 output input input+input_size output+init_size
303 * |-----|--------|--------|--------------|-----------|--|-------------|
306 * output+init_size-ZO_INIT_SIZE output+output_size output+kernel_total_size
308 * [output, output+init_size) is the entire memory range used for
309 * extracting the compressed image.
311 * [output, output+kernel_total_size) is the range needed for the
312 * uncompressed kernel (VO) and its run size (bss, brk, etc).
314 * [output, output+output_size) is VO plus relocs (i.e. the entire
315 * uncompressed payload contained by ZO). This is the area of the buffer
316 * written to during decompression.
318 * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
319 * range of the copied ZO and decompression code. (i.e. the range
320 * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
322 * [input, input+input_size) is the original copied compressed image (ZO)
323 * (i.e. it does not include its run size). This range must be avoided
324 * because it contains the data used for decompression.
326 * [input+input_size, output+init_size) is [_text, _end) for ZO. This
327 * range includes ZO's heap and stack, and must be avoided since it
328 * performs the decompression.
330 * Since the above two ranges need to be avoided and they are adjacent,
331 * they can be merged, resulting in: [input, output+init_size) which
332 * becomes the MEM_AVOID_ZO_RANGE below.
334 static void mem_avoid_init(unsigned long input
, unsigned long input_size
,
335 unsigned long output
)
337 unsigned long init_size
= boot_params
->hdr
.init_size
;
338 u64 initrd_start
, initrd_size
;
339 u64 cmd_line
, cmd_line_size
;
343 * Avoid the region that is unsafe to overlap during
346 mem_avoid
[MEM_AVOID_ZO_RANGE
].start
= input
;
347 mem_avoid
[MEM_AVOID_ZO_RANGE
].size
= (output
+ init_size
) - input
;
348 add_identity_map(mem_avoid
[MEM_AVOID_ZO_RANGE
].start
,
349 mem_avoid
[MEM_AVOID_ZO_RANGE
].size
);
352 initrd_start
= (u64
)boot_params
->ext_ramdisk_image
<< 32;
353 initrd_start
|= boot_params
->hdr
.ramdisk_image
;
354 initrd_size
= (u64
)boot_params
->ext_ramdisk_size
<< 32;
355 initrd_size
|= boot_params
->hdr
.ramdisk_size
;
356 mem_avoid
[MEM_AVOID_INITRD
].start
= initrd_start
;
357 mem_avoid
[MEM_AVOID_INITRD
].size
= initrd_size
;
358 /* No need to set mapping for initrd, it will be handled in VO. */
360 /* Avoid kernel command line. */
361 cmd_line
= (u64
)boot_params
->ext_cmd_line_ptr
<< 32;
362 cmd_line
|= boot_params
->hdr
.cmd_line_ptr
;
363 /* Calculate size of cmd_line. */
364 ptr
= (char *)(unsigned long)cmd_line
;
365 for (cmd_line_size
= 0; ptr
[cmd_line_size
++];)
367 mem_avoid
[MEM_AVOID_CMDLINE
].start
= cmd_line
;
368 mem_avoid
[MEM_AVOID_CMDLINE
].size
= cmd_line_size
;
369 add_identity_map(mem_avoid
[MEM_AVOID_CMDLINE
].start
,
370 mem_avoid
[MEM_AVOID_CMDLINE
].size
);
372 /* Avoid boot parameters. */
373 mem_avoid
[MEM_AVOID_BOOTPARAMS
].start
= (unsigned long)boot_params
;
374 mem_avoid
[MEM_AVOID_BOOTPARAMS
].size
= sizeof(*boot_params
);
375 add_identity_map(mem_avoid
[MEM_AVOID_BOOTPARAMS
].start
,
376 mem_avoid
[MEM_AVOID_BOOTPARAMS
].size
);
378 /* We don't need to set a mapping for setup_data. */
380 /* Mark the memmap regions we need to avoid */
383 #ifdef CONFIG_X86_VERBOSE_BOOTUP
384 /* Make sure video RAM can be used. */
385 add_identity_map(0, PMD_SIZE
);
390 * Does this memory vector overlap a known avoided area? If so, record the
391 * overlap region with the lowest address.
393 static bool mem_avoid_overlap(struct mem_vector
*img
,
394 struct mem_vector
*overlap
)
397 struct setup_data
*ptr
;
398 unsigned long earliest
= img
->start
+ img
->size
;
399 bool is_overlapping
= false;
401 for (i
= 0; i
< MEM_AVOID_MAX
; i
++) {
402 if (mem_overlaps(img
, &mem_avoid
[i
]) &&
403 mem_avoid
[i
].start
< earliest
) {
404 *overlap
= mem_avoid
[i
];
405 earliest
= overlap
->start
;
406 is_overlapping
= true;
410 /* Avoid all entries in the setup_data linked list. */
411 ptr
= (struct setup_data
*)(unsigned long)boot_params
->hdr
.setup_data
;
413 struct mem_vector avoid
;
415 avoid
.start
= (unsigned long)ptr
;
416 avoid
.size
= sizeof(*ptr
) + ptr
->len
;
418 if (mem_overlaps(img
, &avoid
) && (avoid
.start
< earliest
)) {
420 earliest
= overlap
->start
;
421 is_overlapping
= true;
424 ptr
= (struct setup_data
*)(unsigned long)ptr
->next
;
427 return is_overlapping
;
435 #define MAX_SLOT_AREA 100
437 static struct slot_area slot_areas
[MAX_SLOT_AREA
];
439 static unsigned long slot_max
;
441 static unsigned long slot_area_index
;
443 static void store_slot_info(struct mem_vector
*region
, unsigned long image_size
)
445 struct slot_area slot_area
;
447 if (slot_area_index
== MAX_SLOT_AREA
)
450 slot_area
.addr
= region
->start
;
451 slot_area
.num
= (region
->size
- image_size
) /
452 CONFIG_PHYSICAL_ALIGN
+ 1;
454 if (slot_area
.num
> 0) {
455 slot_areas
[slot_area_index
++] = slot_area
;
456 slot_max
+= slot_area
.num
;
460 static unsigned long slots_fetch_random(void)
465 /* Handle case of no slots stored. */
469 slot
= kaslr_get_random_long("Physical") % slot_max
;
471 for (i
= 0; i
< slot_area_index
; i
++) {
472 if (slot
>= slot_areas
[i
].num
) {
473 slot
-= slot_areas
[i
].num
;
476 return slot_areas
[i
].addr
+ slot
* CONFIG_PHYSICAL_ALIGN
;
479 if (i
== slot_area_index
)
480 debug_putstr("slots_fetch_random() failed!?\n");
484 static void process_mem_region(struct mem_vector
*entry
,
485 unsigned long minimum
,
486 unsigned long image_size
)
488 struct mem_vector region
, overlap
;
489 struct slot_area slot_area
;
490 unsigned long start_orig
, end
;
491 struct mem_vector cur_entry
;
493 /* On 32-bit, ignore entries entirely above our maximum. */
494 if (IS_ENABLED(CONFIG_X86_32
) && entry
->start
>= KERNEL_IMAGE_SIZE
)
497 /* Ignore entries entirely below our minimum. */
498 if (entry
->start
+ entry
->size
< minimum
)
501 /* Ignore entries above memory limit */
502 end
= min(entry
->size
+ entry
->start
, mem_limit
);
503 if (entry
->start
>= end
)
505 cur_entry
.start
= entry
->start
;
506 cur_entry
.size
= end
- entry
->start
;
508 region
.start
= cur_entry
.start
;
509 region
.size
= cur_entry
.size
;
511 /* Give up if slot area array is full. */
512 while (slot_area_index
< MAX_SLOT_AREA
) {
513 start_orig
= region
.start
;
515 /* Potentially raise address to minimum location. */
516 if (region
.start
< minimum
)
517 region
.start
= minimum
;
519 /* Potentially raise address to meet alignment needs. */
520 region
.start
= ALIGN(region
.start
, CONFIG_PHYSICAL_ALIGN
);
522 /* Did we raise the address above the passed in memory entry? */
523 if (region
.start
> cur_entry
.start
+ cur_entry
.size
)
526 /* Reduce size by any delta from the original address. */
527 region
.size
-= region
.start
- start_orig
;
529 /* On 32-bit, reduce region size to fit within max size. */
530 if (IS_ENABLED(CONFIG_X86_32
) &&
531 region
.start
+ region
.size
> KERNEL_IMAGE_SIZE
)
532 region
.size
= KERNEL_IMAGE_SIZE
- region
.start
;
534 /* Return if region can't contain decompressed kernel */
535 if (region
.size
< image_size
)
538 /* If nothing overlaps, store the region and return. */
539 if (!mem_avoid_overlap(®ion
, &overlap
)) {
540 store_slot_info(®ion
, image_size
);
544 /* Store beginning of region if holds at least image_size. */
545 if (overlap
.start
> region
.start
+ image_size
) {
546 struct mem_vector beginning
;
548 beginning
.start
= region
.start
;
549 beginning
.size
= overlap
.start
- region
.start
;
550 store_slot_info(&beginning
, image_size
);
553 /* Return if overlap extends to or past end of region. */
554 if (overlap
.start
+ overlap
.size
>= region
.start
+ region
.size
)
557 /* Clip off the overlapping region and start over. */
558 region
.size
-= overlap
.start
- region
.start
+ overlap
.size
;
559 region
.start
= overlap
.start
+ overlap
.size
;
565 * Returns true if mirror region found (and must have been processed
569 process_efi_entries(unsigned long minimum
, unsigned long image_size
)
571 struct efi_info
*e
= &boot_params
->efi_info
;
572 bool efi_mirror_found
= false;
573 struct mem_vector region
;
574 efi_memory_desc_t
*md
;
580 signature
= (char *)&e
->efi_loader_signature
;
581 if (strncmp(signature
, EFI32_LOADER_SIGNATURE
, 4) &&
582 strncmp(signature
, EFI64_LOADER_SIGNATURE
, 4))
586 /* Can't handle data above 4GB at this time */
587 if (e
->efi_memmap_hi
) {
588 warn("EFI memmap is above 4GB, can't be handled now on x86_32. EFI should be disabled.\n");
591 pmap
= e
->efi_memmap
;
593 pmap
= (e
->efi_memmap
| ((__u64
)e
->efi_memmap_hi
<< 32));
596 nr_desc
= e
->efi_memmap_size
/ e
->efi_memdesc_size
;
597 for (i
= 0; i
< nr_desc
; i
++) {
598 md
= efi_early_memdesc_ptr(pmap
, e
->efi_memdesc_size
, i
);
599 if (md
->attribute
& EFI_MEMORY_MORE_RELIABLE
) {
600 efi_mirror_found
= true;
605 for (i
= 0; i
< nr_desc
; i
++) {
606 md
= efi_early_memdesc_ptr(pmap
, e
->efi_memdesc_size
, i
);
609 * Here we are more conservative in picking free memory than
610 * the EFI spec allows:
612 * According to the spec, EFI_BOOT_SERVICES_{CODE|DATA} are also
613 * free memory and thus available to place the kernel image into,
614 * but in practice there's firmware where using that memory leads
617 * Only EFI_CONVENTIONAL_MEMORY is guaranteed to be free.
619 if (md
->type
!= EFI_CONVENTIONAL_MEMORY
)
622 if (efi_mirror_found
&&
623 !(md
->attribute
& EFI_MEMORY_MORE_RELIABLE
))
626 region
.start
= md
->phys_addr
;
627 region
.size
= md
->num_pages
<< EFI_PAGE_SHIFT
;
628 process_mem_region(®ion
, minimum
, image_size
);
629 if (slot_area_index
== MAX_SLOT_AREA
) {
630 debug_putstr("Aborted EFI scan (slot_areas full)!\n");
638 process_efi_entries(unsigned long minimum
, unsigned long image_size
)
644 static void process_e820_entries(unsigned long minimum
,
645 unsigned long image_size
)
648 struct mem_vector region
;
649 struct boot_e820_entry
*entry
;
651 /* Verify potential e820 positions, appending to slots list. */
652 for (i
= 0; i
< boot_params
->e820_entries
; i
++) {
653 entry
= &boot_params
->e820_table
[i
];
654 /* Skip non-RAM entries. */
655 if (entry
->type
!= E820_TYPE_RAM
)
657 region
.start
= entry
->addr
;
658 region
.size
= entry
->size
;
659 process_mem_region(®ion
, minimum
, image_size
);
660 if (slot_area_index
== MAX_SLOT_AREA
) {
661 debug_putstr("Aborted e820 scan (slot_areas full)!\n");
667 static unsigned long find_random_phys_addr(unsigned long minimum
,
668 unsigned long image_size
)
670 /* Check if we had too many memmaps. */
671 if (memmap_too_large
) {
672 debug_putstr("Aborted memory entries scan (more than 4 memmap= args)!\n");
676 /* Make sure minimum is aligned. */
677 minimum
= ALIGN(minimum
, CONFIG_PHYSICAL_ALIGN
);
679 if (process_efi_entries(minimum
, image_size
))
680 return slots_fetch_random();
682 process_e820_entries(minimum
, image_size
);
683 return slots_fetch_random();
686 static unsigned long find_random_virt_addr(unsigned long minimum
,
687 unsigned long image_size
)
689 unsigned long slots
, random_addr
;
691 /* Make sure minimum is aligned. */
692 minimum
= ALIGN(minimum
, CONFIG_PHYSICAL_ALIGN
);
693 /* Align image_size for easy slot calculations. */
694 image_size
= ALIGN(image_size
, CONFIG_PHYSICAL_ALIGN
);
697 * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
698 * that can hold image_size within the range of minimum to
701 slots
= (KERNEL_IMAGE_SIZE
- minimum
- image_size
) /
702 CONFIG_PHYSICAL_ALIGN
+ 1;
704 random_addr
= kaslr_get_random_long("Virtual") % slots
;
706 return random_addr
* CONFIG_PHYSICAL_ALIGN
+ minimum
;
710 * Since this function examines addresses much more numerically,
711 * it takes the input and output pointers as 'unsigned long'.
713 void choose_random_location(unsigned long input
,
714 unsigned long input_size
,
715 unsigned long *output
,
716 unsigned long output_size
,
717 unsigned long *virt_addr
)
719 unsigned long random_addr
, min_addr
;
721 if (cmdline_find_option_bool("nokaslr")) {
722 warn("KASLR disabled: 'nokaslr' on cmdline.");
726 boot_params
->hdr
.loadflags
|= KASLR_FLAG
;
728 /* Prepare to add new identity pagetables on demand. */
729 initialize_identity_maps();
731 /* Record the various known unsafe memory ranges. */
732 mem_avoid_init(input
, input_size
, *output
);
735 * Low end of the randomization range should be the
736 * smaller of 512M or the initial kernel image
739 min_addr
= min(*output
, 512UL << 20);
741 /* Walk available memory entries to find a random address. */
742 random_addr
= find_random_phys_addr(min_addr
, output_size
);
744 warn("Physical KASLR disabled: no suitable memory region!");
746 /* Update the new physical address location. */
747 if (*output
!= random_addr
) {
748 add_identity_map(random_addr
, output_size
);
749 *output
= random_addr
;
753 * This loads the identity mapping page table.
754 * This should only be done if a new physical address
755 * is found for the kernel, otherwise we should keep
756 * the old page table to make it be like the "nokaslr"
759 finalize_identity_maps();
763 /* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
764 if (IS_ENABLED(CONFIG_X86_64
))
765 random_addr
= find_random_virt_addr(LOAD_PHYSICAL_ADDR
, output_size
);
766 *virt_addr
= random_addr
;