blob: 8199a6187251d0179276c96b5260a2226397ef06 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Kees Cook7de828d2016-04-18 09:42:14 -07002/*
3 * kaslr.c
4 *
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.
11 *
12 */
Baoquan Hed52e7d52017-05-13 13:46:28 +080013
14/*
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
18 * here.
19 */
20#define BOOT_CTYPE_H
21
22/*
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)
27 * as empty.
28 */
29#define _LINUX_EXPORT_H
30#define EXPORT_SYMBOL(sym)
31
Kees Cook8ab38202013-10-10 17:18:14 -070032#include "misc.h"
Kees Cookdc425a62016-05-02 15:51:00 -070033#include "error.h"
Arnd Bergmann5b8b9cf2017-05-30 11:14:17 +020034#include "../string.h"
Kees Cook8ab38202013-10-10 17:18:14 -070035
Kees Cooka653f352013-11-11 14:28:39 -080036#include <generated/compile.h>
37#include <linux/module.h>
38#include <linux/uts.h>
39#include <linux/utsname.h>
Baoquan Hed52e7d52017-05-13 13:46:28 +080040#include <linux/ctype.h>
Baoquan Hec05cd792017-08-14 22:54:24 +080041#include <linux/efi.h>
Kees Cooka653f352013-11-11 14:28:39 -080042#include <generated/utsrelease.h>
Baoquan Hec05cd792017-08-14 22:54:24 +080043#include <asm/efi.h>
Kees Cooka653f352013-11-11 14:28:39 -080044
Baoquan Hed52e7d52017-05-13 13:46:28 +080045/* Macros used by the included decompressor code below. */
46#define STATIC
47#include <linux/decompress/mm.h>
48
49extern unsigned long get_cmd_line_ptr(void);
50
Kees Cooka653f352013-11-11 14:28:39 -080051/* Simplified build-specific string for starting entropy. */
Kees Cook327f7d72013-11-12 08:56:07 -080052static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
Kees Cooka653f352013-11-11 14:28:39 -080053 LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;
54
Kees Cooka653f352013-11-11 14:28:39 -080055static unsigned long rotate_xor(unsigned long hash, const void *area,
56 size_t size)
57{
58 size_t i;
59 unsigned long *ptr = (unsigned long *)area;
60
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);
64 hash ^= ptr[i];
65 }
66
67 return hash;
68}
69
70/* Attempt to create a simple but unpredictable starting entropy. */
Thomas Garnierd899a7d2016-06-21 17:46:58 -070071static unsigned long get_boot_seed(void)
Kees Cooka653f352013-11-11 14:28:39 -080072{
73 unsigned long hash = 0;
74
75 hash = rotate_xor(hash, build_str, sizeof(build_str));
Kees Cook6655e0a2016-04-18 09:42:12 -070076 hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
Kees Cooka653f352013-11-11 14:28:39 -080077
78 return hash;
79}
80
Thomas Garnierd899a7d2016-06-21 17:46:58 -070081#define KASLR_COMPRESSED_BOOT
82#include "../../lib/kaslr.c"
Kees Cook8ab38202013-10-10 17:18:14 -070083
Kees Cook82fa9632013-10-10 17:18:16 -070084struct mem_vector {
Dave Jiangf2844242017-01-11 16:20:01 -070085 unsigned long long start;
86 unsigned long long size;
Kees Cook82fa9632013-10-10 17:18:16 -070087};
88
Dave Jiangf2844242017-01-11 16:20:01 -070089/* Only supporting at most 4 unusable memmap regions with kaslr */
90#define MAX_MEMMAP_REGIONS 4
91
92static bool memmap_too_large;
93
Baoquan Hed52e7d52017-05-13 13:46:28 +080094
Baoquan He4cdba142017-05-13 13:46:29 +080095/* Store memory limit specified by "mem=nn[KMG]" or "memmap=nn[KMG]" */
96unsigned long long mem_limit = ULLONG_MAX;
97
98
Kees Cooked09acd2016-05-06 12:44:59 -070099enum mem_avoid_index {
100 MEM_AVOID_ZO_RANGE = 0,
101 MEM_AVOID_INITRD,
102 MEM_AVOID_CMDLINE,
103 MEM_AVOID_BOOTPARAMS,
Dave Jiangf2844242017-01-11 16:20:01 -0700104 MEM_AVOID_MEMMAP_BEGIN,
105 MEM_AVOID_MEMMAP_END = MEM_AVOID_MEMMAP_BEGIN + MAX_MEMMAP_REGIONS - 1,
Kees Cooked09acd2016-05-06 12:44:59 -0700106 MEM_AVOID_MAX,
107};
108
Kees Cooke290e8c2014-02-09 13:56:44 -0800109static struct mem_vector mem_avoid[MEM_AVOID_MAX];
Kees Cook82fa9632013-10-10 17:18:16 -0700110
Kees Cook82fa9632013-10-10 17:18:16 -0700111static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
112{
113 /* Item one is entirely before item two. */
114 if (one->start + one->size <= two->start)
115 return false;
116 /* Item one is entirely after item two. */
117 if (one->start >= two->start + two->size)
118 return false;
119 return true;
120}
121
Baoquan Hed52e7d52017-05-13 13:46:28 +0800122char *skip_spaces(const char *str)
Dave Jiangf2844242017-01-11 16:20:01 -0700123{
Baoquan Hed52e7d52017-05-13 13:46:28 +0800124 while (isspace(*str))
125 ++str;
126 return (char *)str;
Dave Jiangf2844242017-01-11 16:20:01 -0700127}
Baoquan Hed52e7d52017-05-13 13:46:28 +0800128#include "../../../../lib/ctype.c"
129#include "../../../../lib/cmdline.c"
Dave Jiangf2844242017-01-11 16:20:01 -0700130
131static int
132parse_memmap(char *p, unsigned long long *start, unsigned long long *size)
133{
134 char *oldp;
135
136 if (!p)
137 return -EINVAL;
138
139 /* We don't care about this option here */
140 if (!strncmp(p, "exactmap", 8))
141 return -EINVAL;
142
143 oldp = p;
Baoquan Hed52e7d52017-05-13 13:46:28 +0800144 *size = memparse(p, &p);
Dave Jiangf2844242017-01-11 16:20:01 -0700145 if (p == oldp)
146 return -EINVAL;
147
148 switch (*p) {
Dave Jiangf2844242017-01-11 16:20:01 -0700149 case '#':
150 case '$':
151 case '!':
Baoquan Hed52e7d52017-05-13 13:46:28 +0800152 *start = memparse(p + 1, &p);
Dave Jiangf2844242017-01-11 16:20:01 -0700153 return 0;
Baoquan He4cdba142017-05-13 13:46:29 +0800154 case '@':
155 /* memmap=nn@ss specifies usable region, should be skipped */
156 *size = 0;
157 /* Fall through */
158 default:
159 /*
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.
163 */
164 *start = 0;
Dave Jiangf2844242017-01-11 16:20:01 -0700165 return 0;
166 }
167
168 return -EINVAL;
169}
170
Baoquan Hed52e7d52017-05-13 13:46:28 +0800171static void mem_avoid_memmap(char *str)
Dave Jiangf2844242017-01-11 16:20:01 -0700172{
Baoquan Hed52e7d52017-05-13 13:46:28 +0800173 static int i;
Dave Jiangf2844242017-01-11 16:20:01 -0700174
Baoquan Hed52e7d52017-05-13 13:46:28 +0800175 if (i >= MAX_MEMMAP_REGIONS)
Dave Jiangf2844242017-01-11 16:20:01 -0700176 return;
177
Dave Jiangf2844242017-01-11 16:20:01 -0700178 while (str && (i < MAX_MEMMAP_REGIONS)) {
179 int rc;
180 unsigned long long start, size;
181 char *k = strchr(str, ',');
182
183 if (k)
184 *k++ = 0;
185
186 rc = parse_memmap(str, &start, &size);
187 if (rc < 0)
188 break;
189 str = k;
Baoquan He4cdba142017-05-13 13:46:29 +0800190
191 if (start == 0) {
192 /* Store the specified memory limit if size > 0 */
193 if (size > 0)
194 mem_limit = size;
195
Dave Jiangf2844242017-01-11 16:20:01 -0700196 continue;
Baoquan He4cdba142017-05-13 13:46:29 +0800197 }
Dave Jiangf2844242017-01-11 16:20:01 -0700198
199 mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].start = start;
200 mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].size = size;
201 i++;
202 }
203
204 /* More than 4 memmaps, fail kaslr */
205 if ((i >= MAX_MEMMAP_REGIONS) && str)
206 memmap_too_large = true;
207}
208
Baoquan Hed52e7d52017-05-13 13:46:28 +0800209static int handle_mem_memmap(void)
210{
211 char *args = (char *)get_cmd_line_ptr();
212 size_t len = strlen((char *)args);
213 char *tmp_cmdline;
214 char *param, *val;
Baoquan He4cdba142017-05-13 13:46:29 +0800215 u64 mem_size;
Baoquan Hed52e7d52017-05-13 13:46:28 +0800216
Baoquan He4cdba142017-05-13 13:46:29 +0800217 if (!strstr(args, "memmap=") && !strstr(args, "mem="))
Baoquan Hed52e7d52017-05-13 13:46:28 +0800218 return 0;
219
220 tmp_cmdline = malloc(len + 1);
Chao Fan69550d42017-11-23 17:08:47 +0800221 if (!tmp_cmdline)
Baoquan Hed52e7d52017-05-13 13:46:28 +0800222 error("Failed to allocate space for tmp_cmdline");
223
224 memcpy(tmp_cmdline, args, len);
225 tmp_cmdline[len] = 0;
226 args = tmp_cmdline;
227
228 /* Chew leading spaces */
229 args = skip_spaces(args);
230
231 while (*args) {
232 args = next_arg(args, &param, &val);
233 /* Stop at -- */
234 if (!val && strcmp(param, "--") == 0) {
235 warn("Only '--' specified in cmdline");
236 free(tmp_cmdline);
237 return -1;
238 }
239
Baoquan He4cdba142017-05-13 13:46:29 +0800240 if (!strcmp(param, "memmap")) {
Baoquan Hed52e7d52017-05-13 13:46:28 +0800241 mem_avoid_memmap(val);
Baoquan He4cdba142017-05-13 13:46:29 +0800242 } else if (!strcmp(param, "mem")) {
243 char *p = val;
244
245 if (!strcmp(p, "nopentium"))
246 continue;
247 mem_size = memparse(p, &p);
248 if (mem_size == 0) {
249 free(tmp_cmdline);
250 return -EINVAL;
251 }
252 mem_limit = mem_size;
253 }
Baoquan Hed52e7d52017-05-13 13:46:28 +0800254 }
255
256 free(tmp_cmdline);
257 return 0;
258}
259
Yinghai Lu9dc19692016-05-05 15:13:47 -0700260/*
Kees Cooked09acd2016-05-06 12:44:59 -0700261 * 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
Yinghai Lu9dc19692016-05-05 15:13:47 -0700264 * regions that are unsafe to overlap with during decompression, and other
Kees Cooked09acd2016-05-06 12:44:59 -0700265 * 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.
Yinghai Lu9dc19692016-05-05 15:13:47 -0700268 *
Kees Cooked09acd2016-05-06 12:44:59 -0700269 * The initrd, cmdline, and boot_params are trivial to identify for
Kees Cookcb18ef02016-05-09 13:22:05 -0700270 * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
Kees Cooked09acd2016-05-06 12:44:59 -0700271 * MEM_AVOID_BOOTPARAMS respectively below.
Yinghai Lu9dc19692016-05-05 15:13:47 -0700272 *
Kees Cooked09acd2016-05-06 12:44:59 -0700273 * 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.
Yinghai Lu9dc19692016-05-05 15:13:47 -0700277 *
Kees Cooked09acd2016-05-06 12:44:59 -0700278 * 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
280 * easily.
Yinghai Lu9dc19692016-05-05 15:13:47 -0700281 *
Kees Cooked09acd2016-05-06 12:44:59 -0700282 * 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.
Yinghai Lu9dc19692016-05-05 15:13:47 -0700284 *
Kees Cooked09acd2016-05-06 12:44:59 -0700285 * The following conditions are already enforced by the image layouts and
286 * associated code:
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
Yinghai Lu9dc19692016-05-05 15:13:47 -0700291 *
Kees Cooked09acd2016-05-06 12:44:59 -0700292 * (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.)
Yinghai Lu9dc19692016-05-05 15:13:47 -0700297 *
Kees Cooked09acd2016-05-06 12:44:59 -0700298 * The above conditions can be illustrated by a diagram:
Yinghai Lu9dc19692016-05-05 15:13:47 -0700299 *
Kees Cooked09acd2016-05-06 12:44:59 -0700300 * 0 output input input+input_size output+init_size
301 * | | | | |
302 * | | | | |
303 * |-----|--------|--------|--------------|-----------|--|-------------|
304 * | | |
305 * | | |
306 * output+init_size-ZO_INIT_SIZE output+output_size output+kernel_total_size
Yinghai Lu9dc19692016-05-05 15:13:47 -0700307 *
Kees Cooked09acd2016-05-06 12:44:59 -0700308 * [output, output+init_size) is the entire memory range used for
309 * extracting the compressed image.
Yinghai Lu9dc19692016-05-05 15:13:47 -0700310 *
Kees Cooked09acd2016-05-06 12:44:59 -0700311 * [output, output+kernel_total_size) is the range needed for the
312 * uncompressed kernel (VO) and its run size (bss, brk, etc).
313 *
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.
317 *
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.)
321 *
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.
325 *
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.
329 *
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.
Yinghai Lu9dc19692016-05-05 15:13:47 -0700333 */
Kees Cook82fa9632013-10-10 17:18:16 -0700334static void mem_avoid_init(unsigned long input, unsigned long input_size,
Yinghai Lu9dc19692016-05-05 15:13:47 -0700335 unsigned long output)
Kees Cook82fa9632013-10-10 17:18:16 -0700336{
Yinghai Lu9dc19692016-05-05 15:13:47 -0700337 unsigned long init_size = boot_params->hdr.init_size;
Kees Cook82fa9632013-10-10 17:18:16 -0700338 u64 initrd_start, initrd_size;
339 u64 cmd_line, cmd_line_size;
Kees Cook82fa9632013-10-10 17:18:16 -0700340 char *ptr;
341
342 /*
343 * Avoid the region that is unsafe to overlap during
Yinghai Lu9dc19692016-05-05 15:13:47 -0700344 * decompression.
Kees Cook82fa9632013-10-10 17:18:16 -0700345 */
Kees Cooked09acd2016-05-06 12:44:59 -0700346 mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
347 mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
Kees Cook3a947072016-05-06 15:01:35 -0700348 add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
349 mem_avoid[MEM_AVOID_ZO_RANGE].size);
Kees Cook82fa9632013-10-10 17:18:16 -0700350
351 /* Avoid initrd. */
Kees Cook6655e0a2016-04-18 09:42:12 -0700352 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;
Kees Cooked09acd2016-05-06 12:44:59 -0700356 mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
357 mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
Kees Cook3a947072016-05-06 15:01:35 -0700358 /* No need to set mapping for initrd, it will be handled in VO. */
Kees Cook82fa9632013-10-10 17:18:16 -0700359
360 /* Avoid kernel command line. */
Kees Cook6655e0a2016-04-18 09:42:12 -0700361 cmd_line = (u64)boot_params->ext_cmd_line_ptr << 32;
362 cmd_line |= boot_params->hdr.cmd_line_ptr;
Kees Cook82fa9632013-10-10 17:18:16 -0700363 /* Calculate size of cmd_line. */
364 ptr = (char *)(unsigned long)cmd_line;
Chao Fan69550d42017-11-23 17:08:47 +0800365 for (cmd_line_size = 0; ptr[cmd_line_size++];)
Kees Cook82fa9632013-10-10 17:18:16 -0700366 ;
Kees Cooked09acd2016-05-06 12:44:59 -0700367 mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
368 mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
Kees Cook3a947072016-05-06 15:01:35 -0700369 add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
370 mem_avoid[MEM_AVOID_CMDLINE].size);
Kees Cook82fa9632013-10-10 17:18:16 -0700371
Kees Cooked09acd2016-05-06 12:44:59 -0700372 /* Avoid boot parameters. */
373 mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
374 mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
Kees Cook3a947072016-05-06 15:01:35 -0700375 add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
376 mem_avoid[MEM_AVOID_BOOTPARAMS].size);
377
378 /* We don't need to set a mapping for setup_data. */
379
Dave Jiangf2844242017-01-11 16:20:01 -0700380 /* Mark the memmap regions we need to avoid */
Baoquan Hed52e7d52017-05-13 13:46:28 +0800381 handle_mem_memmap();
Dave Jiangf2844242017-01-11 16:20:01 -0700382
Kees Cook3a947072016-05-06 15:01:35 -0700383#ifdef CONFIG_X86_VERBOSE_BOOTUP
384 /* Make sure video RAM can be used. */
385 add_identity_map(0, PMD_SIZE);
386#endif
Kees Cook82fa9632013-10-10 17:18:16 -0700387}
388
Kees Cook06486d62016-05-09 13:22:07 -0700389/*
390 * Does this memory vector overlap a known avoided area? If so, record the
391 * overlap region with the lowest address.
392 */
393static bool mem_avoid_overlap(struct mem_vector *img,
394 struct mem_vector *overlap)
Kees Cook82fa9632013-10-10 17:18:16 -0700395{
396 int i;
Kees Cook0cacbfb2014-09-11 09:19:31 -0700397 struct setup_data *ptr;
Kees Cook06486d62016-05-09 13:22:07 -0700398 unsigned long earliest = img->start + img->size;
399 bool is_overlapping = false;
Kees Cook82fa9632013-10-10 17:18:16 -0700400
401 for (i = 0; i < MEM_AVOID_MAX; i++) {
Kees Cook06486d62016-05-09 13:22:07 -0700402 if (mem_overlaps(img, &mem_avoid[i]) &&
403 mem_avoid[i].start < earliest) {
404 *overlap = mem_avoid[i];
Baoquan He6daa2ec2016-07-01 15:34:40 +0800405 earliest = overlap->start;
Kees Cook06486d62016-05-09 13:22:07 -0700406 is_overlapping = true;
407 }
Kees Cook82fa9632013-10-10 17:18:16 -0700408 }
409
Kees Cook0cacbfb2014-09-11 09:19:31 -0700410 /* Avoid all entries in the setup_data linked list. */
Kees Cook6655e0a2016-04-18 09:42:12 -0700411 ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
Kees Cook0cacbfb2014-09-11 09:19:31 -0700412 while (ptr) {
413 struct mem_vector avoid;
414
Kees Cook20cc2882014-10-01 11:36:32 -0700415 avoid.start = (unsigned long)ptr;
Kees Cook0cacbfb2014-09-11 09:19:31 -0700416 avoid.size = sizeof(*ptr) + ptr->len;
417
Kees Cook06486d62016-05-09 13:22:07 -0700418 if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
419 *overlap = avoid;
Baoquan He6daa2ec2016-07-01 15:34:40 +0800420 earliest = overlap->start;
Kees Cook06486d62016-05-09 13:22:07 -0700421 is_overlapping = true;
422 }
Kees Cook0cacbfb2014-09-11 09:19:31 -0700423
424 ptr = (struct setup_data *)(unsigned long)ptr->next;
425 }
426
Kees Cook06486d62016-05-09 13:22:07 -0700427 return is_overlapping;
Kees Cook82fa9632013-10-10 17:18:16 -0700428}
429
Baoquan Hec401cf12016-05-09 13:22:06 -0700430struct slot_area {
431 unsigned long addr;
432 int num;
433};
434
435#define MAX_SLOT_AREA 100
436
437static struct slot_area slot_areas[MAX_SLOT_AREA];
438
Kees Cooke290e8c2014-02-09 13:56:44 -0800439static unsigned long slot_max;
Kees Cook82fa9632013-10-10 17:18:16 -0700440
Baoquan Hec401cf12016-05-09 13:22:06 -0700441static unsigned long slot_area_index;
442
443static void store_slot_info(struct mem_vector *region, unsigned long image_size)
444{
445 struct slot_area slot_area;
446
447 if (slot_area_index == MAX_SLOT_AREA)
448 return;
449
450 slot_area.addr = region->start;
451 slot_area.num = (region->size - image_size) /
452 CONFIG_PHYSICAL_ALIGN + 1;
453
454 if (slot_area.num > 0) {
455 slot_areas[slot_area_index++] = slot_area;
456 slot_max += slot_area.num;
457 }
458}
459
Kees Cook82fa9632013-10-10 17:18:16 -0700460static unsigned long slots_fetch_random(void)
461{
Kees Cooked9f0072016-05-25 15:45:33 -0700462 unsigned long slot;
463 int i;
464
Kees Cook82fa9632013-10-10 17:18:16 -0700465 /* Handle case of no slots stored. */
466 if (slot_max == 0)
467 return 0;
468
Thomas Garnierd899a7d2016-06-21 17:46:58 -0700469 slot = kaslr_get_random_long("Physical") % slot_max;
Kees Cooked9f0072016-05-25 15:45:33 -0700470
471 for (i = 0; i < slot_area_index; i++) {
472 if (slot >= slot_areas[i].num) {
473 slot -= slot_areas[i].num;
474 continue;
475 }
476 return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
477 }
478
479 if (i == slot_area_index)
480 debug_putstr("slots_fetch_random() failed!?\n");
481 return 0;
Kees Cook82fa9632013-10-10 17:18:16 -0700482}
483
Baoquan He27aac202017-07-09 20:37:41 +0800484static void process_mem_region(struct mem_vector *entry,
Kees Cook82fa9632013-10-10 17:18:16 -0700485 unsigned long minimum,
486 unsigned long image_size)
487{
Kees Cooked9f0072016-05-25 15:45:33 -0700488 struct mem_vector region, overlap;
489 struct slot_area slot_area;
Baoquan He4cdba142017-05-13 13:46:29 +0800490 unsigned long start_orig, end;
Baoquan He87891b02017-07-09 20:37:40 +0800491 struct mem_vector cur_entry;
Kees Cook82fa9632013-10-10 17:18:16 -0700492
Kees Cooked9f0072016-05-25 15:45:33 -0700493 /* On 32-bit, ignore entries entirely above our maximum. */
Baoquan He87891b02017-07-09 20:37:40 +0800494 if (IS_ENABLED(CONFIG_X86_32) && entry->start >= KERNEL_IMAGE_SIZE)
Kees Cook82fa9632013-10-10 17:18:16 -0700495 return;
496
497 /* Ignore entries entirely below our minimum. */
Baoquan He87891b02017-07-09 20:37:40 +0800498 if (entry->start + entry->size < minimum)
Kees Cook82fa9632013-10-10 17:18:16 -0700499 return;
500
Baoquan He4cdba142017-05-13 13:46:29 +0800501 /* Ignore entries above memory limit */
Baoquan He87891b02017-07-09 20:37:40 +0800502 end = min(entry->size + entry->start, mem_limit);
503 if (entry->start >= end)
Baoquan He4cdba142017-05-13 13:46:29 +0800504 return;
Baoquan He87891b02017-07-09 20:37:40 +0800505 cur_entry.start = entry->start;
506 cur_entry.size = end - entry->start;
Baoquan He4cdba142017-05-13 13:46:29 +0800507
Baoquan He87891b02017-07-09 20:37:40 +0800508 region.start = cur_entry.start;
Baoquan He4cdba142017-05-13 13:46:29 +0800509 region.size = cur_entry.size;
Kees Cook82fa9632013-10-10 17:18:16 -0700510
Kees Cooked9f0072016-05-25 15:45:33 -0700511 /* Give up if slot area array is full. */
512 while (slot_area_index < MAX_SLOT_AREA) {
513 start_orig = region.start;
Kees Cook82fa9632013-10-10 17:18:16 -0700514
Kees Cooked9f0072016-05-25 15:45:33 -0700515 /* Potentially raise address to minimum location. */
516 if (region.start < minimum)
517 region.start = minimum;
Kees Cook82fa9632013-10-10 17:18:16 -0700518
Kees Cooked9f0072016-05-25 15:45:33 -0700519 /* Potentially raise address to meet alignment needs. */
520 region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
Kees Cook82fa9632013-10-10 17:18:16 -0700521
Baoquan He27aac202017-07-09 20:37:41 +0800522 /* Did we raise the address above the passed in memory entry? */
Baoquan He87891b02017-07-09 20:37:40 +0800523 if (region.start > cur_entry.start + cur_entry.size)
Kees Cooked9f0072016-05-25 15:45:33 -0700524 return;
Kees Cook82fa9632013-10-10 17:18:16 -0700525
Kees Cooked9f0072016-05-25 15:45:33 -0700526 /* Reduce size by any delta from the original address. */
527 region.size -= region.start - start_orig;
Kees Cook82fa9632013-10-10 17:18:16 -0700528
Kees Cooked9f0072016-05-25 15:45:33 -0700529 /* 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;
533
534 /* Return if region can't contain decompressed kernel */
535 if (region.size < image_size)
536 return;
537
538 /* If nothing overlaps, store the region and return. */
539 if (!mem_avoid_overlap(&region, &overlap)) {
540 store_slot_info(&region, image_size);
541 return;
542 }
543
544 /* Store beginning of region if holds at least image_size. */
545 if (overlap.start > region.start + image_size) {
546 struct mem_vector beginning;
547
548 beginning.start = region.start;
549 beginning.size = overlap.start - region.start;
550 store_slot_info(&beginning, image_size);
551 }
552
553 /* Return if overlap extends to or past end of region. */
554 if (overlap.start + overlap.size >= region.start + region.size)
555 return;
556
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;
Kees Cook82fa9632013-10-10 17:18:16 -0700560 }
561}
562
Baoquan Hec05cd792017-08-14 22:54:24 +0800563#ifdef CONFIG_EFI
564/*
565 * Returns true if mirror region found (and must have been processed
566 * for slots adding)
567 */
568static bool
569process_efi_entries(unsigned long minimum, unsigned long image_size)
570{
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;
575 unsigned long pmap;
576 char *signature;
577 u32 nr_desc;
578 int i;
579
580 signature = (char *)&e->efi_loader_signature;
581 if (strncmp(signature, EFI32_LOADER_SIGNATURE, 4) &&
582 strncmp(signature, EFI64_LOADER_SIGNATURE, 4))
583 return false;
584
585#ifdef CONFIG_X86_32
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");
589 return false;
590 }
591 pmap = e->efi_memmap;
592#else
593 pmap = (e->efi_memmap | ((__u64)e->efi_memmap_hi << 32));
594#endif
595
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) {
Baoquan Hec05cd792017-08-14 22:54:24 +0800600 efi_mirror_found = true;
Naoya Horiguchi0982adc2017-08-28 16:30:59 +0900601 break;
Baoquan Hec05cd792017-08-14 22:54:24 +0800602 }
603 }
604
Naoya Horiguchi0982adc2017-08-28 16:30:59 +0900605 for (i = 0; i < nr_desc; i++) {
606 md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
607
608 /*
609 * Here we are more conservative in picking free memory than
610 * the EFI spec allows:
611 *
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
615 * to crashes.
616 *
617 * Only EFI_CONVENTIONAL_MEMORY is guaranteed to be free.
618 */
619 if (md->type != EFI_CONVENTIONAL_MEMORY)
620 continue;
621
622 if (efi_mirror_found &&
623 !(md->attribute & EFI_MEMORY_MORE_RELIABLE))
624 continue;
625
626 region.start = md->phys_addr;
627 region.size = md->num_pages << EFI_PAGE_SHIFT;
628 process_mem_region(&region, minimum, image_size);
629 if (slot_area_index == MAX_SLOT_AREA) {
630 debug_putstr("Aborted EFI scan (slot_areas full)!\n");
631 break;
632 }
633 }
634 return true;
Baoquan Hec05cd792017-08-14 22:54:24 +0800635}
636#else
637static inline bool
638process_efi_entries(unsigned long minimum, unsigned long image_size)
639{
640 return false;
641}
642#endif
643
Baoquan Hef62995c2017-07-09 20:37:39 +0800644static void process_e820_entries(unsigned long minimum,
645 unsigned long image_size)
646{
647 int i;
Baoquan He87891b02017-07-09 20:37:40 +0800648 struct mem_vector region;
Baoquan Hef62995c2017-07-09 20:37:39 +0800649 struct boot_e820_entry *entry;
650
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)
656 continue;
Baoquan He87891b02017-07-09 20:37:40 +0800657 region.start = entry->addr;
658 region.size = entry->size;
Baoquan He27aac202017-07-09 20:37:41 +0800659 process_mem_region(&region, minimum, image_size);
Baoquan Hef62995c2017-07-09 20:37:39 +0800660 if (slot_area_index == MAX_SLOT_AREA) {
661 debug_putstr("Aborted e820 scan (slot_areas full)!\n");
662 break;
663 }
664 }
665}
666
Baoquan He071a7492016-05-09 13:22:08 -0700667static unsigned long find_random_phys_addr(unsigned long minimum,
668 unsigned long image_size)
Kees Cook82fa9632013-10-10 17:18:16 -0700669{
Dave Jiangf2844242017-01-11 16:20:01 -0700670 /* Check if we had too many memmaps. */
671 if (memmap_too_large) {
Baoquan Hec05cd792017-08-14 22:54:24 +0800672 debug_putstr("Aborted memory entries scan (more than 4 memmap= args)!\n");
Dave Jiangf2844242017-01-11 16:20:01 -0700673 return 0;
674 }
675
Kees Cook82fa9632013-10-10 17:18:16 -0700676 /* Make sure minimum is aligned. */
677 minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
678
Baoquan Hec05cd792017-08-14 22:54:24 +0800679 if (process_efi_entries(minimum, image_size))
680 return slots_fetch_random();
681
Baoquan Hef62995c2017-07-09 20:37:39 +0800682 process_e820_entries(minimum, image_size);
Kees Cook82fa9632013-10-10 17:18:16 -0700683 return slots_fetch_random();
684}
685
Baoquan He071a7492016-05-09 13:22:08 -0700686static unsigned long find_random_virt_addr(unsigned long minimum,
687 unsigned long image_size)
688{
689 unsigned long slots, random_addr;
690
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);
695
696 /*
697 * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
698 * that can hold image_size within the range of minimum to
699 * KERNEL_IMAGE_SIZE?
700 */
701 slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
702 CONFIG_PHYSICAL_ALIGN + 1;
703
Thomas Garnierd899a7d2016-06-21 17:46:58 -0700704 random_addr = kaslr_get_random_long("Virtual") % slots;
Baoquan He071a7492016-05-09 13:22:08 -0700705
706 return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
707}
708
Borislav Petkov549f90d2016-05-06 13:50:15 +0200709/*
710 * Since this function examines addresses much more numerically,
711 * it takes the input and output pointers as 'unsigned long'.
712 */
Baoquan He8391c732016-05-25 15:45:32 -0700713void 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)
Kees Cook8ab38202013-10-10 17:18:14 -0700718{
Yinghai Lue066cc42016-05-25 15:45:34 -0700719 unsigned long random_addr, min_addr;
Kees Cook8ab38202013-10-10 17:18:14 -0700720
Kees Cook24f2e022014-06-13 13:30:36 -0700721 if (cmdline_find_option_bool("nokaslr")) {
Kees Cook0f8ede1b2016-04-20 13:55:46 -0700722 warn("KASLR disabled: 'nokaslr' on cmdline.");
Baoquan He8391c732016-05-25 15:45:32 -0700723 return;
Kees Cook24f2e022014-06-13 13:30:36 -0700724 }
Kees Cook8ab38202013-10-10 17:18:14 -0700725
Kees Cook6655e0a2016-04-18 09:42:12 -0700726 boot_params->hdr.loadflags |= KASLR_FLAG;
Borislav Petkov78cac482015-04-01 12:49:52 +0200727
Kees Cook11fdf972016-05-25 15:45:31 -0700728 /* Prepare to add new identity pagetables on demand. */
729 initialize_identity_maps();
730
Kees Cook82fa9632013-10-10 17:18:16 -0700731 /* Record the various known unsafe memory ranges. */
Baoquan He8391c732016-05-25 15:45:32 -0700732 mem_avoid_init(input, input_size, *output);
Kees Cook8ab38202013-10-10 17:18:14 -0700733
Yinghai Lue066cc42016-05-25 15:45:34 -0700734 /*
735 * Low end of the randomization range should be the
736 * smaller of 512M or the initial kernel image
737 * location:
738 */
739 min_addr = min(*output, 512UL << 20);
740
Baoquan Hec05cd792017-08-14 22:54:24 +0800741 /* Walk available memory entries to find a random address. */
Yinghai Lue066cc42016-05-25 15:45:34 -0700742 random_addr = find_random_phys_addr(min_addr, output_size);
Kees Cook90168752016-04-18 09:42:15 -0700743 if (!random_addr) {
Dave Jiangf2844242017-01-11 16:20:01 -0700744 warn("Physical KASLR disabled: no suitable memory region!");
Baoquan He8391c732016-05-25 15:45:32 -0700745 } else {
746 /* Update the new physical address location. */
747 if (*output != random_addr) {
748 add_identity_map(random_addr, output_size);
749 *output = random_addr;
750 }
Baoquan Heda63b6b2017-04-27 15:42:20 +0800751
752 /*
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"
757 * case.
758 */
759 finalize_identity_maps();
Kees Cook82fa9632013-10-10 17:18:16 -0700760 }
761
Baoquan He8391c732016-05-25 15:45:32 -0700762
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;
Kees Cook8ab38202013-10-10 17:18:14 -0700767}