GNU Linux-libre 4.19.211-gnu1
[releases.git] / kernel / umh.c
1 /*
2  * umh - the kernel usermode helper
3  */
4 #include <linux/module.h>
5 #include <linux/sched.h>
6 #include <linux/sched/task.h>
7 #include <linux/binfmts.h>
8 #include <linux/syscalls.h>
9 #include <linux/unistd.h>
10 #include <linux/kmod.h>
11 #include <linux/slab.h>
12 #include <linux/completion.h>
13 #include <linux/cred.h>
14 #include <linux/file.h>
15 #include <linux/fdtable.h>
16 #include <linux/fs_struct.h>
17 #include <linux/workqueue.h>
18 #include <linux/security.h>
19 #include <linux/mount.h>
20 #include <linux/kernel.h>
21 #include <linux/init.h>
22 #include <linux/resource.h>
23 #include <linux/notifier.h>
24 #include <linux/suspend.h>
25 #include <linux/rwsem.h>
26 #include <linux/ptrace.h>
27 #include <linux/async.h>
28 #include <linux/uaccess.h>
29 #include <linux/shmem_fs.h>
30 #include <linux/pipe_fs_i.h>
31
32 #include <trace/events/module.h>
33
34 #define CAP_BSET        (void *)1
35 #define CAP_PI          (void *)2
36
37 static kernel_cap_t usermodehelper_bset = CAP_FULL_SET;
38 static kernel_cap_t usermodehelper_inheritable = CAP_FULL_SET;
39 static DEFINE_SPINLOCK(umh_sysctl_lock);
40 static DECLARE_RWSEM(umhelper_sem);
41
42 static void call_usermodehelper_freeinfo(struct subprocess_info *info)
43 {
44         if (info->cleanup)
45                 (*info->cleanup)(info);
46         kfree(info);
47 }
48
49 static void umh_complete(struct subprocess_info *sub_info)
50 {
51         struct completion *comp = xchg(&sub_info->complete, NULL);
52         /*
53          * See call_usermodehelper_exec(). If xchg() returns NULL
54          * we own sub_info, the UMH_KILLABLE caller has gone away
55          * or the caller used UMH_NO_WAIT.
56          */
57         if (comp)
58                 complete(comp);
59         else
60                 call_usermodehelper_freeinfo(sub_info);
61 }
62
63 /*
64  * This is the task which runs the usermode application
65  */
66 static int call_usermodehelper_exec_async(void *data)
67 {
68         struct subprocess_info *sub_info = data;
69         struct cred *new;
70         int retval;
71
72         spin_lock_irq(&current->sighand->siglock);
73         flush_signal_handlers(current, 1);
74         spin_unlock_irq(&current->sighand->siglock);
75
76         /*
77          * Initial kernel threads share ther FS with init, in order to
78          * get the init root directory. But we've now created a new
79          * thread that is going to execve a user process and has its own
80          * 'struct fs_struct'. Reset umask to the default.
81          */
82         current->fs->umask = 0022;
83
84         /*
85          * Our parent (unbound workqueue) runs with elevated scheduling
86          * priority. Avoid propagating that into the userspace child.
87          */
88         set_user_nice(current, 0);
89
90         retval = -ENOMEM;
91         new = prepare_kernel_cred(current);
92         if (!new)
93                 goto out;
94
95         spin_lock(&umh_sysctl_lock);
96         new->cap_bset = cap_intersect(usermodehelper_bset, new->cap_bset);
97         new->cap_inheritable = cap_intersect(usermodehelper_inheritable,
98                                              new->cap_inheritable);
99         spin_unlock(&umh_sysctl_lock);
100
101         if (sub_info->init) {
102                 retval = sub_info->init(sub_info, new);
103                 if (retval) {
104                         abort_creds(new);
105                         goto out;
106                 }
107         }
108
109         commit_creds(new);
110
111         sub_info->pid = task_pid_nr(current);
112         if (sub_info->file)
113                 retval = do_execve_file(sub_info->file,
114                                         sub_info->argv, sub_info->envp);
115         else
116                 retval = do_execve(getname_kernel(sub_info->path),
117                                    (const char __user *const __user *)sub_info->argv,
118                                    (const char __user *const __user *)sub_info->envp);
119 out:
120         sub_info->retval = retval;
121         /*
122          * call_usermodehelper_exec_sync() will call umh_complete
123          * if UHM_WAIT_PROC.
124          */
125         if (!(sub_info->wait & UMH_WAIT_PROC))
126                 umh_complete(sub_info);
127         if (!retval)
128                 return 0;
129         do_exit(0);
130 }
131
132 /* Handles UMH_WAIT_PROC.  */
133 static void call_usermodehelper_exec_sync(struct subprocess_info *sub_info)
134 {
135         pid_t pid;
136
137         /* If SIGCLD is ignored kernel_wait4 won't populate the status. */
138         kernel_sigaction(SIGCHLD, SIG_DFL);
139         pid = kernel_thread(call_usermodehelper_exec_async, sub_info, SIGCHLD);
140         if (pid < 0) {
141                 sub_info->retval = pid;
142         } else {
143                 int ret = -ECHILD;
144                 /*
145                  * Normally it is bogus to call wait4() from in-kernel because
146                  * wait4() wants to write the exit code to a userspace address.
147                  * But call_usermodehelper_exec_sync() always runs as kernel
148                  * thread (workqueue) and put_user() to a kernel address works
149                  * OK for kernel threads, due to their having an mm_segment_t
150                  * which spans the entire address space.
151                  *
152                  * Thus the __user pointer cast is valid here.
153                  */
154                 kernel_wait4(pid, (int __user *)&ret, 0, NULL);
155
156                 /*
157                  * If ret is 0, either call_usermodehelper_exec_async failed and
158                  * the real error code is already in sub_info->retval or
159                  * sub_info->retval is 0 anyway, so don't mess with it then.
160                  */
161                 if (ret)
162                         sub_info->retval = ret;
163         }
164
165         /* Restore default kernel sig handler */
166         kernel_sigaction(SIGCHLD, SIG_IGN);
167
168         umh_complete(sub_info);
169 }
170
171 /*
172  * We need to create the usermodehelper kernel thread from a task that is affine
173  * to an optimized set of CPUs (or nohz housekeeping ones) such that they
174  * inherit a widest affinity irrespective of call_usermodehelper() callers with
175  * possibly reduced affinity (eg: per-cpu workqueues). We don't want
176  * usermodehelper targets to contend a busy CPU.
177  *
178  * Unbound workqueues provide such wide affinity and allow to block on
179  * UMH_WAIT_PROC requests without blocking pending request (up to some limit).
180  *
181  * Besides, workqueues provide the privilege level that caller might not have
182  * to perform the usermodehelper request.
183  *
184  */
185 static void call_usermodehelper_exec_work(struct work_struct *work)
186 {
187         struct subprocess_info *sub_info =
188                 container_of(work, struct subprocess_info, work);
189
190         if (sub_info->wait & UMH_WAIT_PROC) {
191                 call_usermodehelper_exec_sync(sub_info);
192         } else {
193                 pid_t pid;
194                 /*
195                  * Use CLONE_PARENT to reparent it to kthreadd; we do not
196                  * want to pollute current->children, and we need a parent
197                  * that always ignores SIGCHLD to ensure auto-reaping.
198                  */
199                 pid = kernel_thread(call_usermodehelper_exec_async, sub_info,
200                                     CLONE_PARENT | SIGCHLD);
201                 if (pid < 0) {
202                         sub_info->retval = pid;
203                         umh_complete(sub_info);
204                 }
205         }
206 }
207
208 /*
209  * If set, call_usermodehelper_exec() will exit immediately returning -EBUSY
210  * (used for preventing user land processes from being created after the user
211  * land has been frozen during a system-wide hibernation or suspend operation).
212  * Should always be manipulated under umhelper_sem acquired for write.
213  */
214 static enum umh_disable_depth usermodehelper_disabled = UMH_DISABLED;
215
216 /* Number of helpers running */
217 static atomic_t running_helpers = ATOMIC_INIT(0);
218
219 /*
220  * Wait queue head used by usermodehelper_disable() to wait for all running
221  * helpers to finish.
222  */
223 static DECLARE_WAIT_QUEUE_HEAD(running_helpers_waitq);
224
225 /*
226  * Used by usermodehelper_read_lock_wait() to wait for usermodehelper_disabled
227  * to become 'false'.
228  */
229 static DECLARE_WAIT_QUEUE_HEAD(usermodehelper_disabled_waitq);
230
231 /*
232  * Time to wait for running_helpers to become zero before the setting of
233  * usermodehelper_disabled in usermodehelper_disable() fails
234  */
235 #define RUNNING_HELPERS_TIMEOUT (5 * HZ)
236
237 int usermodehelper_read_trylock(void)
238 {
239         DEFINE_WAIT(wait);
240         int ret = 0;
241
242         down_read(&umhelper_sem);
243         for (;;) {
244                 prepare_to_wait(&usermodehelper_disabled_waitq, &wait,
245                                 TASK_INTERRUPTIBLE);
246                 if (!usermodehelper_disabled)
247                         break;
248
249                 if (usermodehelper_disabled == UMH_DISABLED)
250                         ret = -EAGAIN;
251
252                 up_read(&umhelper_sem);
253
254                 if (ret)
255                         break;
256
257                 schedule();
258                 try_to_freeze();
259
260                 down_read(&umhelper_sem);
261         }
262         finish_wait(&usermodehelper_disabled_waitq, &wait);
263         return ret;
264 }
265 EXPORT_SYMBOL_GPL(usermodehelper_read_trylock);
266
267 long usermodehelper_read_lock_wait(long timeout)
268 {
269         DEFINE_WAIT(wait);
270
271         if (timeout < 0)
272                 return -EINVAL;
273
274         down_read(&umhelper_sem);
275         for (;;) {
276                 prepare_to_wait(&usermodehelper_disabled_waitq, &wait,
277                                 TASK_UNINTERRUPTIBLE);
278                 if (!usermodehelper_disabled)
279                         break;
280
281                 up_read(&umhelper_sem);
282
283                 timeout = schedule_timeout(timeout);
284                 if (!timeout)
285                         break;
286
287                 down_read(&umhelper_sem);
288         }
289         finish_wait(&usermodehelper_disabled_waitq, &wait);
290         return timeout;
291 }
292 EXPORT_SYMBOL_GPL(usermodehelper_read_lock_wait);
293
294 void usermodehelper_read_unlock(void)
295 {
296         up_read(&umhelper_sem);
297 }
298 EXPORT_SYMBOL_GPL(usermodehelper_read_unlock);
299
300 /**
301  * __usermodehelper_set_disable_depth - Modify usermodehelper_disabled.
302  * @depth: New value to assign to usermodehelper_disabled.
303  *
304  * Change the value of usermodehelper_disabled (under umhelper_sem locked for
305  * writing) and wakeup tasks waiting for it to change.
306  */
307 void __usermodehelper_set_disable_depth(enum umh_disable_depth depth)
308 {
309         down_write(&umhelper_sem);
310         usermodehelper_disabled = depth;
311         wake_up(&usermodehelper_disabled_waitq);
312         up_write(&umhelper_sem);
313 }
314
315 /**
316  * __usermodehelper_disable - Prevent new helpers from being started.
317  * @depth: New value to assign to usermodehelper_disabled.
318  *
319  * Set usermodehelper_disabled to @depth and wait for running helpers to exit.
320  */
321 int __usermodehelper_disable(enum umh_disable_depth depth)
322 {
323         long retval;
324
325         if (!depth)
326                 return -EINVAL;
327
328         down_write(&umhelper_sem);
329         usermodehelper_disabled = depth;
330         up_write(&umhelper_sem);
331
332         /*
333          * From now on call_usermodehelper_exec() won't start any new
334          * helpers, so it is sufficient if running_helpers turns out to
335          * be zero at one point (it may be increased later, but that
336          * doesn't matter).
337          */
338         retval = wait_event_timeout(running_helpers_waitq,
339                                         atomic_read(&running_helpers) == 0,
340                                         RUNNING_HELPERS_TIMEOUT);
341         if (retval)
342                 return 0;
343
344         __usermodehelper_set_disable_depth(UMH_ENABLED);
345         return -EAGAIN;
346 }
347
348 static void helper_lock(void)
349 {
350         atomic_inc(&running_helpers);
351         smp_mb__after_atomic();
352 }
353
354 static void helper_unlock(void)
355 {
356         if (atomic_dec_and_test(&running_helpers))
357                 wake_up(&running_helpers_waitq);
358 }
359
360 /**
361  * call_usermodehelper_setup - prepare to call a usermode helper
362  * @path: path to usermode executable
363  * @argv: arg vector for process
364  * @envp: environment for process
365  * @gfp_mask: gfp mask for memory allocation
366  * @cleanup: a cleanup function
367  * @init: an init function
368  * @data: arbitrary context sensitive data
369  *
370  * Returns either %NULL on allocation failure, or a subprocess_info
371  * structure.  This should be passed to call_usermodehelper_exec to
372  * exec the process and free the structure.
373  *
374  * The init function is used to customize the helper process prior to
375  * exec.  A non-zero return code causes the process to error out, exit,
376  * and return the failure to the calling process
377  *
378  * The cleanup function is just before ethe subprocess_info is about to
379  * be freed.  This can be used for freeing the argv and envp.  The
380  * Function must be runnable in either a process context or the
381  * context in which call_usermodehelper_exec is called.
382  */
383 struct subprocess_info *call_usermodehelper_setup(const char *path, char **argv,
384                 char **envp, gfp_t gfp_mask,
385                 int (*init)(struct subprocess_info *info, struct cred *new),
386                 void (*cleanup)(struct subprocess_info *info),
387                 void *data)
388 {
389         struct subprocess_info *sub_info;
390         sub_info = kzalloc(sizeof(struct subprocess_info), gfp_mask);
391         if (!sub_info)
392                 goto out;
393
394         INIT_WORK(&sub_info->work, call_usermodehelper_exec_work);
395
396 #ifdef CONFIG_STATIC_USERMODEHELPER
397         sub_info->path = CONFIG_STATIC_USERMODEHELPER_PATH;
398 #else
399         sub_info->path = path;
400 #endif
401         sub_info->argv = argv;
402         sub_info->envp = envp;
403
404         sub_info->cleanup = cleanup;
405         sub_info->init = init;
406         sub_info->data = data;
407   out:
408         return sub_info;
409 }
410 EXPORT_SYMBOL(call_usermodehelper_setup);
411
412 struct subprocess_info *call_usermodehelper_setup_file(struct file *file,
413                 int (*init)(struct subprocess_info *info, struct cred *new),
414                 void (*cleanup)(struct subprocess_info *info), void *data)
415 {
416         struct subprocess_info *sub_info;
417
418         sub_info = kzalloc(sizeof(struct subprocess_info), GFP_KERNEL);
419         if (!sub_info)
420                 return NULL;
421
422         INIT_WORK(&sub_info->work, call_usermodehelper_exec_work);
423         sub_info->path = "none";
424         sub_info->file = file;
425         sub_info->init = init;
426         sub_info->cleanup = cleanup;
427         sub_info->data = data;
428         return sub_info;
429 }
430
431 static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
432 {
433         struct umh_info *umh_info = info->data;
434         struct file *from_umh[2];
435         struct file *to_umh[2];
436         int err;
437
438         /* create pipe to send data to umh */
439         err = create_pipe_files(to_umh, 0);
440         if (err)
441                 return err;
442         err = replace_fd(0, to_umh[0], 0);
443         fput(to_umh[0]);
444         if (err < 0) {
445                 fput(to_umh[1]);
446                 return err;
447         }
448
449         /* create pipe to receive data from umh */
450         err = create_pipe_files(from_umh, 0);
451         if (err) {
452                 fput(to_umh[1]);
453                 replace_fd(0, NULL, 0);
454                 return err;
455         }
456         err = replace_fd(1, from_umh[1], 0);
457         fput(from_umh[1]);
458         if (err < 0) {
459                 fput(to_umh[1]);
460                 replace_fd(0, NULL, 0);
461                 fput(from_umh[0]);
462                 return err;
463         }
464
465         umh_info->pipe_to_umh = to_umh[1];
466         umh_info->pipe_from_umh = from_umh[0];
467         return 0;
468 }
469
470 static void umh_save_pid(struct subprocess_info *info)
471 {
472         struct umh_info *umh_info = info->data;
473
474         umh_info->pid = info->pid;
475 }
476
477 /**
478  * fork_usermode_blob - fork a blob of bytes as a usermode process
479  * @data: a blob of bytes that can be do_execv-ed as a file
480  * @len: length of the blob
481  * @info: information about usermode process (shouldn't be NULL)
482  *
483  * Returns either negative error or zero which indicates success
484  * in executing a blob of bytes as a usermode process. In such
485  * case 'struct umh_info *info' is populated with two pipes
486  * and a pid of the process. The caller is responsible for health
487  * check of the user process, killing it via pid, and closing the
488  * pipes when user process is no longer needed.
489  */
490 int fork_usermode_blob(void *data, size_t len, struct umh_info *info)
491 {
492         struct subprocess_info *sub_info;
493         struct file *file;
494         ssize_t written;
495         loff_t pos = 0;
496         int err;
497
498         file = shmem_kernel_file_setup("", len, 0);
499         if (IS_ERR(file))
500                 return PTR_ERR(file);
501
502         written = kernel_write(file, data, len, &pos);
503         if (written != len) {
504                 err = written;
505                 if (err >= 0)
506                         err = -ENOMEM;
507                 goto out;
508         }
509
510         err = -ENOMEM;
511         sub_info = call_usermodehelper_setup_file(file, umh_pipe_setup,
512                                                   umh_save_pid, info);
513         if (!sub_info)
514                 goto out;
515
516         err = call_usermodehelper_exec(sub_info, UMH_WAIT_EXEC);
517 out:
518         fput(file);
519         return err;
520 }
521 EXPORT_SYMBOL_GPL(fork_usermode_blob);
522
523 /**
524  * call_usermodehelper_exec - start a usermode application
525  * @sub_info: information about the subprocessa
526  * @wait: wait for the application to finish and return status.
527  *        when UMH_NO_WAIT don't wait at all, but you get no useful error back
528  *        when the program couldn't be exec'ed. This makes it safe to call
529  *        from interrupt context.
530  *
531  * Runs a user-space application.  The application is started
532  * asynchronously if wait is not set, and runs as a child of system workqueues.
533  * (ie. it runs with full root capabilities and optimized affinity).
534  *
535  * Note: successful return value does not guarantee the helper was called at
536  * all. You can't rely on sub_info->{init,cleanup} being called even for
537  * UMH_WAIT_* wait modes as STATIC_USERMODEHELPER_PATH="" turns all helpers
538  * into a successful no-op.
539  */
540 int call_usermodehelper_exec(struct subprocess_info *sub_info, int wait)
541 {
542         DECLARE_COMPLETION_ONSTACK(done);
543         int retval = 0;
544
545         if (!sub_info->path) {
546                 call_usermodehelper_freeinfo(sub_info);
547                 return -EINVAL;
548         }
549         helper_lock();
550         if (usermodehelper_disabled) {
551                 retval = -EBUSY;
552                 goto out;
553         }
554
555         /*
556          * If there is no binary for us to call, then just return and get out of
557          * here.  This allows us to set STATIC_USERMODEHELPER_PATH to "" and
558          * disable all call_usermodehelper() calls.
559          */
560         if (strlen(sub_info->path) == 0)
561                 goto out;
562
563         /*
564          * Set the completion pointer only if there is a waiter.
565          * This makes it possible to use umh_complete to free
566          * the data structure in case of UMH_NO_WAIT.
567          */
568         sub_info->complete = (wait == UMH_NO_WAIT) ? NULL : &done;
569         sub_info->wait = wait;
570
571         queue_work(system_unbound_wq, &sub_info->work);
572         if (wait == UMH_NO_WAIT)        /* task has freed sub_info */
573                 goto unlock;
574
575         if (wait & UMH_KILLABLE) {
576                 retval = wait_for_completion_killable(&done);
577                 if (!retval)
578                         goto wait_done;
579
580                 /* umh_complete() will see NULL and free sub_info */
581                 if (xchg(&sub_info->complete, NULL))
582                         goto unlock;
583                 /* fallthrough, umh_complete() was already called */
584         }
585
586         wait_for_completion(&done);
587 wait_done:
588         retval = sub_info->retval;
589 out:
590         call_usermodehelper_freeinfo(sub_info);
591 unlock:
592         helper_unlock();
593         return retval;
594 }
595 EXPORT_SYMBOL(call_usermodehelper_exec);
596
597 /**
598  * call_usermodehelper() - prepare and start a usermode application
599  * @path: path to usermode executable
600  * @argv: arg vector for process
601  * @envp: environment for process
602  * @wait: wait for the application to finish and return status.
603  *        when UMH_NO_WAIT don't wait at all, but you get no useful error back
604  *        when the program couldn't be exec'ed. This makes it safe to call
605  *        from interrupt context.
606  *
607  * This function is the equivalent to use call_usermodehelper_setup() and
608  * call_usermodehelper_exec().
609  */
610 int call_usermodehelper(const char *path, char **argv, char **envp, int wait)
611 {
612         struct subprocess_info *info;
613         gfp_t gfp_mask = (wait == UMH_NO_WAIT) ? GFP_ATOMIC : GFP_KERNEL;
614
615         info = call_usermodehelper_setup(path, argv, envp, gfp_mask,
616                                          NULL, NULL, NULL);
617         if (info == NULL)
618                 return -ENOMEM;
619
620         return call_usermodehelper_exec(info, wait);
621 }
622 EXPORT_SYMBOL(call_usermodehelper);
623
624 static int proc_cap_handler(struct ctl_table *table, int write,
625                          void __user *buffer, size_t *lenp, loff_t *ppos)
626 {
627         struct ctl_table t;
628         unsigned long cap_array[_KERNEL_CAPABILITY_U32S];
629         kernel_cap_t new_cap;
630         int err, i;
631
632         if (write && (!capable(CAP_SETPCAP) ||
633                       !capable(CAP_SYS_MODULE)))
634                 return -EPERM;
635
636         /*
637          * convert from the global kernel_cap_t to the ulong array to print to
638          * userspace if this is a read.
639          */
640         spin_lock(&umh_sysctl_lock);
641         for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)  {
642                 if (table->data == CAP_BSET)
643                         cap_array[i] = usermodehelper_bset.cap[i];
644                 else if (table->data == CAP_PI)
645                         cap_array[i] = usermodehelper_inheritable.cap[i];
646                 else
647                         BUG();
648         }
649         spin_unlock(&umh_sysctl_lock);
650
651         t = *table;
652         t.data = &cap_array;
653
654         /*
655          * actually read or write and array of ulongs from userspace.  Remember
656          * these are least significant 32 bits first
657          */
658         err = proc_doulongvec_minmax(&t, write, buffer, lenp, ppos);
659         if (err < 0)
660                 return err;
661
662         /*
663          * convert from the sysctl array of ulongs to the kernel_cap_t
664          * internal representation
665          */
666         for (i = 0; i < _KERNEL_CAPABILITY_U32S; i++)
667                 new_cap.cap[i] = cap_array[i];
668
669         /*
670          * Drop everything not in the new_cap (but don't add things)
671          */
672         if (write) {
673                 spin_lock(&umh_sysctl_lock);
674                 if (table->data == CAP_BSET)
675                         usermodehelper_bset = cap_intersect(usermodehelper_bset, new_cap);
676                 if (table->data == CAP_PI)
677                         usermodehelper_inheritable = cap_intersect(usermodehelper_inheritable, new_cap);
678                 spin_unlock(&umh_sysctl_lock);
679         }
680
681         return 0;
682 }
683
684 struct ctl_table usermodehelper_table[] = {
685         {
686                 .procname       = "bset",
687                 .data           = CAP_BSET,
688                 .maxlen         = _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
689                 .mode           = 0600,
690                 .proc_handler   = proc_cap_handler,
691         },
692         {
693                 .procname       = "inheritable",
694                 .data           = CAP_PI,
695                 .maxlen         = _KERNEL_CAPABILITY_U32S * sizeof(unsigned long),
696                 .mode           = 0600,
697                 .proc_handler   = proc_cap_handler,
698         },
699         { }
700 };