kaslr.c 23 KB

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