kaslr.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*
  2. * kaslr.c
  3. *
  4. * This contains the routines needed to generate a reasonable level of
  5. * entropy to choose a randomized kernel base address offset in support
  6. * of Kernel Address Space Layout Randomization (KASLR). Additionally
  7. * handles walking the physical memory maps (and tracking memory regions
  8. * to avoid) in order to select a physical memory location that can
  9. * contain the entire properly aligned running kernel image.
  10. *
  11. */
  12. #include "misc.h"
  13. #include "error.h"
  14. #include "../boot.h"
  15. #include <generated/compile.h>
  16. #include <linux/module.h>
  17. #include <linux/uts.h>
  18. #include <linux/utsname.h>
  19. #include <generated/utsrelease.h>
  20. /* Simplified build-specific string for starting entropy. */
  21. static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
  22. LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;
  23. static unsigned long rotate_xor(unsigned long hash, const void *area,
  24. size_t size)
  25. {
  26. size_t i;
  27. unsigned long *ptr = (unsigned long *)area;
  28. for (i = 0; i < size / sizeof(hash); i++) {
  29. /* Rotate by odd number of bits and XOR. */
  30. hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
  31. hash ^= ptr[i];
  32. }
  33. return hash;
  34. }
  35. /* Attempt to create a simple but unpredictable starting entropy. */
  36. static unsigned long get_boot_seed(void)
  37. {
  38. unsigned long hash = 0;
  39. hash = rotate_xor(hash, build_str, sizeof(build_str));
  40. hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
  41. return hash;
  42. }
  43. #define KASLR_COMPRESSED_BOOT
  44. #include "../../lib/kaslr.c"
  45. struct mem_vector {
  46. unsigned long long start;
  47. unsigned long long size;
  48. };
  49. /* Only supporting at most 4 unusable memmap regions with kaslr */
  50. #define MAX_MEMMAP_REGIONS 4
  51. static bool memmap_too_large;
  52. enum mem_avoid_index {
  53. MEM_AVOID_ZO_RANGE = 0,
  54. MEM_AVOID_INITRD,
  55. MEM_AVOID_CMDLINE,
  56. MEM_AVOID_BOOTPARAMS,
  57. MEM_AVOID_MEMMAP_BEGIN,
  58. MEM_AVOID_MEMMAP_END = MEM_AVOID_MEMMAP_BEGIN + MAX_MEMMAP_REGIONS - 1,
  59. MEM_AVOID_MAX,
  60. };
  61. static struct mem_vector mem_avoid[MEM_AVOID_MAX];
  62. static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
  63. {
  64. /* Item one is entirely before item two. */
  65. if (one->start + one->size <= two->start)
  66. return false;
  67. /* Item one is entirely after item two. */
  68. if (one->start >= two->start + two->size)
  69. return false;
  70. return true;
  71. }
  72. /**
  73. * _memparse - Parse a string with mem suffixes into a number
  74. * @ptr: Where parse begins
  75. * @retptr: (output) Optional pointer to next char after parse completes
  76. *
  77. * Parses a string into a number. The number stored at @ptr is
  78. * potentially suffixed with K, M, G, T, P, E.
  79. */
  80. static unsigned long long _memparse(const char *ptr, char **retptr)
  81. {
  82. char *endptr; /* Local pointer to end of parsed string */
  83. unsigned long long ret = simple_strtoull(ptr, &endptr, 0);
  84. switch (*endptr) {
  85. case 'E':
  86. case 'e':
  87. ret <<= 10;
  88. case 'P':
  89. case 'p':
  90. ret <<= 10;
  91. case 'T':
  92. case 't':
  93. ret <<= 10;
  94. case 'G':
  95. case 'g':
  96. ret <<= 10;
  97. case 'M':
  98. case 'm':
  99. ret <<= 10;
  100. case 'K':
  101. case 'k':
  102. ret <<= 10;
  103. endptr++;
  104. default:
  105. break;
  106. }
  107. if (retptr)
  108. *retptr = endptr;
  109. return ret;
  110. }
  111. static int
  112. parse_memmap(char *p, unsigned long long *start, unsigned long long *size)
  113. {
  114. char *oldp;
  115. if (!p)
  116. return -EINVAL;
  117. /* We don't care about this option here */
  118. if (!strncmp(p, "exactmap", 8))
  119. return -EINVAL;
  120. oldp = p;
  121. *size = _memparse(p, &p);
  122. if (p == oldp)
  123. return -EINVAL;
  124. switch (*p) {
  125. case '@':
  126. /* Skip this region, usable */
  127. *start = 0;
  128. *size = 0;
  129. return 0;
  130. case '#':
  131. case '$':
  132. case '!':
  133. *start = _memparse(p + 1, &p);
  134. return 0;
  135. }
  136. return -EINVAL;
  137. }
  138. static void mem_avoid_memmap(void)
  139. {
  140. char arg[128];
  141. int rc;
  142. int i;
  143. char *str;
  144. /* See if we have any memmap areas */
  145. rc = cmdline_find_option("memmap", arg, sizeof(arg));
  146. if (rc <= 0)
  147. return;
  148. i = 0;
  149. str = arg;
  150. while (str && (i < MAX_MEMMAP_REGIONS)) {
  151. int rc;
  152. unsigned long long start, size;
  153. char *k = strchr(str, ',');
  154. if (k)
  155. *k++ = 0;
  156. rc = parse_memmap(str, &start, &size);
  157. if (rc < 0)
  158. break;
  159. str = k;
  160. /* A usable region that should not be skipped */
  161. if (size == 0)
  162. continue;
  163. mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].start = start;
  164. mem_avoid[MEM_AVOID_MEMMAP_BEGIN + i].size = size;
  165. i++;
  166. }
  167. /* More than 4 memmaps, fail kaslr */
  168. if ((i >= MAX_MEMMAP_REGIONS) && str)
  169. memmap_too_large = true;
  170. }
  171. /*
  172. * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
  173. * The mem_avoid array is used to store the ranges that need to be avoided
  174. * when KASLR searches for an appropriate random address. We must avoid any
  175. * regions that are unsafe to overlap with during decompression, and other
  176. * things like the initrd, cmdline and boot_params. This comment seeks to
  177. * explain mem_avoid as clearly as possible since incorrect mem_avoid
  178. * memory ranges lead to really hard to debug boot failures.
  179. *
  180. * The initrd, cmdline, and boot_params are trivial to identify for
  181. * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
  182. * MEM_AVOID_BOOTPARAMS respectively below.
  183. *
  184. * What is not obvious how to avoid is the range of memory that is used
  185. * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
  186. * the compressed kernel (ZO) and its run space, which is used to extract
  187. * the uncompressed kernel (VO) and relocs.
  188. *
  189. * ZO's full run size sits against the end of the decompression buffer, so
  190. * we can calculate where text, data, bss, etc of ZO are positioned more
  191. * easily.
  192. *
  193. * For additional background, the decompression calculations can be found
  194. * in header.S, and the memory diagram is based on the one found in misc.c.
  195. *
  196. * The following conditions are already enforced by the image layouts and
  197. * associated code:
  198. * - input + input_size >= output + output_size
  199. * - kernel_total_size <= init_size
  200. * - kernel_total_size <= output_size (see Note below)
  201. * - output + init_size >= output + output_size
  202. *
  203. * (Note that kernel_total_size and output_size have no fundamental
  204. * relationship, but output_size is passed to choose_random_location
  205. * as a maximum of the two. The diagram is showing a case where
  206. * kernel_total_size is larger than output_size, but this case is
  207. * handled by bumping output_size.)
  208. *
  209. * The above conditions can be illustrated by a diagram:
  210. *
  211. * 0 output input input+input_size output+init_size
  212. * | | | | |
  213. * | | | | |
  214. * |-----|--------|--------|--------------|-----------|--|-------------|
  215. * | | |
  216. * | | |
  217. * output+init_size-ZO_INIT_SIZE output+output_size output+kernel_total_size
  218. *
  219. * [output, output+init_size) is the entire memory range used for
  220. * extracting the compressed image.
  221. *
  222. * [output, output+kernel_total_size) is the range needed for the
  223. * uncompressed kernel (VO) and its run size (bss, brk, etc).
  224. *
  225. * [output, output+output_size) is VO plus relocs (i.e. the entire
  226. * uncompressed payload contained by ZO). This is the area of the buffer
  227. * written to during decompression.
  228. *
  229. * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
  230. * range of the copied ZO and decompression code. (i.e. the range
  231. * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
  232. *
  233. * [input, input+input_size) is the original copied compressed image (ZO)
  234. * (i.e. it does not include its run size). This range must be avoided
  235. * because it contains the data used for decompression.
  236. *
  237. * [input+input_size, output+init_size) is [_text, _end) for ZO. This
  238. * range includes ZO's heap and stack, and must be avoided since it
  239. * performs the decompression.
  240. *
  241. * Since the above two ranges need to be avoided and they are adjacent,
  242. * they can be merged, resulting in: [input, output+init_size) which
  243. * becomes the MEM_AVOID_ZO_RANGE below.
  244. */
  245. static void mem_avoid_init(unsigned long input, unsigned long input_size,
  246. unsigned long output)
  247. {
  248. unsigned long init_size = boot_params->hdr.init_size;
  249. u64 initrd_start, initrd_size;
  250. u64 cmd_line, cmd_line_size;
  251. char *ptr;
  252. /*
  253. * Avoid the region that is unsafe to overlap during
  254. * decompression.
  255. */
  256. mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
  257. mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
  258. add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
  259. mem_avoid[MEM_AVOID_ZO_RANGE].size);
  260. /* Avoid initrd. */
  261. initrd_start = (u64)boot_params->ext_ramdisk_image << 32;
  262. initrd_start |= boot_params->hdr.ramdisk_image;
  263. initrd_size = (u64)boot_params->ext_ramdisk_size << 32;
  264. initrd_size |= boot_params->hdr.ramdisk_size;
  265. mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
  266. mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
  267. /* No need to set mapping for initrd, it will be handled in VO. */
  268. /* Avoid kernel command line. */
  269. cmd_line = (u64)boot_params->ext_cmd_line_ptr << 32;
  270. cmd_line |= boot_params->hdr.cmd_line_ptr;
  271. /* Calculate size of cmd_line. */
  272. ptr = (char *)(unsigned long)cmd_line;
  273. for (cmd_line_size = 0; ptr[cmd_line_size++]; )
  274. ;
  275. mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
  276. mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
  277. add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
  278. mem_avoid[MEM_AVOID_CMDLINE].size);
  279. /* Avoid boot parameters. */
  280. mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
  281. mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
  282. add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
  283. mem_avoid[MEM_AVOID_BOOTPARAMS].size);
  284. /* We don't need to set a mapping for setup_data. */
  285. /* Mark the memmap regions we need to avoid */
  286. mem_avoid_memmap();
  287. #ifdef CONFIG_X86_VERBOSE_BOOTUP
  288. /* Make sure video RAM can be used. */
  289. add_identity_map(0, PMD_SIZE);
  290. #endif
  291. }
  292. /*
  293. * Does this memory vector overlap a known avoided area? If so, record the
  294. * overlap region with the lowest address.
  295. */
  296. static bool mem_avoid_overlap(struct mem_vector *img,
  297. struct mem_vector *overlap)
  298. {
  299. int i;
  300. struct setup_data *ptr;
  301. unsigned long earliest = img->start + img->size;
  302. bool is_overlapping = false;
  303. for (i = 0; i < MEM_AVOID_MAX; i++) {
  304. if (mem_overlaps(img, &mem_avoid[i]) &&
  305. mem_avoid[i].start < earliest) {
  306. *overlap = mem_avoid[i];
  307. earliest = overlap->start;
  308. is_overlapping = true;
  309. }
  310. }
  311. /* Avoid all entries in the setup_data linked list. */
  312. ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
  313. while (ptr) {
  314. struct mem_vector avoid;
  315. avoid.start = (unsigned long)ptr;
  316. avoid.size = sizeof(*ptr) + ptr->len;
  317. if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
  318. *overlap = avoid;
  319. earliest = overlap->start;
  320. is_overlapping = true;
  321. }
  322. ptr = (struct setup_data *)(unsigned long)ptr->next;
  323. }
  324. return is_overlapping;
  325. }
  326. struct slot_area {
  327. unsigned long addr;
  328. int num;
  329. };
  330. #define MAX_SLOT_AREA 100
  331. static struct slot_area slot_areas[MAX_SLOT_AREA];
  332. static unsigned long slot_max;
  333. static unsigned long slot_area_index;
  334. static void store_slot_info(struct mem_vector *region, unsigned long image_size)
  335. {
  336. struct slot_area slot_area;
  337. if (slot_area_index == MAX_SLOT_AREA)
  338. return;
  339. slot_area.addr = region->start;
  340. slot_area.num = (region->size - image_size) /
  341. CONFIG_PHYSICAL_ALIGN + 1;
  342. if (slot_area.num > 0) {
  343. slot_areas[slot_area_index++] = slot_area;
  344. slot_max += slot_area.num;
  345. }
  346. }
  347. static unsigned long slots_fetch_random(void)
  348. {
  349. unsigned long slot;
  350. int i;
  351. /* Handle case of no slots stored. */
  352. if (slot_max == 0)
  353. return 0;
  354. slot = kaslr_get_random_long("Physical") % slot_max;
  355. for (i = 0; i < slot_area_index; i++) {
  356. if (slot >= slot_areas[i].num) {
  357. slot -= slot_areas[i].num;
  358. continue;
  359. }
  360. return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
  361. }
  362. if (i == slot_area_index)
  363. debug_putstr("slots_fetch_random() failed!?\n");
  364. return 0;
  365. }
  366. static void process_e820_entry(struct boot_e820_entry *entry,
  367. unsigned long minimum,
  368. unsigned long image_size)
  369. {
  370. struct mem_vector region, overlap;
  371. struct slot_area slot_area;
  372. unsigned long start_orig;
  373. /* Skip non-RAM entries. */
  374. if (entry->type != E820_TYPE_RAM)
  375. return;
  376. /* On 32-bit, ignore entries entirely above our maximum. */
  377. if (IS_ENABLED(CONFIG_X86_32) && entry->addr >= KERNEL_IMAGE_SIZE)
  378. return;
  379. /* Ignore entries entirely below our minimum. */
  380. if (entry->addr + entry->size < minimum)
  381. return;
  382. region.start = entry->addr;
  383. region.size = entry->size;
  384. /* Give up if slot area array is full. */
  385. while (slot_area_index < MAX_SLOT_AREA) {
  386. start_orig = region.start;
  387. /* Potentially raise address to minimum location. */
  388. if (region.start < minimum)
  389. region.start = minimum;
  390. /* Potentially raise address to meet alignment needs. */
  391. region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
  392. /* Did we raise the address above this e820 region? */
  393. if (region.start > entry->addr + entry->size)
  394. return;
  395. /* Reduce size by any delta from the original address. */
  396. region.size -= region.start - start_orig;
  397. /* On 32-bit, reduce region size to fit within max size. */
  398. if (IS_ENABLED(CONFIG_X86_32) &&
  399. region.start + region.size > KERNEL_IMAGE_SIZE)
  400. region.size = KERNEL_IMAGE_SIZE - region.start;
  401. /* Return if region can't contain decompressed kernel */
  402. if (region.size < image_size)
  403. return;
  404. /* If nothing overlaps, store the region and return. */
  405. if (!mem_avoid_overlap(&region, &overlap)) {
  406. store_slot_info(&region, image_size);
  407. return;
  408. }
  409. /* Store beginning of region if holds at least image_size. */
  410. if (overlap.start > region.start + image_size) {
  411. struct mem_vector beginning;
  412. beginning.start = region.start;
  413. beginning.size = overlap.start - region.start;
  414. store_slot_info(&beginning, image_size);
  415. }
  416. /* Return if overlap extends to or past end of region. */
  417. if (overlap.start + overlap.size >= region.start + region.size)
  418. return;
  419. /* Clip off the overlapping region and start over. */
  420. region.size -= overlap.start - region.start + overlap.size;
  421. region.start = overlap.start + overlap.size;
  422. }
  423. }
  424. static unsigned long find_random_phys_addr(unsigned long minimum,
  425. unsigned long image_size)
  426. {
  427. int i;
  428. unsigned long addr;
  429. /* Check if we had too many memmaps. */
  430. if (memmap_too_large) {
  431. debug_putstr("Aborted e820 scan (more than 4 memmap= args)!\n");
  432. return 0;
  433. }
  434. /* Make sure minimum is aligned. */
  435. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  436. /* Verify potential e820 positions, appending to slots list. */
  437. for (i = 0; i < boot_params->e820_entries; i++) {
  438. process_e820_entry(&boot_params->e820_table[i], minimum,
  439. image_size);
  440. if (slot_area_index == MAX_SLOT_AREA) {
  441. debug_putstr("Aborted e820 scan (slot_areas full)!\n");
  442. break;
  443. }
  444. }
  445. return slots_fetch_random();
  446. }
  447. static unsigned long find_random_virt_addr(unsigned long minimum,
  448. unsigned long image_size)
  449. {
  450. unsigned long slots, random_addr;
  451. /* Make sure minimum is aligned. */
  452. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  453. /* Align image_size for easy slot calculations. */
  454. image_size = ALIGN(image_size, CONFIG_PHYSICAL_ALIGN);
  455. /*
  456. * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
  457. * that can hold image_size within the range of minimum to
  458. * KERNEL_IMAGE_SIZE?
  459. */
  460. slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
  461. CONFIG_PHYSICAL_ALIGN + 1;
  462. random_addr = kaslr_get_random_long("Virtual") % slots;
  463. return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
  464. }
  465. /*
  466. * Since this function examines addresses much more numerically,
  467. * it takes the input and output pointers as 'unsigned long'.
  468. */
  469. void choose_random_location(unsigned long input,
  470. unsigned long input_size,
  471. unsigned long *output,
  472. unsigned long output_size,
  473. unsigned long *virt_addr)
  474. {
  475. unsigned long random_addr, min_addr;
  476. /* By default, keep output position unchanged. */
  477. *virt_addr = *output;
  478. if (cmdline_find_option_bool("nokaslr")) {
  479. warn("KASLR disabled: 'nokaslr' on cmdline.");
  480. return;
  481. }
  482. boot_params->hdr.loadflags |= KASLR_FLAG;
  483. /* Prepare to add new identity pagetables on demand. */
  484. initialize_identity_maps();
  485. /* Record the various known unsafe memory ranges. */
  486. mem_avoid_init(input, input_size, *output);
  487. /*
  488. * Low end of the randomization range should be the
  489. * smaller of 512M or the initial kernel image
  490. * location:
  491. */
  492. min_addr = min(*output, 512UL << 20);
  493. /* Walk e820 and find a random address. */
  494. random_addr = find_random_phys_addr(min_addr, output_size);
  495. if (!random_addr) {
  496. warn("Physical KASLR disabled: no suitable memory region!");
  497. } else {
  498. /* Update the new physical address location. */
  499. if (*output != random_addr) {
  500. add_identity_map(random_addr, output_size);
  501. *output = random_addr;
  502. }
  503. /*
  504. * This loads the identity mapping page table.
  505. * This should only be done if a new physical address
  506. * is found for the kernel, otherwise we should keep
  507. * the old page table to make it be like the "nokaslr"
  508. * case.
  509. */
  510. finalize_identity_maps();
  511. }
  512. /* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
  513. if (IS_ENABLED(CONFIG_X86_64))
  514. random_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, output_size);
  515. *virt_addr = random_addr;
  516. }