xref: /linux/kernel/kexec_file.c (revision 7d4e49a77d9930c69751b9192448fda6ff9100f1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * kexec: kexec_file_load system call
4  *
5  * Copyright (C) 2014 Red Hat Inc.
6  * Authors:
7  *      Vivek Goyal <vgoyal@redhat.com>
8  */
9 
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 
12 #include <linux/capability.h>
13 #include <linux/mm.h>
14 #include <linux/file.h>
15 #include <linux/slab.h>
16 #include <linux/kexec.h>
17 #include <linux/memblock.h>
18 #include <linux/mutex.h>
19 #include <linux/list.h>
20 #include <linux/fs.h>
21 #include <linux/ima.h>
22 #include <crypto/sha2.h>
23 #include <linux/elf.h>
24 #include <linux/elfcore.h>
25 #include <linux/kernel.h>
26 #include <linux/kernel_read_file.h>
27 #include <linux/syscalls.h>
28 #include <linux/vmalloc.h>
29 #include "kexec_internal.h"
30 
31 #ifdef CONFIG_KEXEC_SIG
32 static bool sig_enforce = IS_ENABLED(CONFIG_KEXEC_SIG_FORCE);
33 
set_kexec_sig_enforced(void)34 void set_kexec_sig_enforced(void)
35 {
36 	sig_enforce = true;
37 }
38 #endif
39 
40 #ifdef CONFIG_IMA_KEXEC
check_ima_segment_index(struct kimage * image,int i)41 static bool check_ima_segment_index(struct kimage *image, int i)
42 {
43 	if (image->is_ima_segment_index_set && i == image->ima_segment_index)
44 		return true;
45 	else
46 		return false;
47 }
48 #else
check_ima_segment_index(struct kimage * image,int i)49 static bool check_ima_segment_index(struct kimage *image, int i)
50 {
51 	return false;
52 }
53 #endif
54 
55 static int kexec_calculate_store_digests(struct kimage *image);
56 
57 /* Maximum size in bytes for kernel/initrd files. */
58 #define KEXEC_FILE_SIZE_MAX	min_t(s64, 4LL << 30, SSIZE_MAX)
59 
60 /*
61  * Currently this is the only default function that is exported as some
62  * architectures need it to do additional handlings.
63  * In the future, other default functions may be exported too if required.
64  */
kexec_image_probe_default(struct kimage * image,void * buf,unsigned long buf_len)65 int kexec_image_probe_default(struct kimage *image, void *buf,
66 			      unsigned long buf_len)
67 {
68 	const struct kexec_file_ops * const *fops;
69 	int ret = -ENOEXEC;
70 
71 	for (fops = &kexec_file_loaders[0]; *fops && (*fops)->probe; ++fops) {
72 		ret = (*fops)->probe(buf, buf_len);
73 		if (!ret) {
74 			image->fops = *fops;
75 			return ret;
76 		}
77 	}
78 
79 	return ret;
80 }
81 
kexec_image_load_default(struct kimage * image)82 static void *kexec_image_load_default(struct kimage *image)
83 {
84 	if (!image->fops || !image->fops->load)
85 		return ERR_PTR(-ENOEXEC);
86 
87 	return image->fops->load(image, image->kernel_buf,
88 				 image->kernel_buf_len, image->initrd_buf,
89 				 image->initrd_buf_len, image->cmdline_buf,
90 				 image->cmdline_buf_len);
91 }
92 
kexec_image_post_load_cleanup_default(struct kimage * image)93 int kexec_image_post_load_cleanup_default(struct kimage *image)
94 {
95 	if (!image->fops || !image->fops->cleanup)
96 		return 0;
97 
98 	return image->fops->cleanup(image->image_loader_data);
99 }
100 
101 /*
102  * Free up memory used by kernel, initrd, and command line. This is temporary
103  * memory allocation which is not needed any more after these buffers have
104  * been loaded into separate segments and have been copied elsewhere.
105  */
kimage_file_post_load_cleanup(struct kimage * image)106 void kimage_file_post_load_cleanup(struct kimage *image)
107 {
108 	struct purgatory_info *pi = &image->purgatory_info;
109 
110 	vfree(image->kernel_buf);
111 	image->kernel_buf = NULL;
112 
113 	vfree(image->initrd_buf);
114 	image->initrd_buf = NULL;
115 
116 	kfree(image->cmdline_buf);
117 	image->cmdline_buf = NULL;
118 
119 	vfree(pi->purgatory_buf);
120 	pi->purgatory_buf = NULL;
121 
122 	vfree(pi->sechdrs);
123 	pi->sechdrs = NULL;
124 
125 #ifdef CONFIG_IMA_KEXEC
126 	vfree(image->ima_buffer);
127 	image->ima_buffer = NULL;
128 #endif /* CONFIG_IMA_KEXEC */
129 
130 	/* See if architecture has anything to cleanup post load */
131 	arch_kimage_file_post_load_cleanup(image);
132 
133 	/*
134 	 * Above call should have called into bootloader to free up
135 	 * any data stored in kimage->image_loader_data. It should
136 	 * be ok now to free it up.
137 	 */
138 	kfree(image->image_loader_data);
139 	image->image_loader_data = NULL;
140 
141 	kexec_file_dbg_print = false;
142 }
143 
144 #ifdef CONFIG_KEXEC_SIG
145 #ifdef CONFIG_SIGNED_PE_FILE_VERIFICATION
kexec_kernel_verify_pe_sig(const char * kernel,unsigned long kernel_len)146 int kexec_kernel_verify_pe_sig(const char *kernel, unsigned long kernel_len)
147 {
148 	int ret;
149 
150 	ret = verify_pefile_signature(kernel, kernel_len,
151 				      VERIFY_USE_SECONDARY_KEYRING,
152 				      VERIFYING_KEXEC_PE_SIGNATURE);
153 	if (ret == -ENOKEY && IS_ENABLED(CONFIG_INTEGRITY_PLATFORM_KEYRING)) {
154 		ret = verify_pefile_signature(kernel, kernel_len,
155 					      VERIFY_USE_PLATFORM_KEYRING,
156 					      VERIFYING_KEXEC_PE_SIGNATURE);
157 	}
158 	return ret;
159 }
160 #endif
161 
kexec_image_verify_sig(struct kimage * image,void * buf,unsigned long buf_len)162 static int kexec_image_verify_sig(struct kimage *image, void *buf,
163 				  unsigned long buf_len)
164 {
165 	if (!image->fops || !image->fops->verify_sig) {
166 		pr_debug("kernel loader does not support signature verification.\n");
167 		return -EKEYREJECTED;
168 	}
169 
170 	return image->fops->verify_sig(buf, buf_len);
171 }
172 
173 static int
kimage_validate_signature(struct kimage * image)174 kimage_validate_signature(struct kimage *image)
175 {
176 	int ret;
177 
178 	ret = kexec_image_verify_sig(image, image->kernel_buf,
179 				     image->kernel_buf_len);
180 	if (ret) {
181 
182 		if (sig_enforce) {
183 			pr_notice("Enforced kernel signature verification failed (%d).\n", ret);
184 			return ret;
185 		}
186 
187 		/*
188 		 * If IMA is guaranteed to appraise a signature on the kexec
189 		 * image, permit it even if the kernel is otherwise locked
190 		 * down.
191 		 */
192 		if (!ima_appraise_signature(READING_KEXEC_IMAGE) &&
193 		    security_locked_down(LOCKDOWN_KEXEC))
194 			return -EPERM;
195 
196 		pr_debug("kernel signature verification failed (%d).\n", ret);
197 	}
198 
199 	return 0;
200 }
201 #endif
202 
kexec_post_load(struct kimage * image,unsigned long flags)203 static int kexec_post_load(struct kimage *image, unsigned long flags)
204 {
205 #ifdef CONFIG_IMA_KEXEC
206 	if (!(flags & KEXEC_FILE_ON_CRASH))
207 		ima_kexec_post_load(image);
208 #endif
209 	return machine_kexec_post_load(image);
210 }
211 
212 /*
213  * In file mode list of segments is prepared by kernel. Copy relevant
214  * data from user space, do error checking, prepare segment list
215  */
216 static int
kimage_file_prepare_segments(struct kimage * image,int kernel_fd,int initrd_fd,const char __user * cmdline_ptr,unsigned long cmdline_len,unsigned flags)217 kimage_file_prepare_segments(struct kimage *image, int kernel_fd, int initrd_fd,
218 			     const char __user *cmdline_ptr,
219 			     unsigned long cmdline_len, unsigned flags)
220 {
221 	ssize_t ret;
222 	void *ldata;
223 
224 	ret = kernel_read_file_from_fd(kernel_fd, 0, &image->kernel_buf,
225 				       KEXEC_FILE_SIZE_MAX, NULL,
226 				       READING_KEXEC_IMAGE);
227 	if (ret < 0)
228 		return ret;
229 	image->kernel_buf_len = ret;
230 	kexec_dprintk("kernel: %p kernel_size: %#lx\n",
231 		      image->kernel_buf, image->kernel_buf_len);
232 
233 	/* Call arch image probe handlers */
234 	ret = arch_kexec_kernel_image_probe(image, image->kernel_buf,
235 					    image->kernel_buf_len);
236 	if (ret)
237 		goto out;
238 
239 #ifdef CONFIG_KEXEC_SIG
240 	ret = kimage_validate_signature(image);
241 
242 	if (ret)
243 		goto out;
244 #endif
245 	/* It is possible that there no initramfs is being loaded */
246 	if (!(flags & KEXEC_FILE_NO_INITRAMFS)) {
247 		ret = kernel_read_file_from_fd(initrd_fd, 0, &image->initrd_buf,
248 					       KEXEC_FILE_SIZE_MAX, NULL,
249 					       READING_KEXEC_INITRAMFS);
250 		if (ret < 0)
251 			goto out;
252 		image->initrd_buf_len = ret;
253 		ret = 0;
254 	}
255 
256 	if (cmdline_len) {
257 		image->cmdline_buf = memdup_user(cmdline_ptr, cmdline_len);
258 		if (IS_ERR(image->cmdline_buf)) {
259 			ret = PTR_ERR(image->cmdline_buf);
260 			image->cmdline_buf = NULL;
261 			goto out;
262 		}
263 
264 		image->cmdline_buf_len = cmdline_len;
265 
266 		/* command line should be a string with last byte null */
267 		if (image->cmdline_buf[cmdline_len - 1] != '\0') {
268 			ret = -EINVAL;
269 			goto out;
270 		}
271 
272 		ima_kexec_cmdline(kernel_fd, image->cmdline_buf,
273 				  image->cmdline_buf_len - 1);
274 	}
275 
276 	/* IMA needs to pass the measurement list to the next kernel. */
277 	ima_add_kexec_buffer(image);
278 
279 	/* If KHO is active, add its images to the list */
280 	ret = kho_fill_kimage(image);
281 	if (ret)
282 		goto out;
283 
284 	/* Call image load handler */
285 	ldata = kexec_image_load_default(image);
286 
287 	if (IS_ERR(ldata)) {
288 		ret = PTR_ERR(ldata);
289 		goto out;
290 	}
291 
292 	image->image_loader_data = ldata;
293 out:
294 	/* In case of error, free up all allocated memory in this function */
295 	if (ret)
296 		kimage_file_post_load_cleanup(image);
297 	return ret;
298 }
299 
300 static int
kimage_file_alloc_init(struct kimage ** rimage,int kernel_fd,int initrd_fd,const char __user * cmdline_ptr,unsigned long cmdline_len,unsigned long flags)301 kimage_file_alloc_init(struct kimage **rimage, int kernel_fd,
302 		       int initrd_fd, const char __user *cmdline_ptr,
303 		       unsigned long cmdline_len, unsigned long flags)
304 {
305 	int ret;
306 	struct kimage *image;
307 	bool kexec_on_panic = flags & KEXEC_FILE_ON_CRASH;
308 
309 	image = do_kimage_alloc_init();
310 	if (!image)
311 		return -ENOMEM;
312 
313 	kexec_file_dbg_print = !!(flags & KEXEC_FILE_DEBUG);
314 	image->file_mode = 1;
315 
316 #ifdef CONFIG_CRASH_DUMP
317 	if (kexec_on_panic) {
318 		/* Enable special crash kernel control page alloc policy. */
319 		image->control_page = crashk_res.start;
320 		image->type = KEXEC_TYPE_CRASH;
321 	}
322 #endif
323 
324 	ret = kimage_file_prepare_segments(image, kernel_fd, initrd_fd,
325 					   cmdline_ptr, cmdline_len, flags);
326 	if (ret)
327 		goto out_free_image;
328 
329 	ret = sanity_check_segment_list(image);
330 	if (ret)
331 		goto out_free_post_load_bufs;
332 
333 	ret = -ENOMEM;
334 	image->control_code_page = kimage_alloc_control_pages(image,
335 					   get_order(KEXEC_CONTROL_PAGE_SIZE));
336 	if (!image->control_code_page) {
337 		pr_err("Could not allocate control_code_buffer\n");
338 		goto out_free_post_load_bufs;
339 	}
340 
341 	if (!kexec_on_panic) {
342 		image->swap_page = kimage_alloc_control_pages(image, 0);
343 		if (!image->swap_page) {
344 			pr_err("Could not allocate swap buffer\n");
345 			goto out_free_control_pages;
346 		}
347 	}
348 
349 	*rimage = image;
350 	return 0;
351 out_free_control_pages:
352 	kimage_free_page_list(&image->control_pages);
353 out_free_post_load_bufs:
354 	kimage_file_post_load_cleanup(image);
355 out_free_image:
356 	kfree(image);
357 	return ret;
358 }
359 
SYSCALL_DEFINE5(kexec_file_load,int,kernel_fd,int,initrd_fd,unsigned long,cmdline_len,const char __user *,cmdline_ptr,unsigned long,flags)360 SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
361 		unsigned long, cmdline_len, const char __user *, cmdline_ptr,
362 		unsigned long, flags)
363 {
364 	int image_type = (flags & KEXEC_FILE_ON_CRASH) ?
365 			 KEXEC_TYPE_CRASH : KEXEC_TYPE_DEFAULT;
366 	struct kimage **dest_image, *image;
367 	int ret = 0, i;
368 
369 	/* We only trust the superuser with rebooting the system. */
370 	if (!kexec_load_permitted(image_type))
371 		return -EPERM;
372 
373 	/* Make sure we have a legal set of flags */
374 	if (flags != (flags & KEXEC_FILE_FLAGS))
375 		return -EINVAL;
376 
377 	image = NULL;
378 
379 	if (!kexec_trylock())
380 		return -EBUSY;
381 
382 #ifdef CONFIG_CRASH_DUMP
383 	if (image_type == KEXEC_TYPE_CRASH) {
384 		dest_image = &kexec_crash_image;
385 		if (kexec_crash_image)
386 			arch_kexec_unprotect_crashkres();
387 	} else
388 #endif
389 		dest_image = &kexec_image;
390 
391 	if (flags & KEXEC_FILE_UNLOAD)
392 		goto exchange;
393 
394 	/*
395 	 * In case of crash, new kernel gets loaded in reserved region. It is
396 	 * same memory where old crash kernel might be loaded. Free any
397 	 * current crash dump kernel before we corrupt it.
398 	 */
399 	if (flags & KEXEC_FILE_ON_CRASH)
400 		kimage_free(xchg(&kexec_crash_image, NULL));
401 
402 	ret = kimage_file_alloc_init(&image, kernel_fd, initrd_fd, cmdline_ptr,
403 				     cmdline_len, flags);
404 	if (ret)
405 		goto out;
406 
407 #ifdef CONFIG_CRASH_HOTPLUG
408 	if ((flags & KEXEC_FILE_ON_CRASH) && arch_crash_hotplug_support(image, flags))
409 		image->hotplug_support = 1;
410 #endif
411 
412 	ret = machine_kexec_prepare(image);
413 	if (ret)
414 		goto out;
415 
416 	/*
417 	 * Some architecture(like S390) may touch the crash memory before
418 	 * machine_kexec_prepare(), we must copy vmcoreinfo data after it.
419 	 */
420 	ret = kimage_crash_copy_vmcoreinfo(image);
421 	if (ret)
422 		goto out;
423 
424 	ret = kexec_calculate_store_digests(image);
425 	if (ret)
426 		goto out;
427 
428 	kexec_dprintk("nr_segments = %lu\n", image->nr_segments);
429 	for (i = 0; i < image->nr_segments; i++) {
430 		struct kexec_segment *ksegment;
431 
432 		ksegment = &image->segment[i];
433 		kexec_dprintk("segment[%d]: buf=0x%p bufsz=0x%zx mem=0x%lx memsz=0x%zx\n",
434 			      i, ksegment->buf, ksegment->bufsz, ksegment->mem,
435 			      ksegment->memsz);
436 
437 		ret = kimage_load_segment(image, &image->segment[i]);
438 		if (ret)
439 			goto out;
440 	}
441 
442 	kimage_terminate(image);
443 
444 	ret = kexec_post_load(image, flags);
445 	if (ret)
446 		goto out;
447 
448 	kexec_dprintk("kexec_file_load: type:%u, start:0x%lx head:0x%lx flags:0x%lx\n",
449 		      image->type, image->start, image->head, flags);
450 	/*
451 	 * Free up any temporary buffers allocated which are not needed
452 	 * after image has been loaded
453 	 */
454 	kimage_file_post_load_cleanup(image);
455 exchange:
456 	image = xchg(dest_image, image);
457 out:
458 #ifdef CONFIG_CRASH_DUMP
459 	if ((flags & KEXEC_FILE_ON_CRASH) && kexec_crash_image)
460 		arch_kexec_protect_crashkres();
461 #endif
462 
463 	kexec_unlock();
464 	kimage_free(image);
465 	return ret;
466 }
467 
locate_mem_hole_top_down(unsigned long start,unsigned long end,struct kexec_buf * kbuf)468 static int locate_mem_hole_top_down(unsigned long start, unsigned long end,
469 				    struct kexec_buf *kbuf)
470 {
471 	struct kimage *image = kbuf->image;
472 	unsigned long temp_start, temp_end;
473 
474 	temp_end = min(end, kbuf->buf_max);
475 	temp_start = temp_end - kbuf->memsz + 1;
476 	kexec_random_range_start(temp_start, temp_end, kbuf, &temp_start);
477 
478 	do {
479 		/* align down start */
480 		temp_start = ALIGN_DOWN(temp_start, kbuf->buf_align);
481 
482 		if (temp_start < start || temp_start < kbuf->buf_min)
483 			return 0;
484 
485 		temp_end = temp_start + kbuf->memsz - 1;
486 
487 		/*
488 		 * Make sure this does not conflict with any of existing
489 		 * segments
490 		 */
491 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
492 			temp_start = temp_start - PAGE_SIZE;
493 			continue;
494 		}
495 
496 		/* Make sure this does not conflict with exclude range */
497 		if (arch_check_excluded_range(image, temp_start, temp_end)) {
498 			temp_start = temp_start - PAGE_SIZE;
499 			continue;
500 		}
501 
502 		/* We found a suitable memory range */
503 		break;
504 	} while (1);
505 
506 	/* If we are here, we found a suitable memory range */
507 	kbuf->mem = temp_start;
508 
509 	/* Success, stop navigating through remaining System RAM ranges */
510 	return 1;
511 }
512 
locate_mem_hole_bottom_up(unsigned long start,unsigned long end,struct kexec_buf * kbuf)513 static int locate_mem_hole_bottom_up(unsigned long start, unsigned long end,
514 				     struct kexec_buf *kbuf)
515 {
516 	struct kimage *image = kbuf->image;
517 	unsigned long temp_start, temp_end;
518 
519 	temp_start = max(start, kbuf->buf_min);
520 
521 	kexec_random_range_start(temp_start, end, kbuf, &temp_start);
522 
523 	do {
524 		temp_start = ALIGN(temp_start, kbuf->buf_align);
525 		temp_end = temp_start + kbuf->memsz - 1;
526 
527 		if (temp_end > end || temp_end > kbuf->buf_max)
528 			return 0;
529 		/*
530 		 * Make sure this does not conflict with any of existing
531 		 * segments
532 		 */
533 		if (kimage_is_destination_range(image, temp_start, temp_end)) {
534 			temp_start = temp_start + PAGE_SIZE;
535 			continue;
536 		}
537 
538 		/* Make sure this does not conflict with exclude range */
539 		if (arch_check_excluded_range(image, temp_start, temp_end)) {
540 			temp_start = temp_start + PAGE_SIZE;
541 			continue;
542 		}
543 
544 		/* We found a suitable memory range */
545 		break;
546 	} while (1);
547 
548 	/* If we are here, we found a suitable memory range */
549 	kbuf->mem = temp_start;
550 
551 	/* Success, stop navigating through remaining System RAM ranges */
552 	return 1;
553 }
554 
locate_mem_hole_callback(struct resource * res,void * arg)555 static int locate_mem_hole_callback(struct resource *res, void *arg)
556 {
557 	struct kexec_buf *kbuf = (struct kexec_buf *)arg;
558 	u64 start = res->start, end = res->end;
559 	unsigned long sz = end - start + 1;
560 
561 	/* Returning 0 will take to next memory range */
562 
563 	/* Don't use memory that will be detected and handled by a driver. */
564 	if (res->flags & IORESOURCE_SYSRAM_DRIVER_MANAGED)
565 		return 0;
566 
567 	if (sz < kbuf->memsz)
568 		return 0;
569 
570 	if (end < kbuf->buf_min || start > kbuf->buf_max)
571 		return 0;
572 
573 	/*
574 	 * Allocate memory top down with-in ram range. Otherwise bottom up
575 	 * allocation.
576 	 */
577 	if (kbuf->top_down)
578 		return locate_mem_hole_top_down(start, end, kbuf);
579 	return locate_mem_hole_bottom_up(start, end, kbuf);
580 }
581 
582 #ifdef CONFIG_ARCH_KEEP_MEMBLOCK
kexec_walk_memblock(struct kexec_buf * kbuf,int (* func)(struct resource *,void *))583 static int kexec_walk_memblock(struct kexec_buf *kbuf,
584 			       int (*func)(struct resource *, void *))
585 {
586 	int ret = 0;
587 	u64 i;
588 	phys_addr_t mstart, mend;
589 	struct resource res = { };
590 
591 #ifdef CONFIG_CRASH_DUMP
592 	if (kbuf->image->type == KEXEC_TYPE_CRASH)
593 		return func(&crashk_res, kbuf);
594 #endif
595 
596 	/*
597 	 * Using MEMBLOCK_NONE will properly skip MEMBLOCK_DRIVER_MANAGED. See
598 	 * IORESOURCE_SYSRAM_DRIVER_MANAGED handling in
599 	 * locate_mem_hole_callback().
600 	 */
601 	if (kbuf->top_down) {
602 		for_each_free_mem_range_reverse(i, NUMA_NO_NODE, MEMBLOCK_NONE,
603 						&mstart, &mend, NULL) {
604 			/*
605 			 * In memblock, end points to the first byte after the
606 			 * range while in kexec, end points to the last byte
607 			 * in the range.
608 			 */
609 			res.start = mstart;
610 			res.end = mend - 1;
611 			ret = func(&res, kbuf);
612 			if (ret)
613 				break;
614 		}
615 	} else {
616 		for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE,
617 					&mstart, &mend, NULL) {
618 			/*
619 			 * In memblock, end points to the first byte after the
620 			 * range while in kexec, end points to the last byte
621 			 * in the range.
622 			 */
623 			res.start = mstart;
624 			res.end = mend - 1;
625 			ret = func(&res, kbuf);
626 			if (ret)
627 				break;
628 		}
629 	}
630 
631 	return ret;
632 }
633 #else
kexec_walk_memblock(struct kexec_buf * kbuf,int (* func)(struct resource *,void *))634 static int kexec_walk_memblock(struct kexec_buf *kbuf,
635 			       int (*func)(struct resource *, void *))
636 {
637 	return 0;
638 }
639 #endif
640 
641 /**
642  * kexec_walk_resources - call func(data) on free memory regions
643  * @kbuf:	Context info for the search. Also passed to @func.
644  * @func:	Function to call for each memory region.
645  *
646  * Return: The memory walk will stop when func returns a non-zero value
647  * and that value will be returned. If all free regions are visited without
648  * func returning non-zero, then zero will be returned.
649  */
kexec_walk_resources(struct kexec_buf * kbuf,int (* func)(struct resource *,void *))650 static int kexec_walk_resources(struct kexec_buf *kbuf,
651 				int (*func)(struct resource *, void *))
652 {
653 #ifdef CONFIG_CRASH_DUMP
654 	if (kbuf->image->type == KEXEC_TYPE_CRASH)
655 		return walk_iomem_res_desc(crashk_res.desc,
656 					   IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY,
657 					   crashk_res.start, crashk_res.end,
658 					   kbuf, func);
659 #endif
660 	if (kbuf->top_down)
661 		return walk_system_ram_res_rev(0, ULONG_MAX, kbuf, func);
662 	else
663 		return walk_system_ram_res(0, ULONG_MAX, kbuf, func);
664 }
665 
666 /**
667  * kexec_locate_mem_hole - find free memory for the purgatory or the next kernel
668  * @kbuf:	Parameters for the memory search.
669  *
670  * On success, kbuf->mem will have the start address of the memory region found.
671  *
672  * Return: 0 on success, negative errno on error.
673  */
kexec_locate_mem_hole(struct kexec_buf * kbuf)674 int kexec_locate_mem_hole(struct kexec_buf *kbuf)
675 {
676 	int ret;
677 
678 	/* Arch knows where to place */
679 	if (kbuf->mem != KEXEC_BUF_MEM_UNKNOWN)
680 		return 0;
681 
682 	/*
683 	 * If KHO is active, only use KHO scratch memory. All other memory
684 	 * could potentially be handed over.
685 	 */
686 	ret = kho_locate_mem_hole(kbuf, locate_mem_hole_callback);
687 	if (ret <= 0)
688 		return ret;
689 
690 	if (!IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
691 		ret = kexec_walk_resources(kbuf, locate_mem_hole_callback);
692 	else
693 		ret = kexec_walk_memblock(kbuf, locate_mem_hole_callback);
694 
695 	return ret == 1 ? 0 : -EADDRNOTAVAIL;
696 }
697 
698 /**
699  * kexec_add_buffer - place a buffer in a kexec segment
700  * @kbuf:	Buffer contents and memory parameters.
701  *
702  * This function assumes that kexec_lock is held.
703  * On successful return, @kbuf->mem will have the physical address of
704  * the buffer in memory.
705  *
706  * Return: 0 on success, negative errno on error.
707  */
kexec_add_buffer(struct kexec_buf * kbuf)708 int kexec_add_buffer(struct kexec_buf *kbuf)
709 {
710 	struct kexec_segment *ksegment;
711 	int ret;
712 
713 	/* Currently adding segment this way is allowed only in file mode */
714 	if (!kbuf->image->file_mode)
715 		return -EINVAL;
716 
717 	if (kbuf->image->nr_segments >= KEXEC_SEGMENT_MAX)
718 		return -EINVAL;
719 
720 	/*
721 	 * Make sure we are not trying to add buffer after allocating
722 	 * control pages. All segments need to be placed first before
723 	 * any control pages are allocated. As control page allocation
724 	 * logic goes through list of segments to make sure there are
725 	 * no destination overlaps.
726 	 */
727 	if (!list_empty(&kbuf->image->control_pages)) {
728 		WARN_ON(1);
729 		return -EINVAL;
730 	}
731 
732 	/* Ensure minimum alignment needed for segments. */
733 	kbuf->memsz = ALIGN(kbuf->memsz, PAGE_SIZE);
734 	kbuf->buf_align = max(kbuf->buf_align, PAGE_SIZE);
735 
736 	/* Walk the RAM ranges and allocate a suitable range for the buffer */
737 	ret = arch_kexec_locate_mem_hole(kbuf);
738 	if (ret)
739 		return ret;
740 
741 	/* Found a suitable memory range */
742 	ksegment = &kbuf->image->segment[kbuf->image->nr_segments];
743 	ksegment->kbuf = kbuf->buffer;
744 	ksegment->bufsz = kbuf->bufsz;
745 	ksegment->mem = kbuf->mem;
746 	ksegment->memsz = kbuf->memsz;
747 	kbuf->image->nr_segments++;
748 	return 0;
749 }
750 
751 /* Calculate and store the digest of segments */
kexec_calculate_store_digests(struct kimage * image)752 static int kexec_calculate_store_digests(struct kimage *image)
753 {
754 	struct sha256_state state;
755 	int ret = 0, i, j, zero_buf_sz, sha_region_sz;
756 	size_t nullsz;
757 	u8 digest[SHA256_DIGEST_SIZE];
758 	void *zero_buf;
759 	struct kexec_sha_region *sha_regions;
760 	struct purgatory_info *pi = &image->purgatory_info;
761 
762 	if (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY))
763 		return 0;
764 
765 	zero_buf = __va(page_to_pfn(ZERO_PAGE(0)) << PAGE_SHIFT);
766 	zero_buf_sz = PAGE_SIZE;
767 
768 	sha_region_sz = KEXEC_SEGMENT_MAX * sizeof(struct kexec_sha_region);
769 	sha_regions = vzalloc(sha_region_sz);
770 	if (!sha_regions)
771 		return -ENOMEM;
772 
773 	sha256_init(&state);
774 
775 	for (j = i = 0; i < image->nr_segments; i++) {
776 		struct kexec_segment *ksegment;
777 
778 #ifdef CONFIG_CRASH_HOTPLUG
779 		/* Exclude elfcorehdr segment to allow future changes via hotplug */
780 		if (i == image->elfcorehdr_index)
781 			continue;
782 #endif
783 
784 		ksegment = &image->segment[i];
785 		/*
786 		 * Skip purgatory as it will be modified once we put digest
787 		 * info in purgatory.
788 		 */
789 		if (ksegment->kbuf == pi->purgatory_buf)
790 			continue;
791 
792 		/*
793 		 * Skip the segment if ima_segment_index is set and matches
794 		 * the current index
795 		 */
796 		if (check_ima_segment_index(image, i))
797 			continue;
798 
799 		sha256_update(&state, ksegment->kbuf, ksegment->bufsz);
800 
801 		/*
802 		 * Assume rest of the buffer is filled with zero and
803 		 * update digest accordingly.
804 		 */
805 		nullsz = ksegment->memsz - ksegment->bufsz;
806 		while (nullsz) {
807 			unsigned long bytes = nullsz;
808 
809 			if (bytes > zero_buf_sz)
810 				bytes = zero_buf_sz;
811 			sha256_update(&state, zero_buf, bytes);
812 			nullsz -= bytes;
813 		}
814 
815 		sha_regions[j].start = ksegment->mem;
816 		sha_regions[j].len = ksegment->memsz;
817 		j++;
818 	}
819 
820 	sha256_final(&state, digest);
821 
822 	ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha_regions",
823 					     sha_regions, sha_region_sz, 0);
824 	if (ret)
825 		goto out_free_sha_regions;
826 
827 	ret = kexec_purgatory_get_set_symbol(image, "purgatory_sha256_digest",
828 					     digest, SHA256_DIGEST_SIZE, 0);
829 out_free_sha_regions:
830 	vfree(sha_regions);
831 	return ret;
832 }
833 
834 #ifdef CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY
835 /*
836  * kexec_purgatory_setup_kbuf - prepare buffer to load purgatory.
837  * @pi:		Purgatory to be loaded.
838  * @kbuf:	Buffer to setup.
839  *
840  * Allocates the memory needed for the buffer. Caller is responsible to free
841  * the memory after use.
842  *
843  * Return: 0 on success, negative errno on error.
844  */
kexec_purgatory_setup_kbuf(struct purgatory_info * pi,struct kexec_buf * kbuf)845 static int kexec_purgatory_setup_kbuf(struct purgatory_info *pi,
846 				      struct kexec_buf *kbuf)
847 {
848 	const Elf_Shdr *sechdrs;
849 	unsigned long bss_align;
850 	unsigned long bss_sz;
851 	unsigned long align;
852 	int i, ret;
853 
854 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
855 	kbuf->buf_align = bss_align = 1;
856 	kbuf->bufsz = bss_sz = 0;
857 
858 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
859 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
860 			continue;
861 
862 		align = sechdrs[i].sh_addralign;
863 		if (sechdrs[i].sh_type != SHT_NOBITS) {
864 			if (kbuf->buf_align < align)
865 				kbuf->buf_align = align;
866 			kbuf->bufsz = ALIGN(kbuf->bufsz, align);
867 			kbuf->bufsz += sechdrs[i].sh_size;
868 		} else {
869 			if (bss_align < align)
870 				bss_align = align;
871 			bss_sz = ALIGN(bss_sz, align);
872 			bss_sz += sechdrs[i].sh_size;
873 		}
874 	}
875 	kbuf->bufsz = ALIGN(kbuf->bufsz, bss_align);
876 	kbuf->memsz = kbuf->bufsz + bss_sz;
877 	if (kbuf->buf_align < bss_align)
878 		kbuf->buf_align = bss_align;
879 
880 	kbuf->buffer = vzalloc(kbuf->bufsz);
881 	if (!kbuf->buffer)
882 		return -ENOMEM;
883 	pi->purgatory_buf = kbuf->buffer;
884 
885 	ret = kexec_add_buffer(kbuf);
886 	if (ret)
887 		goto out;
888 
889 	return 0;
890 out:
891 	vfree(pi->purgatory_buf);
892 	pi->purgatory_buf = NULL;
893 	return ret;
894 }
895 
896 /*
897  * kexec_purgatory_setup_sechdrs - prepares the pi->sechdrs buffer.
898  * @pi:		Purgatory to be loaded.
899  * @kbuf:	Buffer prepared to store purgatory.
900  *
901  * Allocates the memory needed for the buffer. Caller is responsible to free
902  * the memory after use.
903  *
904  * Return: 0 on success, negative errno on error.
905  */
kexec_purgatory_setup_sechdrs(struct purgatory_info * pi,struct kexec_buf * kbuf)906 static int kexec_purgatory_setup_sechdrs(struct purgatory_info *pi,
907 					 struct kexec_buf *kbuf)
908 {
909 	unsigned long bss_addr;
910 	unsigned long offset;
911 	size_t sechdrs_size;
912 	Elf_Shdr *sechdrs;
913 	int i;
914 
915 	/*
916 	 * The section headers in kexec_purgatory are read-only. In order to
917 	 * have them modifiable make a temporary copy.
918 	 */
919 	sechdrs_size = array_size(sizeof(Elf_Shdr), pi->ehdr->e_shnum);
920 	sechdrs = vzalloc(sechdrs_size);
921 	if (!sechdrs)
922 		return -ENOMEM;
923 	memcpy(sechdrs, (void *)pi->ehdr + pi->ehdr->e_shoff, sechdrs_size);
924 	pi->sechdrs = sechdrs;
925 
926 	offset = 0;
927 	bss_addr = kbuf->mem + kbuf->bufsz;
928 	kbuf->image->start = pi->ehdr->e_entry;
929 
930 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
931 		unsigned long align;
932 		void *src, *dst;
933 
934 		if (!(sechdrs[i].sh_flags & SHF_ALLOC))
935 			continue;
936 
937 		align = sechdrs[i].sh_addralign;
938 		if (sechdrs[i].sh_type == SHT_NOBITS) {
939 			bss_addr = ALIGN(bss_addr, align);
940 			sechdrs[i].sh_addr = bss_addr;
941 			bss_addr += sechdrs[i].sh_size;
942 			continue;
943 		}
944 
945 		offset = ALIGN(offset, align);
946 
947 		/*
948 		 * Check if the segment contains the entry point, if so,
949 		 * calculate the value of image->start based on it.
950 		 * If the compiler has produced more than one .text section
951 		 * (Eg: .text.hot), they are generally after the main .text
952 		 * section, and they shall not be used to calculate
953 		 * image->start. So do not re-calculate image->start if it
954 		 * is not set to the initial value, and warn the user so they
955 		 * have a chance to fix their purgatory's linker script.
956 		 */
957 		if (sechdrs[i].sh_flags & SHF_EXECINSTR &&
958 		    pi->ehdr->e_entry >= sechdrs[i].sh_addr &&
959 		    pi->ehdr->e_entry < (sechdrs[i].sh_addr
960 					 + sechdrs[i].sh_size) &&
961 		    !WARN_ON(kbuf->image->start != pi->ehdr->e_entry)) {
962 			kbuf->image->start -= sechdrs[i].sh_addr;
963 			kbuf->image->start += kbuf->mem + offset;
964 		}
965 
966 		src = (void *)pi->ehdr + sechdrs[i].sh_offset;
967 		dst = pi->purgatory_buf + offset;
968 		memcpy(dst, src, sechdrs[i].sh_size);
969 
970 		sechdrs[i].sh_addr = kbuf->mem + offset;
971 		sechdrs[i].sh_offset = offset;
972 		offset += sechdrs[i].sh_size;
973 	}
974 
975 	return 0;
976 }
977 
kexec_apply_relocations(struct kimage * image)978 static int kexec_apply_relocations(struct kimage *image)
979 {
980 	int i, ret;
981 	struct purgatory_info *pi = &image->purgatory_info;
982 	const Elf_Shdr *sechdrs;
983 
984 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
985 
986 	for (i = 0; i < pi->ehdr->e_shnum; i++) {
987 		const Elf_Shdr *relsec;
988 		const Elf_Shdr *symtab;
989 		Elf_Shdr *section;
990 
991 		relsec = sechdrs + i;
992 
993 		if (relsec->sh_type != SHT_RELA &&
994 		    relsec->sh_type != SHT_REL)
995 			continue;
996 
997 		/*
998 		 * For section of type SHT_RELA/SHT_REL,
999 		 * ->sh_link contains section header index of associated
1000 		 * symbol table. And ->sh_info contains section header
1001 		 * index of section to which relocations apply.
1002 		 */
1003 		if (relsec->sh_info >= pi->ehdr->e_shnum ||
1004 		    relsec->sh_link >= pi->ehdr->e_shnum)
1005 			return -ENOEXEC;
1006 
1007 		section = pi->sechdrs + relsec->sh_info;
1008 		symtab = sechdrs + relsec->sh_link;
1009 
1010 		if (!(section->sh_flags & SHF_ALLOC))
1011 			continue;
1012 
1013 		/*
1014 		 * symtab->sh_link contain section header index of associated
1015 		 * string table.
1016 		 */
1017 		if (symtab->sh_link >= pi->ehdr->e_shnum)
1018 			/* Invalid section number? */
1019 			continue;
1020 
1021 		/*
1022 		 * Respective architecture needs to provide support for applying
1023 		 * relocations of type SHT_RELA/SHT_REL.
1024 		 */
1025 		if (relsec->sh_type == SHT_RELA)
1026 			ret = arch_kexec_apply_relocations_add(pi, section,
1027 							       relsec, symtab);
1028 		else if (relsec->sh_type == SHT_REL)
1029 			ret = arch_kexec_apply_relocations(pi, section,
1030 							   relsec, symtab);
1031 		if (ret)
1032 			return ret;
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 /*
1039  * kexec_load_purgatory - Load and relocate the purgatory object.
1040  * @image:	Image to add the purgatory to.
1041  * @kbuf:	Memory parameters to use.
1042  *
1043  * Allocates the memory needed for image->purgatory_info.sechdrs and
1044  * image->purgatory_info.purgatory_buf/kbuf->buffer. Caller is responsible
1045  * to free the memory after use.
1046  *
1047  * Return: 0 on success, negative errno on error.
1048  */
kexec_load_purgatory(struct kimage * image,struct kexec_buf * kbuf)1049 int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf)
1050 {
1051 	struct purgatory_info *pi = &image->purgatory_info;
1052 	int ret;
1053 
1054 	if (kexec_purgatory_size <= 0)
1055 		return -EINVAL;
1056 
1057 	pi->ehdr = (const Elf_Ehdr *)kexec_purgatory;
1058 
1059 	ret = kexec_purgatory_setup_kbuf(pi, kbuf);
1060 	if (ret)
1061 		return ret;
1062 
1063 	ret = kexec_purgatory_setup_sechdrs(pi, kbuf);
1064 	if (ret)
1065 		goto out_free_kbuf;
1066 
1067 	ret = kexec_apply_relocations(image);
1068 	if (ret)
1069 		goto out;
1070 
1071 	return 0;
1072 out:
1073 	vfree(pi->sechdrs);
1074 	pi->sechdrs = NULL;
1075 out_free_kbuf:
1076 	vfree(pi->purgatory_buf);
1077 	pi->purgatory_buf = NULL;
1078 	return ret;
1079 }
1080 
1081 /*
1082  * kexec_purgatory_find_symbol - find a symbol in the purgatory
1083  * @pi:		Purgatory to search in.
1084  * @name:	Name of the symbol.
1085  *
1086  * Return: pointer to symbol in read-only symtab on success, NULL on error.
1087  */
kexec_purgatory_find_symbol(struct purgatory_info * pi,const char * name)1088 static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
1089 						  const char *name)
1090 {
1091 	const Elf_Shdr *sechdrs;
1092 	const Elf_Ehdr *ehdr;
1093 	const Elf_Sym *syms;
1094 	const char *strtab;
1095 	int i, k;
1096 
1097 	if (!pi->ehdr)
1098 		return NULL;
1099 
1100 	ehdr = pi->ehdr;
1101 	sechdrs = (void *)ehdr + ehdr->e_shoff;
1102 
1103 	for (i = 0; i < ehdr->e_shnum; i++) {
1104 		if (sechdrs[i].sh_type != SHT_SYMTAB)
1105 			continue;
1106 
1107 		if (sechdrs[i].sh_link >= ehdr->e_shnum)
1108 			/* Invalid strtab section number */
1109 			continue;
1110 		strtab = (void *)ehdr + sechdrs[sechdrs[i].sh_link].sh_offset;
1111 		syms = (void *)ehdr + sechdrs[i].sh_offset;
1112 
1113 		/* Go through symbols for a match */
1114 		for (k = 0; k < sechdrs[i].sh_size/sizeof(Elf_Sym); k++) {
1115 			if (ELF_ST_BIND(syms[k].st_info) != STB_GLOBAL)
1116 				continue;
1117 
1118 			if (strcmp(strtab + syms[k].st_name, name) != 0)
1119 				continue;
1120 
1121 			if (syms[k].st_shndx == SHN_UNDEF ||
1122 			    syms[k].st_shndx >= ehdr->e_shnum) {
1123 				pr_debug("Symbol: %s has bad section index %d.\n",
1124 						name, syms[k].st_shndx);
1125 				return NULL;
1126 			}
1127 
1128 			/* Found the symbol we are looking for */
1129 			return &syms[k];
1130 		}
1131 	}
1132 
1133 	return NULL;
1134 }
1135 
kexec_purgatory_get_symbol_addr(struct kimage * image,const char * name)1136 void *kexec_purgatory_get_symbol_addr(struct kimage *image, const char *name)
1137 {
1138 	struct purgatory_info *pi = &image->purgatory_info;
1139 	const Elf_Sym *sym;
1140 	Elf_Shdr *sechdr;
1141 
1142 	sym = kexec_purgatory_find_symbol(pi, name);
1143 	if (!sym)
1144 		return ERR_PTR(-EINVAL);
1145 
1146 	sechdr = &pi->sechdrs[sym->st_shndx];
1147 
1148 	/*
1149 	 * Returns the address where symbol will finally be loaded after
1150 	 * kexec_load_segment()
1151 	 */
1152 	return (void *)(sechdr->sh_addr + sym->st_value);
1153 }
1154 
1155 /*
1156  * Get or set value of a symbol. If "get_value" is true, symbol value is
1157  * returned in buf otherwise symbol value is set based on value in buf.
1158  */
kexec_purgatory_get_set_symbol(struct kimage * image,const char * name,void * buf,unsigned int size,bool get_value)1159 int kexec_purgatory_get_set_symbol(struct kimage *image, const char *name,
1160 				   void *buf, unsigned int size, bool get_value)
1161 {
1162 	struct purgatory_info *pi = &image->purgatory_info;
1163 	const Elf_Sym *sym;
1164 	Elf_Shdr *sec;
1165 	char *sym_buf;
1166 
1167 	sym = kexec_purgatory_find_symbol(pi, name);
1168 	if (!sym)
1169 		return -EINVAL;
1170 
1171 	if (sym->st_size != size) {
1172 		pr_err("symbol %s size mismatch: expected %lu actual %u\n",
1173 		       name, (unsigned long)sym->st_size, size);
1174 		return -EINVAL;
1175 	}
1176 
1177 	sec = pi->sechdrs + sym->st_shndx;
1178 
1179 	if (sec->sh_type == SHT_NOBITS) {
1180 		pr_err("symbol %s is in a bss section. Cannot %s\n", name,
1181 		       get_value ? "get" : "set");
1182 		return -EINVAL;
1183 	}
1184 
1185 	sym_buf = (char *)pi->purgatory_buf + sec->sh_offset + sym->st_value;
1186 
1187 	if (get_value)
1188 		memcpy((void *)buf, sym_buf, size);
1189 	else
1190 		memcpy((void *)sym_buf, buf, size);
1191 
1192 	return 0;
1193 }
1194 #endif /* CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY */
1195