1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2002 Richard Henderson
4 * Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
5 * Copyright (C) 2023 Luis Chamberlain <mcgrof@kernel.org>
6 */
7
8 #define INCLUDE_VERMAGIC
9
10 #include <linux/export.h>
11 #include <linux/extable.h>
12 #include <linux/moduleloader.h>
13 #include <linux/module_signature.h>
14 #include <linux/trace_events.h>
15 #include <linux/init.h>
16 #include <linux/kallsyms.h>
17 #include <linux/buildid.h>
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/kernel_read_file.h>
21 #include <linux/kstrtox.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <linux/elf.h>
25 #include <linux/seq_file.h>
26 #include <linux/syscalls.h>
27 #include <linux/fcntl.h>
28 #include <linux/rcupdate.h>
29 #include <linux/capability.h>
30 #include <linux/cpu.h>
31 #include <linux/moduleparam.h>
32 #include <linux/errno.h>
33 #include <linux/err.h>
34 #include <linux/vermagic.h>
35 #include <linux/notifier.h>
36 #include <linux/sched.h>
37 #include <linux/device.h>
38 #include <linux/string.h>
39 #include <linux/mutex.h>
40 #include <linux/rculist.h>
41 #include <linux/uaccess.h>
42 #include <asm/cacheflush.h>
43 #include <linux/set_memory.h>
44 #include <asm/mmu_context.h>
45 #include <linux/license.h>
46 #include <asm/sections.h>
47 #include <linux/tracepoint.h>
48 #include <linux/ftrace.h>
49 #include <linux/livepatch.h>
50 #include <linux/async.h>
51 #include <linux/percpu.h>
52 #include <linux/kmemleak.h>
53 #include <linux/jump_label.h>
54 #include <linux/pfn.h>
55 #include <linux/bsearch.h>
56 #include <linux/dynamic_debug.h>
57 #include <linux/audit.h>
58 #include <linux/cfi.h>
59 #include <linux/codetag.h>
60 #include <linux/debugfs.h>
61 #include <linux/execmem.h>
62 #include <uapi/linux/module.h>
63 #include "internal.h"
64
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/module.h>
67
68 #undef CREATE_TRACE_POINTS
69 #include <trace/hooks/module.h>
70
71 /*
72 * Mutex protects:
73 * 1) List of modules (also safely readable with preempt_disable),
74 * 2) module_use links,
75 * 3) mod_tree.addr_min/mod_tree.addr_max.
76 * (delete and add uses RCU list operations).
77 */
78 DEFINE_MUTEX(module_mutex);
79 LIST_HEAD(modules);
80
81 /* Work queue for freeing init sections in success case */
82 static void do_free_init(struct work_struct *w);
83 static DECLARE_WORK(init_free_wq, do_free_init);
84 static LLIST_HEAD(init_free_list);
85
86 struct mod_tree_root mod_tree __cacheline_aligned = {
87 .addr_min = -1UL,
88 };
89
90 struct symsearch {
91 const struct kernel_symbol *start, *stop;
92 const u32 *crcs;
93 enum mod_license license;
94 };
95
96 #if defined(CONFIG_MODULE_SIG_PROTECT) || defined(CONFIG_TRIM_UNUSED_KSYMS)
cmp_string(const void * a,const void * b)97 static int cmp_string(const void *a, const void *b)
98 {
99 return strcmp((const char *)a, *(const char **)b);
100 }
101 #endif
102
103 /*
104 * Bounds of module memory, for speeding up __module_address.
105 * Protected by module_mutex.
106 */
__mod_update_bounds(enum mod_mem_type type __maybe_unused,void * base,unsigned int size,struct mod_tree_root * tree)107 static void __mod_update_bounds(enum mod_mem_type type __maybe_unused, void *base,
108 unsigned int size, struct mod_tree_root *tree)
109 {
110 unsigned long min = (unsigned long)base;
111 unsigned long max = min + size;
112
113 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
114 if (mod_mem_type_is_core_data(type)) {
115 if (min < tree->data_addr_min)
116 tree->data_addr_min = min;
117 if (max > tree->data_addr_max)
118 tree->data_addr_max = max;
119 return;
120 }
121 #endif
122 if (min < tree->addr_min)
123 tree->addr_min = min;
124 if (max > tree->addr_max)
125 tree->addr_max = max;
126 }
127
mod_update_bounds(struct module * mod)128 static void mod_update_bounds(struct module *mod)
129 {
130 for_each_mod_mem_type(type) {
131 struct module_memory *mod_mem = &mod->mem[type];
132
133 if (mod_mem->size)
134 __mod_update_bounds(type, mod_mem->base, mod_mem->size, &mod_tree);
135 }
136 }
137
138 /* Block module loading/unloading? */
139 int modules_disabled;
140 core_param(nomodule, modules_disabled, bint, 0);
141
142 /* Waiting for a module to finish initializing? */
143 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
144
145 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
146
register_module_notifier(struct notifier_block * nb)147 int register_module_notifier(struct notifier_block *nb)
148 {
149 return blocking_notifier_chain_register(&module_notify_list, nb);
150 }
151 EXPORT_SYMBOL(register_module_notifier);
152
unregister_module_notifier(struct notifier_block * nb)153 int unregister_module_notifier(struct notifier_block *nb)
154 {
155 return blocking_notifier_chain_unregister(&module_notify_list, nb);
156 }
157 EXPORT_SYMBOL(unregister_module_notifier);
158
159 /*
160 * We require a truly strong try_module_get(): 0 means success.
161 * Otherwise an error is returned due to ongoing or failed
162 * initialization etc.
163 */
strong_try_module_get(struct module * mod)164 static inline int strong_try_module_get(struct module *mod)
165 {
166 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
167 if (mod && mod->state == MODULE_STATE_COMING)
168 return -EBUSY;
169 if (try_module_get(mod))
170 return 0;
171 else
172 return -ENOENT;
173 }
174
add_taint_module(struct module * mod,unsigned flag,enum lockdep_ok lockdep_ok)175 static inline void add_taint_module(struct module *mod, unsigned flag,
176 enum lockdep_ok lockdep_ok)
177 {
178 add_taint(flag, lockdep_ok);
179 set_bit(flag, &mod->taints);
180 }
181
182 /*
183 * A thread that wants to hold a reference to a module only while it
184 * is running can call this to safely exit.
185 */
__module_put_and_kthread_exit(struct module * mod,long code)186 void __noreturn __module_put_and_kthread_exit(struct module *mod, long code)
187 {
188 module_put(mod);
189 kthread_exit(code);
190 }
191 EXPORT_SYMBOL(__module_put_and_kthread_exit);
192
193 /* Find a module section: 0 means not found. */
find_sec(const struct load_info * info,const char * name)194 static unsigned int find_sec(const struct load_info *info, const char *name)
195 {
196 unsigned int i;
197
198 for (i = 1; i < info->hdr->e_shnum; i++) {
199 Elf_Shdr *shdr = &info->sechdrs[i];
200 /* Alloc bit cleared means "ignore it." */
201 if ((shdr->sh_flags & SHF_ALLOC)
202 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
203 return i;
204 }
205 return 0;
206 }
207
208 /**
209 * find_any_unique_sec() - Find a unique section index by name
210 * @info: Load info for the module to scan
211 * @name: Name of the section we're looking for
212 *
213 * Locates a unique section by name. Ignores SHF_ALLOC.
214 *
215 * Return: Section index if found uniquely, zero if absent, negative count
216 * of total instances if multiple were found.
217 */
find_any_unique_sec(const struct load_info * info,const char * name)218 static int find_any_unique_sec(const struct load_info *info, const char *name)
219 {
220 unsigned int idx;
221 unsigned int count = 0;
222 int i;
223
224 for (i = 1; i < info->hdr->e_shnum; i++) {
225 if (strcmp(info->secstrings + info->sechdrs[i].sh_name,
226 name) == 0) {
227 count++;
228 idx = i;
229 }
230 }
231 if (count == 1) {
232 return idx;
233 } else if (count == 0) {
234 return 0;
235 } else {
236 return -count;
237 }
238 }
239
240 /* Find a module section, or NULL. */
section_addr(const struct load_info * info,const char * name)241 static void *section_addr(const struct load_info *info, const char *name)
242 {
243 /* Section 0 has sh_addr 0. */
244 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
245 }
246
247 /* Find a module section, or NULL. Fill in number of "objects" in section. */
section_objs(const struct load_info * info,const char * name,size_t object_size,unsigned int * num)248 static void *section_objs(const struct load_info *info,
249 const char *name,
250 size_t object_size,
251 unsigned int *num)
252 {
253 unsigned int sec = find_sec(info, name);
254
255 /* Section 0 has sh_addr 0 and sh_size 0. */
256 *num = info->sechdrs[sec].sh_size / object_size;
257 return (void *)info->sechdrs[sec].sh_addr;
258 }
259
260 /* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */
find_any_sec(const struct load_info * info,const char * name)261 static unsigned int find_any_sec(const struct load_info *info, const char *name)
262 {
263 unsigned int i;
264
265 for (i = 1; i < info->hdr->e_shnum; i++) {
266 Elf_Shdr *shdr = &info->sechdrs[i];
267 if (strcmp(info->secstrings + shdr->sh_name, name) == 0)
268 return i;
269 }
270 return 0;
271 }
272
273 /*
274 * Find a module section, or NULL. Fill in number of "objects" in section.
275 * Ignores SHF_ALLOC flag.
276 */
any_section_objs(const struct load_info * info,const char * name,size_t object_size,unsigned int * num)277 static __maybe_unused void *any_section_objs(const struct load_info *info,
278 const char *name,
279 size_t object_size,
280 unsigned int *num)
281 {
282 unsigned int sec = find_any_sec(info, name);
283
284 /* Section 0 has sh_addr 0 and sh_size 0. */
285 *num = info->sechdrs[sec].sh_size / object_size;
286 return (void *)info->sechdrs[sec].sh_addr;
287 }
288
289 #ifndef CONFIG_MODVERSIONS
290 #define symversion(base, idx) NULL
291 #else
292 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
293 #endif
294
kernel_symbol_name(const struct kernel_symbol * sym)295 static const char *kernel_symbol_name(const struct kernel_symbol *sym)
296 {
297 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
298 return offset_to_ptr(&sym->name_offset);
299 #else
300 return sym->name;
301 #endif
302 }
303
kernel_symbol_namespace(const struct kernel_symbol * sym)304 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
305 {
306 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
307 if (!sym->namespace_offset)
308 return NULL;
309 return offset_to_ptr(&sym->namespace_offset);
310 #else
311 return sym->namespace;
312 #endif
313 }
314
cmp_name(const void * name,const void * sym)315 int cmp_name(const void *name, const void *sym)
316 {
317 return strcmp(name, kernel_symbol_name(sym));
318 }
319
find_exported_symbol_in_section(const struct symsearch * syms,struct module * owner,struct find_symbol_arg * fsa)320 static bool find_exported_symbol_in_section(const struct symsearch *syms,
321 struct module *owner,
322 struct find_symbol_arg *fsa)
323 {
324 struct kernel_symbol *sym;
325
326 if (!fsa->gplok && syms->license == GPL_ONLY)
327 return false;
328
329 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
330 sizeof(struct kernel_symbol), cmp_name);
331 if (!sym)
332 return false;
333
334 fsa->owner = owner;
335 fsa->crc = symversion(syms->crcs, sym - syms->start);
336 fsa->sym = sym;
337 fsa->license = syms->license;
338
339 return true;
340 }
341
342 /*
343 * Find an exported symbol and return it, along with, (optional) crc and
344 * (optional) module which owns it. Needs preempt disabled or module_mutex.
345 */
find_symbol(struct find_symbol_arg * fsa)346 bool find_symbol(struct find_symbol_arg *fsa)
347 {
348 static const struct symsearch arr[] = {
349 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
350 NOT_GPL_ONLY },
351 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
352 __start___kcrctab_gpl,
353 GPL_ONLY },
354 };
355 struct module *mod;
356 unsigned int i;
357
358 module_assert_mutex_or_preempt();
359
360 for (i = 0; i < ARRAY_SIZE(arr); i++)
361 if (find_exported_symbol_in_section(&arr[i], NULL, fsa))
362 return true;
363
364 list_for_each_entry_rcu(mod, &modules, list,
365 lockdep_is_held(&module_mutex)) {
366 struct symsearch arr[] = {
367 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
368 NOT_GPL_ONLY },
369 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
370 mod->gpl_crcs,
371 GPL_ONLY },
372 };
373
374 if (mod->state == MODULE_STATE_UNFORMED)
375 continue;
376
377 for (i = 0; i < ARRAY_SIZE(arr); i++)
378 if (find_exported_symbol_in_section(&arr[i], mod, fsa))
379 return true;
380 }
381
382 pr_debug("Failed to find symbol %s\n", fsa->name);
383 return false;
384 }
385
386 /*
387 * Search for module by name: must hold module_mutex (or preempt disabled
388 * for read-only access).
389 */
find_module_all(const char * name,size_t len,bool even_unformed)390 struct module *find_module_all(const char *name, size_t len,
391 bool even_unformed)
392 {
393 struct module *mod;
394
395 module_assert_mutex_or_preempt();
396
397 list_for_each_entry_rcu(mod, &modules, list,
398 lockdep_is_held(&module_mutex)) {
399 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
400 continue;
401 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
402 return mod;
403 }
404 return NULL;
405 }
406
find_module(const char * name)407 struct module *find_module(const char *name)
408 {
409 return find_module_all(name, strlen(name), false);
410 }
411
412 #ifdef CONFIG_SMP
413
mod_percpu(struct module * mod)414 static inline void __percpu *mod_percpu(struct module *mod)
415 {
416 return mod->percpu;
417 }
418
percpu_modalloc(struct module * mod,struct load_info * info)419 static int percpu_modalloc(struct module *mod, struct load_info *info)
420 {
421 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
422 unsigned long align = pcpusec->sh_addralign;
423
424 if (!pcpusec->sh_size)
425 return 0;
426
427 if (align > PAGE_SIZE) {
428 pr_warn("%s: per-cpu alignment %li > %li\n",
429 mod->name, align, PAGE_SIZE);
430 align = PAGE_SIZE;
431 }
432
433 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
434 if (!mod->percpu) {
435 pr_warn("%s: Could not allocate %lu bytes percpu data\n",
436 mod->name, (unsigned long)pcpusec->sh_size);
437 return -ENOMEM;
438 }
439 mod->percpu_size = pcpusec->sh_size;
440 return 0;
441 }
442
percpu_modfree(struct module * mod)443 static void percpu_modfree(struct module *mod)
444 {
445 free_percpu(mod->percpu);
446 }
447
find_pcpusec(struct load_info * info)448 static unsigned int find_pcpusec(struct load_info *info)
449 {
450 return find_sec(info, ".data..percpu");
451 }
452
percpu_modcopy(struct module * mod,const void * from,unsigned long size)453 static void percpu_modcopy(struct module *mod,
454 const void *from, unsigned long size)
455 {
456 int cpu;
457
458 for_each_possible_cpu(cpu)
459 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
460 }
461
__is_module_percpu_address(unsigned long addr,unsigned long * can_addr)462 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
463 {
464 struct module *mod;
465 unsigned int cpu;
466
467 preempt_disable();
468
469 list_for_each_entry_rcu(mod, &modules, list) {
470 if (mod->state == MODULE_STATE_UNFORMED)
471 continue;
472 if (!mod->percpu_size)
473 continue;
474 for_each_possible_cpu(cpu) {
475 void *start = per_cpu_ptr(mod->percpu, cpu);
476 void *va = (void *)addr;
477
478 if (va >= start && va < start + mod->percpu_size) {
479 if (can_addr) {
480 *can_addr = (unsigned long) (va - start);
481 *can_addr += (unsigned long)
482 per_cpu_ptr(mod->percpu,
483 get_boot_cpu_id());
484 }
485 preempt_enable();
486 return true;
487 }
488 }
489 }
490
491 preempt_enable();
492 return false;
493 }
494
495 /**
496 * is_module_percpu_address() - test whether address is from module static percpu
497 * @addr: address to test
498 *
499 * Test whether @addr belongs to module static percpu area.
500 *
501 * Return: %true if @addr is from module static percpu area
502 */
is_module_percpu_address(unsigned long addr)503 bool is_module_percpu_address(unsigned long addr)
504 {
505 return __is_module_percpu_address(addr, NULL);
506 }
507
508 #else /* ... !CONFIG_SMP */
509
mod_percpu(struct module * mod)510 static inline void __percpu *mod_percpu(struct module *mod)
511 {
512 return NULL;
513 }
percpu_modalloc(struct module * mod,struct load_info * info)514 static int percpu_modalloc(struct module *mod, struct load_info *info)
515 {
516 /* UP modules shouldn't have this section: ENOMEM isn't quite right */
517 if (info->sechdrs[info->index.pcpu].sh_size != 0)
518 return -ENOMEM;
519 return 0;
520 }
percpu_modfree(struct module * mod)521 static inline void percpu_modfree(struct module *mod)
522 {
523 }
find_pcpusec(struct load_info * info)524 static unsigned int find_pcpusec(struct load_info *info)
525 {
526 return 0;
527 }
percpu_modcopy(struct module * mod,const void * from,unsigned long size)528 static inline void percpu_modcopy(struct module *mod,
529 const void *from, unsigned long size)
530 {
531 /* pcpusec should be 0, and size of that section should be 0. */
532 BUG_ON(size != 0);
533 }
is_module_percpu_address(unsigned long addr)534 bool is_module_percpu_address(unsigned long addr)
535 {
536 return false;
537 }
538
__is_module_percpu_address(unsigned long addr,unsigned long * can_addr)539 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
540 {
541 return false;
542 }
543
544 #endif /* CONFIG_SMP */
545
546 #define MODINFO_ATTR(field) \
547 static void setup_modinfo_##field(struct module *mod, const char *s) \
548 { \
549 mod->field = kstrdup(s, GFP_KERNEL); \
550 } \
551 static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
552 struct module_kobject *mk, char *buffer) \
553 { \
554 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
555 } \
556 static int modinfo_##field##_exists(struct module *mod) \
557 { \
558 return mod->field != NULL; \
559 } \
560 static void free_modinfo_##field(struct module *mod) \
561 { \
562 kfree(mod->field); \
563 mod->field = NULL; \
564 } \
565 static struct module_attribute modinfo_##field = { \
566 .attr = { .name = __stringify(field), .mode = 0444 }, \
567 .show = show_modinfo_##field, \
568 .setup = setup_modinfo_##field, \
569 .test = modinfo_##field##_exists, \
570 .free = free_modinfo_##field, \
571 };
572
573 MODINFO_ATTR(version);
574 MODINFO_ATTR(srcversion);
575 MODINFO_ATTR(scmversion);
576
577 static struct {
578 char name[MODULE_NAME_LEN + 1];
579 char taints[MODULE_FLAGS_BUF_SIZE];
580 } last_unloaded_module;
581
582 #ifdef CONFIG_MODULE_UNLOAD
583
584 EXPORT_TRACEPOINT_SYMBOL(module_get);
585
586 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
587 #define MODULE_REF_BASE 1
588
589 /* Init the unload section of the module. */
module_unload_init(struct module * mod)590 static int module_unload_init(struct module *mod)
591 {
592 /*
593 * Initialize reference counter to MODULE_REF_BASE.
594 * refcnt == 0 means module is going.
595 */
596 atomic_set(&mod->refcnt, MODULE_REF_BASE);
597
598 INIT_LIST_HEAD(&mod->source_list);
599 INIT_LIST_HEAD(&mod->target_list);
600
601 /* Hold reference count during initialization. */
602 atomic_inc(&mod->refcnt);
603
604 return 0;
605 }
606
607 /* Does a already use b? */
already_uses(struct module * a,struct module * b)608 static int already_uses(struct module *a, struct module *b)
609 {
610 struct module_use *use;
611
612 list_for_each_entry(use, &b->source_list, source_list) {
613 if (use->source == a)
614 return 1;
615 }
616 pr_debug("%s does not use %s!\n", a->name, b->name);
617 return 0;
618 }
619
620 /*
621 * Module a uses b
622 * - we add 'a' as a "source", 'b' as a "target" of module use
623 * - the module_use is added to the list of 'b' sources (so
624 * 'b' can walk the list to see who sourced them), and of 'a'
625 * targets (so 'a' can see what modules it targets).
626 */
add_module_usage(struct module * a,struct module * b)627 static int add_module_usage(struct module *a, struct module *b)
628 {
629 struct module_use *use;
630
631 pr_debug("Allocating new usage for %s.\n", a->name);
632 use = kmalloc(sizeof(*use), GFP_ATOMIC);
633 if (!use)
634 return -ENOMEM;
635
636 use->source = a;
637 use->target = b;
638 list_add(&use->source_list, &b->source_list);
639 list_add(&use->target_list, &a->target_list);
640 return 0;
641 }
642
643 /* Module a uses b: caller needs module_mutex() */
ref_module(struct module * a,struct module * b)644 static int ref_module(struct module *a, struct module *b)
645 {
646 int err;
647
648 if (b == NULL || already_uses(a, b))
649 return 0;
650
651 /* If module isn't available, we fail. */
652 err = strong_try_module_get(b);
653 if (err)
654 return err;
655
656 err = add_module_usage(a, b);
657 if (err) {
658 module_put(b);
659 return err;
660 }
661 return 0;
662 }
663
664 /* Clear the unload stuff of the module. */
module_unload_free(struct module * mod)665 static void module_unload_free(struct module *mod)
666 {
667 struct module_use *use, *tmp;
668
669 mutex_lock(&module_mutex);
670 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
671 struct module *i = use->target;
672 pr_debug("%s unusing %s\n", mod->name, i->name);
673 module_put(i);
674 list_del(&use->source_list);
675 list_del(&use->target_list);
676 kfree(use);
677 }
678 mutex_unlock(&module_mutex);
679 }
680
681 #ifdef CONFIG_MODULE_FORCE_UNLOAD
try_force_unload(unsigned int flags)682 static inline int try_force_unload(unsigned int flags)
683 {
684 int ret = (flags & O_TRUNC);
685 if (ret)
686 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
687 return ret;
688 }
689 #else
try_force_unload(unsigned int flags)690 static inline int try_force_unload(unsigned int flags)
691 {
692 return 0;
693 }
694 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
695
696 /* Try to release refcount of module, 0 means success. */
try_release_module_ref(struct module * mod)697 static int try_release_module_ref(struct module *mod)
698 {
699 int ret;
700
701 /* Try to decrement refcnt which we set at loading */
702 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
703 BUG_ON(ret < 0);
704 if (ret)
705 /* Someone can put this right now, recover with checking */
706 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
707
708 return ret;
709 }
710
try_stop_module(struct module * mod,int flags,int * forced)711 static int try_stop_module(struct module *mod, int flags, int *forced)
712 {
713 /* If it's not unused, quit unless we're forcing. */
714 if (try_release_module_ref(mod) != 0) {
715 *forced = try_force_unload(flags);
716 if (!(*forced))
717 return -EWOULDBLOCK;
718 }
719
720 /* Mark it as dying. */
721 mod->state = MODULE_STATE_GOING;
722
723 return 0;
724 }
725
726 /**
727 * module_refcount() - return the refcount or -1 if unloading
728 * @mod: the module we're checking
729 *
730 * Return:
731 * -1 if the module is in the process of unloading
732 * otherwise the number of references in the kernel to the module
733 */
module_refcount(struct module * mod)734 int module_refcount(struct module *mod)
735 {
736 return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
737 }
738 EXPORT_SYMBOL(module_refcount);
739
740 /* This exists whether we can unload or not */
741 static void free_module(struct module *mod);
742
SYSCALL_DEFINE2(delete_module,const char __user *,name_user,unsigned int,flags)743 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
744 unsigned int, flags)
745 {
746 struct module *mod;
747 char name[MODULE_NAME_LEN];
748 char buf[MODULE_FLAGS_BUF_SIZE];
749 int ret, len, forced = 0;
750
751 if (!capable(CAP_SYS_MODULE) || modules_disabled)
752 return -EPERM;
753
754 len = strncpy_from_user(name, name_user, MODULE_NAME_LEN);
755 if (len == 0 || len == MODULE_NAME_LEN)
756 return -ENOENT;
757 if (len < 0)
758 return len;
759
760 audit_log_kern_module(name);
761
762 if (mutex_lock_interruptible(&module_mutex) != 0)
763 return -EINTR;
764
765 mod = find_module(name);
766 if (!mod) {
767 ret = -ENOENT;
768 goto out;
769 }
770
771 if (!list_empty(&mod->source_list)) {
772 /* Other modules depend on us: get rid of them first. */
773 ret = -EWOULDBLOCK;
774 goto out;
775 }
776
777 /* Doing init or already dying? */
778 if (mod->state != MODULE_STATE_LIVE) {
779 /* FIXME: if (force), slam module count damn the torpedoes */
780 pr_debug("%s already dying\n", mod->name);
781 ret = -EBUSY;
782 goto out;
783 }
784
785 /* If it has an init func, it must have an exit func to unload */
786 if (mod->init && !mod->exit) {
787 forced = try_force_unload(flags);
788 if (!forced) {
789 /* This module can't be removed */
790 ret = -EBUSY;
791 goto out;
792 }
793 }
794
795 ret = try_stop_module(mod, flags, &forced);
796 if (ret != 0)
797 goto out;
798
799 mutex_unlock(&module_mutex);
800 /* Final destruction now no one is using it. */
801 if (mod->exit != NULL)
802 mod->exit();
803 blocking_notifier_call_chain(&module_notify_list,
804 MODULE_STATE_GOING, mod);
805 klp_module_going(mod);
806 ftrace_release_mod(mod);
807
808 async_synchronize_full();
809
810 /* Store the name and taints of the last unloaded module for diagnostic purposes */
811 strscpy(last_unloaded_module.name, mod->name, sizeof(last_unloaded_module.name));
812 strscpy(last_unloaded_module.taints, module_flags(mod, buf, false), sizeof(last_unloaded_module.taints));
813
814 free_module(mod);
815 /* someone could wait for the module in add_unformed_module() */
816 wake_up_all(&module_wq);
817 return 0;
818 out:
819 mutex_unlock(&module_mutex);
820 return ret;
821 }
822
__symbol_put(const char * symbol)823 void __symbol_put(const char *symbol)
824 {
825 struct find_symbol_arg fsa = {
826 .name = symbol,
827 .gplok = true,
828 };
829
830 preempt_disable();
831 BUG_ON(!find_symbol(&fsa));
832 module_put(fsa.owner);
833 preempt_enable();
834 }
835 EXPORT_SYMBOL(__symbol_put);
836
837 /* Note this assumes addr is a function, which it currently always is. */
symbol_put_addr(void * addr)838 void symbol_put_addr(void *addr)
839 {
840 struct module *modaddr;
841 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
842
843 if (core_kernel_text(a))
844 return;
845
846 /*
847 * Even though we hold a reference on the module; we still need to
848 * disable preemption in order to safely traverse the data structure.
849 */
850 preempt_disable();
851 modaddr = __module_text_address(a);
852 BUG_ON(!modaddr);
853 module_put(modaddr);
854 preempt_enable();
855 }
856 EXPORT_SYMBOL_GPL(symbol_put_addr);
857
show_refcnt(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)858 static ssize_t show_refcnt(struct module_attribute *mattr,
859 struct module_kobject *mk, char *buffer)
860 {
861 return sprintf(buffer, "%i\n", module_refcount(mk->mod));
862 }
863
864 static struct module_attribute modinfo_refcnt =
865 __ATTR(refcnt, 0444, show_refcnt, NULL);
866
__module_get(struct module * module)867 void __module_get(struct module *module)
868 {
869 if (module) {
870 atomic_inc(&module->refcnt);
871 trace_module_get(module, _RET_IP_);
872 }
873 }
874 EXPORT_SYMBOL(__module_get);
875
try_module_get(struct module * module)876 bool try_module_get(struct module *module)
877 {
878 bool ret = true;
879
880 if (module) {
881 /* Note: here, we can fail to get a reference */
882 if (likely(module_is_live(module) &&
883 atomic_inc_not_zero(&module->refcnt) != 0))
884 trace_module_get(module, _RET_IP_);
885 else
886 ret = false;
887 }
888 return ret;
889 }
890 EXPORT_SYMBOL(try_module_get);
891
module_put(struct module * module)892 void module_put(struct module *module)
893 {
894 int ret;
895
896 if (module) {
897 ret = atomic_dec_if_positive(&module->refcnt);
898 WARN_ON(ret < 0); /* Failed to put refcount */
899 trace_module_put(module, _RET_IP_);
900 }
901 }
902 EXPORT_SYMBOL(module_put);
903
904 #else /* !CONFIG_MODULE_UNLOAD */
module_unload_free(struct module * mod)905 static inline void module_unload_free(struct module *mod)
906 {
907 }
908
ref_module(struct module * a,struct module * b)909 static int ref_module(struct module *a, struct module *b)
910 {
911 return strong_try_module_get(b);
912 }
913
module_unload_init(struct module * mod)914 static inline int module_unload_init(struct module *mod)
915 {
916 return 0;
917 }
918 #endif /* CONFIG_MODULE_UNLOAD */
919
module_flags_taint(unsigned long taints,char * buf)920 size_t module_flags_taint(unsigned long taints, char *buf)
921 {
922 size_t l = 0;
923 int i;
924
925 for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
926 if (taint_flags[i].module && test_bit(i, &taints))
927 buf[l++] = taint_flags[i].c_true;
928 }
929
930 return l;
931 }
932
show_initstate(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)933 static ssize_t show_initstate(struct module_attribute *mattr,
934 struct module_kobject *mk, char *buffer)
935 {
936 const char *state = "unknown";
937
938 switch (mk->mod->state) {
939 case MODULE_STATE_LIVE:
940 state = "live";
941 break;
942 case MODULE_STATE_COMING:
943 state = "coming";
944 break;
945 case MODULE_STATE_GOING:
946 state = "going";
947 break;
948 default:
949 BUG();
950 }
951 return sprintf(buffer, "%s\n", state);
952 }
953
954 static struct module_attribute modinfo_initstate =
955 __ATTR(initstate, 0444, show_initstate, NULL);
956
store_uevent(struct module_attribute * mattr,struct module_kobject * mk,const char * buffer,size_t count)957 static ssize_t store_uevent(struct module_attribute *mattr,
958 struct module_kobject *mk,
959 const char *buffer, size_t count)
960 {
961 int rc;
962
963 rc = kobject_synth_uevent(&mk->kobj, buffer, count);
964 return rc ? rc : count;
965 }
966
967 struct module_attribute module_uevent =
968 __ATTR(uevent, 0200, NULL, store_uevent);
969
show_coresize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)970 static ssize_t show_coresize(struct module_attribute *mattr,
971 struct module_kobject *mk, char *buffer)
972 {
973 unsigned int size = mk->mod->mem[MOD_TEXT].size;
974
975 if (!IS_ENABLED(CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC)) {
976 for_class_mod_mem_type(type, core_data)
977 size += mk->mod->mem[type].size;
978 }
979 return sprintf(buffer, "%u\n", size);
980 }
981
982 static struct module_attribute modinfo_coresize =
983 __ATTR(coresize, 0444, show_coresize, NULL);
984
985 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
show_datasize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)986 static ssize_t show_datasize(struct module_attribute *mattr,
987 struct module_kobject *mk, char *buffer)
988 {
989 unsigned int size = 0;
990
991 for_class_mod_mem_type(type, core_data)
992 size += mk->mod->mem[type].size;
993 return sprintf(buffer, "%u\n", size);
994 }
995
996 static struct module_attribute modinfo_datasize =
997 __ATTR(datasize, 0444, show_datasize, NULL);
998 #endif
999
show_initsize(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)1000 static ssize_t show_initsize(struct module_attribute *mattr,
1001 struct module_kobject *mk, char *buffer)
1002 {
1003 unsigned int size = 0;
1004
1005 for_class_mod_mem_type(type, init)
1006 size += mk->mod->mem[type].size;
1007 return sprintf(buffer, "%u\n", size);
1008 }
1009
1010 static struct module_attribute modinfo_initsize =
1011 __ATTR(initsize, 0444, show_initsize, NULL);
1012
show_taint(struct module_attribute * mattr,struct module_kobject * mk,char * buffer)1013 static ssize_t show_taint(struct module_attribute *mattr,
1014 struct module_kobject *mk, char *buffer)
1015 {
1016 size_t l;
1017
1018 l = module_flags_taint(mk->mod->taints, buffer);
1019 buffer[l++] = '\n';
1020 return l;
1021 }
1022
1023 static struct module_attribute modinfo_taint =
1024 __ATTR(taint, 0444, show_taint, NULL);
1025
1026 struct module_attribute *modinfo_attrs[] = {
1027 &module_uevent,
1028 &modinfo_version,
1029 &modinfo_srcversion,
1030 &modinfo_scmversion,
1031 &modinfo_initstate,
1032 &modinfo_coresize,
1033 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
1034 &modinfo_datasize,
1035 #endif
1036 &modinfo_initsize,
1037 &modinfo_taint,
1038 #ifdef CONFIG_MODULE_UNLOAD
1039 &modinfo_refcnt,
1040 #endif
1041 NULL,
1042 };
1043
1044 size_t modinfo_attrs_count = ARRAY_SIZE(modinfo_attrs);
1045
1046 static const char vermagic[] = VERMAGIC_STRING;
1047
try_to_force_load(struct module * mod,const char * reason)1048 int try_to_force_load(struct module *mod, const char *reason)
1049 {
1050 #ifdef CONFIG_MODULE_FORCE_LOAD
1051 if (!test_taint(TAINT_FORCED_MODULE))
1052 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1053 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1054 return 0;
1055 #else
1056 return -ENOEXEC;
1057 #endif
1058 }
1059
1060 /* Parse tag=value strings from .modinfo section */
module_next_tag_pair(char * string,unsigned long * secsize)1061 char *module_next_tag_pair(char *string, unsigned long *secsize)
1062 {
1063 /* Skip non-zero chars */
1064 while (string[0]) {
1065 string++;
1066 if ((*secsize)-- <= 1)
1067 return NULL;
1068 }
1069
1070 /* Skip any zero padding. */
1071 while (!string[0]) {
1072 string++;
1073 if ((*secsize)-- <= 1)
1074 return NULL;
1075 }
1076 return string;
1077 }
1078
get_next_modinfo(const struct load_info * info,const char * tag,char * prev)1079 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1080 char *prev)
1081 {
1082 char *p;
1083 unsigned int taglen = strlen(tag);
1084 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
1085 unsigned long size = infosec->sh_size;
1086
1087 /*
1088 * get_modinfo() calls made before rewrite_section_headers()
1089 * must use sh_offset, as sh_addr isn't set!
1090 */
1091 char *modinfo = (char *)info->hdr + infosec->sh_offset;
1092
1093 if (prev) {
1094 size -= prev - modinfo;
1095 modinfo = module_next_tag_pair(prev, &size);
1096 }
1097
1098 for (p = modinfo; p; p = module_next_tag_pair(p, &size)) {
1099 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
1100 return p + taglen + 1;
1101 }
1102 return NULL;
1103 }
1104
get_modinfo(const struct load_info * info,const char * tag)1105 static char *get_modinfo(const struct load_info *info, const char *tag)
1106 {
1107 return get_next_modinfo(info, tag, NULL);
1108 }
1109
verify_namespace_is_imported(const struct load_info * info,const struct kernel_symbol * sym,struct module * mod)1110 static int verify_namespace_is_imported(const struct load_info *info,
1111 const struct kernel_symbol *sym,
1112 struct module *mod)
1113 {
1114 const char *namespace;
1115 char *imported_namespace;
1116
1117 namespace = kernel_symbol_namespace(sym);
1118 if (namespace && namespace[0]) {
1119 for_each_modinfo_entry(imported_namespace, info, "import_ns") {
1120 if (strcmp(namespace, imported_namespace) == 0)
1121 return 0;
1122 }
1123 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1124 pr_warn(
1125 #else
1126 pr_err(
1127 #endif
1128 "%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1129 mod->name, kernel_symbol_name(sym), namespace);
1130 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1131 return -EINVAL;
1132 #endif
1133 }
1134 return 0;
1135 }
1136
inherit_taint(struct module * mod,struct module * owner,const char * name)1137 static bool inherit_taint(struct module *mod, struct module *owner, const char *name)
1138 {
1139 if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1140 return true;
1141
1142 if (mod->using_gplonly_symbols) {
1143 pr_err("%s: module using GPL-only symbols uses symbols %s from proprietary module %s.\n",
1144 mod->name, name, owner->name);
1145 return false;
1146 }
1147
1148 if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1149 pr_warn("%s: module uses symbols %s from proprietary module %s, inheriting taint.\n",
1150 mod->name, name, owner->name);
1151 set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1152 }
1153 return true;
1154 }
1155
1156 #ifdef CONFIG_TRIM_UNUSED_KSYMS
is_permitted_symbol_import(const char * name)1157 static bool is_permitted_symbol_import(const char *name)
1158 {
1159 return bsearch(name, permitted_symbol_imports,
1160 permitted_symbol_imports_count,
1161 sizeof(const char *), cmp_string) != NULL;
1162 }
1163 #endif
1164
1165 /* Resolve a symbol for this module. I.e. if we find one, record usage. */
resolve_symbol(struct module * mod,const struct load_info * info,const char * name,char ownername[])1166 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1167 const struct load_info *info,
1168 const char *name,
1169 char ownername[])
1170 {
1171 #ifdef CONFIG_TRIM_UNUSED_KSYMS
1172 bool is_vendor_module;
1173 bool is_vendor_exported_symbol;
1174 #endif
1175 struct find_symbol_arg fsa = {
1176 .name = name,
1177 .gplok = !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)),
1178 .warn = true,
1179 };
1180 int err;
1181
1182 /*
1183 * The module_mutex should not be a heavily contended lock;
1184 * if we get the occasional sleep here, we'll go an extra iteration
1185 * in the wait_event_interruptible(), which is harmless.
1186 */
1187 sched_annotate_sleep();
1188 mutex_lock(&module_mutex);
1189 if (!find_symbol(&fsa))
1190 goto unlock;
1191
1192 if (fsa.license == GPL_ONLY)
1193 mod->using_gplonly_symbols = true;
1194
1195 if (!inherit_taint(mod, fsa.owner, name)) {
1196 fsa.sym = NULL;
1197 goto getname;
1198 }
1199
1200 if (!check_version(info, name, mod, fsa.crc)) {
1201 fsa.sym = ERR_PTR(-EINVAL);
1202 goto getname;
1203 }
1204
1205 err = verify_namespace_is_imported(info, fsa.sym, mod);
1206 if (err) {
1207 fsa.sym = ERR_PTR(err);
1208 goto getname;
1209 }
1210
1211 /*
1212 * ANDROID GKI
1213 *
1214 * Vendor (i.e., unsigned) modules are only permitted to use:
1215 *
1216 * 1. symbols exported by other vendor (unsigned) modules
1217 * 2. symbols which are permitted explicitly
1218 */
1219 #ifdef CONFIG_TRIM_UNUSED_KSYMS
1220 is_vendor_module = !mod->sig_ok;
1221 is_vendor_exported_symbol = fsa.owner && !fsa.owner->sig_ok;
1222
1223 if (is_vendor_module &&
1224 !is_vendor_exported_symbol &&
1225 !is_permitted_symbol_import(name)) {
1226 fsa.sym = ERR_PTR(-EACCES);
1227 goto getname;
1228 }
1229 #endif
1230
1231 err = ref_module(mod, fsa.owner);
1232 if (err) {
1233 fsa.sym = ERR_PTR(err);
1234 goto getname;
1235 }
1236
1237 getname:
1238 /* We must make copy under the lock if we failed to get ref. */
1239 strncpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
1240 unlock:
1241 mutex_unlock(&module_mutex);
1242 return fsa.sym;
1243 }
1244
1245 static const struct kernel_symbol *
resolve_symbol_wait(struct module * mod,const struct load_info * info,const char * name)1246 resolve_symbol_wait(struct module *mod,
1247 const struct load_info *info,
1248 const char *name)
1249 {
1250 const struct kernel_symbol *ksym;
1251 char owner[MODULE_NAME_LEN];
1252
1253 if (wait_event_interruptible_timeout(module_wq,
1254 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1255 || PTR_ERR(ksym) != -EBUSY,
1256 30 * HZ) <= 0) {
1257 pr_warn("%s: gave up waiting for init of module %s.\n",
1258 mod->name, owner);
1259 }
1260 return ksym;
1261 }
1262
module_arch_cleanup(struct module * mod)1263 void __weak module_arch_cleanup(struct module *mod)
1264 {
1265 }
1266
module_arch_freeing_init(struct module * mod)1267 void __weak module_arch_freeing_init(struct module *mod)
1268 {
1269 }
1270
module_memory_alloc(struct module * mod,enum mod_mem_type type)1271 static int module_memory_alloc(struct module *mod, enum mod_mem_type type)
1272 {
1273 unsigned int size = PAGE_ALIGN(mod->mem[type].size);
1274 enum execmem_type execmem_type;
1275 void *ptr;
1276
1277 mod->mem[type].size = size;
1278
1279 if (mod_mem_type_is_data(type))
1280 execmem_type = EXECMEM_MODULE_DATA;
1281 else
1282 execmem_type = EXECMEM_MODULE_TEXT;
1283
1284 ptr = execmem_alloc(execmem_type, size);
1285 if (!ptr)
1286 return -ENOMEM;
1287
1288 /*
1289 * The pointer to these blocks of memory are stored on the module
1290 * structure and we keep that around so long as the module is
1291 * around. We only free that memory when we unload the module.
1292 * Just mark them as not being a leak then. The .init* ELF
1293 * sections *do* get freed after boot so we *could* treat them
1294 * slightly differently with kmemleak_ignore() and only grey
1295 * them out as they work as typical memory allocations which
1296 * *do* eventually get freed, but let's just keep things simple
1297 * and avoid *any* false positives.
1298 */
1299 kmemleak_not_leak(ptr);
1300
1301 memset(ptr, 0, size);
1302 mod->mem[type].base = ptr;
1303
1304 return 0;
1305 }
1306
module_memory_free(struct module * mod,enum mod_mem_type type)1307 static void module_memory_free(struct module *mod, enum mod_mem_type type)
1308 {
1309 execmem_free(mod->mem[type].base);
1310 }
1311
free_mod_mem(struct module * mod)1312 static void free_mod_mem(struct module *mod)
1313 {
1314 trace_android_vh_free_mod_mem(mod);
1315 for_each_mod_mem_type(type) {
1316 struct module_memory *mod_mem = &mod->mem[type];
1317
1318 if (type == MOD_DATA)
1319 continue;
1320
1321 /* Free lock-classes; relies on the preceding sync_rcu(). */
1322 lockdep_free_key_range(mod_mem->base, mod_mem->size);
1323 if (mod_mem->size)
1324 module_memory_free(mod, type);
1325 }
1326
1327 /* MOD_DATA hosts mod, so free it at last */
1328 lockdep_free_key_range(mod->mem[MOD_DATA].base, mod->mem[MOD_DATA].size);
1329 module_memory_free(mod, MOD_DATA);
1330 }
1331
1332 /* Free a module, remove from lists, etc. */
free_module(struct module * mod)1333 static void free_module(struct module *mod)
1334 {
1335 trace_module_free(mod);
1336
1337 codetag_unload_module(mod);
1338
1339 mod_sysfs_teardown(mod);
1340
1341 /*
1342 * We leave it in list to prevent duplicate loads, but make sure
1343 * that noone uses it while it's being deconstructed.
1344 */
1345 mutex_lock(&module_mutex);
1346 mod->state = MODULE_STATE_UNFORMED;
1347 mutex_unlock(&module_mutex);
1348
1349 /* Arch-specific cleanup. */
1350 module_arch_cleanup(mod);
1351
1352 /* Module unload stuff */
1353 module_unload_free(mod);
1354
1355 /* Free any allocated parameters. */
1356 destroy_params(mod->kp, mod->num_kp);
1357
1358 if (is_livepatch_module(mod))
1359 free_module_elf(mod);
1360
1361 /* Now we can delete it from the lists */
1362 mutex_lock(&module_mutex);
1363 /* Unlink carefully: kallsyms could be walking list. */
1364 list_del_rcu(&mod->list);
1365 mod_tree_remove(mod);
1366 /* Remove this module from bug list, this uses list_del_rcu */
1367 module_bug_cleanup(mod);
1368 /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
1369 synchronize_rcu();
1370 if (try_add_tainted_module(mod))
1371 pr_err("%s: adding tainted module to the unloaded tainted modules list failed.\n",
1372 mod->name);
1373 mutex_unlock(&module_mutex);
1374
1375 /* This may be empty, but that's OK */
1376 module_arch_freeing_init(mod);
1377 kfree(mod->args);
1378 percpu_modfree(mod);
1379
1380 free_mod_mem(mod);
1381 }
1382
__symbol_get(const char * symbol)1383 void *__symbol_get(const char *symbol)
1384 {
1385 struct find_symbol_arg fsa = {
1386 .name = symbol,
1387 .gplok = true,
1388 .warn = true,
1389 };
1390
1391 preempt_disable();
1392 if (!find_symbol(&fsa))
1393 goto fail;
1394 if (fsa.license != GPL_ONLY) {
1395 pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n",
1396 symbol);
1397 goto fail;
1398 }
1399 if (strong_try_module_get(fsa.owner))
1400 goto fail;
1401 preempt_enable();
1402 return (void *)kernel_symbol_value(fsa.sym);
1403 fail:
1404 preempt_enable();
1405 return NULL;
1406 }
1407 EXPORT_SYMBOL_GPL(__symbol_get);
1408
1409 #ifdef CONFIG_MODULE_SIG_PROTECT
is_protected_symbol_export(const char * name)1410 static bool is_protected_symbol_export(const char *name)
1411 {
1412 return bsearch(name, protected_symbol_exports,
1413 protected_symbol_exports_count,
1414 sizeof(const char *), cmp_string) != NULL;
1415 }
1416 #endif
1417
1418 /*
1419 * Ensure that an exported symbol [global namespace] does not already exist
1420 * in the kernel or in some other module's exported symbol table.
1421 *
1422 * You must hold the module_mutex.
1423 */
verify_exported_symbols(struct module * mod)1424 static int verify_exported_symbols(struct module *mod)
1425 {
1426 unsigned int i;
1427 const struct kernel_symbol *s;
1428 struct {
1429 const struct kernel_symbol *sym;
1430 unsigned int num;
1431 } arr[] = {
1432 { mod->syms, mod->num_syms },
1433 { mod->gpl_syms, mod->num_gpl_syms },
1434 };
1435
1436 for (i = 0; i < ARRAY_SIZE(arr); i++) {
1437 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1438 struct find_symbol_arg fsa = {
1439 .name = kernel_symbol_name(s),
1440 .gplok = true,
1441 };
1442 if (find_symbol(&fsa)) {
1443 pr_err("%s: exports duplicate symbol %s"
1444 " (owned by %s)\n",
1445 mod->name, kernel_symbol_name(s),
1446 module_name(fsa.owner));
1447 return -ENOEXEC;
1448 }
1449 #ifdef CONFIG_MODULE_SIG_PROTECT
1450 if (!mod->sig_ok && is_protected_symbol_export(kernel_symbol_name(s))) {
1451 pr_err("%s: exports protected symbol %s\n",
1452 mod->name, kernel_symbol_name(s));
1453 return -EACCES;
1454 }
1455 #endif
1456 }
1457 }
1458 return 0;
1459 }
1460
ignore_undef_symbol(Elf_Half emachine,const char * name)1461 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
1462 {
1463 /*
1464 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
1465 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
1466 * i386 has a similar problem but may not deserve a fix.
1467 *
1468 * If we ever have to ignore many symbols, consider refactoring the code to
1469 * only warn if referenced by a relocation.
1470 */
1471 if (emachine == EM_386 || emachine == EM_X86_64)
1472 return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
1473 return false;
1474 }
1475
1476 /* Change all symbols so that st_value encodes the pointer directly. */
simplify_symbols(struct module * mod,const struct load_info * info)1477 static int simplify_symbols(struct module *mod, const struct load_info *info)
1478 {
1479 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1480 Elf_Sym *sym = (void *)symsec->sh_addr;
1481 unsigned long secbase;
1482 unsigned int i;
1483 int ret = 0;
1484 const struct kernel_symbol *ksym;
1485
1486 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1487 const char *name = info->strtab + sym[i].st_name;
1488
1489 switch (sym[i].st_shndx) {
1490 case SHN_COMMON:
1491 /* Ignore common symbols */
1492 if (!strncmp(name, "__gnu_lto", 9))
1493 break;
1494
1495 /*
1496 * We compiled with -fno-common. These are not
1497 * supposed to happen.
1498 */
1499 pr_debug("Common symbol: %s\n", name);
1500 pr_warn("%s: please compile with -fno-common\n",
1501 mod->name);
1502 ret = -ENOEXEC;
1503 break;
1504
1505 case SHN_ABS:
1506 /* Don't need to do anything */
1507 pr_debug("Absolute symbol: 0x%08lx %s\n",
1508 (long)sym[i].st_value, name);
1509 break;
1510
1511 case SHN_LIVEPATCH:
1512 /* Livepatch symbols are resolved by livepatch */
1513 break;
1514
1515 case SHN_UNDEF:
1516 ksym = resolve_symbol_wait(mod, info, name);
1517 /* Ok if resolved. */
1518 if (ksym && !IS_ERR(ksym)) {
1519 sym[i].st_value = kernel_symbol_value(ksym);
1520 break;
1521 }
1522
1523 /* Ok if weak or ignored. */
1524 if (!ksym &&
1525 (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
1526 ignore_undef_symbol(info->hdr->e_machine, name)))
1527 break;
1528
1529 if (PTR_ERR(ksym) == -EACCES) {
1530 ret = -EACCES;
1531 pr_warn("%s: Protected symbol: %s (err %d)\n",
1532 mod->name, name, ret);
1533 } else {
1534 ret = PTR_ERR(ksym) ?: -ENOENT;
1535 pr_warn("%s: Unknown symbol %s (err %d)\n",
1536 mod->name, name, ret);
1537 }
1538 break;
1539
1540 default:
1541 /* Divert to percpu allocation if a percpu var. */
1542 if (sym[i].st_shndx == info->index.pcpu)
1543 secbase = (unsigned long)mod_percpu(mod);
1544 else
1545 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1546 sym[i].st_value += secbase;
1547 break;
1548 }
1549 }
1550
1551 return ret;
1552 }
1553
apply_relocations(struct module * mod,const struct load_info * info)1554 static int apply_relocations(struct module *mod, const struct load_info *info)
1555 {
1556 unsigned int i;
1557 int err = 0;
1558
1559 /* Now do relocations. */
1560 for (i = 1; i < info->hdr->e_shnum; i++) {
1561 unsigned int infosec = info->sechdrs[i].sh_info;
1562
1563 /* Not a valid relocation section? */
1564 if (infosec >= info->hdr->e_shnum)
1565 continue;
1566
1567 /* Don't bother with non-allocated sections */
1568 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
1569 continue;
1570
1571 if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
1572 err = klp_apply_section_relocs(mod, info->sechdrs,
1573 info->secstrings,
1574 info->strtab,
1575 info->index.sym, i,
1576 NULL);
1577 else if (info->sechdrs[i].sh_type == SHT_REL)
1578 err = apply_relocate(info->sechdrs, info->strtab,
1579 info->index.sym, i, mod);
1580 else if (info->sechdrs[i].sh_type == SHT_RELA)
1581 err = apply_relocate_add(info->sechdrs, info->strtab,
1582 info->index.sym, i, mod);
1583 if (err < 0)
1584 break;
1585 }
1586 return err;
1587 }
1588
1589 /* Additional bytes needed by arch in front of individual sections */
arch_mod_section_prepend(struct module * mod,unsigned int section)1590 unsigned int __weak arch_mod_section_prepend(struct module *mod,
1591 unsigned int section)
1592 {
1593 /* default implementation just returns zero */
1594 return 0;
1595 }
1596
module_get_offset_and_type(struct module * mod,enum mod_mem_type type,Elf_Shdr * sechdr,unsigned int section)1597 long module_get_offset_and_type(struct module *mod, enum mod_mem_type type,
1598 Elf_Shdr *sechdr, unsigned int section)
1599 {
1600 long offset;
1601 long mask = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK) << SH_ENTSIZE_TYPE_SHIFT;
1602
1603 mod->mem[type].size += arch_mod_section_prepend(mod, section);
1604 offset = ALIGN(mod->mem[type].size, sechdr->sh_addralign ?: 1);
1605 mod->mem[type].size = offset + sechdr->sh_size;
1606
1607 WARN_ON_ONCE(offset & mask);
1608 return offset | mask;
1609 }
1610
module_init_layout_section(const char * sname)1611 bool module_init_layout_section(const char *sname)
1612 {
1613 #ifndef CONFIG_MODULE_UNLOAD
1614 if (module_exit_section(sname))
1615 return true;
1616 #endif
1617 return module_init_section(sname);
1618 }
1619
__layout_sections(struct module * mod,struct load_info * info,bool is_init)1620 static void __layout_sections(struct module *mod, struct load_info *info, bool is_init)
1621 {
1622 unsigned int m, i;
1623
1624 static const unsigned long masks[][2] = {
1625 /*
1626 * NOTE: all executable code must be the first section
1627 * in this array; otherwise modify the text_size
1628 * finder in the two loops below
1629 */
1630 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1631 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
1632 { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
1633 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1634 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1635 };
1636 static const int core_m_to_mem_type[] = {
1637 MOD_TEXT,
1638 MOD_RODATA,
1639 MOD_RO_AFTER_INIT,
1640 MOD_DATA,
1641 MOD_DATA,
1642 };
1643 static const int init_m_to_mem_type[] = {
1644 MOD_INIT_TEXT,
1645 MOD_INIT_RODATA,
1646 MOD_INVALID,
1647 MOD_INIT_DATA,
1648 MOD_INIT_DATA,
1649 };
1650
1651 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1652 enum mod_mem_type type = is_init ? init_m_to_mem_type[m] : core_m_to_mem_type[m];
1653
1654 for (i = 0; i < info->hdr->e_shnum; ++i) {
1655 Elf_Shdr *s = &info->sechdrs[i];
1656 const char *sname = info->secstrings + s->sh_name;
1657
1658 if ((s->sh_flags & masks[m][0]) != masks[m][0]
1659 || (s->sh_flags & masks[m][1])
1660 || s->sh_entsize != ~0UL
1661 || is_init != module_init_layout_section(sname))
1662 continue;
1663
1664 if (WARN_ON_ONCE(type == MOD_INVALID))
1665 continue;
1666
1667 /*
1668 * Do not allocate codetag memory as we load it into
1669 * preallocated contiguous memory.
1670 */
1671 if (codetag_needs_module_section(mod, sname, s->sh_size)) {
1672 /*
1673 * s->sh_entsize won't be used but populate the
1674 * type field to avoid confusion.
1675 */
1676 s->sh_entsize = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK)
1677 << SH_ENTSIZE_TYPE_SHIFT;
1678 continue;
1679 }
1680
1681 s->sh_entsize = module_get_offset_and_type(mod, type, s, i);
1682 pr_debug("\t%s\n", sname);
1683 }
1684 }
1685 }
1686
1687 /*
1688 * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1689 * might -- code, read-only data, read-write data, small data. Tally
1690 * sizes, and place the offsets into sh_entsize fields: high bit means it
1691 * belongs in init.
1692 */
layout_sections(struct module * mod,struct load_info * info)1693 static void layout_sections(struct module *mod, struct load_info *info)
1694 {
1695 unsigned int i;
1696
1697 for (i = 0; i < info->hdr->e_shnum; i++)
1698 info->sechdrs[i].sh_entsize = ~0UL;
1699
1700 pr_debug("Core section allocation order for %s:\n", mod->name);
1701 __layout_sections(mod, info, false);
1702
1703 pr_debug("Init section allocation order for %s:\n", mod->name);
1704 __layout_sections(mod, info, true);
1705 }
1706
module_license_taint_check(struct module * mod,const char * license)1707 static void module_license_taint_check(struct module *mod, const char *license)
1708 {
1709 if (!license)
1710 license = "unspecified";
1711
1712 if (!license_is_gpl_compatible(license)) {
1713 if (!test_taint(TAINT_PROPRIETARY_MODULE))
1714 pr_warn("%s: module license '%s' taints kernel.\n",
1715 mod->name, license);
1716 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
1717 LOCKDEP_NOW_UNRELIABLE);
1718 }
1719 }
1720
setup_modinfo(struct module * mod,struct load_info * info)1721 static void setup_modinfo(struct module *mod, struct load_info *info)
1722 {
1723 struct module_attribute *attr;
1724 int i;
1725
1726 for (i = 0; (attr = modinfo_attrs[i]); i++) {
1727 if (attr->setup)
1728 attr->setup(mod, get_modinfo(info, attr->attr.name));
1729 }
1730 }
1731
free_modinfo(struct module * mod)1732 static void free_modinfo(struct module *mod)
1733 {
1734 struct module_attribute *attr;
1735 int i;
1736
1737 for (i = 0; (attr = modinfo_attrs[i]); i++) {
1738 if (attr->free)
1739 attr->free(mod);
1740 }
1741 }
1742
module_init_section(const char * name)1743 bool __weak module_init_section(const char *name)
1744 {
1745 return strstarts(name, ".init");
1746 }
1747
module_exit_section(const char * name)1748 bool __weak module_exit_section(const char *name)
1749 {
1750 return strstarts(name, ".exit");
1751 }
1752
validate_section_offset(const struct load_info * info,Elf_Shdr * shdr)1753 static int validate_section_offset(const struct load_info *info, Elf_Shdr *shdr)
1754 {
1755 #if defined(CONFIG_64BIT)
1756 unsigned long long secend;
1757 #else
1758 unsigned long secend;
1759 #endif
1760
1761 /*
1762 * Check for both overflow and offset/size being
1763 * too large.
1764 */
1765 secend = shdr->sh_offset + shdr->sh_size;
1766 if (secend < shdr->sh_offset || secend > info->len)
1767 return -ENOEXEC;
1768
1769 return 0;
1770 }
1771
1772 /**
1773 * elf_validity_ehdr() - Checks an ELF header for module validity
1774 * @info: Load info containing the ELF header to check
1775 *
1776 * Checks whether an ELF header could belong to a valid module. Checks:
1777 *
1778 * * ELF header is within the data the user provided
1779 * * ELF magic is present
1780 * * It is relocatable (not final linked, not core file, etc.)
1781 * * The header's machine type matches what the architecture expects.
1782 * * Optional arch-specific hook for other properties
1783 * - module_elf_check_arch() is currently only used by PPC to check
1784 * ELF ABI version, but may be used by others in the future.
1785 *
1786 * Return: %0 if valid, %-ENOEXEC on failure.
1787 */
elf_validity_ehdr(const struct load_info * info)1788 static int elf_validity_ehdr(const struct load_info *info)
1789 {
1790 if (info->len < sizeof(*(info->hdr))) {
1791 pr_err("Invalid ELF header len %lu\n", info->len);
1792 return -ENOEXEC;
1793 }
1794 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
1795 pr_err("Invalid ELF header magic: != %s\n", ELFMAG);
1796 return -ENOEXEC;
1797 }
1798 if (info->hdr->e_type != ET_REL) {
1799 pr_err("Invalid ELF header type: %u != %u\n",
1800 info->hdr->e_type, ET_REL);
1801 return -ENOEXEC;
1802 }
1803 if (!elf_check_arch(info->hdr)) {
1804 pr_err("Invalid architecture in ELF header: %u\n",
1805 info->hdr->e_machine);
1806 return -ENOEXEC;
1807 }
1808 if (!module_elf_check_arch(info->hdr)) {
1809 pr_err("Invalid module architecture in ELF header: %u\n",
1810 info->hdr->e_machine);
1811 return -ENOEXEC;
1812 }
1813 return 0;
1814 }
1815
1816 /**
1817 * elf_validity_cache_sechdrs() - Cache section headers if valid
1818 * @info: Load info to compute section headers from
1819 *
1820 * Checks:
1821 *
1822 * * ELF header is valid (see elf_validity_ehdr())
1823 * * Section headers are the size we expect
1824 * * Section array fits in the user provided data
1825 * * Section index 0 is NULL
1826 * * Section contents are inbounds
1827 *
1828 * Then updates @info with a &load_info->sechdrs pointer if valid.
1829 *
1830 * Return: %0 if valid, negative error code if validation failed.
1831 */
elf_validity_cache_sechdrs(struct load_info * info)1832 static int elf_validity_cache_sechdrs(struct load_info *info)
1833 {
1834 Elf_Shdr *sechdrs;
1835 Elf_Shdr *shdr;
1836 int i;
1837 int err;
1838
1839 err = elf_validity_ehdr(info);
1840 if (err < 0)
1841 return err;
1842
1843 if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) {
1844 pr_err("Invalid ELF section header size\n");
1845 return -ENOEXEC;
1846 }
1847
1848 /*
1849 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
1850 * known and small. So e_shnum * sizeof(Elf_Shdr)
1851 * will not overflow unsigned long on any platform.
1852 */
1853 if (info->hdr->e_shoff >= info->len
1854 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
1855 info->len - info->hdr->e_shoff)) {
1856 pr_err("Invalid ELF section header overflow\n");
1857 return -ENOEXEC;
1858 }
1859
1860 sechdrs = (void *)info->hdr + info->hdr->e_shoff;
1861
1862 /*
1863 * The code assumes that section 0 has a length of zero and
1864 * an addr of zero, so check for it.
1865 */
1866 if (sechdrs[0].sh_type != SHT_NULL
1867 || sechdrs[0].sh_size != 0
1868 || sechdrs[0].sh_addr != 0) {
1869 pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n",
1870 sechdrs[0].sh_type);
1871 return -ENOEXEC;
1872 }
1873
1874 /* Validate contents are inbounds */
1875 for (i = 1; i < info->hdr->e_shnum; i++) {
1876 shdr = &sechdrs[i];
1877 switch (shdr->sh_type) {
1878 case SHT_NULL:
1879 case SHT_NOBITS:
1880 /* No contents, offset/size don't mean anything */
1881 continue;
1882 default:
1883 err = validate_section_offset(info, shdr);
1884 if (err < 0) {
1885 pr_err("Invalid ELF section in module (section %u type %u)\n",
1886 i, shdr->sh_type);
1887 return err;
1888 }
1889 }
1890 }
1891
1892 info->sechdrs = sechdrs;
1893
1894 return 0;
1895 }
1896
1897 /**
1898 * elf_validity_cache_secstrings() - Caches section names if valid
1899 * @info: Load info to cache section names from. Must have valid sechdrs.
1900 *
1901 * Specifically checks:
1902 *
1903 * * Section name table index is inbounds of section headers
1904 * * Section name table is not empty
1905 * * Section name table is NUL terminated
1906 * * All section name offsets are inbounds of the section
1907 *
1908 * Then updates @info with a &load_info->secstrings pointer if valid.
1909 *
1910 * Return: %0 if valid, negative error code if validation failed.
1911 */
elf_validity_cache_secstrings(struct load_info * info)1912 static int elf_validity_cache_secstrings(struct load_info *info)
1913 {
1914 Elf_Shdr *strhdr, *shdr;
1915 char *secstrings;
1916 int i;
1917
1918 /*
1919 * Verify if the section name table index is valid.
1920 */
1921 if (info->hdr->e_shstrndx == SHN_UNDEF
1922 || info->hdr->e_shstrndx >= info->hdr->e_shnum) {
1923 pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n",
1924 info->hdr->e_shstrndx, info->hdr->e_shstrndx,
1925 info->hdr->e_shnum);
1926 return -ENOEXEC;
1927 }
1928
1929 strhdr = &info->sechdrs[info->hdr->e_shstrndx];
1930
1931 /*
1932 * The section name table must be NUL-terminated, as required
1933 * by the spec. This makes strcmp and pr_* calls that access
1934 * strings in the section safe.
1935 */
1936 secstrings = (void *)info->hdr + strhdr->sh_offset;
1937 if (strhdr->sh_size == 0) {
1938 pr_err("empty section name table\n");
1939 return -ENOEXEC;
1940 }
1941 if (secstrings[strhdr->sh_size - 1] != '\0') {
1942 pr_err("ELF Spec violation: section name table isn't null terminated\n");
1943 return -ENOEXEC;
1944 }
1945
1946 for (i = 0; i < info->hdr->e_shnum; i++) {
1947 shdr = &info->sechdrs[i];
1948 /* SHT_NULL means sh_name has an undefined value */
1949 if (shdr->sh_type == SHT_NULL)
1950 continue;
1951 if (shdr->sh_name >= strhdr->sh_size) {
1952 pr_err("Invalid ELF section name in module (section %u type %u)\n",
1953 i, shdr->sh_type);
1954 return -ENOEXEC;
1955 }
1956 }
1957
1958 info->secstrings = secstrings;
1959 return 0;
1960 }
1961
1962 /**
1963 * elf_validity_cache_index_info() - Validate and cache modinfo section
1964 * @info: Load info to populate the modinfo index on.
1965 * Must have &load_info->sechdrs and &load_info->secstrings populated
1966 *
1967 * Checks that if there is a .modinfo section, it is unique.
1968 * Then, it caches its index in &load_info->index.info.
1969 * Finally, it tries to populate the name to improve error messages.
1970 *
1971 * Return: %0 if valid, %-ENOEXEC if multiple modinfo sections were found.
1972 */
elf_validity_cache_index_info(struct load_info * info)1973 static int elf_validity_cache_index_info(struct load_info *info)
1974 {
1975 int info_idx;
1976
1977 info_idx = find_any_unique_sec(info, ".modinfo");
1978
1979 if (info_idx == 0)
1980 /* Early return, no .modinfo */
1981 return 0;
1982
1983 if (info_idx < 0) {
1984 pr_err("Only one .modinfo section must exist.\n");
1985 return -ENOEXEC;
1986 }
1987
1988 info->index.info = info_idx;
1989 /* Try to find a name early so we can log errors with a module name */
1990 info->name = get_modinfo(info, "name");
1991
1992 return 0;
1993 }
1994
1995 /**
1996 * elf_validity_cache_index_mod() - Validates and caches this_module section
1997 * @info: Load info to cache this_module on.
1998 * Must have &load_info->sechdrs and &load_info->secstrings populated
1999 *
2000 * The ".gnu.linkonce.this_module" ELF section is special. It is what modpost
2001 * uses to refer to __this_module and let's use rely on THIS_MODULE to point
2002 * to &__this_module properly. The kernel's modpost declares it on each
2003 * modules's *.mod.c file. If the struct module of the kernel changes a full
2004 * kernel rebuild is required.
2005 *
2006 * We have a few expectations for this special section, this function
2007 * validates all this for us:
2008 *
2009 * * The section has contents
2010 * * The section is unique
2011 * * We expect the kernel to always have to allocate it: SHF_ALLOC
2012 * * The section size must match the kernel's run time's struct module
2013 * size
2014 *
2015 * If all checks pass, the index will be cached in &load_info->index.mod
2016 *
2017 * Return: %0 on validation success, %-ENOEXEC on failure
2018 */
elf_validity_cache_index_mod(struct load_info * info)2019 static int elf_validity_cache_index_mod(struct load_info *info)
2020 {
2021 Elf_Shdr *shdr;
2022 int mod_idx;
2023
2024 mod_idx = find_any_unique_sec(info, ".gnu.linkonce.this_module");
2025 if (mod_idx <= 0) {
2026 pr_err("module %s: Exactly one .gnu.linkonce.this_module section must exist.\n",
2027 info->name ?: "(missing .modinfo section or name field)");
2028 return -ENOEXEC;
2029 }
2030
2031 shdr = &info->sechdrs[mod_idx];
2032
2033 if (shdr->sh_type == SHT_NOBITS) {
2034 pr_err("module %s: .gnu.linkonce.this_module section must have a size set\n",
2035 info->name ?: "(missing .modinfo section or name field)");
2036 return -ENOEXEC;
2037 }
2038
2039 if (!(shdr->sh_flags & SHF_ALLOC)) {
2040 pr_err("module %s: .gnu.linkonce.this_module must occupy memory during process execution\n",
2041 info->name ?: "(missing .modinfo section or name field)");
2042 return -ENOEXEC;
2043 }
2044
2045 if (shdr->sh_size != sizeof(struct module)) {
2046 pr_err("module %s: .gnu.linkonce.this_module section size must match the kernel's built struct module size at run time\n",
2047 info->name ?: "(missing .modinfo section or name field)");
2048 return -ENOEXEC;
2049 }
2050
2051 info->index.mod = mod_idx;
2052
2053 return 0;
2054 }
2055
2056 /**
2057 * elf_validity_cache_index_sym() - Validate and cache symtab index
2058 * @info: Load info to cache symtab index in.
2059 * Must have &load_info->sechdrs and &load_info->secstrings populated.
2060 *
2061 * Checks that there is exactly one symbol table, then caches its index in
2062 * &load_info->index.sym.
2063 *
2064 * Return: %0 if valid, %-ENOEXEC on failure.
2065 */
elf_validity_cache_index_sym(struct load_info * info)2066 static int elf_validity_cache_index_sym(struct load_info *info)
2067 {
2068 unsigned int sym_idx;
2069 unsigned int num_sym_secs = 0;
2070 int i;
2071
2072 for (i = 1; i < info->hdr->e_shnum; i++) {
2073 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2074 num_sym_secs++;
2075 sym_idx = i;
2076 }
2077 }
2078
2079 if (num_sym_secs != 1) {
2080 pr_warn("%s: module has no symbols (stripped?)\n",
2081 info->name ?: "(missing .modinfo section or name field)");
2082 return -ENOEXEC;
2083 }
2084
2085 info->index.sym = sym_idx;
2086
2087 return 0;
2088 }
2089
2090 /**
2091 * elf_validity_cache_index_str() - Validate and cache strtab index
2092 * @info: Load info to cache strtab index in.
2093 * Must have &load_info->sechdrs and &load_info->secstrings populated.
2094 * Must have &load_info->index.sym populated.
2095 *
2096 * Looks at the symbol table's associated string table, makes sure it is
2097 * in-bounds, and caches it.
2098 *
2099 * Return: %0 if valid, %-ENOEXEC on failure.
2100 */
elf_validity_cache_index_str(struct load_info * info)2101 static int elf_validity_cache_index_str(struct load_info *info)
2102 {
2103 unsigned int str_idx = info->sechdrs[info->index.sym].sh_link;
2104
2105 if (str_idx == SHN_UNDEF || str_idx >= info->hdr->e_shnum) {
2106 pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n",
2107 str_idx, str_idx, info->hdr->e_shnum);
2108 return -ENOEXEC;
2109 }
2110
2111 info->index.str = str_idx;
2112 return 0;
2113 }
2114
2115 /**
2116 * elf_validity_cache_index_versions() - Validate and cache version indices
2117 * @info: Load info to cache version indices in.
2118 * Must have &load_info->sechdrs and &load_info->secstrings populated.
2119 * @flags: Load flags, relevant to suppress version loading, see
2120 * uapi/linux/module.h
2121 *
2122 * If we're ignoring modversions based on @flags, zero all version indices
2123 * and return validity. Othewrise check:
2124 *
2125 * * If "__version_ext_crcs" is present, "__version_ext_names" is present
2126 * * There is a name present for every crc
2127 *
2128 * Then populate:
2129 *
2130 * * &load_info->index.vers
2131 * * &load_info->index.vers_ext_crc
2132 * * &load_info->index.vers_ext_names
2133 *
2134 * if present.
2135 *
2136 * Return: %0 if valid, %-ENOEXEC on failure.
2137 */
elf_validity_cache_index_versions(struct load_info * info,int flags)2138 static int elf_validity_cache_index_versions(struct load_info *info, int flags)
2139 {
2140 unsigned int vers_ext_crc;
2141 unsigned int vers_ext_name;
2142 size_t crc_count;
2143 size_t remaining_len;
2144 size_t name_size;
2145 char *name;
2146
2147 /* If modversions were suppressed, pretend we didn't find any */
2148 if (flags & MODULE_INIT_IGNORE_MODVERSIONS) {
2149 info->index.vers = 0;
2150 info->index.vers_ext_crc = 0;
2151 info->index.vers_ext_name = 0;
2152 return 0;
2153 }
2154
2155 vers_ext_crc = find_sec(info, "__version_ext_crcs");
2156 vers_ext_name = find_sec(info, "__version_ext_names");
2157
2158 /* If we have one field, we must have the other */
2159 if (!!vers_ext_crc != !!vers_ext_name) {
2160 pr_err("extended version crc+name presence does not match");
2161 return -ENOEXEC;
2162 }
2163
2164 /*
2165 * If we have extended version information, we should have the same
2166 * number of entries in every section.
2167 */
2168 if (vers_ext_crc) {
2169 crc_count = info->sechdrs[vers_ext_crc].sh_size / sizeof(u32);
2170 name = (void *)info->hdr +
2171 info->sechdrs[vers_ext_name].sh_offset;
2172 remaining_len = info->sechdrs[vers_ext_name].sh_size;
2173
2174 while (crc_count--) {
2175 name_size = strnlen(name, remaining_len) + 1;
2176 if (name_size > remaining_len) {
2177 pr_err("more extended version crcs than names");
2178 return -ENOEXEC;
2179 }
2180 remaining_len -= name_size;
2181 name += name_size;
2182 }
2183 }
2184
2185 info->index.vers = find_sec(info, "__versions");
2186 info->index.vers_ext_crc = vers_ext_crc;
2187 info->index.vers_ext_name = vers_ext_name;
2188 return 0;
2189 }
2190
2191 /**
2192 * elf_validity_cache_index() - Resolve, validate, cache section indices
2193 * @info: Load info to read from and update.
2194 * &load_info->sechdrs and &load_info->secstrings must be populated.
2195 * @flags: Load flags, relevant to suppress version loading, see
2196 * uapi/linux/module.h
2197 *
2198 * Populates &load_info->index, validating as it goes.
2199 * See child functions for per-field validation:
2200 *
2201 * * elf_validity_cache_index_info()
2202 * * elf_validity_cache_index_mod()
2203 * * elf_validity_cache_index_sym()
2204 * * elf_validity_cache_index_str()
2205 * * elf_validity_cache_index_versions()
2206 *
2207 * If CONFIG_SMP is enabled, load the percpu section by name with no
2208 * validation.
2209 *
2210 * Return: 0 on success, negative error code if an index failed validation.
2211 */
elf_validity_cache_index(struct load_info * info,int flags)2212 static int elf_validity_cache_index(struct load_info *info, int flags)
2213 {
2214 int err;
2215
2216 err = elf_validity_cache_index_info(info);
2217 if (err < 0)
2218 return err;
2219 err = elf_validity_cache_index_mod(info);
2220 if (err < 0)
2221 return err;
2222 err = elf_validity_cache_index_sym(info);
2223 if (err < 0)
2224 return err;
2225 err = elf_validity_cache_index_str(info);
2226 if (err < 0)
2227 return err;
2228 err = elf_validity_cache_index_versions(info, flags);
2229 if (err < 0)
2230 return err;
2231
2232 info->index.pcpu = find_pcpusec(info);
2233
2234 return 0;
2235 }
2236
2237 /**
2238 * elf_validity_cache_strtab() - Validate and cache symbol string table
2239 * @info: Load info to read from and update.
2240 * Must have &load_info->sechdrs and &load_info->secstrings populated.
2241 * Must have &load_info->index populated.
2242 *
2243 * Checks:
2244 *
2245 * * The string table is not empty.
2246 * * The string table starts and ends with NUL (required by ELF spec).
2247 * * Every &Elf_Sym->st_name offset in the symbol table is inbounds of the
2248 * string table.
2249 *
2250 * And caches the pointer as &load_info->strtab in @info.
2251 *
2252 * Return: 0 on success, negative error code if a check failed.
2253 */
elf_validity_cache_strtab(struct load_info * info)2254 static int elf_validity_cache_strtab(struct load_info *info)
2255 {
2256 Elf_Shdr *str_shdr = &info->sechdrs[info->index.str];
2257 Elf_Shdr *sym_shdr = &info->sechdrs[info->index.sym];
2258 char *strtab = (char *)info->hdr + str_shdr->sh_offset;
2259 Elf_Sym *syms = (void *)info->hdr + sym_shdr->sh_offset;
2260 int i;
2261
2262 if (str_shdr->sh_size == 0) {
2263 pr_err("empty symbol string table\n");
2264 return -ENOEXEC;
2265 }
2266 if (strtab[0] != '\0') {
2267 pr_err("symbol string table missing leading NUL\n");
2268 return -ENOEXEC;
2269 }
2270 if (strtab[str_shdr->sh_size - 1] != '\0') {
2271 pr_err("symbol string table isn't NUL terminated\n");
2272 return -ENOEXEC;
2273 }
2274
2275 /*
2276 * Now that we know strtab is correctly structured, check symbol
2277 * starts are inbounds before they're used later.
2278 */
2279 for (i = 0; i < sym_shdr->sh_size / sizeof(*syms); i++) {
2280 if (syms[i].st_name >= str_shdr->sh_size) {
2281 pr_err("symbol name out of bounds in string table");
2282 return -ENOEXEC;
2283 }
2284 }
2285
2286 info->strtab = strtab;
2287 return 0;
2288 }
2289
2290 /*
2291 * Check userspace passed ELF module against our expectations, and cache
2292 * useful variables for further processing as we go.
2293 *
2294 * This does basic validity checks against section offsets and sizes, the
2295 * section name string table, and the indices used for it (sh_name).
2296 *
2297 * As a last step, since we're already checking the ELF sections we cache
2298 * useful variables which will be used later for our convenience:
2299 *
2300 * o pointers to section headers
2301 * o cache the modinfo symbol section
2302 * o cache the string symbol section
2303 * o cache the module section
2304 *
2305 * As a last step we set info->mod to the temporary copy of the module in
2306 * info->hdr. The final one will be allocated in move_module(). Any
2307 * modifications we make to our copy of the module will be carried over
2308 * to the final minted module.
2309 */
elf_validity_cache_copy(struct load_info * info,int flags)2310 static int elf_validity_cache_copy(struct load_info *info, int flags)
2311 {
2312 int err;
2313
2314 err = elf_validity_cache_sechdrs(info);
2315 if (err < 0)
2316 return err;
2317 err = elf_validity_cache_secstrings(info);
2318 if (err < 0)
2319 return err;
2320 err = elf_validity_cache_index(info, flags);
2321 if (err < 0)
2322 return err;
2323 err = elf_validity_cache_strtab(info);
2324 if (err < 0)
2325 return err;
2326
2327 /* This is temporary: point mod into copy of data. */
2328 info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
2329
2330 /*
2331 * If we didn't load the .modinfo 'name' field earlier, fall back to
2332 * on-disk struct mod 'name' field.
2333 */
2334 if (!info->name)
2335 info->name = info->mod->name;
2336
2337 return 0;
2338 }
2339
2340 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
2341
copy_chunked_from_user(void * dst,const void __user * usrc,unsigned long len)2342 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
2343 {
2344 do {
2345 unsigned long n = min(len, COPY_CHUNK_SIZE);
2346
2347 if (copy_from_user(dst, usrc, n) != 0)
2348 return -EFAULT;
2349 cond_resched();
2350 dst += n;
2351 usrc += n;
2352 len -= n;
2353 } while (len);
2354 return 0;
2355 }
2356
check_modinfo_livepatch(struct module * mod,struct load_info * info)2357 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
2358 {
2359 if (!get_modinfo(info, "livepatch"))
2360 /* Nothing more to do */
2361 return 0;
2362
2363 if (set_livepatch_module(mod))
2364 return 0;
2365
2366 pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
2367 mod->name);
2368 return -ENOEXEC;
2369 }
2370
check_modinfo_retpoline(struct module * mod,struct load_info * info)2371 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
2372 {
2373 if (retpoline_module_ok(get_modinfo(info, "retpoline")))
2374 return;
2375
2376 pr_warn("%s: loading module not compiled with retpoline compiler.\n",
2377 mod->name);
2378 }
2379
2380 /* Sets info->hdr and info->len. */
copy_module_from_user(const void __user * umod,unsigned long len,struct load_info * info)2381 static int copy_module_from_user(const void __user *umod, unsigned long len,
2382 struct load_info *info)
2383 {
2384 int err;
2385
2386 info->len = len;
2387 if (info->len < sizeof(*(info->hdr)))
2388 return -ENOEXEC;
2389
2390 err = security_kernel_load_data(LOADING_MODULE, true);
2391 if (err)
2392 return err;
2393
2394 /* Suck in entire file: we'll want most of it. */
2395 info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
2396 if (!info->hdr)
2397 return -ENOMEM;
2398
2399 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
2400 err = -EFAULT;
2401 goto out;
2402 }
2403
2404 err = security_kernel_post_load_data((char *)info->hdr, info->len,
2405 LOADING_MODULE, "init_module");
2406 out:
2407 if (err)
2408 vfree(info->hdr);
2409
2410 return err;
2411 }
2412
free_copy(struct load_info * info,int flags)2413 static void free_copy(struct load_info *info, int flags)
2414 {
2415 if (flags & MODULE_INIT_COMPRESSED_FILE)
2416 module_decompress_cleanup(info);
2417 else
2418 vfree(info->hdr);
2419 }
2420
rewrite_section_headers(struct load_info * info,int flags)2421 static int rewrite_section_headers(struct load_info *info, int flags)
2422 {
2423 unsigned int i;
2424
2425 /* This should always be true, but let's be sure. */
2426 info->sechdrs[0].sh_addr = 0;
2427
2428 for (i = 1; i < info->hdr->e_shnum; i++) {
2429 Elf_Shdr *shdr = &info->sechdrs[i];
2430
2431 /*
2432 * Mark all sections sh_addr with their address in the
2433 * temporary image.
2434 */
2435 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2436
2437 }
2438
2439 /* Track but don't keep modinfo and version sections. */
2440 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2441 info->sechdrs[info->index.vers_ext_crc].sh_flags &=
2442 ~(unsigned long)SHF_ALLOC;
2443 info->sechdrs[info->index.vers_ext_name].sh_flags &=
2444 ~(unsigned long)SHF_ALLOC;
2445 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2446
2447 return 0;
2448 }
2449
2450 /*
2451 * These calls taint the kernel depending certain module circumstances */
module_augment_kernel_taints(struct module * mod,struct load_info * info)2452 static void module_augment_kernel_taints(struct module *mod, struct load_info *info)
2453 {
2454 int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
2455
2456 if (!get_modinfo(info, "intree")) {
2457 if (!test_taint(TAINT_OOT_MODULE))
2458 pr_warn("%s: loading out-of-tree module taints kernel.\n",
2459 mod->name);
2460 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2461 }
2462
2463 check_modinfo_retpoline(mod, info);
2464
2465 if (get_modinfo(info, "staging")) {
2466 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
2467 pr_warn("%s: module is from the staging directory, the quality "
2468 "is unknown, you have been warned.\n", mod->name);
2469 }
2470
2471 if (is_livepatch_module(mod)) {
2472 add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
2473 pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
2474 mod->name);
2475 }
2476
2477 module_license_taint_check(mod, get_modinfo(info, "license"));
2478
2479 if (get_modinfo(info, "test")) {
2480 if (!test_taint(TAINT_TEST))
2481 pr_warn("%s: loading test module taints kernel.\n",
2482 mod->name);
2483 add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK);
2484 }
2485 #ifdef CONFIG_MODULE_SIG
2486 mod->sig_ok = info->sig_ok;
2487 #ifndef CONFIG_MODULE_SIG_PROTECT
2488 if (!mod->sig_ok) {
2489 pr_notice_once("%s: module verification failed: signature "
2490 "and/or required key missing - tainting "
2491 "kernel\n", mod->name);
2492 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
2493 }
2494 #endif
2495 #else
2496 mod->sig_ok = 0;
2497 #endif
2498
2499 /*
2500 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2501 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2502 * using GPL-only symbols it needs.
2503 */
2504 if (strcmp(mod->name, "ndiswrapper") == 0)
2505 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
2506
2507 /* driverloader was caught wrongly pretending to be under GPL */
2508 if (strcmp(mod->name, "driverloader") == 0)
2509 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2510 LOCKDEP_NOW_UNRELIABLE);
2511
2512 /* lve claims to be GPL but upstream won't provide source */
2513 if (strcmp(mod->name, "lve") == 0)
2514 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2515 LOCKDEP_NOW_UNRELIABLE);
2516
2517 if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
2518 pr_warn("%s: module license taints kernel.\n", mod->name);
2519
2520 }
2521
check_modinfo(struct module * mod,struct load_info * info,int flags)2522 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
2523 {
2524 const char *modmagic = get_modinfo(info, "vermagic");
2525 int err;
2526
2527 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2528 modmagic = NULL;
2529
2530 /* This is allowed: modprobe --force will invalidate it. */
2531 if (!modmagic) {
2532 err = try_to_force_load(mod, "bad vermagic");
2533 if (err)
2534 return err;
2535 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2536 pr_err("%s: version magic '%s' should be '%s'\n",
2537 info->name, modmagic, vermagic);
2538 return -ENOEXEC;
2539 }
2540
2541 err = check_modinfo_livepatch(mod, info);
2542 if (err)
2543 return err;
2544
2545 return 0;
2546 }
2547
find_module_sections(struct module * mod,struct load_info * info)2548 static int find_module_sections(struct module *mod, struct load_info *info)
2549 {
2550 mod->kp = section_objs(info, "__param",
2551 sizeof(*mod->kp), &mod->num_kp);
2552 mod->syms = section_objs(info, "__ksymtab",
2553 sizeof(*mod->syms), &mod->num_syms);
2554 mod->crcs = section_addr(info, "__kcrctab");
2555 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2556 sizeof(*mod->gpl_syms),
2557 &mod->num_gpl_syms);
2558 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2559
2560 #ifdef CONFIG_CONSTRUCTORS
2561 mod->ctors = section_objs(info, ".ctors",
2562 sizeof(*mod->ctors), &mod->num_ctors);
2563 if (!mod->ctors)
2564 mod->ctors = section_objs(info, ".init_array",
2565 sizeof(*mod->ctors), &mod->num_ctors);
2566 else if (find_sec(info, ".init_array")) {
2567 /*
2568 * This shouldn't happen with same compiler and binutils
2569 * building all parts of the module.
2570 */
2571 pr_warn("%s: has both .ctors and .init_array.\n",
2572 mod->name);
2573 return -EINVAL;
2574 }
2575 #endif
2576
2577 mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
2578 &mod->noinstr_text_size);
2579
2580 #ifdef CONFIG_TRACEPOINTS
2581 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2582 sizeof(*mod->tracepoints_ptrs),
2583 &mod->num_tracepoints);
2584 #endif
2585 #ifdef CONFIG_TREE_SRCU
2586 mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
2587 sizeof(*mod->srcu_struct_ptrs),
2588 &mod->num_srcu_structs);
2589 #endif
2590 #ifdef CONFIG_BPF_EVENTS
2591 mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
2592 sizeof(*mod->bpf_raw_events),
2593 &mod->num_bpf_raw_events);
2594 #endif
2595 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2596 mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
2597 mod->btf_base_data = any_section_objs(info, ".BTF.base", 1,
2598 &mod->btf_base_data_size);
2599 #endif
2600 #ifdef CONFIG_JUMP_LABEL
2601 mod->jump_entries = section_objs(info, "__jump_table",
2602 sizeof(*mod->jump_entries),
2603 &mod->num_jump_entries);
2604 #endif
2605 #ifdef CONFIG_EVENT_TRACING
2606 mod->trace_events = section_objs(info, "_ftrace_events",
2607 sizeof(*mod->trace_events),
2608 &mod->num_trace_events);
2609 mod->trace_evals = section_objs(info, "_ftrace_eval_map",
2610 sizeof(*mod->trace_evals),
2611 &mod->num_trace_evals);
2612 #endif
2613 #ifdef CONFIG_TRACING
2614 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2615 sizeof(*mod->trace_bprintk_fmt_start),
2616 &mod->num_trace_bprintk_fmt);
2617 #endif
2618 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2619 /* sechdrs[0].sh_size is always zero */
2620 mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
2621 sizeof(*mod->ftrace_callsites),
2622 &mod->num_ftrace_callsites);
2623 #endif
2624 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
2625 mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
2626 sizeof(*mod->ei_funcs),
2627 &mod->num_ei_funcs);
2628 #endif
2629 #ifdef CONFIG_KPROBES
2630 mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
2631 &mod->kprobes_text_size);
2632 mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
2633 sizeof(unsigned long),
2634 &mod->num_kprobe_blacklist);
2635 #endif
2636 #ifdef CONFIG_PRINTK_INDEX
2637 mod->printk_index_start = section_objs(info, ".printk_index",
2638 sizeof(*mod->printk_index_start),
2639 &mod->printk_index_size);
2640 #endif
2641 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
2642 mod->static_call_sites = section_objs(info, ".static_call_sites",
2643 sizeof(*mod->static_call_sites),
2644 &mod->num_static_call_sites);
2645 #endif
2646 #if IS_ENABLED(CONFIG_KUNIT)
2647 mod->kunit_suites = section_objs(info, ".kunit_test_suites",
2648 sizeof(*mod->kunit_suites),
2649 &mod->num_kunit_suites);
2650 mod->kunit_init_suites = section_objs(info, ".kunit_init_test_suites",
2651 sizeof(*mod->kunit_init_suites),
2652 &mod->num_kunit_init_suites);
2653 #endif
2654
2655 mod->extable = section_objs(info, "__ex_table",
2656 sizeof(*mod->extable), &mod->num_exentries);
2657
2658 if (section_addr(info, "__obsparm"))
2659 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
2660
2661 #ifdef CONFIG_DYNAMIC_DEBUG_CORE
2662 mod->dyndbg_info.descs = section_objs(info, "__dyndbg",
2663 sizeof(*mod->dyndbg_info.descs),
2664 &mod->dyndbg_info.num_descs);
2665 mod->dyndbg_info.classes = section_objs(info, "__dyndbg_classes",
2666 sizeof(*mod->dyndbg_info.classes),
2667 &mod->dyndbg_info.num_classes);
2668 #endif
2669
2670 return 0;
2671 }
2672
move_module(struct module * mod,struct load_info * info)2673 static int move_module(struct module *mod, struct load_info *info)
2674 {
2675 int i;
2676 enum mod_mem_type t = 0;
2677 int ret = -ENOMEM;
2678 bool codetag_section_found = false;
2679
2680 for_each_mod_mem_type(type) {
2681 if (!mod->mem[type].size) {
2682 mod->mem[type].base = NULL;
2683 continue;
2684 }
2685
2686 ret = module_memory_alloc(mod, type);
2687 if (ret) {
2688 t = type;
2689 goto out_err;
2690 }
2691 }
2692
2693 /* Transfer each section which specifies SHF_ALLOC */
2694 pr_debug("Final section addresses for %s:\n", mod->name);
2695 for (i = 0; i < info->hdr->e_shnum; i++) {
2696 void *dest;
2697 Elf_Shdr *shdr = &info->sechdrs[i];
2698 const char *sname;
2699
2700 if (!(shdr->sh_flags & SHF_ALLOC))
2701 continue;
2702
2703 sname = info->secstrings + shdr->sh_name;
2704 /*
2705 * Load codetag sections separately as they might still be used
2706 * after module unload.
2707 */
2708 if (codetag_needs_module_section(mod, sname, shdr->sh_size)) {
2709 dest = codetag_alloc_module_section(mod, sname, shdr->sh_size,
2710 arch_mod_section_prepend(mod, i), shdr->sh_addralign);
2711 if (WARN_ON(!dest)) {
2712 ret = -EINVAL;
2713 goto out_err;
2714 }
2715 if (IS_ERR(dest)) {
2716 ret = PTR_ERR(dest);
2717 goto out_err;
2718 }
2719 codetag_section_found = true;
2720 } else {
2721 enum mod_mem_type type = shdr->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT;
2722
2723 dest = mod->mem[type].base + (shdr->sh_entsize & SH_ENTSIZE_OFFSET_MASK);
2724 }
2725
2726 if (shdr->sh_type != SHT_NOBITS) {
2727 /*
2728 * Our ELF checker already validated this, but let's
2729 * be pedantic and make the goal clearer. We actually
2730 * end up copying over all modifications made to the
2731 * userspace copy of the entire struct module.
2732 */
2733 if (i == info->index.mod &&
2734 (WARN_ON_ONCE(shdr->sh_size != sizeof(struct module)))) {
2735 ret = -ENOEXEC;
2736 goto out_err;
2737 }
2738 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2739 }
2740 /*
2741 * Update the userspace copy's ELF section address to point to
2742 * our newly allocated memory as a pure convenience so that
2743 * users of info can keep taking advantage and using the newly
2744 * minted official memory area.
2745 */
2746 shdr->sh_addr = (unsigned long)dest;
2747 pr_debug("\t0x%lx 0x%.8lx %s\n", (long)shdr->sh_addr,
2748 (long)shdr->sh_size, info->secstrings + shdr->sh_name);
2749 }
2750
2751 return 0;
2752 out_err:
2753 for (t--; t >= 0; t--)
2754 module_memory_free(mod, t);
2755 if (codetag_section_found)
2756 codetag_free_module_sections(mod);
2757
2758 return ret;
2759 }
2760
check_export_symbol_versions(struct module * mod)2761 static int check_export_symbol_versions(struct module *mod)
2762 {
2763 #ifdef CONFIG_MODVERSIONS
2764 if ((mod->num_syms && !mod->crcs) ||
2765 (mod->num_gpl_syms && !mod->gpl_crcs)) {
2766 return try_to_force_load(mod,
2767 "no versions for exported symbols");
2768 }
2769 #endif
2770 return 0;
2771 }
2772
flush_module_icache(const struct module * mod)2773 static void flush_module_icache(const struct module *mod)
2774 {
2775 /*
2776 * Flush the instruction cache, since we've played with text.
2777 * Do it before processing of module parameters, so the module
2778 * can provide parameter accessor functions of its own.
2779 */
2780 for_each_mod_mem_type(type) {
2781 const struct module_memory *mod_mem = &mod->mem[type];
2782
2783 if (mod_mem->size) {
2784 flush_icache_range((unsigned long)mod_mem->base,
2785 (unsigned long)mod_mem->base + mod_mem->size);
2786 }
2787 }
2788 }
2789
module_elf_check_arch(Elf_Ehdr * hdr)2790 bool __weak module_elf_check_arch(Elf_Ehdr *hdr)
2791 {
2792 return true;
2793 }
2794
module_frob_arch_sections(Elf_Ehdr * hdr,Elf_Shdr * sechdrs,char * secstrings,struct module * mod)2795 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2796 Elf_Shdr *sechdrs,
2797 char *secstrings,
2798 struct module *mod)
2799 {
2800 return 0;
2801 }
2802
2803 /* module_blacklist is a comma-separated list of module names */
2804 static char *module_blacklist;
blacklisted(const char * module_name)2805 static bool blacklisted(const char *module_name)
2806 {
2807 const char *p;
2808 size_t len;
2809
2810 if (!module_blacklist)
2811 return false;
2812
2813 for (p = module_blacklist; *p; p += len) {
2814 len = strcspn(p, ",");
2815 if (strlen(module_name) == len && !memcmp(module_name, p, len))
2816 return true;
2817 if (p[len] == ',')
2818 len++;
2819 }
2820 return false;
2821 }
2822 core_param(module_blacklist, module_blacklist, charp, 0400);
2823
layout_and_allocate(struct load_info * info,int flags)2824 static struct module *layout_and_allocate(struct load_info *info, int flags)
2825 {
2826 struct module *mod;
2827 unsigned int ndx;
2828 int err;
2829
2830 /* Allow arches to frob section contents and sizes. */
2831 err = module_frob_arch_sections(info->hdr, info->sechdrs,
2832 info->secstrings, info->mod);
2833 if (err < 0)
2834 return ERR_PTR(err);
2835
2836 err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
2837 info->secstrings, info->mod);
2838 if (err < 0)
2839 return ERR_PTR(err);
2840
2841 /* We will do a special allocation for per-cpu sections later. */
2842 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
2843
2844 /*
2845 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
2846 * layout_sections() can put it in the right place.
2847 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
2848 */
2849 ndx = find_sec(info, ".data..ro_after_init");
2850 if (ndx)
2851 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2852 /*
2853 * Mark the __jump_table section as ro_after_init as well: these data
2854 * structures are never modified, with the exception of entries that
2855 * refer to code in the __init section, which are annotated as such
2856 * at module load time.
2857 */
2858 ndx = find_sec(info, "__jump_table");
2859 if (ndx)
2860 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2861
2862 /*
2863 * Determine total sizes, and put offsets in sh_entsize. For now
2864 * this is done generically; there doesn't appear to be any
2865 * special cases for the architectures.
2866 */
2867 layout_sections(info->mod, info);
2868 layout_symtab(info->mod, info);
2869
2870 /* Allocate and move to the final place */
2871 err = move_module(info->mod, info);
2872 if (err)
2873 return ERR_PTR(err);
2874
2875 /* Module has been copied to its final place now: return it. */
2876 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2877 kmemleak_load_module(mod, info);
2878 codetag_module_replaced(info->mod, mod);
2879
2880 return mod;
2881 }
2882
2883 /* mod is no longer valid after this! */
module_deallocate(struct module * mod,struct load_info * info)2884 static void module_deallocate(struct module *mod, struct load_info *info)
2885 {
2886 percpu_modfree(mod);
2887 module_arch_freeing_init(mod);
2888
2889 free_mod_mem(mod);
2890 }
2891
module_finalize(const Elf_Ehdr * hdr,const Elf_Shdr * sechdrs,struct module * me)2892 int __weak module_finalize(const Elf_Ehdr *hdr,
2893 const Elf_Shdr *sechdrs,
2894 struct module *me)
2895 {
2896 return 0;
2897 }
2898
post_relocation(struct module * mod,const struct load_info * info)2899 static int post_relocation(struct module *mod, const struct load_info *info)
2900 {
2901 /* Sort exception table now relocations are done. */
2902 sort_extable(mod->extable, mod->extable + mod->num_exentries);
2903
2904 /* Copy relocated percpu area over. */
2905 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2906 info->sechdrs[info->index.pcpu].sh_size);
2907
2908 /* Setup kallsyms-specific fields. */
2909 add_kallsyms(mod, info);
2910
2911 /* Arch-specific module finalizing. */
2912 return module_finalize(info->hdr, info->sechdrs, mod);
2913 }
2914
2915 /* Call module constructors. */
do_mod_ctors(struct module * mod)2916 static void do_mod_ctors(struct module *mod)
2917 {
2918 #ifdef CONFIG_CONSTRUCTORS
2919 unsigned long i;
2920
2921 for (i = 0; i < mod->num_ctors; i++)
2922 mod->ctors[i]();
2923 #endif
2924 }
2925
2926 /* For freeing module_init on success, in case kallsyms traversing */
2927 struct mod_initfree {
2928 struct llist_node node;
2929 void *init_text;
2930 void *init_data;
2931 void *init_rodata;
2932 };
2933
do_free_init(struct work_struct * w)2934 static void do_free_init(struct work_struct *w)
2935 {
2936 struct llist_node *pos, *n, *list;
2937 struct mod_initfree *initfree;
2938
2939 list = llist_del_all(&init_free_list);
2940
2941 synchronize_rcu();
2942
2943 llist_for_each_safe(pos, n, list) {
2944 initfree = container_of(pos, struct mod_initfree, node);
2945 execmem_free(initfree->init_text);
2946 execmem_free(initfree->init_data);
2947 execmem_free(initfree->init_rodata);
2948 kfree(initfree);
2949 }
2950 }
2951
flush_module_init_free_work(void)2952 void flush_module_init_free_work(void)
2953 {
2954 flush_work(&init_free_wq);
2955 }
2956
2957 #undef MODULE_PARAM_PREFIX
2958 #define MODULE_PARAM_PREFIX "module."
2959 /* Default value for module->async_probe_requested */
2960 static bool async_probe;
2961 module_param(async_probe, bool, 0644);
2962
2963 /*
2964 * This is where the real work happens.
2965 *
2966 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
2967 * helper command 'lx-symbols'.
2968 */
do_init_module(struct module * mod)2969 static noinline int do_init_module(struct module *mod)
2970 {
2971 int ret = 0;
2972 struct mod_initfree *freeinit;
2973 #if defined(CONFIG_MODULE_STATS)
2974 unsigned int text_size = 0, total_size = 0;
2975
2976 for_each_mod_mem_type(type) {
2977 const struct module_memory *mod_mem = &mod->mem[type];
2978 if (mod_mem->size) {
2979 total_size += mod_mem->size;
2980 if (type == MOD_TEXT || type == MOD_INIT_TEXT)
2981 text_size += mod_mem->size;
2982 }
2983 }
2984 #endif
2985
2986 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
2987 if (!freeinit) {
2988 ret = -ENOMEM;
2989 goto fail;
2990 }
2991 freeinit->init_text = mod->mem[MOD_INIT_TEXT].base;
2992 freeinit->init_data = mod->mem[MOD_INIT_DATA].base;
2993 freeinit->init_rodata = mod->mem[MOD_INIT_RODATA].base;
2994
2995 do_mod_ctors(mod);
2996 /* Start the module */
2997 if (mod->init != NULL)
2998 ret = do_one_initcall(mod->init);
2999 if (ret < 0) {
3000 goto fail_free_freeinit;
3001 }
3002 if (ret > 0) {
3003 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3004 "follow 0/-E convention\n"
3005 "%s: loading module anyway...\n",
3006 __func__, mod->name, ret, __func__);
3007 dump_stack();
3008 }
3009
3010 /* Now it's a first class citizen! */
3011 mod->state = MODULE_STATE_LIVE;
3012 blocking_notifier_call_chain(&module_notify_list,
3013 MODULE_STATE_LIVE, mod);
3014
3015 /* Delay uevent until module has finished its init routine */
3016 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
3017
3018 /*
3019 * We need to finish all async code before the module init sequence
3020 * is done. This has potential to deadlock if synchronous module
3021 * loading is requested from async (which is not allowed!).
3022 *
3023 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
3024 * request_module() from async workers") for more details.
3025 */
3026 if (!mod->async_probe_requested)
3027 async_synchronize_full();
3028
3029 ftrace_free_mem(mod, mod->mem[MOD_INIT_TEXT].base,
3030 mod->mem[MOD_INIT_TEXT].base + mod->mem[MOD_INIT_TEXT].size);
3031 mutex_lock(&module_mutex);
3032 /* Drop initial reference. */
3033 module_put(mod);
3034 trim_init_extable(mod);
3035 #ifdef CONFIG_KALLSYMS
3036 /* Switch to core kallsyms now init is done: kallsyms may be walking! */
3037 rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3038 #endif
3039 ret = module_enable_rodata_ro(mod, true);
3040 if (ret)
3041 pr_warn("%s: module_enable_rodata_ro_after_init() returned %d, "
3042 "ro_after_init data might still be writable\n",
3043 mod->name, ret);
3044 trace_android_vh_set_mod_perm_after_init(mod);
3045
3046 mod_tree_remove_init(mod);
3047 module_arch_freeing_init(mod);
3048 for_class_mod_mem_type(type, init) {
3049 mod->mem[type].base = NULL;
3050 mod->mem[type].size = 0;
3051 }
3052
3053 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
3054 /* .BTF is not SHF_ALLOC and will get removed, so sanitize pointers */
3055 mod->btf_data = NULL;
3056 mod->btf_base_data = NULL;
3057 #endif
3058 /*
3059 * We want to free module_init, but be aware that kallsyms may be
3060 * walking this with preempt disabled. In all the failure paths, we
3061 * call synchronize_rcu(), but we don't want to slow down the success
3062 * path. execmem_free() cannot be called in an interrupt, so do the
3063 * work and call synchronize_rcu() in a work queue.
3064 *
3065 * Note that execmem_alloc() on most architectures creates W+X page
3066 * mappings which won't be cleaned up until do_free_init() runs. Any
3067 * code such as mark_rodata_ro() which depends on those mappings to
3068 * be cleaned up needs to sync with the queued work by invoking
3069 * flush_module_init_free_work().
3070 */
3071 if (llist_add(&freeinit->node, &init_free_list))
3072 schedule_work(&init_free_wq);
3073
3074 mutex_unlock(&module_mutex);
3075 wake_up_all(&module_wq);
3076
3077 mod_stat_add_long(text_size, &total_text_size);
3078 mod_stat_add_long(total_size, &total_mod_size);
3079
3080 mod_stat_inc(&modcount);
3081
3082 return 0;
3083
3084 fail_free_freeinit:
3085 kfree(freeinit);
3086 fail:
3087 /* Try to protect us from buggy refcounters. */
3088 mod->state = MODULE_STATE_GOING;
3089 synchronize_rcu();
3090 module_put(mod);
3091 blocking_notifier_call_chain(&module_notify_list,
3092 MODULE_STATE_GOING, mod);
3093 klp_module_going(mod);
3094 ftrace_release_mod(mod);
3095 free_module(mod);
3096 wake_up_all(&module_wq);
3097
3098 return ret;
3099 }
3100
may_init_module(void)3101 static int may_init_module(void)
3102 {
3103 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3104 return -EPERM;
3105
3106 return 0;
3107 }
3108
3109 /* Is this module of this name done loading? No locks held. */
finished_loading(const char * name)3110 static bool finished_loading(const char *name)
3111 {
3112 struct module *mod;
3113 bool ret;
3114
3115 /*
3116 * The module_mutex should not be a heavily contended lock;
3117 * if we get the occasional sleep here, we'll go an extra iteration
3118 * in the wait_event_interruptible(), which is harmless.
3119 */
3120 sched_annotate_sleep();
3121 mutex_lock(&module_mutex);
3122 mod = find_module_all(name, strlen(name), true);
3123 ret = !mod || mod->state == MODULE_STATE_LIVE
3124 || mod->state == MODULE_STATE_GOING;
3125 mutex_unlock(&module_mutex);
3126
3127 return ret;
3128 }
3129
3130 /* Must be called with module_mutex held */
module_patient_check_exists(const char * name,enum fail_dup_mod_reason reason)3131 static int module_patient_check_exists(const char *name,
3132 enum fail_dup_mod_reason reason)
3133 {
3134 struct module *old;
3135 int err = 0;
3136
3137 old = find_module_all(name, strlen(name), true);
3138 if (old == NULL)
3139 return 0;
3140
3141 if (old->state == MODULE_STATE_COMING ||
3142 old->state == MODULE_STATE_UNFORMED) {
3143 /* Wait in case it fails to load. */
3144 mutex_unlock(&module_mutex);
3145 err = wait_event_interruptible(module_wq,
3146 finished_loading(name));
3147 mutex_lock(&module_mutex);
3148 if (err)
3149 return err;
3150
3151 /* The module might have gone in the meantime. */
3152 old = find_module_all(name, strlen(name), true);
3153 }
3154
3155 if (try_add_failed_module(name, reason))
3156 pr_warn("Could not add fail-tracking for module: %s\n", name);
3157
3158 /*
3159 * We are here only when the same module was being loaded. Do
3160 * not try to load it again right now. It prevents long delays
3161 * caused by serialized module load failures. It might happen
3162 * when more devices of the same type trigger load of
3163 * a particular module.
3164 */
3165 if (old && old->state == MODULE_STATE_LIVE)
3166 return -EEXIST;
3167 return -EBUSY;
3168 }
3169
3170 /*
3171 * We try to place it in the list now to make sure it's unique before
3172 * we dedicate too many resources. In particular, temporary percpu
3173 * memory exhaustion.
3174 */
add_unformed_module(struct module * mod)3175 static int add_unformed_module(struct module *mod)
3176 {
3177 int err;
3178
3179 mod->state = MODULE_STATE_UNFORMED;
3180
3181 mutex_lock(&module_mutex);
3182 err = module_patient_check_exists(mod->name, FAIL_DUP_MOD_LOAD);
3183 if (err)
3184 goto out;
3185
3186 mod_update_bounds(mod);
3187 list_add_rcu(&mod->list, &modules);
3188 mod_tree_insert(mod);
3189 err = 0;
3190
3191 out:
3192 mutex_unlock(&module_mutex);
3193 return err;
3194 }
3195
complete_formation(struct module * mod,struct load_info * info)3196 static int complete_formation(struct module *mod, struct load_info *info)
3197 {
3198 int err;
3199
3200 mutex_lock(&module_mutex);
3201
3202 /* Find duplicate symbols (must be called under lock). */
3203 err = verify_exported_symbols(mod);
3204 if (err < 0)
3205 goto out;
3206
3207 /* These rely on module_mutex for list integrity. */
3208 module_bug_finalize(info->hdr, info->sechdrs, mod);
3209 module_cfi_finalize(info->hdr, info->sechdrs, mod);
3210
3211 err = module_enable_rodata_ro(mod, false);
3212 if (err)
3213 goto out_strict_rwx;
3214 err = module_enable_data_nx(mod);
3215 if (err)
3216 goto out_strict_rwx;
3217 err = module_enable_text_rox(mod);
3218 if (err)
3219 goto out_strict_rwx;
3220 trace_android_vh_set_mod_perm_before_init(mod);
3221
3222 /*
3223 * Mark state as coming so strong_try_module_get() ignores us,
3224 * but kallsyms etc. can see us.
3225 */
3226 mod->state = MODULE_STATE_COMING;
3227 mutex_unlock(&module_mutex);
3228
3229 return 0;
3230
3231 out_strict_rwx:
3232 module_bug_cleanup(mod);
3233 out:
3234 mutex_unlock(&module_mutex);
3235 return err;
3236 }
3237
prepare_coming_module(struct module * mod)3238 static int prepare_coming_module(struct module *mod)
3239 {
3240 int err;
3241
3242 ftrace_module_enable(mod);
3243 err = klp_module_coming(mod);
3244 if (err)
3245 return err;
3246
3247 err = blocking_notifier_call_chain_robust(&module_notify_list,
3248 MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
3249 err = notifier_to_errno(err);
3250 if (err)
3251 klp_module_going(mod);
3252
3253 return err;
3254 }
3255
unknown_module_param_cb(char * param,char * val,const char * modname,void * arg)3256 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3257 void *arg)
3258 {
3259 struct module *mod = arg;
3260 int ret;
3261
3262 if (strcmp(param, "async_probe") == 0) {
3263 if (kstrtobool(val, &mod->async_probe_requested))
3264 mod->async_probe_requested = true;
3265 return 0;
3266 }
3267
3268 /* Check for magic 'dyndbg' arg */
3269 ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3270 if (ret != 0)
3271 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3272 return 0;
3273 }
3274
3275 /* Module within temporary copy, this doesn't do any allocation */
early_mod_check(struct load_info * info,int flags)3276 static int early_mod_check(struct load_info *info, int flags)
3277 {
3278 int err;
3279
3280 /*
3281 * Now that we know we have the correct module name, check
3282 * if it's blacklisted.
3283 */
3284 if (blacklisted(info->name)) {
3285 pr_err("Module %s is blacklisted\n", info->name);
3286 return -EPERM;
3287 }
3288
3289 err = rewrite_section_headers(info, flags);
3290 if (err)
3291 return err;
3292
3293 /* Check module struct version now, before we try to use module. */
3294 if (!check_modstruct_version(info, info->mod))
3295 return -ENOEXEC;
3296
3297 err = check_modinfo(info->mod, info, flags);
3298 if (err)
3299 return err;
3300
3301 mutex_lock(&module_mutex);
3302 err = module_patient_check_exists(info->mod->name, FAIL_DUP_MOD_BECOMING);
3303 mutex_unlock(&module_mutex);
3304
3305 return err;
3306 }
3307
3308 /*
3309 * Allocate and load the module: note that size of section 0 is always
3310 * zero, and we rely on this for optional sections.
3311 */
load_module(struct load_info * info,const char __user * uargs,int flags)3312 static int load_module(struct load_info *info, const char __user *uargs,
3313 int flags)
3314 {
3315 struct module *mod;
3316 bool module_allocated = false;
3317 long err = 0;
3318 char *after_dashes;
3319
3320 /*
3321 * Do the signature check (if any) first. All that
3322 * the signature check needs is info->len, it does
3323 * not need any of the section info. That can be
3324 * set up later. This will minimize the chances
3325 * of a corrupt module causing problems before
3326 * we even get to the signature check.
3327 *
3328 * The check will also adjust info->len by stripping
3329 * off the sig length at the end of the module, making
3330 * checks against info->len more correct.
3331 */
3332 err = module_sig_check(info, flags);
3333 if (err)
3334 goto free_copy;
3335
3336 /*
3337 * Do basic sanity checks against the ELF header and
3338 * sections. Cache useful sections and set the
3339 * info->mod to the userspace passed struct module.
3340 */
3341 err = elf_validity_cache_copy(info, flags);
3342 if (err)
3343 goto free_copy;
3344
3345 err = early_mod_check(info, flags);
3346 if (err)
3347 goto free_copy;
3348
3349 /* Figure out module layout, and allocate all the memory. */
3350 mod = layout_and_allocate(info, flags);
3351 if (IS_ERR(mod)) {
3352 err = PTR_ERR(mod);
3353 goto free_copy;
3354 }
3355
3356 module_allocated = true;
3357
3358 audit_log_kern_module(mod->name);
3359
3360 /* Reserve our place in the list. */
3361 err = add_unformed_module(mod);
3362 if (err)
3363 goto free_module;
3364
3365 /*
3366 * We are tainting your kernel if your module gets into
3367 * the modules linked list somehow.
3368 */
3369 module_augment_kernel_taints(mod, info);
3370
3371 /* To avoid stressing percpu allocator, do this once we're unique. */
3372 err = percpu_modalloc(mod, info);
3373 if (err)
3374 goto unlink_mod;
3375
3376 /* Now module is in final location, initialize linked lists, etc. */
3377 err = module_unload_init(mod);
3378 if (err)
3379 goto unlink_mod;
3380
3381 init_param_lock(mod);
3382
3383 /*
3384 * Now we've got everything in the final locations, we can
3385 * find optional sections.
3386 */
3387 err = find_module_sections(mod, info);
3388 if (err)
3389 goto free_unload;
3390
3391 err = check_export_symbol_versions(mod);
3392 if (err)
3393 goto free_unload;
3394
3395 /* Set up MODINFO_ATTR fields */
3396 setup_modinfo(mod, info);
3397
3398 /* Fix up syms, so that st_value is a pointer to location. */
3399 err = simplify_symbols(mod, info);
3400 if (err < 0)
3401 goto free_modinfo;
3402
3403 err = apply_relocations(mod, info);
3404 if (err < 0)
3405 goto free_modinfo;
3406
3407 err = post_relocation(mod, info);
3408 if (err < 0)
3409 goto free_modinfo;
3410
3411 flush_module_icache(mod);
3412
3413 /* Now copy in args */
3414 mod->args = strndup_user(uargs, ~0UL >> 1);
3415 if (IS_ERR(mod->args)) {
3416 err = PTR_ERR(mod->args);
3417 goto free_arch_cleanup;
3418 }
3419
3420 init_build_id(mod, info);
3421
3422 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
3423 ftrace_module_init(mod);
3424
3425 /* Finally it's fully formed, ready to start executing. */
3426 err = complete_formation(mod, info);
3427 if (err)
3428 goto ddebug_cleanup;
3429
3430 err = prepare_coming_module(mod);
3431 if (err)
3432 goto bug_cleanup;
3433
3434 mod->async_probe_requested = async_probe;
3435
3436 /* Module is ready to execute: parsing args may do that. */
3437 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
3438 -32768, 32767, mod,
3439 unknown_module_param_cb);
3440 if (IS_ERR(after_dashes)) {
3441 err = PTR_ERR(after_dashes);
3442 goto coming_cleanup;
3443 } else if (after_dashes) {
3444 pr_warn("%s: parameters '%s' after `--' ignored\n",
3445 mod->name, after_dashes);
3446 }
3447
3448 /* Link in to sysfs. */
3449 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3450 if (err < 0)
3451 goto coming_cleanup;
3452
3453 if (is_livepatch_module(mod)) {
3454 err = copy_module_elf(mod, info);
3455 if (err < 0)
3456 goto sysfs_cleanup;
3457 }
3458
3459 /* Get rid of temporary copy. */
3460 free_copy(info, flags);
3461
3462 codetag_load_module(mod);
3463
3464 /* Done! */
3465 trace_module_load(mod);
3466
3467 return do_init_module(mod);
3468
3469 sysfs_cleanup:
3470 mod_sysfs_teardown(mod);
3471 coming_cleanup:
3472 mod->state = MODULE_STATE_GOING;
3473 destroy_params(mod->kp, mod->num_kp);
3474 blocking_notifier_call_chain(&module_notify_list,
3475 MODULE_STATE_GOING, mod);
3476 klp_module_going(mod);
3477 bug_cleanup:
3478 mod->state = MODULE_STATE_GOING;
3479 /* module_bug_cleanup needs module_mutex protection */
3480 mutex_lock(&module_mutex);
3481 module_bug_cleanup(mod);
3482 mutex_unlock(&module_mutex);
3483
3484 ddebug_cleanup:
3485 ftrace_release_mod(mod);
3486 synchronize_rcu();
3487 kfree(mod->args);
3488 free_arch_cleanup:
3489 module_arch_cleanup(mod);
3490 free_modinfo:
3491 free_modinfo(mod);
3492 free_unload:
3493 module_unload_free(mod);
3494 unlink_mod:
3495 mutex_lock(&module_mutex);
3496 /* Unlink carefully: kallsyms could be walking list. */
3497 list_del_rcu(&mod->list);
3498 mod_tree_remove(mod);
3499 wake_up_all(&module_wq);
3500 /* Wait for RCU-sched synchronizing before releasing mod->list. */
3501 synchronize_rcu();
3502 mutex_unlock(&module_mutex);
3503 free_module:
3504 mod_stat_bump_invalid(info, flags);
3505 /* Free lock-classes; relies on the preceding sync_rcu() */
3506 for_class_mod_mem_type(type, core_data) {
3507 lockdep_free_key_range(mod->mem[type].base,
3508 mod->mem[type].size);
3509 }
3510
3511 module_deallocate(mod, info);
3512 free_copy:
3513 /*
3514 * The info->len is always set. We distinguish between
3515 * failures once the proper module was allocated and
3516 * before that.
3517 */
3518 if (!module_allocated)
3519 mod_stat_bump_becoming(info, flags);
3520 free_copy(info, flags);
3521 return err;
3522 }
3523
SYSCALL_DEFINE3(init_module,void __user *,umod,unsigned long,len,const char __user *,uargs)3524 SYSCALL_DEFINE3(init_module, void __user *, umod,
3525 unsigned long, len, const char __user *, uargs)
3526 {
3527 int err;
3528 struct load_info info = { };
3529
3530 err = may_init_module();
3531 if (err)
3532 return err;
3533
3534 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3535 umod, len, uargs);
3536
3537 err = copy_module_from_user(umod, len, &info);
3538 if (err) {
3539 mod_stat_inc(&failed_kreads);
3540 mod_stat_add_long(len, &invalid_kread_bytes);
3541 return err;
3542 }
3543
3544 return load_module(&info, uargs, 0);
3545 }
3546
3547 struct idempotent {
3548 const void *cookie;
3549 struct hlist_node entry;
3550 struct completion complete;
3551 int ret;
3552 };
3553
3554 #define IDEM_HASH_BITS 8
3555 static struct hlist_head idem_hash[1 << IDEM_HASH_BITS];
3556 static DEFINE_SPINLOCK(idem_lock);
3557
idempotent(struct idempotent * u,const void * cookie)3558 static bool idempotent(struct idempotent *u, const void *cookie)
3559 {
3560 int hash = hash_ptr(cookie, IDEM_HASH_BITS);
3561 struct hlist_head *head = idem_hash + hash;
3562 struct idempotent *existing;
3563 bool first;
3564
3565 u->ret = -EINTR;
3566 u->cookie = cookie;
3567 init_completion(&u->complete);
3568
3569 spin_lock(&idem_lock);
3570 first = true;
3571 hlist_for_each_entry(existing, head, entry) {
3572 if (existing->cookie != cookie)
3573 continue;
3574 first = false;
3575 break;
3576 }
3577 hlist_add_head(&u->entry, idem_hash + hash);
3578 spin_unlock(&idem_lock);
3579
3580 return !first;
3581 }
3582
3583 /*
3584 * We were the first one with 'cookie' on the list, and we ended
3585 * up completing the operation. We now need to walk the list,
3586 * remove everybody - which includes ourselves - fill in the return
3587 * value, and then complete the operation.
3588 */
idempotent_complete(struct idempotent * u,int ret)3589 static int idempotent_complete(struct idempotent *u, int ret)
3590 {
3591 const void *cookie = u->cookie;
3592 int hash = hash_ptr(cookie, IDEM_HASH_BITS);
3593 struct hlist_head *head = idem_hash + hash;
3594 struct hlist_node *next;
3595 struct idempotent *pos;
3596
3597 spin_lock(&idem_lock);
3598 hlist_for_each_entry_safe(pos, next, head, entry) {
3599 if (pos->cookie != cookie)
3600 continue;
3601 hlist_del_init(&pos->entry);
3602 pos->ret = ret;
3603 complete(&pos->complete);
3604 }
3605 spin_unlock(&idem_lock);
3606 return ret;
3607 }
3608
3609 /*
3610 * Wait for the idempotent worker.
3611 *
3612 * If we get interrupted, we need to remove ourselves from the
3613 * the idempotent list, and the completion may still come in.
3614 *
3615 * The 'idem_lock' protects against the race, and 'idem.ret' was
3616 * initialized to -EINTR and is thus always the right return
3617 * value even if the idempotent work then completes between
3618 * the wait_for_completion and the cleanup.
3619 */
idempotent_wait_for_completion(struct idempotent * u)3620 static int idempotent_wait_for_completion(struct idempotent *u)
3621 {
3622 if (wait_for_completion_interruptible(&u->complete)) {
3623 spin_lock(&idem_lock);
3624 if (!hlist_unhashed(&u->entry))
3625 hlist_del(&u->entry);
3626 spin_unlock(&idem_lock);
3627 }
3628 return u->ret;
3629 }
3630
init_module_from_file(struct file * f,const char __user * uargs,int flags)3631 static int init_module_from_file(struct file *f, const char __user * uargs, int flags)
3632 {
3633 struct load_info info = { };
3634 void *buf = NULL;
3635 int len;
3636
3637 len = kernel_read_file(f, 0, &buf, INT_MAX, NULL, READING_MODULE);
3638 if (len < 0) {
3639 mod_stat_inc(&failed_kreads);
3640 return len;
3641 }
3642
3643 if (flags & MODULE_INIT_COMPRESSED_FILE) {
3644 int err = module_decompress(&info, buf, len);
3645 vfree(buf); /* compressed data is no longer needed */
3646 if (err) {
3647 mod_stat_inc(&failed_decompress);
3648 mod_stat_add_long(len, &invalid_decompress_bytes);
3649 return err;
3650 }
3651 } else {
3652 info.hdr = buf;
3653 info.len = len;
3654 }
3655
3656 return load_module(&info, uargs, flags);
3657 }
3658
idempotent_init_module(struct file * f,const char __user * uargs,int flags)3659 static int idempotent_init_module(struct file *f, const char __user * uargs, int flags)
3660 {
3661 struct idempotent idem;
3662
3663 if (!f || !(f->f_mode & FMODE_READ))
3664 return -EBADF;
3665
3666 /* Are we the winners of the race and get to do this? */
3667 if (!idempotent(&idem, file_inode(f))) {
3668 int ret = init_module_from_file(f, uargs, flags);
3669 return idempotent_complete(&idem, ret);
3670 }
3671
3672 /*
3673 * Somebody else won the race and is loading the module.
3674 */
3675 return idempotent_wait_for_completion(&idem);
3676 }
3677
SYSCALL_DEFINE3(finit_module,int,fd,const char __user *,uargs,int,flags)3678 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3679 {
3680 int err;
3681 struct fd f;
3682
3683 err = may_init_module();
3684 if (err)
3685 return err;
3686
3687 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3688
3689 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
3690 |MODULE_INIT_IGNORE_VERMAGIC
3691 |MODULE_INIT_COMPRESSED_FILE))
3692 return -EINVAL;
3693
3694 f = fdget(fd);
3695 err = idempotent_init_module(fd_file(f), uargs, flags);
3696 fdput(f);
3697 return err;
3698 }
3699
3700 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
module_flags(struct module * mod,char * buf,bool show_state)3701 char *module_flags(struct module *mod, char *buf, bool show_state)
3702 {
3703 int bx = 0;
3704
3705 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
3706 if (!mod->taints && !show_state)
3707 goto out;
3708 if (mod->taints ||
3709 mod->state == MODULE_STATE_GOING ||
3710 mod->state == MODULE_STATE_COMING) {
3711 buf[bx++] = '(';
3712 bx += module_flags_taint(mod->taints, buf + bx);
3713 /* Show a - for module-is-being-unloaded */
3714 if (mod->state == MODULE_STATE_GOING && show_state)
3715 buf[bx++] = '-';
3716 /* Show a + for module-is-being-loaded */
3717 if (mod->state == MODULE_STATE_COMING && show_state)
3718 buf[bx++] = '+';
3719 buf[bx++] = ')';
3720 }
3721 out:
3722 buf[bx] = '\0';
3723
3724 return buf;
3725 }
3726
3727 /* Given an address, look for it in the module exception tables. */
search_module_extables(unsigned long addr)3728 const struct exception_table_entry *search_module_extables(unsigned long addr)
3729 {
3730 const struct exception_table_entry *e = NULL;
3731 struct module *mod;
3732
3733 preempt_disable();
3734 mod = __module_address(addr);
3735 if (!mod)
3736 goto out;
3737
3738 if (!mod->num_exentries)
3739 goto out;
3740
3741 e = search_extable(mod->extable,
3742 mod->num_exentries,
3743 addr);
3744 out:
3745 preempt_enable();
3746
3747 /*
3748 * Now, if we found one, we are running inside it now, hence
3749 * we cannot unload the module, hence no refcnt needed.
3750 */
3751 return e;
3752 }
3753
3754 /**
3755 * is_module_address() - is this address inside a module?
3756 * @addr: the address to check.
3757 *
3758 * See is_module_text_address() if you simply want to see if the address
3759 * is code (not data).
3760 */
is_module_address(unsigned long addr)3761 bool is_module_address(unsigned long addr)
3762 {
3763 bool ret;
3764
3765 preempt_disable();
3766 ret = __module_address(addr) != NULL;
3767 preempt_enable();
3768
3769 return ret;
3770 }
3771
3772 /**
3773 * __module_address() - get the module which contains an address.
3774 * @addr: the address.
3775 *
3776 * Must be called with preempt disabled or module mutex held so that
3777 * module doesn't get freed during this.
3778 */
__module_address(unsigned long addr)3779 struct module *__module_address(unsigned long addr)
3780 {
3781 struct module *mod;
3782
3783 if (addr >= mod_tree.addr_min && addr <= mod_tree.addr_max)
3784 goto lookup;
3785
3786 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
3787 if (addr >= mod_tree.data_addr_min && addr <= mod_tree.data_addr_max)
3788 goto lookup;
3789 #endif
3790
3791 return NULL;
3792
3793 lookup:
3794 module_assert_mutex_or_preempt();
3795
3796 mod = mod_find(addr, &mod_tree);
3797 if (mod) {
3798 BUG_ON(!within_module(addr, mod));
3799 if (mod->state == MODULE_STATE_UNFORMED)
3800 mod = NULL;
3801 }
3802 return mod;
3803 }
3804
3805 /**
3806 * is_module_text_address() - is this address inside module code?
3807 * @addr: the address to check.
3808 *
3809 * See is_module_address() if you simply want to see if the address is
3810 * anywhere in a module. See kernel_text_address() for testing if an
3811 * address corresponds to kernel or module code.
3812 */
is_module_text_address(unsigned long addr)3813 bool is_module_text_address(unsigned long addr)
3814 {
3815 bool ret;
3816
3817 preempt_disable();
3818 ret = __module_text_address(addr) != NULL;
3819 preempt_enable();
3820
3821 return ret;
3822 }
3823
3824 /**
3825 * __module_text_address() - get the module whose code contains an address.
3826 * @addr: the address.
3827 *
3828 * Must be called with preempt disabled or module mutex held so that
3829 * module doesn't get freed during this.
3830 */
__module_text_address(unsigned long addr)3831 struct module *__module_text_address(unsigned long addr)
3832 {
3833 struct module *mod = __module_address(addr);
3834 if (mod) {
3835 /* Make sure it's within the text section. */
3836 if (!within_module_mem_type(addr, mod, MOD_TEXT) &&
3837 !within_module_mem_type(addr, mod, MOD_INIT_TEXT))
3838 mod = NULL;
3839 }
3840 return mod;
3841 }
3842
3843 /* Don't grab lock, we're oopsing. */
print_modules(void)3844 void print_modules(void)
3845 {
3846 struct module *mod;
3847 char buf[MODULE_FLAGS_BUF_SIZE];
3848
3849 printk(KERN_DEFAULT "Modules linked in:");
3850 /* Most callers should already have preempt disabled, but make sure */
3851 preempt_disable();
3852 list_for_each_entry_rcu(mod, &modules, list) {
3853 if (mod->state == MODULE_STATE_UNFORMED)
3854 continue;
3855 pr_cont(" %s%s", mod->name, module_flags(mod, buf, true));
3856 }
3857
3858 print_unloaded_tainted_modules();
3859 preempt_enable();
3860 if (last_unloaded_module.name[0])
3861 pr_cont(" [last unloaded: %s%s]", last_unloaded_module.name,
3862 last_unloaded_module.taints);
3863 pr_cont("\n");
3864 }
3865
3866 #ifdef CONFIG_MODULE_DEBUGFS
3867 struct dentry *mod_debugfs_root;
3868
module_debugfs_init(void)3869 static int module_debugfs_init(void)
3870 {
3871 mod_debugfs_root = debugfs_create_dir("modules", NULL);
3872 return 0;
3873 }
3874 module_init(module_debugfs_init);
3875 #endif
3876