kaslr.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  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. */
  13. /*
  14. * isspace() in linux/ctype.h is expected by next_args() to filter
  15. * out "space/lf/tab". While boot/ctype.h conflicts with linux/ctype.h,
  16. * since isdigit() is implemented in both of them. Hence disable it
  17. * here.
  18. */
  19. #define BOOT_CTYPE_H
  20. /*
  21. * _ctype[] in lib/ctype.c is needed by isspace() of linux/ctype.h.
  22. * While both lib/ctype.c and lib/cmdline.c will bring EXPORT_SYMBOL
  23. * which is meaningless and will cause compiling error in some cases.
  24. */
  25. #define __DISABLE_EXPORTS
  26. #include "misc.h"
  27. #include "error.h"
  28. #include "../string.h"
  29. #include <generated/compile.h>
  30. #include <linux/module.h>
  31. #include <linux/uts.h>
  32. #include <linux/utsname.h>
  33. #include <linux/ctype.h>
  34. #include <linux/efi.h>
  35. #include <generated/utsrelease.h>
  36. #include <asm/efi.h>
  37. /* Macros used by the included decompressor code below. */
  38. #define STATIC
  39. #include <linux/decompress/mm.h>
  40. #ifdef CONFIG_X86_5LEVEL
  41. unsigned int __pgtable_l5_enabled;
  42. unsigned int pgdir_shift __ro_after_init = 39;
  43. unsigned int ptrs_per_p4d __ro_after_init = 1;
  44. #endif
  45. extern unsigned long get_cmd_line_ptr(void);
  46. /* Used by PAGE_KERN* macros: */
  47. pteval_t __default_kernel_pte_mask __read_mostly = ~0;
  48. /* Simplified build-specific string for starting entropy. */
  49. static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
  50. LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;
  51. static unsigned long rotate_xor(unsigned long hash, const void *area,
  52. size_t size)
  53. {
  54. size_t i;
  55. unsigned long *ptr = (unsigned long *)area;
  56. for (i = 0; i < size / sizeof(hash); i++) {
  57. /* Rotate by odd number of bits and XOR. */
  58. hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
  59. hash ^= ptr[i];
  60. }
  61. return hash;
  62. }
  63. /* Attempt to create a simple but unpredictable starting entropy. */
  64. static unsigned long get_boot_seed(void)
  65. {
  66. unsigned long hash = 0;
  67. hash = rotate_xor(hash, build_str, sizeof(build_str));
  68. hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
  69. return hash;
  70. }
  71. #define KASLR_COMPRESSED_BOOT
  72. #include "../../lib/kaslr.c"
  73. struct mem_vector {
  74. unsigned long long start;
  75. unsigned long long size;
  76. };
  77. /* Only supporting at most 4 unusable memmap regions with kaslr */
  78. #define MAX_MEMMAP_REGIONS 4
  79. static bool memmap_too_large;
  80. /* Store memory limit specified by "mem=nn[KMG]" or "memmap=nn[KMG]" */
  81. static unsigned long long mem_limit = ULLONG_MAX;
  82. enum mem_avoid_index {
  83. MEM_AVOID_ZO_RANGE = 0,
  84. MEM_AVOID_INITRD,
  85. MEM_AVOID_CMDLINE,
  86. MEM_AVOID_BOOTPARAMS,
  87. MEM_AVOID_MEMMAP_BEGIN,
  88. MEM_AVOID_MEMMAP_END = MEM_AVOID_MEMMAP_BEGIN + MAX_MEMMAP_REGIONS - 1,
  89. MEM_AVOID_MAX,
  90. };
  91. static struct mem_vector mem_avoid[MEM_AVOID_MAX];
  92. static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
  93. {
  94. /* Item one is entirely before item two. */
  95. if (one->start + one->size <= two->start)
  96. return false;
  97. /* Item one is entirely after item two. */
  98. if (one->start >= two->start + two->size)
  99. return false;
  100. return true;
  101. }
  102. char *skip_spaces(const char *str)
  103. {
  104. while (isspace(*str))
  105. ++str;
  106. return (char *)str;
  107. }
  108. #include "../../../../lib/ctype.c"
  109. #include "../../../../lib/cmdline.c"
  110. static int
  111. parse_memmap(char *p, unsigned long long *start, unsigned long long *size)
  112. {
  113. char *oldp;
  114. if (!p)
  115. return -EINVAL;
  116. /* We don't care about this option here */
  117. if (!strncmp(p, "exactmap", 8))
  118. return -EINVAL;
  119. oldp = p;
  120. *size = memparse(p, &p);
  121. if (p == oldp)
  122. return -EINVAL;
  123. switch (*p) {
  124. case '#':
  125. case '$':
  126. case '!':
  127. *start = memparse(p + 1, &p);
  128. return 0;
  129. case '@':
  130. /* memmap=nn@ss specifies usable region, should be skipped */
  131. *size = 0;
  132. /* Fall through */
  133. default:
  134. /*
  135. * If w/o offset, only size specified, memmap=nn[KMG] has the
  136. * same behaviour as mem=nn[KMG]. It limits the max address
  137. * system can use. Region above the limit should be avoided.
  138. */
  139. *start = 0;
  140. return 0;
  141. }
  142. return -EINVAL;
  143. }
  144. static void mem_avoid_memmap(char *str)
  145. {
  146. static int i;
  147. if (i >= MAX_MEMMAP_REGIONS)
  148. return;
  149. while (str && (i < MAX_MEMMAP_REGIONS)) {
  150. int rc;
  151. unsigned long long start, size;
  152. char *k = strchr(str, ',');
  153. if (k)
  154. *k++ = 0;
  155. rc = parse_memmap(str, &start, &size);
  156. if (rc < 0)
  157. break;
  158. str = k;
  159. if (start == 0) {
  160. /* Store the specified memory limit if size > 0 */
  161. if (size > 0)
  162. mem_limit = size;
  163. continue;
  164. }
  165. mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].start = start;
  166. mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].size = size;
  167. i++;
  168. }
  169. /* More than 4 memmaps, fail kaslr */
  170. if ((i >= MAX_MEMMAP_REGIONS) && str)
  171. memmap_too_large = true;
  172. }
  173. /* Store the number of 1GB huge pages which users specified: */
  174. static unsigned long max_gb_huge_pages;
  175. static void parse_gb_huge_pages(char *param, char *val)
  176. {
  177. static bool gbpage_sz;
  178. char *p;
  179. if (!strcmp(param, "hugepagesz")) {
  180. p = val;
  181. if (memparse(p, &p) != PUD_SIZE) {
  182. gbpage_sz = false;
  183. return;
  184. }
  185. if (gbpage_sz)
  186. warn("Repeatedly set hugeTLB page size of 1G!\n");
  187. gbpage_sz = true;
  188. return;
  189. }
  190. if (!strcmp(param, "hugepages") && gbpage_sz) {
  191. p = val;
  192. max_gb_huge_pages = simple_strtoull(p, &p, 0);
  193. return;
  194. }
  195. }
  196. static void handle_mem_options(void)
  197. {
  198. char *args = (char *)get_cmd_line_ptr();
  199. size_t len = strlen((char *)args);
  200. char *tmp_cmdline;
  201. char *param, *val;
  202. u64 mem_size;
  203. if (!strstr(args, "memmap=") && !strstr(args, "mem=") &&
  204. !strstr(args, "hugepages"))
  205. return;
  206. tmp_cmdline = malloc(len + 1);
  207. if (!tmp_cmdline)
  208. error("Failed to allocate space for tmp_cmdline");
  209. memcpy(tmp_cmdline, args, len);
  210. tmp_cmdline[len] = 0;
  211. args = tmp_cmdline;
  212. /* Chew leading spaces */
  213. args = skip_spaces(args);
  214. while (*args) {
  215. args = next_arg(args, &param, &val);
  216. /* Stop at -- */
  217. if (!val && strcmp(param, "--") == 0) {
  218. warn("Only '--' specified in cmdline");
  219. goto out;
  220. }
  221. if (!strcmp(param, "memmap")) {
  222. mem_avoid_memmap(val);
  223. } else if (strstr(param, "hugepages")) {
  224. parse_gb_huge_pages(param, val);
  225. } else if (!strcmp(param, "mem")) {
  226. char *p = val;
  227. if (!strcmp(p, "nopentium"))
  228. continue;
  229. mem_size = memparse(p, &p);
  230. if (mem_size == 0)
  231. goto out;
  232. mem_limit = mem_size;
  233. }
  234. }
  235. out:
  236. free(tmp_cmdline);
  237. return;
  238. }
  239. /*
  240. * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
  241. * The mem_avoid array is used to store the ranges that need to be avoided
  242. * when KASLR searches for an appropriate random address. We must avoid any
  243. * regions that are unsafe to overlap with during decompression, and other
  244. * things like the initrd, cmdline and boot_params. This comment seeks to
  245. * explain mem_avoid as clearly as possible since incorrect mem_avoid
  246. * memory ranges lead to really hard to debug boot failures.
  247. *
  248. * The initrd, cmdline, and boot_params are trivial to identify for
  249. * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
  250. * MEM_AVOID_BOOTPARAMS respectively below.
  251. *
  252. * What is not obvious how to avoid is the range of memory that is used
  253. * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
  254. * the compressed kernel (ZO) and its run space, which is used to extract
  255. * the uncompressed kernel (VO) and relocs.
  256. *
  257. * ZO's full run size sits against the end of the decompression buffer, so
  258. * we can calculate where text, data, bss, etc of ZO are positioned more
  259. * easily.
  260. *
  261. * For additional background, the decompression calculations can be found
  262. * in header.S, and the memory diagram is based on the one found in misc.c.
  263. *
  264. * The following conditions are already enforced by the image layouts and
  265. * associated code:
  266. * - input + input_size >= output + output_size
  267. * - kernel_total_size <= init_size
  268. * - kernel_total_size <= output_size (see Note below)
  269. * - output + init_size >= output + output_size
  270. *
  271. * (Note that kernel_total_size and output_size have no fundamental
  272. * relationship, but output_size is passed to choose_random_location
  273. * as a maximum of the two. The diagram is showing a case where
  274. * kernel_total_size is larger than output_size, but this case is
  275. * handled by bumping output_size.)
  276. *
  277. * The above conditions can be illustrated by a diagram:
  278. *
  279. * 0 output input input+input_size output+init_size
  280. * | | | | |
  281. * | | | | |
  282. * |-----|--------|--------|--------------|-----------|--|-------------|
  283. * | | |
  284. * | | |
  285. * output+init_size-ZO_INIT_SIZE output+output_size output+kernel_total_size
  286. *
  287. * [output, output+init_size) is the entire memory range used for
  288. * extracting the compressed image.
  289. *
  290. * [output, output+kernel_total_size) is the range needed for the
  291. * uncompressed kernel (VO) and its run size (bss, brk, etc).
  292. *
  293. * [output, output+output_size) is VO plus relocs (i.e. the entire
  294. * uncompressed payload contained by ZO). This is the area of the buffer
  295. * written to during decompression.
  296. *
  297. * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
  298. * range of the copied ZO and decompression code. (i.e. the range
  299. * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
  300. *
  301. * [input, input+input_size) is the original copied compressed image (ZO)
  302. * (i.e. it does not include its run size). This range must be avoided
  303. * because it contains the data used for decompression.
  304. *
  305. * [input+input_size, output+init_size) is [_text, _end) for ZO. This
  306. * range includes ZO's heap and stack, and must be avoided since it
  307. * performs the decompression.
  308. *
  309. * Since the above two ranges need to be avoided and they are adjacent,
  310. * they can be merged, resulting in: [input, output+init_size) which
  311. * becomes the MEM_AVOID_ZO_RANGE below.
  312. */
  313. static void mem_avoid_init(unsigned long input, unsigned long input_size,
  314. unsigned long output)
  315. {
  316. unsigned long init_size = boot_params->hdr.init_size;
  317. u64 initrd_start, initrd_size;
  318. u64 cmd_line, cmd_line_size;
  319. char *ptr;
  320. /*
  321. * Avoid the region that is unsafe to overlap during
  322. * decompression.
  323. */
  324. mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
  325. mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
  326. add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
  327. mem_avoid[MEM_AVOID_ZO_RANGE].size);
  328. /* Avoid initrd. */
  329. initrd_start = (u64)boot_params->ext_ramdisk_image << 32;
  330. initrd_start |= boot_params->hdr.ramdisk_image;
  331. initrd_size = (u64)boot_params->ext_ramdisk_size << 32;
  332. initrd_size |= boot_params->hdr.ramdisk_size;
  333. mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
  334. mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
  335. /* No need to set mapping for initrd, it will be handled in VO. */
  336. /* Avoid kernel command line. */
  337. cmd_line = (u64)boot_params->ext_cmd_line_ptr << 32;
  338. cmd_line |= boot_params->hdr.cmd_line_ptr;
  339. /* Calculate size of cmd_line. */
  340. ptr = (char *)(unsigned long)cmd_line;
  341. for (cmd_line_size = 0; ptr[cmd_line_size++];)
  342. ;
  343. mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
  344. mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
  345. add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
  346. mem_avoid[MEM_AVOID_CMDLINE].size);
  347. /* Avoid boot parameters. */
  348. mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
  349. mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
  350. add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
  351. mem_avoid[MEM_AVOID_BOOTPARAMS].size);
  352. /* We don't need to set a mapping for setup_data. */
  353. /* Mark the memmap regions we need to avoid */
  354. handle_mem_options();
  355. #ifdef CONFIG_X86_VERBOSE_BOOTUP
  356. /* Make sure video RAM can be used. */
  357. add_identity_map(0, PMD_SIZE);
  358. #endif
  359. }
  360. /*
  361. * Does this memory vector overlap a known avoided area? If so, record the
  362. * overlap region with the lowest address.
  363. */
  364. static bool mem_avoid_overlap(struct mem_vector *img,
  365. struct mem_vector *overlap)
  366. {
  367. int i;
  368. struct setup_data *ptr;
  369. unsigned long earliest = img->start + img->size;
  370. bool is_overlapping = false;
  371. for (i = 0; i < MEM_AVOID_MAX; i++) {
  372. if (mem_overlaps(img, &mem_avoid[i]) &&
  373. mem_avoid[i].start < earliest) {
  374. *overlap = mem_avoid[i];
  375. earliest = overlap->start;
  376. is_overlapping = true;
  377. }
  378. }
  379. /* Avoid all entries in the setup_data linked list. */
  380. ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
  381. while (ptr) {
  382. struct mem_vector avoid;
  383. avoid.start = (unsigned long)ptr;
  384. avoid.size = sizeof(*ptr) + ptr->len;
  385. if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
  386. *overlap = avoid;
  387. earliest = overlap->start;
  388. is_overlapping = true;
  389. }
  390. ptr = (struct setup_data *)(unsigned long)ptr->next;
  391. }
  392. return is_overlapping;
  393. }
  394. struct slot_area {
  395. unsigned long addr;
  396. int num;
  397. };
  398. #define MAX_SLOT_AREA 100
  399. static struct slot_area slot_areas[MAX_SLOT_AREA];
  400. static unsigned long slot_max;
  401. static unsigned long slot_area_index;
  402. static void store_slot_info(struct mem_vector *region, unsigned long image_size)
  403. {
  404. struct slot_area slot_area;
  405. if (slot_area_index == MAX_SLOT_AREA)
  406. return;
  407. slot_area.addr = region->start;
  408. slot_area.num = (region->size - image_size) /
  409. CONFIG_PHYSICAL_ALIGN + 1;
  410. if (slot_area.num > 0) {
  411. slot_areas[slot_area_index++] = slot_area;
  412. slot_max += slot_area.num;
  413. }
  414. }
  415. /*
  416. * Skip as many 1GB huge pages as possible in the passed region
  417. * according to the number which users specified:
  418. */
  419. static void
  420. process_gb_huge_pages(struct mem_vector *region, unsigned long image_size)
  421. {
  422. unsigned long addr, size = 0;
  423. struct mem_vector tmp;
  424. int i = 0;
  425. if (!max_gb_huge_pages) {
  426. store_slot_info(region, image_size);
  427. return;
  428. }
  429. addr = ALIGN(region->start, PUD_SIZE);
  430. /* Did we raise the address above the passed in memory entry? */
  431. if (addr < region->start + region->size)
  432. size = region->size - (addr - region->start);
  433. /* Check how many 1GB huge pages can be filtered out: */
  434. while (size > PUD_SIZE && max_gb_huge_pages) {
  435. size -= PUD_SIZE;
  436. max_gb_huge_pages--;
  437. i++;
  438. }
  439. /* No good 1GB huge pages found: */
  440. if (!i) {
  441. store_slot_info(region, image_size);
  442. return;
  443. }
  444. /*
  445. * Skip those 'i'*1GB good huge pages, and continue checking and
  446. * processing the remaining head or tail part of the passed region
  447. * if available.
  448. */
  449. if (addr >= region->start + image_size) {
  450. tmp.start = region->start;
  451. tmp.size = addr - region->start;
  452. store_slot_info(&tmp, image_size);
  453. }
  454. size = region->size - (addr - region->start) - i * PUD_SIZE;
  455. if (size >= image_size) {
  456. tmp.start = addr + i * PUD_SIZE;
  457. tmp.size = size;
  458. store_slot_info(&tmp, image_size);
  459. }
  460. }
  461. static unsigned long slots_fetch_random(void)
  462. {
  463. unsigned long slot;
  464. int i;
  465. /* Handle case of no slots stored. */
  466. if (slot_max == 0)
  467. return 0;
  468. slot = kaslr_get_random_long("Physical") % slot_max;
  469. for (i = 0; i < slot_area_index; i++) {
  470. if (slot >= slot_areas[i].num) {
  471. slot -= slot_areas[i].num;
  472. continue;
  473. }
  474. return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
  475. }
  476. if (i == slot_area_index)
  477. debug_putstr("slots_fetch_random() failed!?\n");
  478. return 0;
  479. }
  480. static void process_mem_region(struct mem_vector *entry,
  481. unsigned long minimum,
  482. unsigned long image_size)
  483. {
  484. struct mem_vector region, overlap;
  485. unsigned long start_orig, end;
  486. struct mem_vector cur_entry;
  487. /* On 32-bit, ignore entries entirely above our maximum. */
  488. if (IS_ENABLED(CONFIG_X86_32) && entry->start >= KERNEL_IMAGE_SIZE)
  489. return;
  490. /* Ignore entries entirely below our minimum. */
  491. if (entry->start + entry->size < minimum)
  492. return;
  493. /* Ignore entries above memory limit */
  494. end = min(entry->size + entry->start, mem_limit);
  495. if (entry->start >= end)
  496. return;
  497. cur_entry.start = entry->start;
  498. cur_entry.size = end - entry->start;
  499. region.start = cur_entry.start;
  500. region.size = cur_entry.size;
  501. /* Give up if slot area array is full. */
  502. while (slot_area_index < MAX_SLOT_AREA) {
  503. start_orig = region.start;
  504. /* Potentially raise address to minimum location. */
  505. if (region.start < minimum)
  506. region.start = minimum;
  507. /* Potentially raise address to meet alignment needs. */
  508. region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
  509. /* Did we raise the address above the passed in memory entry? */
  510. if (region.start > cur_entry.start + cur_entry.size)
  511. return;
  512. /* Reduce size by any delta from the original address. */
  513. region.size -= region.start - start_orig;
  514. /* On 32-bit, reduce region size to fit within max size. */
  515. if (IS_ENABLED(CONFIG_X86_32) &&
  516. region.start + region.size > KERNEL_IMAGE_SIZE)
  517. region.size = KERNEL_IMAGE_SIZE - region.start;
  518. /* Return if region can't contain decompressed kernel */
  519. if (region.size < image_size)
  520. return;
  521. /* If nothing overlaps, store the region and return. */
  522. if (!mem_avoid_overlap(&region, &overlap)) {
  523. process_gb_huge_pages(&region, image_size);
  524. return;
  525. }
  526. /* Store beginning of region if holds at least image_size. */
  527. if (overlap.start > region.start + image_size) {
  528. struct mem_vector beginning;
  529. beginning.start = region.start;
  530. beginning.size = overlap.start - region.start;
  531. process_gb_huge_pages(&beginning, image_size);
  532. }
  533. /* Return if overlap extends to or past end of region. */
  534. if (overlap.start + overlap.size >= region.start + region.size)
  535. return;
  536. /* Clip off the overlapping region and start over. */
  537. region.size -= overlap.start - region.start + overlap.size;
  538. region.start = overlap.start + overlap.size;
  539. }
  540. }
  541. #ifdef CONFIG_EFI
  542. /*
  543. * Returns true if mirror region found (and must have been processed
  544. * for slots adding)
  545. */
  546. static bool
  547. process_efi_entries(unsigned long minimum, unsigned long image_size)
  548. {
  549. struct efi_info *e = &boot_params->efi_info;
  550. bool efi_mirror_found = false;
  551. struct mem_vector region;
  552. efi_memory_desc_t *md;
  553. unsigned long pmap;
  554. char *signature;
  555. u32 nr_desc;
  556. int i;
  557. signature = (char *)&e->efi_loader_signature;
  558. if (strncmp(signature, EFI32_LOADER_SIGNATURE, 4) &&
  559. strncmp(signature, EFI64_LOADER_SIGNATURE, 4))
  560. return false;
  561. #ifdef CONFIG_X86_32
  562. /* Can't handle data above 4GB at this time */
  563. if (e->efi_memmap_hi) {
  564. warn("EFI memmap is above 4GB, can't be handled now on x86_32. EFI should be disabled.\n");
  565. return false;
  566. }
  567. pmap = e->efi_memmap;
  568. #else
  569. pmap = (e->efi_memmap | ((__u64)e->efi_memmap_hi << 32));
  570. #endif
  571. nr_desc = e->efi_memmap_size / e->efi_memdesc_size;
  572. for (i = 0; i < nr_desc; i++) {
  573. md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
  574. if (md->attribute & EFI_MEMORY_MORE_RELIABLE) {
  575. efi_mirror_found = true;
  576. break;
  577. }
  578. }
  579. for (i = 0; i < nr_desc; i++) {
  580. md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
  581. /*
  582. * Here we are more conservative in picking free memory than
  583. * the EFI spec allows:
  584. *
  585. * According to the spec, EFI_BOOT_SERVICES_{CODE|DATA} are also
  586. * free memory and thus available to place the kernel image into,
  587. * but in practice there's firmware where using that memory leads
  588. * to crashes.
  589. *
  590. * Only EFI_CONVENTIONAL_MEMORY is guaranteed to be free.
  591. */
  592. if (md->type != EFI_CONVENTIONAL_MEMORY)
  593. continue;
  594. if (efi_mirror_found &&
  595. !(md->attribute & EFI_MEMORY_MORE_RELIABLE))
  596. continue;
  597. region.start = md->phys_addr;
  598. region.size = md->num_pages << EFI_PAGE_SHIFT;
  599. process_mem_region(&region, minimum, image_size);
  600. if (slot_area_index == MAX_SLOT_AREA) {
  601. debug_putstr("Aborted EFI scan (slot_areas full)!\n");
  602. break;
  603. }
  604. }
  605. return true;
  606. }
  607. #else
  608. static inline bool
  609. process_efi_entries(unsigned long minimum, unsigned long image_size)
  610. {
  611. return false;
  612. }
  613. #endif
  614. static void process_e820_entries(unsigned long minimum,
  615. unsigned long image_size)
  616. {
  617. int i;
  618. struct mem_vector region;
  619. struct boot_e820_entry *entry;
  620. /* Verify potential e820 positions, appending to slots list. */
  621. for (i = 0; i < boot_params->e820_entries; i++) {
  622. entry = &boot_params->e820_table[i];
  623. /* Skip non-RAM entries. */
  624. if (entry->type != E820_TYPE_RAM)
  625. continue;
  626. region.start = entry->addr;
  627. region.size = entry->size;
  628. process_mem_region(&region, minimum, image_size);
  629. if (slot_area_index == MAX_SLOT_AREA) {
  630. debug_putstr("Aborted e820 scan (slot_areas full)!\n");
  631. break;
  632. }
  633. }
  634. }
  635. static unsigned long find_random_phys_addr(unsigned long minimum,
  636. unsigned long image_size)
  637. {
  638. /* Check if we had too many memmaps. */
  639. if (memmap_too_large) {
  640. debug_putstr("Aborted memory entries scan (more than 4 memmap= args)!\n");
  641. return 0;
  642. }
  643. /* Make sure minimum is aligned. */
  644. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  645. if (process_efi_entries(minimum, image_size))
  646. return slots_fetch_random();
  647. process_e820_entries(minimum, image_size);
  648. return slots_fetch_random();
  649. }
  650. static unsigned long find_random_virt_addr(unsigned long minimum,
  651. unsigned long image_size)
  652. {
  653. unsigned long slots, random_addr;
  654. /* Make sure minimum is aligned. */
  655. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  656. /* Align image_size for easy slot calculations. */
  657. image_size = ALIGN(image_size, CONFIG_PHYSICAL_ALIGN);
  658. /*
  659. * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
  660. * that can hold image_size within the range of minimum to
  661. * KERNEL_IMAGE_SIZE?
  662. */
  663. slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
  664. CONFIG_PHYSICAL_ALIGN + 1;
  665. random_addr = kaslr_get_random_long("Virtual") % slots;
  666. return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
  667. }
  668. /*
  669. * Since this function examines addresses much more numerically,
  670. * it takes the input and output pointers as 'unsigned long'.
  671. */
  672. void choose_random_location(unsigned long input,
  673. unsigned long input_size,
  674. unsigned long *output,
  675. unsigned long output_size,
  676. unsigned long *virt_addr)
  677. {
  678. unsigned long random_addr, min_addr;
  679. if (cmdline_find_option_bool("nokaslr")) {
  680. warn("KASLR disabled: 'nokaslr' on cmdline.");
  681. return;
  682. }
  683. #ifdef CONFIG_X86_5LEVEL
  684. if (__read_cr4() & X86_CR4_LA57) {
  685. __pgtable_l5_enabled = 1;
  686. pgdir_shift = 48;
  687. ptrs_per_p4d = 512;
  688. }
  689. #endif
  690. boot_params->hdr.loadflags |= KASLR_FLAG;
  691. /* Prepare to add new identity pagetables on demand. */
  692. initialize_identity_maps();
  693. /* Record the various known unsafe memory ranges. */
  694. mem_avoid_init(input, input_size, *output);
  695. /*
  696. * Low end of the randomization range should be the
  697. * smaller of 512M or the initial kernel image
  698. * location:
  699. */
  700. min_addr = min(*output, 512UL << 20);
  701. /* Walk available memory entries to find a random address. */
  702. random_addr = find_random_phys_addr(min_addr, output_size);
  703. if (!random_addr) {
  704. warn("Physical KASLR disabled: no suitable memory region!");
  705. } else {
  706. /* Update the new physical address location. */
  707. if (*output != random_addr) {
  708. add_identity_map(random_addr, output_size);
  709. *output = random_addr;
  710. }
  711. /*
  712. * This loads the identity mapping page table.
  713. * This should only be done if a new physical address
  714. * is found for the kernel, otherwise we should keep
  715. * the old page table to make it be like the "nokaslr"
  716. * case.
  717. */
  718. finalize_identity_maps();
  719. }
  720. /* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
  721. if (IS_ENABLED(CONFIG_X86_64))
  722. random_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, output_size);
  723. *virt_addr = random_addr;
  724. }