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