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