kaslr.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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 int 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 0;
  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. free(tmp_cmdline);
  220. return -1;
  221. }
  222. if (!strcmp(param, "memmap")) {
  223. mem_avoid_memmap(val);
  224. } else if (strstr(param, "hugepages")) {
  225. parse_gb_huge_pages(param, val);
  226. } else if (!strcmp(param, "mem")) {
  227. char *p = val;
  228. if (!strcmp(p, "nopentium"))
  229. continue;
  230. mem_size = memparse(p, &p);
  231. if (mem_size == 0) {
  232. free(tmp_cmdline);
  233. return -EINVAL;
  234. }
  235. mem_limit = mem_size;
  236. }
  237. }
  238. free(tmp_cmdline);
  239. return 0;
  240. }
  241. /*
  242. * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
  243. * The mem_avoid array is used to store the ranges that need to be avoided
  244. * when KASLR searches for an appropriate random address. We must avoid any
  245. * regions that are unsafe to overlap with during decompression, and other
  246. * things like the initrd, cmdline and boot_params. This comment seeks to
  247. * explain mem_avoid as clearly as possible since incorrect mem_avoid
  248. * memory ranges lead to really hard to debug boot failures.
  249. *
  250. * The initrd, cmdline, and boot_params are trivial to identify for
  251. * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
  252. * MEM_AVOID_BOOTPARAMS respectively below.
  253. *
  254. * What is not obvious how to avoid is the range of memory that is used
  255. * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
  256. * the compressed kernel (ZO) and its run space, which is used to extract
  257. * the uncompressed kernel (VO) and relocs.
  258. *
  259. * ZO's full run size sits against the end of the decompression buffer, so
  260. * we can calculate where text, data, bss, etc of ZO are positioned more
  261. * easily.
  262. *
  263. * For additional background, the decompression calculations can be found
  264. * in header.S, and the memory diagram is based on the one found in misc.c.
  265. *
  266. * The following conditions are already enforced by the image layouts and
  267. * associated code:
  268. * - input + input_size >= output + output_size
  269. * - kernel_total_size <= init_size
  270. * - kernel_total_size <= output_size (see Note below)
  271. * - output + init_size >= output + output_size
  272. *
  273. * (Note that kernel_total_size and output_size have no fundamental
  274. * relationship, but output_size is passed to choose_random_location
  275. * as a maximum of the two. The diagram is showing a case where
  276. * kernel_total_size is larger than output_size, but this case is
  277. * handled by bumping output_size.)
  278. *
  279. * The above conditions can be illustrated by a diagram:
  280. *
  281. * 0 output input input+input_size output+init_size
  282. * | | | | |
  283. * | | | | |
  284. * |-----|--------|--------|--------------|-----------|--|-------------|
  285. * | | |
  286. * | | |
  287. * output+init_size-ZO_INIT_SIZE output+output_size output+kernel_total_size
  288. *
  289. * [output, output+init_size) is the entire memory range used for
  290. * extracting the compressed image.
  291. *
  292. * [output, output+kernel_total_size) is the range needed for the
  293. * uncompressed kernel (VO) and its run size (bss, brk, etc).
  294. *
  295. * [output, output+output_size) is VO plus relocs (i.e. the entire
  296. * uncompressed payload contained by ZO). This is the area of the buffer
  297. * written to during decompression.
  298. *
  299. * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
  300. * range of the copied ZO and decompression code. (i.e. the range
  301. * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
  302. *
  303. * [input, input+input_size) is the original copied compressed image (ZO)
  304. * (i.e. it does not include its run size). This range must be avoided
  305. * because it contains the data used for decompression.
  306. *
  307. * [input+input_size, output+init_size) is [_text, _end) for ZO. This
  308. * range includes ZO's heap and stack, and must be avoided since it
  309. * performs the decompression.
  310. *
  311. * Since the above two ranges need to be avoided and they are adjacent,
  312. * they can be merged, resulting in: [input, output+init_size) which
  313. * becomes the MEM_AVOID_ZO_RANGE below.
  314. */
  315. static void mem_avoid_init(unsigned long input, unsigned long input_size,
  316. unsigned long output)
  317. {
  318. unsigned long init_size = boot_params->hdr.init_size;
  319. u64 initrd_start, initrd_size;
  320. u64 cmd_line, cmd_line_size;
  321. char *ptr;
  322. /*
  323. * Avoid the region that is unsafe to overlap during
  324. * decompression.
  325. */
  326. mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
  327. mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
  328. add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
  329. mem_avoid[MEM_AVOID_ZO_RANGE].size);
  330. /* Avoid initrd. */
  331. initrd_start = (u64)boot_params->ext_ramdisk_image << 32;
  332. initrd_start |= boot_params->hdr.ramdisk_image;
  333. initrd_size = (u64)boot_params->ext_ramdisk_size << 32;
  334. initrd_size |= boot_params->hdr.ramdisk_size;
  335. mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
  336. mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
  337. /* No need to set mapping for initrd, it will be handled in VO. */
  338. /* Avoid kernel command line. */
  339. cmd_line = (u64)boot_params->ext_cmd_line_ptr << 32;
  340. cmd_line |= boot_params->hdr.cmd_line_ptr;
  341. /* Calculate size of cmd_line. */
  342. ptr = (char *)(unsigned long)cmd_line;
  343. for (cmd_line_size = 0; ptr[cmd_line_size++];)
  344. ;
  345. mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
  346. mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
  347. add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
  348. mem_avoid[MEM_AVOID_CMDLINE].size);
  349. /* Avoid boot parameters. */
  350. mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
  351. mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
  352. add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
  353. mem_avoid[MEM_AVOID_BOOTPARAMS].size);
  354. /* We don't need to set a mapping for setup_data. */
  355. /* Mark the memmap regions we need to avoid */
  356. handle_mem_options();
  357. #ifdef CONFIG_X86_VERBOSE_BOOTUP
  358. /* Make sure video RAM can be used. */
  359. add_identity_map(0, PMD_SIZE);
  360. #endif
  361. }
  362. /*
  363. * Does this memory vector overlap a known avoided area? If so, record the
  364. * overlap region with the lowest address.
  365. */
  366. static bool mem_avoid_overlap(struct mem_vector *img,
  367. struct mem_vector *overlap)
  368. {
  369. int i;
  370. struct setup_data *ptr;
  371. unsigned long earliest = img->start + img->size;
  372. bool is_overlapping = false;
  373. for (i = 0; i < MEM_AVOID_MAX; i++) {
  374. if (mem_overlaps(img, &mem_avoid[i]) &&
  375. mem_avoid[i].start < earliest) {
  376. *overlap = mem_avoid[i];
  377. earliest = overlap->start;
  378. is_overlapping = true;
  379. }
  380. }
  381. /* Avoid all entries in the setup_data linked list. */
  382. ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
  383. while (ptr) {
  384. struct mem_vector avoid;
  385. avoid.start = (unsigned long)ptr;
  386. avoid.size = sizeof(*ptr) + ptr->len;
  387. if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
  388. *overlap = avoid;
  389. earliest = overlap->start;
  390. is_overlapping = true;
  391. }
  392. ptr = (struct setup_data *)(unsigned long)ptr->next;
  393. }
  394. return is_overlapping;
  395. }
  396. struct slot_area {
  397. unsigned long addr;
  398. int num;
  399. };
  400. #define MAX_SLOT_AREA 100
  401. static struct slot_area slot_areas[MAX_SLOT_AREA];
  402. static unsigned long slot_max;
  403. static unsigned long slot_area_index;
  404. static void store_slot_info(struct mem_vector *region, unsigned long image_size)
  405. {
  406. struct slot_area slot_area;
  407. if (slot_area_index == MAX_SLOT_AREA)
  408. return;
  409. slot_area.addr = region->start;
  410. slot_area.num = (region->size - image_size) /
  411. CONFIG_PHYSICAL_ALIGN + 1;
  412. if (slot_area.num > 0) {
  413. slot_areas[slot_area_index++] = slot_area;
  414. slot_max += slot_area.num;
  415. }
  416. }
  417. /*
  418. * Skip as many 1GB huge pages as possible in the passed region
  419. * according to the number which users specified:
  420. */
  421. static void
  422. process_gb_huge_pages(struct mem_vector *region, unsigned long image_size)
  423. {
  424. unsigned long addr, size = 0;
  425. struct mem_vector tmp;
  426. int i = 0;
  427. if (!max_gb_huge_pages) {
  428. store_slot_info(region, image_size);
  429. return;
  430. }
  431. addr = ALIGN(region->start, PUD_SIZE);
  432. /* Did we raise the address above the passed in memory entry? */
  433. if (addr < region->start + region->size)
  434. size = region->size - (addr - region->start);
  435. /* Check how many 1GB huge pages can be filtered out: */
  436. while (size > PUD_SIZE && max_gb_huge_pages) {
  437. size -= PUD_SIZE;
  438. max_gb_huge_pages--;
  439. i++;
  440. }
  441. /* No good 1GB huge pages found: */
  442. if (!i) {
  443. store_slot_info(region, image_size);
  444. return;
  445. }
  446. /*
  447. * Skip those 'i'*1GB good huge pages, and continue checking and
  448. * processing the remaining head or tail part of the passed region
  449. * if available.
  450. */
  451. if (addr >= region->start + image_size) {
  452. tmp.start = region->start;
  453. tmp.size = addr - region->start;
  454. store_slot_info(&tmp, image_size);
  455. }
  456. size = region->size - (addr - region->start) - i * PUD_SIZE;
  457. if (size >= image_size) {
  458. tmp.start = addr + i * PUD_SIZE;
  459. tmp.size = size;
  460. store_slot_info(&tmp, image_size);
  461. }
  462. }
  463. static unsigned long slots_fetch_random(void)
  464. {
  465. unsigned long slot;
  466. int i;
  467. /* Handle case of no slots stored. */
  468. if (slot_max == 0)
  469. return 0;
  470. 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;
  474. continue;
  475. }
  476. return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
  477. }
  478. if (i == slot_area_index)
  479. debug_putstr("slots_fetch_random() failed!?\n");
  480. return 0;
  481. }
  482. static void process_mem_region(struct mem_vector *entry,
  483. unsigned long minimum,
  484. unsigned long image_size)
  485. {
  486. struct mem_vector region, overlap;
  487. struct slot_area slot_area;
  488. unsigned long start_orig, end;
  489. struct mem_vector cur_entry;
  490. /* On 32-bit, ignore entries entirely above our maximum. */
  491. if (IS_ENABLED(CONFIG_X86_32) && entry->start >= KERNEL_IMAGE_SIZE)
  492. return;
  493. /* Ignore entries entirely below our minimum. */
  494. if (entry->start + entry->size < minimum)
  495. return;
  496. /* Ignore entries above memory limit */
  497. end = min(entry->size + entry->start, mem_limit);
  498. if (entry->start >= end)
  499. return;
  500. cur_entry.start = entry->start;
  501. cur_entry.size = end - entry->start;
  502. region.start = cur_entry.start;
  503. region.size = cur_entry.size;
  504. /* Give up if slot area array is full. */
  505. while (slot_area_index < MAX_SLOT_AREA) {
  506. start_orig = region.start;
  507. /* Potentially raise address to minimum location. */
  508. if (region.start < minimum)
  509. region.start = minimum;
  510. /* Potentially raise address to meet alignment needs. */
  511. region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
  512. /* Did we raise the address above the passed in memory entry? */
  513. if (region.start > cur_entry.start + cur_entry.size)
  514. return;
  515. /* Reduce size by any delta from the original address. */
  516. region.size -= region.start - start_orig;
  517. /* On 32-bit, reduce region size to fit within max size. */
  518. if (IS_ENABLED(CONFIG_X86_32) &&
  519. region.start + region.size > KERNEL_IMAGE_SIZE)
  520. region.size = KERNEL_IMAGE_SIZE - region.start;
  521. /* Return if region can't contain decompressed kernel */
  522. if (region.size < image_size)
  523. return;
  524. /* If nothing overlaps, store the region and return. */
  525. if (!mem_avoid_overlap(&region, &overlap)) {
  526. process_gb_huge_pages(&region, image_size);
  527. return;
  528. }
  529. /* Store beginning of region if holds at least image_size. */
  530. if (overlap.start > region.start + image_size) {
  531. struct mem_vector beginning;
  532. beginning.start = region.start;
  533. beginning.size = overlap.start - region.start;
  534. process_gb_huge_pages(&beginning, image_size);
  535. }
  536. /* Return if overlap extends to or past end of region. */
  537. if (overlap.start + overlap.size >= region.start + region.size)
  538. return;
  539. /* Clip off the overlapping region and start over. */
  540. region.size -= overlap.start - region.start + overlap.size;
  541. region.start = overlap.start + overlap.size;
  542. }
  543. }
  544. #ifdef CONFIG_EFI
  545. /*
  546. * Returns true if mirror region found (and must have been processed
  547. * for slots adding)
  548. */
  549. static bool
  550. process_efi_entries(unsigned long minimum, unsigned long image_size)
  551. {
  552. struct efi_info *e = &boot_params->efi_info;
  553. bool efi_mirror_found = false;
  554. struct mem_vector region;
  555. efi_memory_desc_t *md;
  556. unsigned long pmap;
  557. char *signature;
  558. u32 nr_desc;
  559. int i;
  560. signature = (char *)&e->efi_loader_signature;
  561. if (strncmp(signature, EFI32_LOADER_SIGNATURE, 4) &&
  562. strncmp(signature, EFI64_LOADER_SIGNATURE, 4))
  563. return false;
  564. #ifdef CONFIG_X86_32
  565. /* Can't handle data above 4GB at this time */
  566. if (e->efi_memmap_hi) {
  567. warn("EFI memmap is above 4GB, can't be handled now on x86_32. EFI should be disabled.\n");
  568. return false;
  569. }
  570. pmap = e->efi_memmap;
  571. #else
  572. pmap = (e->efi_memmap | ((__u64)e->efi_memmap_hi << 32));
  573. #endif
  574. nr_desc = e->efi_memmap_size / e->efi_memdesc_size;
  575. for (i = 0; i < nr_desc; i++) {
  576. md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
  577. if (md->attribute & EFI_MEMORY_MORE_RELIABLE) {
  578. efi_mirror_found = true;
  579. break;
  580. }
  581. }
  582. for (i = 0; i < nr_desc; i++) {
  583. md = efi_early_memdesc_ptr(pmap, e->efi_memdesc_size, i);
  584. /*
  585. * Here we are more conservative in picking free memory than
  586. * the EFI spec allows:
  587. *
  588. * According to the spec, EFI_BOOT_SERVICES_{CODE|DATA} are also
  589. * free memory and thus available to place the kernel image into,
  590. * but in practice there's firmware where using that memory leads
  591. * to crashes.
  592. *
  593. * Only EFI_CONVENTIONAL_MEMORY is guaranteed to be free.
  594. */
  595. if (md->type != EFI_CONVENTIONAL_MEMORY)
  596. continue;
  597. if (efi_mirror_found &&
  598. !(md->attribute & EFI_MEMORY_MORE_RELIABLE))
  599. continue;
  600. region.start = md->phys_addr;
  601. region.size = md->num_pages << EFI_PAGE_SHIFT;
  602. process_mem_region(&region, minimum, image_size);
  603. if (slot_area_index == MAX_SLOT_AREA) {
  604. debug_putstr("Aborted EFI scan (slot_areas full)!\n");
  605. break;
  606. }
  607. }
  608. return true;
  609. }
  610. #else
  611. static inline bool
  612. process_efi_entries(unsigned long minimum, unsigned long image_size)
  613. {
  614. return false;
  615. }
  616. #endif
  617. static void process_e820_entries(unsigned long minimum,
  618. unsigned long image_size)
  619. {
  620. int i;
  621. struct mem_vector region;
  622. struct boot_e820_entry *entry;
  623. /* Verify potential e820 positions, appending to slots list. */
  624. for (i = 0; i < boot_params->e820_entries; i++) {
  625. entry = &boot_params->e820_table[i];
  626. /* Skip non-RAM entries. */
  627. if (entry->type != E820_TYPE_RAM)
  628. continue;
  629. region.start = entry->addr;
  630. region.size = entry->size;
  631. process_mem_region(&region, minimum, image_size);
  632. if (slot_area_index == MAX_SLOT_AREA) {
  633. debug_putstr("Aborted e820 scan (slot_areas full)!\n");
  634. break;
  635. }
  636. }
  637. }
  638. static unsigned long find_random_phys_addr(unsigned long minimum,
  639. unsigned long image_size)
  640. {
  641. /* Check if we had too many memmaps. */
  642. if (memmap_too_large) {
  643. debug_putstr("Aborted memory entries scan (more than 4 memmap= args)!\n");
  644. return 0;
  645. }
  646. /* Make sure minimum is aligned. */
  647. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  648. if (process_efi_entries(minimum, image_size))
  649. return slots_fetch_random();
  650. process_e820_entries(minimum, image_size);
  651. return slots_fetch_random();
  652. }
  653. static unsigned long find_random_virt_addr(unsigned long minimum,
  654. unsigned long image_size)
  655. {
  656. unsigned long slots, random_addr;
  657. /* Make sure minimum is aligned. */
  658. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  659. /* Align image_size for easy slot calculations. */
  660. image_size = ALIGN(image_size, CONFIG_PHYSICAL_ALIGN);
  661. /*
  662. * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
  663. * that can hold image_size within the range of minimum to
  664. * KERNEL_IMAGE_SIZE?
  665. */
  666. slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
  667. CONFIG_PHYSICAL_ALIGN + 1;
  668. random_addr = kaslr_get_random_long("Virtual") % slots;
  669. return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
  670. }
  671. /*
  672. * Since this function examines addresses much more numerically,
  673. * it takes the input and output pointers as 'unsigned long'.
  674. */
  675. void choose_random_location(unsigned long input,
  676. unsigned long input_size,
  677. unsigned long *output,
  678. unsigned long output_size,
  679. unsigned long *virt_addr)
  680. {
  681. unsigned long random_addr, min_addr;
  682. if (cmdline_find_option_bool("nokaslr")) {
  683. warn("KASLR disabled: 'nokaslr' on cmdline.");
  684. return;
  685. }
  686. #ifdef CONFIG_X86_5LEVEL
  687. if (__read_cr4() & X86_CR4_LA57) {
  688. __pgtable_l5_enabled = 1;
  689. pgdir_shift = 48;
  690. ptrs_per_p4d = 512;
  691. }
  692. #endif
  693. boot_params->hdr.loadflags |= KASLR_FLAG;
  694. /* Prepare to add new identity pagetables on demand. */
  695. initialize_identity_maps();
  696. /* Record the various known unsafe memory ranges. */
  697. mem_avoid_init(input, input_size, *output);
  698. /*
  699. * Low end of the randomization range should be the
  700. * smaller of 512M or the initial kernel image
  701. * location:
  702. */
  703. min_addr = min(*output, 512UL << 20);
  704. /* Walk available memory entries to find a random address. */
  705. random_addr = find_random_phys_addr(min_addr, output_size);
  706. if (!random_addr) {
  707. warn("Physical KASLR disabled: no suitable memory region!");
  708. } else {
  709. /* Update the new physical address location. */
  710. if (*output != random_addr) {
  711. add_identity_map(random_addr, output_size);
  712. *output = random_addr;
  713. }
  714. /*
  715. * This loads the identity mapping page table.
  716. * This should only be done if a new physical address
  717. * is found for the kernel, otherwise we should keep
  718. * the old page table to make it be like the "nokaslr"
  719. * case.
  720. */
  721. finalize_identity_maps();
  722. }
  723. /* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
  724. if (IS_ENABLED(CONFIG_X86_64))
  725. random_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, output_size);
  726. *virt_addr = random_addr;
  727. }