kaslr.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 <generated/compile.h>
  15. #include <linux/module.h>
  16. #include <linux/uts.h>
  17. #include <linux/utsname.h>
  18. #include <generated/utsrelease.h>
  19. /* Simplified build-specific string for starting entropy. */
  20. static const char build_str[] = UTS_RELEASE " (" LINUX_COMPILE_BY "@"
  21. LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION;
  22. static unsigned long rotate_xor(unsigned long hash, const void *area,
  23. size_t size)
  24. {
  25. size_t i;
  26. unsigned long *ptr = (unsigned long *)area;
  27. for (i = 0; i < size / sizeof(hash); i++) {
  28. /* Rotate by odd number of bits and XOR. */
  29. hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
  30. hash ^= ptr[i];
  31. }
  32. return hash;
  33. }
  34. /* Attempt to create a simple but unpredictable starting entropy. */
  35. static unsigned long get_boot_seed(void)
  36. {
  37. unsigned long hash = 0;
  38. hash = rotate_xor(hash, build_str, sizeof(build_str));
  39. hash = rotate_xor(hash, boot_params, sizeof(*boot_params));
  40. return hash;
  41. }
  42. #define KASLR_COMPRESSED_BOOT
  43. #include "../../lib/kaslr.c"
  44. struct mem_vector {
  45. unsigned long start;
  46. unsigned long size;
  47. };
  48. enum mem_avoid_index {
  49. MEM_AVOID_ZO_RANGE = 0,
  50. MEM_AVOID_INITRD,
  51. MEM_AVOID_CMDLINE,
  52. MEM_AVOID_BOOTPARAMS,
  53. MEM_AVOID_MAX,
  54. };
  55. static struct mem_vector mem_avoid[MEM_AVOID_MAX];
  56. static bool mem_overlaps(struct mem_vector *one, struct mem_vector *two)
  57. {
  58. /* Item one is entirely before item two. */
  59. if (one->start + one->size <= two->start)
  60. return false;
  61. /* Item one is entirely after item two. */
  62. if (one->start >= two->start + two->size)
  63. return false;
  64. return true;
  65. }
  66. /*
  67. * In theory, KASLR can put the kernel anywhere in the range of [16M, 64T).
  68. * The mem_avoid array is used to store the ranges that need to be avoided
  69. * when KASLR searches for an appropriate random address. We must avoid any
  70. * regions that are unsafe to overlap with during decompression, and other
  71. * things like the initrd, cmdline and boot_params. This comment seeks to
  72. * explain mem_avoid as clearly as possible since incorrect mem_avoid
  73. * memory ranges lead to really hard to debug boot failures.
  74. *
  75. * The initrd, cmdline, and boot_params are trivial to identify for
  76. * avoiding. They are MEM_AVOID_INITRD, MEM_AVOID_CMDLINE, and
  77. * MEM_AVOID_BOOTPARAMS respectively below.
  78. *
  79. * What is not obvious how to avoid is the range of memory that is used
  80. * during decompression (MEM_AVOID_ZO_RANGE below). This range must cover
  81. * the compressed kernel (ZO) and its run space, which is used to extract
  82. * the uncompressed kernel (VO) and relocs.
  83. *
  84. * ZO's full run size sits against the end of the decompression buffer, so
  85. * we can calculate where text, data, bss, etc of ZO are positioned more
  86. * easily.
  87. *
  88. * For additional background, the decompression calculations can be found
  89. * in header.S, and the memory diagram is based on the one found in misc.c.
  90. *
  91. * The following conditions are already enforced by the image layouts and
  92. * associated code:
  93. * - input + input_size >= output + output_size
  94. * - kernel_total_size <= init_size
  95. * - kernel_total_size <= output_size (see Note below)
  96. * - output + init_size >= output + output_size
  97. *
  98. * (Note that kernel_total_size and output_size have no fundamental
  99. * relationship, but output_size is passed to choose_random_location
  100. * as a maximum of the two. The diagram is showing a case where
  101. * kernel_total_size is larger than output_size, but this case is
  102. * handled by bumping output_size.)
  103. *
  104. * The above conditions can be illustrated by a diagram:
  105. *
  106. * 0 output input input+input_size output+init_size
  107. * | | | | |
  108. * | | | | |
  109. * |-----|--------|--------|--------------|-----------|--|-------------|
  110. * | | |
  111. * | | |
  112. * output+init_size-ZO_INIT_SIZE output+output_size output+kernel_total_size
  113. *
  114. * [output, output+init_size) is the entire memory range used for
  115. * extracting the compressed image.
  116. *
  117. * [output, output+kernel_total_size) is the range needed for the
  118. * uncompressed kernel (VO) and its run size (bss, brk, etc).
  119. *
  120. * [output, output+output_size) is VO plus relocs (i.e. the entire
  121. * uncompressed payload contained by ZO). This is the area of the buffer
  122. * written to during decompression.
  123. *
  124. * [output+init_size-ZO_INIT_SIZE, output+init_size) is the worst-case
  125. * range of the copied ZO and decompression code. (i.e. the range
  126. * covered backwards of size ZO_INIT_SIZE, starting from output+init_size.)
  127. *
  128. * [input, input+input_size) is the original copied compressed image (ZO)
  129. * (i.e. it does not include its run size). This range must be avoided
  130. * because it contains the data used for decompression.
  131. *
  132. * [input+input_size, output+init_size) is [_text, _end) for ZO. This
  133. * range includes ZO's heap and stack, and must be avoided since it
  134. * performs the decompression.
  135. *
  136. * Since the above two ranges need to be avoided and they are adjacent,
  137. * they can be merged, resulting in: [input, output+init_size) which
  138. * becomes the MEM_AVOID_ZO_RANGE below.
  139. */
  140. static void mem_avoid_init(unsigned long input, unsigned long input_size,
  141. unsigned long output)
  142. {
  143. unsigned long init_size = boot_params->hdr.init_size;
  144. u64 initrd_start, initrd_size;
  145. u64 cmd_line, cmd_line_size;
  146. char *ptr;
  147. /*
  148. * Avoid the region that is unsafe to overlap during
  149. * decompression.
  150. */
  151. mem_avoid[MEM_AVOID_ZO_RANGE].start = input;
  152. mem_avoid[MEM_AVOID_ZO_RANGE].size = (output + init_size) - input;
  153. add_identity_map(mem_avoid[MEM_AVOID_ZO_RANGE].start,
  154. mem_avoid[MEM_AVOID_ZO_RANGE].size);
  155. /* Avoid initrd. */
  156. initrd_start = (u64)boot_params->ext_ramdisk_image << 32;
  157. initrd_start |= boot_params->hdr.ramdisk_image;
  158. initrd_size = (u64)boot_params->ext_ramdisk_size << 32;
  159. initrd_size |= boot_params->hdr.ramdisk_size;
  160. mem_avoid[MEM_AVOID_INITRD].start = initrd_start;
  161. mem_avoid[MEM_AVOID_INITRD].size = initrd_size;
  162. /* No need to set mapping for initrd, it will be handled in VO. */
  163. /* Avoid kernel command line. */
  164. cmd_line = (u64)boot_params->ext_cmd_line_ptr << 32;
  165. cmd_line |= boot_params->hdr.cmd_line_ptr;
  166. /* Calculate size of cmd_line. */
  167. ptr = (char *)(unsigned long)cmd_line;
  168. for (cmd_line_size = 0; ptr[cmd_line_size++]; )
  169. ;
  170. mem_avoid[MEM_AVOID_CMDLINE].start = cmd_line;
  171. mem_avoid[MEM_AVOID_CMDLINE].size = cmd_line_size;
  172. add_identity_map(mem_avoid[MEM_AVOID_CMDLINE].start,
  173. mem_avoid[MEM_AVOID_CMDLINE].size);
  174. /* Avoid boot parameters. */
  175. mem_avoid[MEM_AVOID_BOOTPARAMS].start = (unsigned long)boot_params;
  176. mem_avoid[MEM_AVOID_BOOTPARAMS].size = sizeof(*boot_params);
  177. add_identity_map(mem_avoid[MEM_AVOID_BOOTPARAMS].start,
  178. mem_avoid[MEM_AVOID_BOOTPARAMS].size);
  179. /* We don't need to set a mapping for setup_data. */
  180. #ifdef CONFIG_X86_VERBOSE_BOOTUP
  181. /* Make sure video RAM can be used. */
  182. add_identity_map(0, PMD_SIZE);
  183. #endif
  184. }
  185. /*
  186. * Does this memory vector overlap a known avoided area? If so, record the
  187. * overlap region with the lowest address.
  188. */
  189. static bool mem_avoid_overlap(struct mem_vector *img,
  190. struct mem_vector *overlap)
  191. {
  192. int i;
  193. struct setup_data *ptr;
  194. unsigned long earliest = img->start + img->size;
  195. bool is_overlapping = false;
  196. for (i = 0; i < MEM_AVOID_MAX; i++) {
  197. if (mem_overlaps(img, &mem_avoid[i]) &&
  198. mem_avoid[i].start < earliest) {
  199. *overlap = mem_avoid[i];
  200. earliest = overlap->start;
  201. is_overlapping = true;
  202. }
  203. }
  204. /* Avoid all entries in the setup_data linked list. */
  205. ptr = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
  206. while (ptr) {
  207. struct mem_vector avoid;
  208. avoid.start = (unsigned long)ptr;
  209. avoid.size = sizeof(*ptr) + ptr->len;
  210. if (mem_overlaps(img, &avoid) && (avoid.start < earliest)) {
  211. *overlap = avoid;
  212. earliest = overlap->start;
  213. is_overlapping = true;
  214. }
  215. ptr = (struct setup_data *)(unsigned long)ptr->next;
  216. }
  217. return is_overlapping;
  218. }
  219. struct slot_area {
  220. unsigned long addr;
  221. int num;
  222. };
  223. #define MAX_SLOT_AREA 100
  224. static struct slot_area slot_areas[MAX_SLOT_AREA];
  225. static unsigned long slot_max;
  226. static unsigned long slot_area_index;
  227. static void store_slot_info(struct mem_vector *region, unsigned long image_size)
  228. {
  229. struct slot_area slot_area;
  230. if (slot_area_index == MAX_SLOT_AREA)
  231. return;
  232. slot_area.addr = region->start;
  233. slot_area.num = (region->size - image_size) /
  234. CONFIG_PHYSICAL_ALIGN + 1;
  235. if (slot_area.num > 0) {
  236. slot_areas[slot_area_index++] = slot_area;
  237. slot_max += slot_area.num;
  238. }
  239. }
  240. static unsigned long slots_fetch_random(void)
  241. {
  242. unsigned long slot;
  243. int i;
  244. /* Handle case of no slots stored. */
  245. if (slot_max == 0)
  246. return 0;
  247. slot = kaslr_get_random_long("Physical") % slot_max;
  248. for (i = 0; i < slot_area_index; i++) {
  249. if (slot >= slot_areas[i].num) {
  250. slot -= slot_areas[i].num;
  251. continue;
  252. }
  253. return slot_areas[i].addr + slot * CONFIG_PHYSICAL_ALIGN;
  254. }
  255. if (i == slot_area_index)
  256. debug_putstr("slots_fetch_random() failed!?\n");
  257. return 0;
  258. }
  259. static void process_e820_entry(struct e820entry *entry,
  260. unsigned long minimum,
  261. unsigned long image_size)
  262. {
  263. struct mem_vector region, overlap;
  264. struct slot_area slot_area;
  265. unsigned long start_orig;
  266. /* Skip non-RAM entries. */
  267. if (entry->type != E820_RAM)
  268. return;
  269. /* On 32-bit, ignore entries entirely above our maximum. */
  270. if (IS_ENABLED(CONFIG_X86_32) && entry->addr >= KERNEL_IMAGE_SIZE)
  271. return;
  272. /* Ignore entries entirely below our minimum. */
  273. if (entry->addr + entry->size < minimum)
  274. return;
  275. region.start = entry->addr;
  276. region.size = entry->size;
  277. /* Give up if slot area array is full. */
  278. while (slot_area_index < MAX_SLOT_AREA) {
  279. start_orig = region.start;
  280. /* Potentially raise address to minimum location. */
  281. if (region.start < minimum)
  282. region.start = minimum;
  283. /* Potentially raise address to meet alignment needs. */
  284. region.start = ALIGN(region.start, CONFIG_PHYSICAL_ALIGN);
  285. /* Did we raise the address above this e820 region? */
  286. if (region.start > entry->addr + entry->size)
  287. return;
  288. /* Reduce size by any delta from the original address. */
  289. region.size -= region.start - start_orig;
  290. /* On 32-bit, reduce region size to fit within max size. */
  291. if (IS_ENABLED(CONFIG_X86_32) &&
  292. region.start + region.size > KERNEL_IMAGE_SIZE)
  293. region.size = KERNEL_IMAGE_SIZE - region.start;
  294. /* Return if region can't contain decompressed kernel */
  295. if (region.size < image_size)
  296. return;
  297. /* If nothing overlaps, store the region and return. */
  298. if (!mem_avoid_overlap(&region, &overlap)) {
  299. store_slot_info(&region, image_size);
  300. return;
  301. }
  302. /* Store beginning of region if holds at least image_size. */
  303. if (overlap.start > region.start + image_size) {
  304. struct mem_vector beginning;
  305. beginning.start = region.start;
  306. beginning.size = overlap.start - region.start;
  307. store_slot_info(&beginning, image_size);
  308. }
  309. /* Return if overlap extends to or past end of region. */
  310. if (overlap.start + overlap.size >= region.start + region.size)
  311. return;
  312. /* Clip off the overlapping region and start over. */
  313. region.size -= overlap.start - region.start + overlap.size;
  314. region.start = overlap.start + overlap.size;
  315. }
  316. }
  317. static unsigned long find_random_phys_addr(unsigned long minimum,
  318. unsigned long image_size)
  319. {
  320. int i;
  321. unsigned long addr;
  322. /* Make sure minimum is aligned. */
  323. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  324. /* Verify potential e820 positions, appending to slots list. */
  325. for (i = 0; i < boot_params->e820_entries; i++) {
  326. process_e820_entry(&boot_params->e820_map[i], minimum,
  327. image_size);
  328. if (slot_area_index == MAX_SLOT_AREA) {
  329. debug_putstr("Aborted e820 scan (slot_areas full)!\n");
  330. break;
  331. }
  332. }
  333. return slots_fetch_random();
  334. }
  335. static unsigned long find_random_virt_addr(unsigned long minimum,
  336. unsigned long image_size)
  337. {
  338. unsigned long slots, random_addr;
  339. /* Make sure minimum is aligned. */
  340. minimum = ALIGN(minimum, CONFIG_PHYSICAL_ALIGN);
  341. /* Align image_size for easy slot calculations. */
  342. image_size = ALIGN(image_size, CONFIG_PHYSICAL_ALIGN);
  343. /*
  344. * There are how many CONFIG_PHYSICAL_ALIGN-sized slots
  345. * that can hold image_size within the range of minimum to
  346. * KERNEL_IMAGE_SIZE?
  347. */
  348. slots = (KERNEL_IMAGE_SIZE - minimum - image_size) /
  349. CONFIG_PHYSICAL_ALIGN + 1;
  350. random_addr = kaslr_get_random_long("Virtual") % slots;
  351. return random_addr * CONFIG_PHYSICAL_ALIGN + minimum;
  352. }
  353. /*
  354. * Since this function examines addresses much more numerically,
  355. * it takes the input and output pointers as 'unsigned long'.
  356. */
  357. void choose_random_location(unsigned long input,
  358. unsigned long input_size,
  359. unsigned long *output,
  360. unsigned long output_size,
  361. unsigned long *virt_addr)
  362. {
  363. unsigned long random_addr, min_addr;
  364. if (cmdline_find_option_bool("nokaslr")) {
  365. warn("KASLR disabled: 'nokaslr' on cmdline.");
  366. return;
  367. }
  368. boot_params->hdr.loadflags |= KASLR_FLAG;
  369. /* Prepare to add new identity pagetables on demand. */
  370. initialize_identity_maps();
  371. /* Record the various known unsafe memory ranges. */
  372. mem_avoid_init(input, input_size, *output);
  373. /*
  374. * Low end of the randomization range should be the
  375. * smaller of 512M or the initial kernel image
  376. * location:
  377. */
  378. min_addr = min(*output, 512UL << 20);
  379. /* Walk e820 and find a random address. */
  380. random_addr = find_random_phys_addr(min_addr, output_size);
  381. if (!random_addr) {
  382. warn("KASLR disabled: could not find suitable E820 region!");
  383. } else {
  384. /* Update the new physical address location. */
  385. if (*output != random_addr) {
  386. add_identity_map(random_addr, output_size);
  387. *output = random_addr;
  388. }
  389. /*
  390. * This loads the identity mapping page table.
  391. * This should only be done if a new physical address
  392. * is found for the kernel, otherwise we should keep
  393. * the old page table to make it be like the "nokaslr"
  394. * case.
  395. */
  396. finalize_identity_maps();
  397. }
  398. /* Pick random virtual address starting from LOAD_PHYSICAL_ADDR. */
  399. if (IS_ENABLED(CONFIG_X86_64))
  400. random_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, output_size);
  401. *virt_addr = random_addr;
  402. }