seccomp/cache: Lookup syscall allowlist bitmap for fast path
[linux-block.git] / kernel / seccomp.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * linux/kernel/seccomp.c
4  *
5  * Copyright 2004-2005  Andrea Arcangeli <andrea@cpushare.com>
6  *
7  * Copyright (C) 2012 Google, Inc.
8  * Will Drewry <wad@chromium.org>
9  *
10  * This defines a simple but solid secure-computing facility.
11  *
12  * Mode 1 uses a fixed list of allowed system calls.
13  * Mode 2 allows user-defined system call filters in the form
14  *        of Berkeley Packet Filters/Linux Socket Filters.
15  */
16 #define pr_fmt(fmt) "seccomp: " fmt
17
18 #include <linux/refcount.h>
19 #include <linux/audit.h>
20 #include <linux/compat.h>
21 #include <linux/coredump.h>
22 #include <linux/kmemleak.h>
23 #include <linux/nospec.h>
24 #include <linux/prctl.h>
25 #include <linux/sched.h>
26 #include <linux/sched/task_stack.h>
27 #include <linux/seccomp.h>
28 #include <linux/slab.h>
29 #include <linux/syscalls.h>
30 #include <linux/sysctl.h>
31
32 #ifdef CONFIG_HAVE_ARCH_SECCOMP_FILTER
33 #include <asm/syscall.h>
34 #endif
35
36 #ifdef CONFIG_SECCOMP_FILTER
37 #include <linux/file.h>
38 #include <linux/filter.h>
39 #include <linux/pid.h>
40 #include <linux/ptrace.h>
41 #include <linux/security.h>
42 #include <linux/tracehook.h>
43 #include <linux/uaccess.h>
44 #include <linux/anon_inodes.h>
45 #include <linux/lockdep.h>
46
47 /*
48  * When SECCOMP_IOCTL_NOTIF_ID_VALID was first introduced, it had the
49  * wrong direction flag in the ioctl number. This is the broken one,
50  * which the kernel needs to keep supporting until all userspaces stop
51  * using the wrong command number.
52  */
53 #define SECCOMP_IOCTL_NOTIF_ID_VALID_WRONG_DIR  SECCOMP_IOR(2, __u64)
54
55 enum notify_state {
56         SECCOMP_NOTIFY_INIT,
57         SECCOMP_NOTIFY_SENT,
58         SECCOMP_NOTIFY_REPLIED,
59 };
60
61 struct seccomp_knotif {
62         /* The struct pid of the task whose filter triggered the notification */
63         struct task_struct *task;
64
65         /* The "cookie" for this request; this is unique for this filter. */
66         u64 id;
67
68         /*
69          * The seccomp data. This pointer is valid the entire time this
70          * notification is active, since it comes from __seccomp_filter which
71          * eclipses the entire lifecycle here.
72          */
73         const struct seccomp_data *data;
74
75         /*
76          * Notification states. When SECCOMP_RET_USER_NOTIF is returned, a
77          * struct seccomp_knotif is created and starts out in INIT. Once the
78          * handler reads the notification off of an FD, it transitions to SENT.
79          * If a signal is received the state transitions back to INIT and
80          * another message is sent. When the userspace handler replies, state
81          * transitions to REPLIED.
82          */
83         enum notify_state state;
84
85         /* The return values, only valid when in SECCOMP_NOTIFY_REPLIED */
86         int error;
87         long val;
88         u32 flags;
89
90         /*
91          * Signals when this has changed states, such as the listener
92          * dying, a new seccomp addfd message, or changing to REPLIED
93          */
94         struct completion ready;
95
96         struct list_head list;
97
98         /* outstanding addfd requests */
99         struct list_head addfd;
100 };
101
102 /**
103  * struct seccomp_kaddfd - container for seccomp_addfd ioctl messages
104  *
105  * @file: A reference to the file to install in the other task
106  * @fd: The fd number to install it at. If the fd number is -1, it means the
107  *      installing process should allocate the fd as normal.
108  * @flags: The flags for the new file descriptor. At the moment, only O_CLOEXEC
109  *         is allowed.
110  * @ret: The return value of the installing process. It is set to the fd num
111  *       upon success (>= 0).
112  * @completion: Indicates that the installing process has completed fd
113  *              installation, or gone away (either due to successful
114  *              reply, or signal)
115  *
116  */
117 struct seccomp_kaddfd {
118         struct file *file;
119         int fd;
120         unsigned int flags;
121
122         /* To only be set on reply */
123         int ret;
124         struct completion completion;
125         struct list_head list;
126 };
127
128 /**
129  * struct notification - container for seccomp userspace notifications. Since
130  * most seccomp filters will not have notification listeners attached and this
131  * structure is fairly large, we store the notification-specific stuff in a
132  * separate structure.
133  *
134  * @request: A semaphore that users of this notification can wait on for
135  *           changes. Actual reads and writes are still controlled with
136  *           filter->notify_lock.
137  * @next_id: The id of the next request.
138  * @notifications: A list of struct seccomp_knotif elements.
139  */
140 struct notification {
141         struct semaphore request;
142         u64 next_id;
143         struct list_head notifications;
144 };
145
146 #ifdef SECCOMP_ARCH_NATIVE
147 /**
148  * struct action_cache - per-filter cache of seccomp actions per
149  * arch/syscall pair
150  *
151  * @allow_native: A bitmap where each bit represents whether the
152  *                filter will always allow the syscall, for the
153  *                native architecture.
154  * @allow_compat: A bitmap where each bit represents whether the
155  *                filter will always allow the syscall, for the
156  *                compat architecture.
157  */
158 struct action_cache {
159         DECLARE_BITMAP(allow_native, SECCOMP_ARCH_NATIVE_NR);
160 #ifdef SECCOMP_ARCH_COMPAT
161         DECLARE_BITMAP(allow_compat, SECCOMP_ARCH_COMPAT_NR);
162 #endif
163 };
164 #else
165 struct action_cache { };
166
167 static inline bool seccomp_cache_check_allow(const struct seccomp_filter *sfilter,
168                                              const struct seccomp_data *sd)
169 {
170         return false;
171 }
172 #endif /* SECCOMP_ARCH_NATIVE */
173
174 /**
175  * struct seccomp_filter - container for seccomp BPF programs
176  *
177  * @refs: Reference count to manage the object lifetime.
178  *        A filter's reference count is incremented for each directly
179  *        attached task, once for the dependent filter, and if
180  *        requested for the user notifier. When @refs reaches zero,
181  *        the filter can be freed.
182  * @users: A filter's @users count is incremented for each directly
183  *         attached task (filter installation, fork(), thread_sync),
184  *         and once for the dependent filter (tracked in filter->prev).
185  *         When it reaches zero it indicates that no direct or indirect
186  *         users of that filter exist. No new tasks can get associated with
187  *         this filter after reaching 0. The @users count is always smaller
188  *         or equal to @refs. Hence, reaching 0 for @users does not mean
189  *         the filter can be freed.
190  * @log: true if all actions except for SECCOMP_RET_ALLOW should be logged
191  * @prev: points to a previously installed, or inherited, filter
192  * @prog: the BPF program to evaluate
193  * @notif: the struct that holds all notification related information
194  * @notify_lock: A lock for all notification-related accesses.
195  * @wqh: A wait queue for poll if a notifier is in use.
196  *
197  * seccomp_filter objects are organized in a tree linked via the @prev
198  * pointer.  For any task, it appears to be a singly-linked list starting
199  * with current->seccomp.filter, the most recently attached or inherited filter.
200  * However, multiple filters may share a @prev node, by way of fork(), which
201  * results in a unidirectional tree existing in memory.  This is similar to
202  * how namespaces work.
203  *
204  * seccomp_filter objects should never be modified after being attached
205  * to a task_struct (other than @refs).
206  */
207 struct seccomp_filter {
208         refcount_t refs;
209         refcount_t users;
210         bool log;
211         struct seccomp_filter *prev;
212         struct bpf_prog *prog;
213         struct notification *notif;
214         struct mutex notify_lock;
215         wait_queue_head_t wqh;
216 };
217
218 /* Limit any path through the tree to 256KB worth of instructions. */
219 #define MAX_INSNS_PER_PATH ((1 << 18) / sizeof(struct sock_filter))
220
221 /*
222  * Endianness is explicitly ignored and left for BPF program authors to manage
223  * as per the specific architecture.
224  */
225 static void populate_seccomp_data(struct seccomp_data *sd)
226 {
227         /*
228          * Instead of using current_pt_reg(), we're already doing the work
229          * to safely fetch "current", so just use "task" everywhere below.
230          */
231         struct task_struct *task = current;
232         struct pt_regs *regs = task_pt_regs(task);
233         unsigned long args[6];
234
235         sd->nr = syscall_get_nr(task, regs);
236         sd->arch = syscall_get_arch(task);
237         syscall_get_arguments(task, regs, args);
238         sd->args[0] = args[0];
239         sd->args[1] = args[1];
240         sd->args[2] = args[2];
241         sd->args[3] = args[3];
242         sd->args[4] = args[4];
243         sd->args[5] = args[5];
244         sd->instruction_pointer = KSTK_EIP(task);
245 }
246
247 /**
248  *      seccomp_check_filter - verify seccomp filter code
249  *      @filter: filter to verify
250  *      @flen: length of filter
251  *
252  * Takes a previously checked filter (by bpf_check_classic) and
253  * redirects all filter code that loads struct sk_buff data
254  * and related data through seccomp_bpf_load.  It also
255  * enforces length and alignment checking of those loads.
256  *
257  * Returns 0 if the rule set is legal or -EINVAL if not.
258  */
259 static int seccomp_check_filter(struct sock_filter *filter, unsigned int flen)
260 {
261         int pc;
262         for (pc = 0; pc < flen; pc++) {
263                 struct sock_filter *ftest = &filter[pc];
264                 u16 code = ftest->code;
265                 u32 k = ftest->k;
266
267                 switch (code) {
268                 case BPF_LD | BPF_W | BPF_ABS:
269                         ftest->code = BPF_LDX | BPF_W | BPF_ABS;
270                         /* 32-bit aligned and not out of bounds. */
271                         if (k >= sizeof(struct seccomp_data) || k & 3)
272                                 return -EINVAL;
273                         continue;
274                 case BPF_LD | BPF_W | BPF_LEN:
275                         ftest->code = BPF_LD | BPF_IMM;
276                         ftest->k = sizeof(struct seccomp_data);
277                         continue;
278                 case BPF_LDX | BPF_W | BPF_LEN:
279                         ftest->code = BPF_LDX | BPF_IMM;
280                         ftest->k = sizeof(struct seccomp_data);
281                         continue;
282                 /* Explicitly include allowed calls. */
283                 case BPF_RET | BPF_K:
284                 case BPF_RET | BPF_A:
285                 case BPF_ALU | BPF_ADD | BPF_K:
286                 case BPF_ALU | BPF_ADD | BPF_X:
287                 case BPF_ALU | BPF_SUB | BPF_K:
288                 case BPF_ALU | BPF_SUB | BPF_X:
289                 case BPF_ALU | BPF_MUL | BPF_K:
290                 case BPF_ALU | BPF_MUL | BPF_X:
291                 case BPF_ALU | BPF_DIV | BPF_K:
292                 case BPF_ALU | BPF_DIV | BPF_X:
293                 case BPF_ALU | BPF_AND | BPF_K:
294                 case BPF_ALU | BPF_AND | BPF_X:
295                 case BPF_ALU | BPF_OR | BPF_K:
296                 case BPF_ALU | BPF_OR | BPF_X:
297                 case BPF_ALU | BPF_XOR | BPF_K:
298                 case BPF_ALU | BPF_XOR | BPF_X:
299                 case BPF_ALU | BPF_LSH | BPF_K:
300                 case BPF_ALU | BPF_LSH | BPF_X:
301                 case BPF_ALU | BPF_RSH | BPF_K:
302                 case BPF_ALU | BPF_RSH | BPF_X:
303                 case BPF_ALU | BPF_NEG:
304                 case BPF_LD | BPF_IMM:
305                 case BPF_LDX | BPF_IMM:
306                 case BPF_MISC | BPF_TAX:
307                 case BPF_MISC | BPF_TXA:
308                 case BPF_LD | BPF_MEM:
309                 case BPF_LDX | BPF_MEM:
310                 case BPF_ST:
311                 case BPF_STX:
312                 case BPF_JMP | BPF_JA:
313                 case BPF_JMP | BPF_JEQ | BPF_K:
314                 case BPF_JMP | BPF_JEQ | BPF_X:
315                 case BPF_JMP | BPF_JGE | BPF_K:
316                 case BPF_JMP | BPF_JGE | BPF_X:
317                 case BPF_JMP | BPF_JGT | BPF_K:
318                 case BPF_JMP | BPF_JGT | BPF_X:
319                 case BPF_JMP | BPF_JSET | BPF_K:
320                 case BPF_JMP | BPF_JSET | BPF_X:
321                         continue;
322                 default:
323                         return -EINVAL;
324                 }
325         }
326         return 0;
327 }
328
329 #ifdef SECCOMP_ARCH_NATIVE
330 static inline bool seccomp_cache_check_allow_bitmap(const void *bitmap,
331                                                     size_t bitmap_size,
332                                                     int syscall_nr)
333 {
334         if (unlikely(syscall_nr < 0 || syscall_nr >= bitmap_size))
335                 return false;
336         syscall_nr = array_index_nospec(syscall_nr, bitmap_size);
337
338         return test_bit(syscall_nr, bitmap);
339 }
340
341 /**
342  * seccomp_cache_check_allow - lookup seccomp cache
343  * @sfilter: The seccomp filter
344  * @sd: The seccomp data to lookup the cache with
345  *
346  * Returns true if the seccomp_data is cached and allowed.
347  */
348 static inline bool seccomp_cache_check_allow(const struct seccomp_filter *sfilter,
349                                              const struct seccomp_data *sd)
350 {
351         int syscall_nr = sd->nr;
352         const struct action_cache *cache = &sfilter->cache;
353
354 #ifndef SECCOMP_ARCH_COMPAT
355         /* A native-only architecture doesn't need to check sd->arch. */
356         return seccomp_cache_check_allow_bitmap(cache->allow_native,
357                                                 SECCOMP_ARCH_NATIVE_NR,
358                                                 syscall_nr);
359 #else
360         if (likely(sd->arch == SECCOMP_ARCH_NATIVE))
361                 return seccomp_cache_check_allow_bitmap(cache->allow_native,
362                                                         SECCOMP_ARCH_NATIVE_NR,
363                                                         syscall_nr);
364         if (likely(sd->arch == SECCOMP_ARCH_COMPAT))
365                 return seccomp_cache_check_allow_bitmap(cache->allow_compat,
366                                                         SECCOMP_ARCH_COMPAT_NR,
367                                                         syscall_nr);
368 #endif /* SECCOMP_ARCH_COMPAT */
369
370         WARN_ON_ONCE(true);
371         return false;
372 }
373 #endif /* SECCOMP_ARCH_NATIVE */
374
375 /**
376  * seccomp_run_filters - evaluates all seccomp filters against @sd
377  * @sd: optional seccomp data to be passed to filters
378  * @match: stores struct seccomp_filter that resulted in the return value,
379  *         unless filter returned SECCOMP_RET_ALLOW, in which case it will
380  *         be unchanged.
381  *
382  * Returns valid seccomp BPF response codes.
383  */
384 #define ACTION_ONLY(ret) ((s32)((ret) & (SECCOMP_RET_ACTION_FULL)))
385 static u32 seccomp_run_filters(const struct seccomp_data *sd,
386                                struct seccomp_filter **match)
387 {
388         u32 ret = SECCOMP_RET_ALLOW;
389         /* Make sure cross-thread synced filter points somewhere sane. */
390         struct seccomp_filter *f =
391                         READ_ONCE(current->seccomp.filter);
392
393         /* Ensure unexpected behavior doesn't result in failing open. */
394         if (WARN_ON(f == NULL))
395                 return SECCOMP_RET_KILL_PROCESS;
396
397         if (seccomp_cache_check_allow(f, sd))
398                 return SECCOMP_RET_ALLOW;
399
400         /*
401          * All filters in the list are evaluated and the lowest BPF return
402          * value always takes priority (ignoring the DATA).
403          */
404         for (; f; f = f->prev) {
405                 u32 cur_ret = bpf_prog_run_pin_on_cpu(f->prog, sd);
406
407                 if (ACTION_ONLY(cur_ret) < ACTION_ONLY(ret)) {
408                         ret = cur_ret;
409                         *match = f;
410                 }
411         }
412         return ret;
413 }
414 #endif /* CONFIG_SECCOMP_FILTER */
415
416 static inline bool seccomp_may_assign_mode(unsigned long seccomp_mode)
417 {
418         assert_spin_locked(&current->sighand->siglock);
419
420         if (current->seccomp.mode && current->seccomp.mode != seccomp_mode)
421                 return false;
422
423         return true;
424 }
425
426 void __weak arch_seccomp_spec_mitigate(struct task_struct *task) { }
427
428 static inline void seccomp_assign_mode(struct task_struct *task,
429                                        unsigned long seccomp_mode,
430                                        unsigned long flags)
431 {
432         assert_spin_locked(&task->sighand->siglock);
433
434         task->seccomp.mode = seccomp_mode;
435         /*
436          * Make sure TIF_SECCOMP cannot be set before the mode (and
437          * filter) is set.
438          */
439         smp_mb__before_atomic();
440         /* Assume default seccomp processes want spec flaw mitigation. */
441         if ((flags & SECCOMP_FILTER_FLAG_SPEC_ALLOW) == 0)
442                 arch_seccomp_spec_mitigate(task);
443         set_tsk_thread_flag(task, TIF_SECCOMP);
444 }
445
446 #ifdef CONFIG_SECCOMP_FILTER
447 /* Returns 1 if the parent is an ancestor of the child. */
448 static int is_ancestor(struct seccomp_filter *parent,
449                        struct seccomp_filter *child)
450 {
451         /* NULL is the root ancestor. */
452         if (parent == NULL)
453                 return 1;
454         for (; child; child = child->prev)
455                 if (child == parent)
456                         return 1;
457         return 0;
458 }
459
460 /**
461  * seccomp_can_sync_threads: checks if all threads can be synchronized
462  *
463  * Expects sighand and cred_guard_mutex locks to be held.
464  *
465  * Returns 0 on success, -ve on error, or the pid of a thread which was
466  * either not in the correct seccomp mode or did not have an ancestral
467  * seccomp filter.
468  */
469 static inline pid_t seccomp_can_sync_threads(void)
470 {
471         struct task_struct *thread, *caller;
472
473         BUG_ON(!mutex_is_locked(&current->signal->cred_guard_mutex));
474         assert_spin_locked(&current->sighand->siglock);
475
476         /* Validate all threads being eligible for synchronization. */
477         caller = current;
478         for_each_thread(caller, thread) {
479                 pid_t failed;
480
481                 /* Skip current, since it is initiating the sync. */
482                 if (thread == caller)
483                         continue;
484
485                 if (thread->seccomp.mode == SECCOMP_MODE_DISABLED ||
486                     (thread->seccomp.mode == SECCOMP_MODE_FILTER &&
487                      is_ancestor(thread->seccomp.filter,
488                                  caller->seccomp.filter)))
489                         continue;
490
491                 /* Return the first thread that cannot be synchronized. */
492                 failed = task_pid_vnr(thread);
493                 /* If the pid cannot be resolved, then return -ESRCH */
494                 if (WARN_ON(failed == 0))
495                         failed = -ESRCH;
496                 return failed;
497         }
498
499         return 0;
500 }
501
502 static inline void seccomp_filter_free(struct seccomp_filter *filter)
503 {
504         if (filter) {
505                 bpf_prog_destroy(filter->prog);
506                 kfree(filter);
507         }
508 }
509
510 static void __seccomp_filter_orphan(struct seccomp_filter *orig)
511 {
512         while (orig && refcount_dec_and_test(&orig->users)) {
513                 if (waitqueue_active(&orig->wqh))
514                         wake_up_poll(&orig->wqh, EPOLLHUP);
515                 orig = orig->prev;
516         }
517 }
518
519 static void __put_seccomp_filter(struct seccomp_filter *orig)
520 {
521         /* Clean up single-reference branches iteratively. */
522         while (orig && refcount_dec_and_test(&orig->refs)) {
523                 struct seccomp_filter *freeme = orig;
524                 orig = orig->prev;
525                 seccomp_filter_free(freeme);
526         }
527 }
528
529 static void __seccomp_filter_release(struct seccomp_filter *orig)
530 {
531         /* Notify about any unused filters in the task's former filter tree. */
532         __seccomp_filter_orphan(orig);
533         /* Finally drop all references to the task's former tree. */
534         __put_seccomp_filter(orig);
535 }
536
537 /**
538  * seccomp_filter_release - Detach the task from its filter tree,
539  *                          drop its reference count, and notify
540  *                          about unused filters
541  *
542  * This function should only be called when the task is exiting as
543  * it detaches it from its filter tree. As such, READ_ONCE() and
544  * barriers are not needed here, as would normally be needed.
545  */
546 void seccomp_filter_release(struct task_struct *tsk)
547 {
548         struct seccomp_filter *orig = tsk->seccomp.filter;
549
550         /* Detach task from its filter tree. */
551         tsk->seccomp.filter = NULL;
552         __seccomp_filter_release(orig);
553 }
554
555 /**
556  * seccomp_sync_threads: sets all threads to use current's filter
557  *
558  * Expects sighand and cred_guard_mutex locks to be held, and for
559  * seccomp_can_sync_threads() to have returned success already
560  * without dropping the locks.
561  *
562  */
563 static inline void seccomp_sync_threads(unsigned long flags)
564 {
565         struct task_struct *thread, *caller;
566
567         BUG_ON(!mutex_is_locked(&current->signal->cred_guard_mutex));
568         assert_spin_locked(&current->sighand->siglock);
569
570         /* Synchronize all threads. */
571         caller = current;
572         for_each_thread(caller, thread) {
573                 /* Skip current, since it needs no changes. */
574                 if (thread == caller)
575                         continue;
576
577                 /* Get a task reference for the new leaf node. */
578                 get_seccomp_filter(caller);
579
580                 /*
581                  * Drop the task reference to the shared ancestor since
582                  * current's path will hold a reference.  (This also
583                  * allows a put before the assignment.)
584                  */
585                 __seccomp_filter_release(thread->seccomp.filter);
586
587                 /* Make our new filter tree visible. */
588                 smp_store_release(&thread->seccomp.filter,
589                                   caller->seccomp.filter);
590                 atomic_set(&thread->seccomp.filter_count,
591                            atomic_read(&thread->seccomp.filter_count));
592
593                 /*
594                  * Don't let an unprivileged task work around
595                  * the no_new_privs restriction by creating
596                  * a thread that sets it up, enters seccomp,
597                  * then dies.
598                  */
599                 if (task_no_new_privs(caller))
600                         task_set_no_new_privs(thread);
601
602                 /*
603                  * Opt the other thread into seccomp if needed.
604                  * As threads are considered to be trust-realm
605                  * equivalent (see ptrace_may_access), it is safe to
606                  * allow one thread to transition the other.
607                  */
608                 if (thread->seccomp.mode == SECCOMP_MODE_DISABLED)
609                         seccomp_assign_mode(thread, SECCOMP_MODE_FILTER,
610                                             flags);
611         }
612 }
613
614 /**
615  * seccomp_prepare_filter: Prepares a seccomp filter for use.
616  * @fprog: BPF program to install
617  *
618  * Returns filter on success or an ERR_PTR on failure.
619  */
620 static struct seccomp_filter *seccomp_prepare_filter(struct sock_fprog *fprog)
621 {
622         struct seccomp_filter *sfilter;
623         int ret;
624         const bool save_orig = IS_ENABLED(CONFIG_CHECKPOINT_RESTORE);
625
626         if (fprog->len == 0 || fprog->len > BPF_MAXINSNS)
627                 return ERR_PTR(-EINVAL);
628
629         BUG_ON(INT_MAX / fprog->len < sizeof(struct sock_filter));
630
631         /*
632          * Installing a seccomp filter requires that the task has
633          * CAP_SYS_ADMIN in its namespace or be running with no_new_privs.
634          * This avoids scenarios where unprivileged tasks can affect the
635          * behavior of privileged children.
636          */
637         if (!task_no_new_privs(current) &&
638             security_capable(current_cred(), current_user_ns(),
639                                      CAP_SYS_ADMIN, CAP_OPT_NOAUDIT) != 0)
640                 return ERR_PTR(-EACCES);
641
642         /* Allocate a new seccomp_filter */
643         sfilter = kzalloc(sizeof(*sfilter), GFP_KERNEL | __GFP_NOWARN);
644         if (!sfilter)
645                 return ERR_PTR(-ENOMEM);
646
647         mutex_init(&sfilter->notify_lock);
648         ret = bpf_prog_create_from_user(&sfilter->prog, fprog,
649                                         seccomp_check_filter, save_orig);
650         if (ret < 0) {
651                 kfree(sfilter);
652                 return ERR_PTR(ret);
653         }
654
655         refcount_set(&sfilter->refs, 1);
656         refcount_set(&sfilter->users, 1);
657         init_waitqueue_head(&sfilter->wqh);
658
659         return sfilter;
660 }
661
662 /**
663  * seccomp_prepare_user_filter - prepares a user-supplied sock_fprog
664  * @user_filter: pointer to the user data containing a sock_fprog.
665  *
666  * Returns 0 on success and non-zero otherwise.
667  */
668 static struct seccomp_filter *
669 seccomp_prepare_user_filter(const char __user *user_filter)
670 {
671         struct sock_fprog fprog;
672         struct seccomp_filter *filter = ERR_PTR(-EFAULT);
673
674 #ifdef CONFIG_COMPAT
675         if (in_compat_syscall()) {
676                 struct compat_sock_fprog fprog32;
677                 if (copy_from_user(&fprog32, user_filter, sizeof(fprog32)))
678                         goto out;
679                 fprog.len = fprog32.len;
680                 fprog.filter = compat_ptr(fprog32.filter);
681         } else /* falls through to the if below. */
682 #endif
683         if (copy_from_user(&fprog, user_filter, sizeof(fprog)))
684                 goto out;
685         filter = seccomp_prepare_filter(&fprog);
686 out:
687         return filter;
688 }
689
690 /**
691  * seccomp_attach_filter: validate and attach filter
692  * @flags:  flags to change filter behavior
693  * @filter: seccomp filter to add to the current process
694  *
695  * Caller must be holding current->sighand->siglock lock.
696  *
697  * Returns 0 on success, -ve on error, or
698  *   - in TSYNC mode: the pid of a thread which was either not in the correct
699  *     seccomp mode or did not have an ancestral seccomp filter
700  *   - in NEW_LISTENER mode: the fd of the new listener
701  */
702 static long seccomp_attach_filter(unsigned int flags,
703                                   struct seccomp_filter *filter)
704 {
705         unsigned long total_insns;
706         struct seccomp_filter *walker;
707
708         assert_spin_locked(&current->sighand->siglock);
709
710         /* Validate resulting filter length. */
711         total_insns = filter->prog->len;
712         for (walker = current->seccomp.filter; walker; walker = walker->prev)
713                 total_insns += walker->prog->len + 4;  /* 4 instr penalty */
714         if (total_insns > MAX_INSNS_PER_PATH)
715                 return -ENOMEM;
716
717         /* If thread sync has been requested, check that it is possible. */
718         if (flags & SECCOMP_FILTER_FLAG_TSYNC) {
719                 int ret;
720
721                 ret = seccomp_can_sync_threads();
722                 if (ret) {
723                         if (flags & SECCOMP_FILTER_FLAG_TSYNC_ESRCH)
724                                 return -ESRCH;
725                         else
726                                 return ret;
727                 }
728         }
729
730         /* Set log flag, if present. */
731         if (flags & SECCOMP_FILTER_FLAG_LOG)
732                 filter->log = true;
733
734         /*
735          * If there is an existing filter, make it the prev and don't drop its
736          * task reference.
737          */
738         filter->prev = current->seccomp.filter;
739         current->seccomp.filter = filter;
740         atomic_inc(&current->seccomp.filter_count);
741
742         /* Now that the new filter is in place, synchronize to all threads. */
743         if (flags & SECCOMP_FILTER_FLAG_TSYNC)
744                 seccomp_sync_threads(flags);
745
746         return 0;
747 }
748
749 static void __get_seccomp_filter(struct seccomp_filter *filter)
750 {
751         refcount_inc(&filter->refs);
752 }
753
754 /* get_seccomp_filter - increments the reference count of the filter on @tsk */
755 void get_seccomp_filter(struct task_struct *tsk)
756 {
757         struct seccomp_filter *orig = tsk->seccomp.filter;
758         if (!orig)
759                 return;
760         __get_seccomp_filter(orig);
761         refcount_inc(&orig->users);
762 }
763
764 static void seccomp_init_siginfo(kernel_siginfo_t *info, int syscall, int reason)
765 {
766         clear_siginfo(info);
767         info->si_signo = SIGSYS;
768         info->si_code = SYS_SECCOMP;
769         info->si_call_addr = (void __user *)KSTK_EIP(current);
770         info->si_errno = reason;
771         info->si_arch = syscall_get_arch(current);
772         info->si_syscall = syscall;
773 }
774
775 /**
776  * seccomp_send_sigsys - signals the task to allow in-process syscall emulation
777  * @syscall: syscall number to send to userland
778  * @reason: filter-supplied reason code to send to userland (via si_errno)
779  *
780  * Forces a SIGSYS with a code of SYS_SECCOMP and related sigsys info.
781  */
782 static void seccomp_send_sigsys(int syscall, int reason)
783 {
784         struct kernel_siginfo info;
785         seccomp_init_siginfo(&info, syscall, reason);
786         force_sig_info(&info);
787 }
788 #endif  /* CONFIG_SECCOMP_FILTER */
789
790 /* For use with seccomp_actions_logged */
791 #define SECCOMP_LOG_KILL_PROCESS        (1 << 0)
792 #define SECCOMP_LOG_KILL_THREAD         (1 << 1)
793 #define SECCOMP_LOG_TRAP                (1 << 2)
794 #define SECCOMP_LOG_ERRNO               (1 << 3)
795 #define SECCOMP_LOG_TRACE               (1 << 4)
796 #define SECCOMP_LOG_LOG                 (1 << 5)
797 #define SECCOMP_LOG_ALLOW               (1 << 6)
798 #define SECCOMP_LOG_USER_NOTIF          (1 << 7)
799
800 static u32 seccomp_actions_logged = SECCOMP_LOG_KILL_PROCESS |
801                                     SECCOMP_LOG_KILL_THREAD  |
802                                     SECCOMP_LOG_TRAP  |
803                                     SECCOMP_LOG_ERRNO |
804                                     SECCOMP_LOG_USER_NOTIF |
805                                     SECCOMP_LOG_TRACE |
806                                     SECCOMP_LOG_LOG;
807
808 static inline void seccomp_log(unsigned long syscall, long signr, u32 action,
809                                bool requested)
810 {
811         bool log = false;
812
813         switch (action) {
814         case SECCOMP_RET_ALLOW:
815                 break;
816         case SECCOMP_RET_TRAP:
817                 log = requested && seccomp_actions_logged & SECCOMP_LOG_TRAP;
818                 break;
819         case SECCOMP_RET_ERRNO:
820                 log = requested && seccomp_actions_logged & SECCOMP_LOG_ERRNO;
821                 break;
822         case SECCOMP_RET_TRACE:
823                 log = requested && seccomp_actions_logged & SECCOMP_LOG_TRACE;
824                 break;
825         case SECCOMP_RET_USER_NOTIF:
826                 log = requested && seccomp_actions_logged & SECCOMP_LOG_USER_NOTIF;
827                 break;
828         case SECCOMP_RET_LOG:
829                 log = seccomp_actions_logged & SECCOMP_LOG_LOG;
830                 break;
831         case SECCOMP_RET_KILL_THREAD:
832                 log = seccomp_actions_logged & SECCOMP_LOG_KILL_THREAD;
833                 break;
834         case SECCOMP_RET_KILL_PROCESS:
835         default:
836                 log = seccomp_actions_logged & SECCOMP_LOG_KILL_PROCESS;
837         }
838
839         /*
840          * Emit an audit message when the action is RET_KILL_*, RET_LOG, or the
841          * FILTER_FLAG_LOG bit was set. The admin has the ability to silence
842          * any action from being logged by removing the action name from the
843          * seccomp_actions_logged sysctl.
844          */
845         if (!log)
846                 return;
847
848         audit_seccomp(syscall, signr, action);
849 }
850
851 /*
852  * Secure computing mode 1 allows only read/write/exit/sigreturn.
853  * To be fully secure this must be combined with rlimit
854  * to limit the stack allocations too.
855  */
856 static const int mode1_syscalls[] = {
857         __NR_seccomp_read, __NR_seccomp_write, __NR_seccomp_exit, __NR_seccomp_sigreturn,
858         -1, /* negative terminated */
859 };
860
861 static void __secure_computing_strict(int this_syscall)
862 {
863         const int *allowed_syscalls = mode1_syscalls;
864 #ifdef CONFIG_COMPAT
865         if (in_compat_syscall())
866                 allowed_syscalls = get_compat_mode1_syscalls();
867 #endif
868         do {
869                 if (*allowed_syscalls == this_syscall)
870                         return;
871         } while (*++allowed_syscalls != -1);
872
873 #ifdef SECCOMP_DEBUG
874         dump_stack();
875 #endif
876         seccomp_log(this_syscall, SIGKILL, SECCOMP_RET_KILL_THREAD, true);
877         do_exit(SIGKILL);
878 }
879
880 #ifndef CONFIG_HAVE_ARCH_SECCOMP_FILTER
881 void secure_computing_strict(int this_syscall)
882 {
883         int mode = current->seccomp.mode;
884
885         if (IS_ENABLED(CONFIG_CHECKPOINT_RESTORE) &&
886             unlikely(current->ptrace & PT_SUSPEND_SECCOMP))
887                 return;
888
889         if (mode == SECCOMP_MODE_DISABLED)
890                 return;
891         else if (mode == SECCOMP_MODE_STRICT)
892                 __secure_computing_strict(this_syscall);
893         else
894                 BUG();
895 }
896 #else
897
898 #ifdef CONFIG_SECCOMP_FILTER
899 static u64 seccomp_next_notify_id(struct seccomp_filter *filter)
900 {
901         /*
902          * Note: overflow is ok here, the id just needs to be unique per
903          * filter.
904          */
905         lockdep_assert_held(&filter->notify_lock);
906         return filter->notif->next_id++;
907 }
908
909 static void seccomp_handle_addfd(struct seccomp_kaddfd *addfd)
910 {
911         /*
912          * Remove the notification, and reset the list pointers, indicating
913          * that it has been handled.
914          */
915         list_del_init(&addfd->list);
916         addfd->ret = receive_fd_replace(addfd->fd, addfd->file, addfd->flags);
917         complete(&addfd->completion);
918 }
919
920 static int seccomp_do_user_notification(int this_syscall,
921                                         struct seccomp_filter *match,
922                                         const struct seccomp_data *sd)
923 {
924         int err;
925         u32 flags = 0;
926         long ret = 0;
927         struct seccomp_knotif n = {};
928         struct seccomp_kaddfd *addfd, *tmp;
929
930         mutex_lock(&match->notify_lock);
931         err = -ENOSYS;
932         if (!match->notif)
933                 goto out;
934
935         n.task = current;
936         n.state = SECCOMP_NOTIFY_INIT;
937         n.data = sd;
938         n.id = seccomp_next_notify_id(match);
939         init_completion(&n.ready);
940         list_add(&n.list, &match->notif->notifications);
941         INIT_LIST_HEAD(&n.addfd);
942
943         up(&match->notif->request);
944         wake_up_poll(&match->wqh, EPOLLIN | EPOLLRDNORM);
945         mutex_unlock(&match->notify_lock);
946
947         /*
948          * This is where we wait for a reply from userspace.
949          */
950 wait:
951         err = wait_for_completion_interruptible(&n.ready);
952         mutex_lock(&match->notify_lock);
953         if (err == 0) {
954                 /* Check if we were woken up by a addfd message */
955                 addfd = list_first_entry_or_null(&n.addfd,
956                                                  struct seccomp_kaddfd, list);
957                 if (addfd && n.state != SECCOMP_NOTIFY_REPLIED) {
958                         seccomp_handle_addfd(addfd);
959                         mutex_unlock(&match->notify_lock);
960                         goto wait;
961                 }
962                 ret = n.val;
963                 err = n.error;
964                 flags = n.flags;
965         }
966
967         /* If there were any pending addfd calls, clear them out */
968         list_for_each_entry_safe(addfd, tmp, &n.addfd, list) {
969                 /* The process went away before we got a chance to handle it */
970                 addfd->ret = -ESRCH;
971                 list_del_init(&addfd->list);
972                 complete(&addfd->completion);
973         }
974
975         /*
976          * Note that it's possible the listener died in between the time when
977          * we were notified of a response (or a signal) and when we were able to
978          * re-acquire the lock, so only delete from the list if the
979          * notification actually exists.
980          *
981          * Also note that this test is only valid because there's no way to
982          * *reattach* to a notifier right now. If one is added, we'll need to
983          * keep track of the notif itself and make sure they match here.
984          */
985         if (match->notif)
986                 list_del(&n.list);
987 out:
988         mutex_unlock(&match->notify_lock);
989
990         /* Userspace requests to continue the syscall. */
991         if (flags & SECCOMP_USER_NOTIF_FLAG_CONTINUE)
992                 return 0;
993
994         syscall_set_return_value(current, current_pt_regs(),
995                                  err, ret);
996         return -1;
997 }
998
999 static int __seccomp_filter(int this_syscall, const struct seccomp_data *sd,
1000                             const bool recheck_after_trace)
1001 {
1002         u32 filter_ret, action;
1003         struct seccomp_filter *match = NULL;
1004         int data;
1005         struct seccomp_data sd_local;
1006
1007         /*
1008          * Make sure that any changes to mode from another thread have
1009          * been seen after TIF_SECCOMP was seen.
1010          */
1011         rmb();
1012
1013         if (!sd) {
1014                 populate_seccomp_data(&sd_local);
1015                 sd = &sd_local;
1016         }
1017
1018         filter_ret = seccomp_run_filters(sd, &match);
1019         data = filter_ret & SECCOMP_RET_DATA;
1020         action = filter_ret & SECCOMP_RET_ACTION_FULL;
1021
1022         switch (action) {
1023         case SECCOMP_RET_ERRNO:
1024                 /* Set low-order bits as an errno, capped at MAX_ERRNO. */
1025                 if (data > MAX_ERRNO)
1026                         data = MAX_ERRNO;
1027                 syscall_set_return_value(current, current_pt_regs(),
1028                                          -data, 0);
1029                 goto skip;
1030
1031         case SECCOMP_RET_TRAP:
1032                 /* Show the handler the original registers. */
1033                 syscall_rollback(current, current_pt_regs());
1034                 /* Let the filter pass back 16 bits of data. */
1035                 seccomp_send_sigsys(this_syscall, data);
1036                 goto skip;
1037
1038         case SECCOMP_RET_TRACE:
1039                 /* We've been put in this state by the ptracer already. */
1040                 if (recheck_after_trace)
1041                         return 0;
1042
1043                 /* ENOSYS these calls if there is no tracer attached. */
1044                 if (!ptrace_event_enabled(current, PTRACE_EVENT_SECCOMP)) {
1045                         syscall_set_return_value(current,
1046                                                  current_pt_regs(),
1047                                                  -ENOSYS, 0);
1048                         goto skip;
1049                 }
1050
1051                 /* Allow the BPF to provide the event message */
1052                 ptrace_event(PTRACE_EVENT_SECCOMP, data);
1053                 /*
1054                  * The delivery of a fatal signal during event
1055                  * notification may silently skip tracer notification,
1056                  * which could leave us with a potentially unmodified
1057                  * syscall that the tracer would have liked to have
1058                  * changed. Since the process is about to die, we just
1059                  * force the syscall to be skipped and let the signal
1060                  * kill the process and correctly handle any tracer exit
1061                  * notifications.
1062                  */
1063                 if (fatal_signal_pending(current))
1064                         goto skip;
1065                 /* Check if the tracer forced the syscall to be skipped. */
1066                 this_syscall = syscall_get_nr(current, current_pt_regs());
1067                 if (this_syscall < 0)
1068                         goto skip;
1069
1070                 /*
1071                  * Recheck the syscall, since it may have changed. This
1072                  * intentionally uses a NULL struct seccomp_data to force
1073                  * a reload of all registers. This does not goto skip since
1074                  * a skip would have already been reported.
1075                  */
1076                 if (__seccomp_filter(this_syscall, NULL, true))
1077                         return -1;
1078
1079                 return 0;
1080
1081         case SECCOMP_RET_USER_NOTIF:
1082                 if (seccomp_do_user_notification(this_syscall, match, sd))
1083                         goto skip;
1084
1085                 return 0;
1086
1087         case SECCOMP_RET_LOG:
1088                 seccomp_log(this_syscall, 0, action, true);
1089                 return 0;
1090
1091         case SECCOMP_RET_ALLOW:
1092                 /*
1093                  * Note that the "match" filter will always be NULL for
1094                  * this action since SECCOMP_RET_ALLOW is the starting
1095                  * state in seccomp_run_filters().
1096                  */
1097                 return 0;
1098
1099         case SECCOMP_RET_KILL_THREAD:
1100         case SECCOMP_RET_KILL_PROCESS:
1101         default:
1102                 seccomp_log(this_syscall, SIGSYS, action, true);
1103                 /* Dump core only if this is the last remaining thread. */
1104                 if (action != SECCOMP_RET_KILL_THREAD ||
1105                     get_nr_threads(current) == 1) {
1106                         kernel_siginfo_t info;
1107
1108                         /* Show the original registers in the dump. */
1109                         syscall_rollback(current, current_pt_regs());
1110                         /* Trigger a manual coredump since do_exit skips it. */
1111                         seccomp_init_siginfo(&info, this_syscall, data);
1112                         do_coredump(&info);
1113                 }
1114                 if (action == SECCOMP_RET_KILL_THREAD)
1115                         do_exit(SIGSYS);
1116                 else
1117                         do_group_exit(SIGSYS);
1118         }
1119
1120         unreachable();
1121
1122 skip:
1123         seccomp_log(this_syscall, 0, action, match ? match->log : false);
1124         return -1;
1125 }
1126 #else
1127 static int __seccomp_filter(int this_syscall, const struct seccomp_data *sd,
1128                             const bool recheck_after_trace)
1129 {
1130         BUG();
1131 }
1132 #endif
1133
1134 int __secure_computing(const struct seccomp_data *sd)
1135 {
1136         int mode = current->seccomp.mode;
1137         int this_syscall;
1138
1139         if (IS_ENABLED(CONFIG_CHECKPOINT_RESTORE) &&
1140             unlikely(current->ptrace & PT_SUSPEND_SECCOMP))
1141                 return 0;
1142
1143         this_syscall = sd ? sd->nr :
1144                 syscall_get_nr(current, current_pt_regs());
1145
1146         switch (mode) {
1147         case SECCOMP_MODE_STRICT:
1148                 __secure_computing_strict(this_syscall);  /* may call do_exit */
1149                 return 0;
1150         case SECCOMP_MODE_FILTER:
1151                 return __seccomp_filter(this_syscall, sd, false);
1152         default:
1153                 BUG();
1154         }
1155 }
1156 #endif /* CONFIG_HAVE_ARCH_SECCOMP_FILTER */
1157
1158 long prctl_get_seccomp(void)
1159 {
1160         return current->seccomp.mode;
1161 }
1162
1163 /**
1164  * seccomp_set_mode_strict: internal function for setting strict seccomp
1165  *
1166  * Once current->seccomp.mode is non-zero, it may not be changed.
1167  *
1168  * Returns 0 on success or -EINVAL on failure.
1169  */
1170 static long seccomp_set_mode_strict(void)
1171 {
1172         const unsigned long seccomp_mode = SECCOMP_MODE_STRICT;
1173         long ret = -EINVAL;
1174
1175         spin_lock_irq(&current->sighand->siglock);
1176
1177         if (!seccomp_may_assign_mode(seccomp_mode))
1178                 goto out;
1179
1180 #ifdef TIF_NOTSC
1181         disable_TSC();
1182 #endif
1183         seccomp_assign_mode(current, seccomp_mode, 0);
1184         ret = 0;
1185
1186 out:
1187         spin_unlock_irq(&current->sighand->siglock);
1188
1189         return ret;
1190 }
1191
1192 #ifdef CONFIG_SECCOMP_FILTER
1193 static void seccomp_notify_free(struct seccomp_filter *filter)
1194 {
1195         kfree(filter->notif);
1196         filter->notif = NULL;
1197 }
1198
1199 static void seccomp_notify_detach(struct seccomp_filter *filter)
1200 {
1201         struct seccomp_knotif *knotif;
1202
1203         if (!filter)
1204                 return;
1205
1206         mutex_lock(&filter->notify_lock);
1207
1208         /*
1209          * If this file is being closed because e.g. the task who owned it
1210          * died, let's wake everyone up who was waiting on us.
1211          */
1212         list_for_each_entry(knotif, &filter->notif->notifications, list) {
1213                 if (knotif->state == SECCOMP_NOTIFY_REPLIED)
1214                         continue;
1215
1216                 knotif->state = SECCOMP_NOTIFY_REPLIED;
1217                 knotif->error = -ENOSYS;
1218                 knotif->val = 0;
1219
1220                 /*
1221                  * We do not need to wake up any pending addfd messages, as
1222                  * the notifier will do that for us, as this just looks
1223                  * like a standard reply.
1224                  */
1225                 complete(&knotif->ready);
1226         }
1227
1228         seccomp_notify_free(filter);
1229         mutex_unlock(&filter->notify_lock);
1230 }
1231
1232 static int seccomp_notify_release(struct inode *inode, struct file *file)
1233 {
1234         struct seccomp_filter *filter = file->private_data;
1235
1236         seccomp_notify_detach(filter);
1237         __put_seccomp_filter(filter);
1238         return 0;
1239 }
1240
1241 /* must be called with notif_lock held */
1242 static inline struct seccomp_knotif *
1243 find_notification(struct seccomp_filter *filter, u64 id)
1244 {
1245         struct seccomp_knotif *cur;
1246
1247         lockdep_assert_held(&filter->notify_lock);
1248
1249         list_for_each_entry(cur, &filter->notif->notifications, list) {
1250                 if (cur->id == id)
1251                         return cur;
1252         }
1253
1254         return NULL;
1255 }
1256
1257
1258 static long seccomp_notify_recv(struct seccomp_filter *filter,
1259                                 void __user *buf)
1260 {
1261         struct seccomp_knotif *knotif = NULL, *cur;
1262         struct seccomp_notif unotif;
1263         ssize_t ret;
1264
1265         /* Verify that we're not given garbage to keep struct extensible. */
1266         ret = check_zeroed_user(buf, sizeof(unotif));
1267         if (ret < 0)
1268                 return ret;
1269         if (!ret)
1270                 return -EINVAL;
1271
1272         memset(&unotif, 0, sizeof(unotif));
1273
1274         ret = down_interruptible(&filter->notif->request);
1275         if (ret < 0)
1276                 return ret;
1277
1278         mutex_lock(&filter->notify_lock);
1279         list_for_each_entry(cur, &filter->notif->notifications, list) {
1280                 if (cur->state == SECCOMP_NOTIFY_INIT) {
1281                         knotif = cur;
1282                         break;
1283                 }
1284         }
1285
1286         /*
1287          * If we didn't find a notification, it could be that the task was
1288          * interrupted by a fatal signal between the time we were woken and
1289          * when we were able to acquire the rw lock.
1290          */
1291         if (!knotif) {
1292                 ret = -ENOENT;
1293                 goto out;
1294         }
1295
1296         unotif.id = knotif->id;
1297         unotif.pid = task_pid_vnr(knotif->task);
1298         unotif.data = *(knotif->data);
1299
1300         knotif->state = SECCOMP_NOTIFY_SENT;
1301         wake_up_poll(&filter->wqh, EPOLLOUT | EPOLLWRNORM);
1302         ret = 0;
1303 out:
1304         mutex_unlock(&filter->notify_lock);
1305
1306         if (ret == 0 && copy_to_user(buf, &unotif, sizeof(unotif))) {
1307                 ret = -EFAULT;
1308
1309                 /*
1310                  * Userspace screwed up. To make sure that we keep this
1311                  * notification alive, let's reset it back to INIT. It
1312                  * may have died when we released the lock, so we need to make
1313                  * sure it's still around.
1314                  */
1315                 mutex_lock(&filter->notify_lock);
1316                 knotif = find_notification(filter, unotif.id);
1317                 if (knotif) {
1318                         knotif->state = SECCOMP_NOTIFY_INIT;
1319                         up(&filter->notif->request);
1320                 }
1321                 mutex_unlock(&filter->notify_lock);
1322         }
1323
1324         return ret;
1325 }
1326
1327 static long seccomp_notify_send(struct seccomp_filter *filter,
1328                                 void __user *buf)
1329 {
1330         struct seccomp_notif_resp resp = {};
1331         struct seccomp_knotif *knotif;
1332         long ret;
1333
1334         if (copy_from_user(&resp, buf, sizeof(resp)))
1335                 return -EFAULT;
1336
1337         if (resp.flags & ~SECCOMP_USER_NOTIF_FLAG_CONTINUE)
1338                 return -EINVAL;
1339
1340         if ((resp.flags & SECCOMP_USER_NOTIF_FLAG_CONTINUE) &&
1341             (resp.error || resp.val))
1342                 return -EINVAL;
1343
1344         ret = mutex_lock_interruptible(&filter->notify_lock);
1345         if (ret < 0)
1346                 return ret;
1347
1348         knotif = find_notification(filter, resp.id);
1349         if (!knotif) {
1350                 ret = -ENOENT;
1351                 goto out;
1352         }
1353
1354         /* Allow exactly one reply. */
1355         if (knotif->state != SECCOMP_NOTIFY_SENT) {
1356                 ret = -EINPROGRESS;
1357                 goto out;
1358         }
1359
1360         ret = 0;
1361         knotif->state = SECCOMP_NOTIFY_REPLIED;
1362         knotif->error = resp.error;
1363         knotif->val = resp.val;
1364         knotif->flags = resp.flags;
1365         complete(&knotif->ready);
1366 out:
1367         mutex_unlock(&filter->notify_lock);
1368         return ret;
1369 }
1370
1371 static long seccomp_notify_id_valid(struct seccomp_filter *filter,
1372                                     void __user *buf)
1373 {
1374         struct seccomp_knotif *knotif;
1375         u64 id;
1376         long ret;
1377
1378         if (copy_from_user(&id, buf, sizeof(id)))
1379                 return -EFAULT;
1380
1381         ret = mutex_lock_interruptible(&filter->notify_lock);
1382         if (ret < 0)
1383                 return ret;
1384
1385         knotif = find_notification(filter, id);
1386         if (knotif && knotif->state == SECCOMP_NOTIFY_SENT)
1387                 ret = 0;
1388         else
1389                 ret = -ENOENT;
1390
1391         mutex_unlock(&filter->notify_lock);
1392         return ret;
1393 }
1394
1395 static long seccomp_notify_addfd(struct seccomp_filter *filter,
1396                                  struct seccomp_notif_addfd __user *uaddfd,
1397                                  unsigned int size)
1398 {
1399         struct seccomp_notif_addfd addfd;
1400         struct seccomp_knotif *knotif;
1401         struct seccomp_kaddfd kaddfd;
1402         int ret;
1403
1404         BUILD_BUG_ON(sizeof(addfd) < SECCOMP_NOTIFY_ADDFD_SIZE_VER0);
1405         BUILD_BUG_ON(sizeof(addfd) != SECCOMP_NOTIFY_ADDFD_SIZE_LATEST);
1406
1407         if (size < SECCOMP_NOTIFY_ADDFD_SIZE_VER0 || size >= PAGE_SIZE)
1408                 return -EINVAL;
1409
1410         ret = copy_struct_from_user(&addfd, sizeof(addfd), uaddfd, size);
1411         if (ret)
1412                 return ret;
1413
1414         if (addfd.newfd_flags & ~O_CLOEXEC)
1415                 return -EINVAL;
1416
1417         if (addfd.flags & ~SECCOMP_ADDFD_FLAG_SETFD)
1418                 return -EINVAL;
1419
1420         if (addfd.newfd && !(addfd.flags & SECCOMP_ADDFD_FLAG_SETFD))
1421                 return -EINVAL;
1422
1423         kaddfd.file = fget(addfd.srcfd);
1424         if (!kaddfd.file)
1425                 return -EBADF;
1426
1427         kaddfd.flags = addfd.newfd_flags;
1428         kaddfd.fd = (addfd.flags & SECCOMP_ADDFD_FLAG_SETFD) ?
1429                     addfd.newfd : -1;
1430         init_completion(&kaddfd.completion);
1431
1432         ret = mutex_lock_interruptible(&filter->notify_lock);
1433         if (ret < 0)
1434                 goto out;
1435
1436         knotif = find_notification(filter, addfd.id);
1437         if (!knotif) {
1438                 ret = -ENOENT;
1439                 goto out_unlock;
1440         }
1441
1442         /*
1443          * We do not want to allow for FD injection to occur before the
1444          * notification has been picked up by a userspace handler, or after
1445          * the notification has been replied to.
1446          */
1447         if (knotif->state != SECCOMP_NOTIFY_SENT) {
1448                 ret = -EINPROGRESS;
1449                 goto out_unlock;
1450         }
1451
1452         list_add(&kaddfd.list, &knotif->addfd);
1453         complete(&knotif->ready);
1454         mutex_unlock(&filter->notify_lock);
1455
1456         /* Now we wait for it to be processed or be interrupted */
1457         ret = wait_for_completion_interruptible(&kaddfd.completion);
1458         if (ret == 0) {
1459                 /*
1460                  * We had a successful completion. The other side has already
1461                  * removed us from the addfd queue, and
1462                  * wait_for_completion_interruptible has a memory barrier upon
1463                  * success that lets us read this value directly without
1464                  * locking.
1465                  */
1466                 ret = kaddfd.ret;
1467                 goto out;
1468         }
1469
1470         mutex_lock(&filter->notify_lock);
1471         /*
1472          * Even though we were woken up by a signal and not a successful
1473          * completion, a completion may have happened in the mean time.
1474          *
1475          * We need to check again if the addfd request has been handled,
1476          * and if not, we will remove it from the queue.
1477          */
1478         if (list_empty(&kaddfd.list))
1479                 ret = kaddfd.ret;
1480         else
1481                 list_del(&kaddfd.list);
1482
1483 out_unlock:
1484         mutex_unlock(&filter->notify_lock);
1485 out:
1486         fput(kaddfd.file);
1487
1488         return ret;
1489 }
1490
1491 static long seccomp_notify_ioctl(struct file *file, unsigned int cmd,
1492                                  unsigned long arg)
1493 {
1494         struct seccomp_filter *filter = file->private_data;
1495         void __user *buf = (void __user *)arg;
1496
1497         /* Fixed-size ioctls */
1498         switch (cmd) {
1499         case SECCOMP_IOCTL_NOTIF_RECV:
1500                 return seccomp_notify_recv(filter, buf);
1501         case SECCOMP_IOCTL_NOTIF_SEND:
1502                 return seccomp_notify_send(filter, buf);
1503         case SECCOMP_IOCTL_NOTIF_ID_VALID_WRONG_DIR:
1504         case SECCOMP_IOCTL_NOTIF_ID_VALID:
1505                 return seccomp_notify_id_valid(filter, buf);
1506         }
1507
1508         /* Extensible Argument ioctls */
1509 #define EA_IOCTL(cmd)   ((cmd) & ~(IOC_INOUT | IOCSIZE_MASK))
1510         switch (EA_IOCTL(cmd)) {
1511         case EA_IOCTL(SECCOMP_IOCTL_NOTIF_ADDFD):
1512                 return seccomp_notify_addfd(filter, buf, _IOC_SIZE(cmd));
1513         default:
1514                 return -EINVAL;
1515         }
1516 }
1517
1518 static __poll_t seccomp_notify_poll(struct file *file,
1519                                     struct poll_table_struct *poll_tab)
1520 {
1521         struct seccomp_filter *filter = file->private_data;
1522         __poll_t ret = 0;
1523         struct seccomp_knotif *cur;
1524
1525         poll_wait(file, &filter->wqh, poll_tab);
1526
1527         if (mutex_lock_interruptible(&filter->notify_lock) < 0)
1528                 return EPOLLERR;
1529
1530         list_for_each_entry(cur, &filter->notif->notifications, list) {
1531                 if (cur->state == SECCOMP_NOTIFY_INIT)
1532                         ret |= EPOLLIN | EPOLLRDNORM;
1533                 if (cur->state == SECCOMP_NOTIFY_SENT)
1534                         ret |= EPOLLOUT | EPOLLWRNORM;
1535                 if ((ret & EPOLLIN) && (ret & EPOLLOUT))
1536                         break;
1537         }
1538
1539         mutex_unlock(&filter->notify_lock);
1540
1541         if (refcount_read(&filter->users) == 0)
1542                 ret |= EPOLLHUP;
1543
1544         return ret;
1545 }
1546
1547 static const struct file_operations seccomp_notify_ops = {
1548         .poll = seccomp_notify_poll,
1549         .release = seccomp_notify_release,
1550         .unlocked_ioctl = seccomp_notify_ioctl,
1551         .compat_ioctl = seccomp_notify_ioctl,
1552 };
1553
1554 static struct file *init_listener(struct seccomp_filter *filter)
1555 {
1556         struct file *ret;
1557
1558         ret = ERR_PTR(-ENOMEM);
1559         filter->notif = kzalloc(sizeof(*(filter->notif)), GFP_KERNEL);
1560         if (!filter->notif)
1561                 goto out;
1562
1563         sema_init(&filter->notif->request, 0);
1564         filter->notif->next_id = get_random_u64();
1565         INIT_LIST_HEAD(&filter->notif->notifications);
1566
1567         ret = anon_inode_getfile("seccomp notify", &seccomp_notify_ops,
1568                                  filter, O_RDWR);
1569         if (IS_ERR(ret))
1570                 goto out_notif;
1571
1572         /* The file has a reference to it now */
1573         __get_seccomp_filter(filter);
1574
1575 out_notif:
1576         if (IS_ERR(ret))
1577                 seccomp_notify_free(filter);
1578 out:
1579         return ret;
1580 }
1581
1582 /*
1583  * Does @new_child have a listener while an ancestor also has a listener?
1584  * If so, we'll want to reject this filter.
1585  * This only has to be tested for the current process, even in the TSYNC case,
1586  * because TSYNC installs @child with the same parent on all threads.
1587  * Note that @new_child is not hooked up to its parent at this point yet, so
1588  * we use current->seccomp.filter.
1589  */
1590 static bool has_duplicate_listener(struct seccomp_filter *new_child)
1591 {
1592         struct seccomp_filter *cur;
1593
1594         /* must be protected against concurrent TSYNC */
1595         lockdep_assert_held(&current->sighand->siglock);
1596
1597         if (!new_child->notif)
1598                 return false;
1599         for (cur = current->seccomp.filter; cur; cur = cur->prev) {
1600                 if (cur->notif)
1601                         return true;
1602         }
1603
1604         return false;
1605 }
1606
1607 /**
1608  * seccomp_set_mode_filter: internal function for setting seccomp filter
1609  * @flags:  flags to change filter behavior
1610  * @filter: struct sock_fprog containing filter
1611  *
1612  * This function may be called repeatedly to install additional filters.
1613  * Every filter successfully installed will be evaluated (in reverse order)
1614  * for each system call the task makes.
1615  *
1616  * Once current->seccomp.mode is non-zero, it may not be changed.
1617  *
1618  * Returns 0 on success or -EINVAL on failure.
1619  */
1620 static long seccomp_set_mode_filter(unsigned int flags,
1621                                     const char __user *filter)
1622 {
1623         const unsigned long seccomp_mode = SECCOMP_MODE_FILTER;
1624         struct seccomp_filter *prepared = NULL;
1625         long ret = -EINVAL;
1626         int listener = -1;
1627         struct file *listener_f = NULL;
1628
1629         /* Validate flags. */
1630         if (flags & ~SECCOMP_FILTER_FLAG_MASK)
1631                 return -EINVAL;
1632
1633         /*
1634          * In the successful case, NEW_LISTENER returns the new listener fd.
1635          * But in the failure case, TSYNC returns the thread that died. If you
1636          * combine these two flags, there's no way to tell whether something
1637          * succeeded or failed. So, let's disallow this combination if the user
1638          * has not explicitly requested no errors from TSYNC.
1639          */
1640         if ((flags & SECCOMP_FILTER_FLAG_TSYNC) &&
1641             (flags & SECCOMP_FILTER_FLAG_NEW_LISTENER) &&
1642             ((flags & SECCOMP_FILTER_FLAG_TSYNC_ESRCH) == 0))
1643                 return -EINVAL;
1644
1645         /* Prepare the new filter before holding any locks. */
1646         prepared = seccomp_prepare_user_filter(filter);
1647         if (IS_ERR(prepared))
1648                 return PTR_ERR(prepared);
1649
1650         if (flags & SECCOMP_FILTER_FLAG_NEW_LISTENER) {
1651                 listener = get_unused_fd_flags(O_CLOEXEC);
1652                 if (listener < 0) {
1653                         ret = listener;
1654                         goto out_free;
1655                 }
1656
1657                 listener_f = init_listener(prepared);
1658                 if (IS_ERR(listener_f)) {
1659                         put_unused_fd(listener);
1660                         ret = PTR_ERR(listener_f);
1661                         goto out_free;
1662                 }
1663         }
1664
1665         /*
1666          * Make sure we cannot change seccomp or nnp state via TSYNC
1667          * while another thread is in the middle of calling exec.
1668          */
1669         if (flags & SECCOMP_FILTER_FLAG_TSYNC &&
1670             mutex_lock_killable(&current->signal->cred_guard_mutex))
1671                 goto out_put_fd;
1672
1673         spin_lock_irq(&current->sighand->siglock);
1674
1675         if (!seccomp_may_assign_mode(seccomp_mode))
1676                 goto out;
1677
1678         if (has_duplicate_listener(prepared)) {
1679                 ret = -EBUSY;
1680                 goto out;
1681         }
1682
1683         ret = seccomp_attach_filter(flags, prepared);
1684         if (ret)
1685                 goto out;
1686         /* Do not free the successfully attached filter. */
1687         prepared = NULL;
1688
1689         seccomp_assign_mode(current, seccomp_mode, flags);
1690 out:
1691         spin_unlock_irq(&current->sighand->siglock);
1692         if (flags & SECCOMP_FILTER_FLAG_TSYNC)
1693                 mutex_unlock(&current->signal->cred_guard_mutex);
1694 out_put_fd:
1695         if (flags & SECCOMP_FILTER_FLAG_NEW_LISTENER) {
1696                 if (ret) {
1697                         listener_f->private_data = NULL;
1698                         fput(listener_f);
1699                         put_unused_fd(listener);
1700                         seccomp_notify_detach(prepared);
1701                 } else {
1702                         fd_install(listener, listener_f);
1703                         ret = listener;
1704                 }
1705         }
1706 out_free:
1707         seccomp_filter_free(prepared);
1708         return ret;
1709 }
1710 #else
1711 static inline long seccomp_set_mode_filter(unsigned int flags,
1712                                            const char __user *filter)
1713 {
1714         return -EINVAL;
1715 }
1716 #endif
1717
1718 static long seccomp_get_action_avail(const char __user *uaction)
1719 {
1720         u32 action;
1721
1722         if (copy_from_user(&action, uaction, sizeof(action)))
1723                 return -EFAULT;
1724
1725         switch (action) {
1726         case SECCOMP_RET_KILL_PROCESS:
1727         case SECCOMP_RET_KILL_THREAD:
1728         case SECCOMP_RET_TRAP:
1729         case SECCOMP_RET_ERRNO:
1730         case SECCOMP_RET_USER_NOTIF:
1731         case SECCOMP_RET_TRACE:
1732         case SECCOMP_RET_LOG:
1733         case SECCOMP_RET_ALLOW:
1734                 break;
1735         default:
1736                 return -EOPNOTSUPP;
1737         }
1738
1739         return 0;
1740 }
1741
1742 static long seccomp_get_notif_sizes(void __user *usizes)
1743 {
1744         struct seccomp_notif_sizes sizes = {
1745                 .seccomp_notif = sizeof(struct seccomp_notif),
1746                 .seccomp_notif_resp = sizeof(struct seccomp_notif_resp),
1747                 .seccomp_data = sizeof(struct seccomp_data),
1748         };
1749
1750         if (copy_to_user(usizes, &sizes, sizeof(sizes)))
1751                 return -EFAULT;
1752
1753         return 0;
1754 }
1755
1756 /* Common entry point for both prctl and syscall. */
1757 static long do_seccomp(unsigned int op, unsigned int flags,
1758                        void __user *uargs)
1759 {
1760         switch (op) {
1761         case SECCOMP_SET_MODE_STRICT:
1762                 if (flags != 0 || uargs != NULL)
1763                         return -EINVAL;
1764                 return seccomp_set_mode_strict();
1765         case SECCOMP_SET_MODE_FILTER:
1766                 return seccomp_set_mode_filter(flags, uargs);
1767         case SECCOMP_GET_ACTION_AVAIL:
1768                 if (flags != 0)
1769                         return -EINVAL;
1770
1771                 return seccomp_get_action_avail(uargs);
1772         case SECCOMP_GET_NOTIF_SIZES:
1773                 if (flags != 0)
1774                         return -EINVAL;
1775
1776                 return seccomp_get_notif_sizes(uargs);
1777         default:
1778                 return -EINVAL;
1779         }
1780 }
1781
1782 SYSCALL_DEFINE3(seccomp, unsigned int, op, unsigned int, flags,
1783                          void __user *, uargs)
1784 {
1785         return do_seccomp(op, flags, uargs);
1786 }
1787
1788 /**
1789  * prctl_set_seccomp: configures current->seccomp.mode
1790  * @seccomp_mode: requested mode to use
1791  * @filter: optional struct sock_fprog for use with SECCOMP_MODE_FILTER
1792  *
1793  * Returns 0 on success or -EINVAL on failure.
1794  */
1795 long prctl_set_seccomp(unsigned long seccomp_mode, void __user *filter)
1796 {
1797         unsigned int op;
1798         void __user *uargs;
1799
1800         switch (seccomp_mode) {
1801         case SECCOMP_MODE_STRICT:
1802                 op = SECCOMP_SET_MODE_STRICT;
1803                 /*
1804                  * Setting strict mode through prctl always ignored filter,
1805                  * so make sure it is always NULL here to pass the internal
1806                  * check in do_seccomp().
1807                  */
1808                 uargs = NULL;
1809                 break;
1810         case SECCOMP_MODE_FILTER:
1811                 op = SECCOMP_SET_MODE_FILTER;
1812                 uargs = filter;
1813                 break;
1814         default:
1815                 return -EINVAL;
1816         }
1817
1818         /* prctl interface doesn't have flags, so they are always zero. */
1819         return do_seccomp(op, 0, uargs);
1820 }
1821
1822 #if defined(CONFIG_SECCOMP_FILTER) && defined(CONFIG_CHECKPOINT_RESTORE)
1823 static struct seccomp_filter *get_nth_filter(struct task_struct *task,
1824                                              unsigned long filter_off)
1825 {
1826         struct seccomp_filter *orig, *filter;
1827         unsigned long count;
1828
1829         /*
1830          * Note: this is only correct because the caller should be the (ptrace)
1831          * tracer of the task, otherwise lock_task_sighand is needed.
1832          */
1833         spin_lock_irq(&task->sighand->siglock);
1834
1835         if (task->seccomp.mode != SECCOMP_MODE_FILTER) {
1836                 spin_unlock_irq(&task->sighand->siglock);
1837                 return ERR_PTR(-EINVAL);
1838         }
1839
1840         orig = task->seccomp.filter;
1841         __get_seccomp_filter(orig);
1842         spin_unlock_irq(&task->sighand->siglock);
1843
1844         count = 0;
1845         for (filter = orig; filter; filter = filter->prev)
1846                 count++;
1847
1848         if (filter_off >= count) {
1849                 filter = ERR_PTR(-ENOENT);
1850                 goto out;
1851         }
1852
1853         count -= filter_off;
1854         for (filter = orig; filter && count > 1; filter = filter->prev)
1855                 count--;
1856
1857         if (WARN_ON(count != 1 || !filter)) {
1858                 filter = ERR_PTR(-ENOENT);
1859                 goto out;
1860         }
1861
1862         __get_seccomp_filter(filter);
1863
1864 out:
1865         __put_seccomp_filter(orig);
1866         return filter;
1867 }
1868
1869 long seccomp_get_filter(struct task_struct *task, unsigned long filter_off,
1870                         void __user *data)
1871 {
1872         struct seccomp_filter *filter;
1873         struct sock_fprog_kern *fprog;
1874         long ret;
1875
1876         if (!capable(CAP_SYS_ADMIN) ||
1877             current->seccomp.mode != SECCOMP_MODE_DISABLED) {
1878                 return -EACCES;
1879         }
1880
1881         filter = get_nth_filter(task, filter_off);
1882         if (IS_ERR(filter))
1883                 return PTR_ERR(filter);
1884
1885         fprog = filter->prog->orig_prog;
1886         if (!fprog) {
1887                 /* This must be a new non-cBPF filter, since we save
1888                  * every cBPF filter's orig_prog above when
1889                  * CONFIG_CHECKPOINT_RESTORE is enabled.
1890                  */
1891                 ret = -EMEDIUMTYPE;
1892                 goto out;
1893         }
1894
1895         ret = fprog->len;
1896         if (!data)
1897                 goto out;
1898
1899         if (copy_to_user(data, fprog->filter, bpf_classic_proglen(fprog)))
1900                 ret = -EFAULT;
1901
1902 out:
1903         __put_seccomp_filter(filter);
1904         return ret;
1905 }
1906
1907 long seccomp_get_metadata(struct task_struct *task,
1908                           unsigned long size, void __user *data)
1909 {
1910         long ret;
1911         struct seccomp_filter *filter;
1912         struct seccomp_metadata kmd = {};
1913
1914         if (!capable(CAP_SYS_ADMIN) ||
1915             current->seccomp.mode != SECCOMP_MODE_DISABLED) {
1916                 return -EACCES;
1917         }
1918
1919         size = min_t(unsigned long, size, sizeof(kmd));
1920
1921         if (size < sizeof(kmd.filter_off))
1922                 return -EINVAL;
1923
1924         if (copy_from_user(&kmd.filter_off, data, sizeof(kmd.filter_off)))
1925                 return -EFAULT;
1926
1927         filter = get_nth_filter(task, kmd.filter_off);
1928         if (IS_ERR(filter))
1929                 return PTR_ERR(filter);
1930
1931         if (filter->log)
1932                 kmd.flags |= SECCOMP_FILTER_FLAG_LOG;
1933
1934         ret = size;
1935         if (copy_to_user(data, &kmd, size))
1936                 ret = -EFAULT;
1937
1938         __put_seccomp_filter(filter);
1939         return ret;
1940 }
1941 #endif
1942
1943 #ifdef CONFIG_SYSCTL
1944
1945 /* Human readable action names for friendly sysctl interaction */
1946 #define SECCOMP_RET_KILL_PROCESS_NAME   "kill_process"
1947 #define SECCOMP_RET_KILL_THREAD_NAME    "kill_thread"
1948 #define SECCOMP_RET_TRAP_NAME           "trap"
1949 #define SECCOMP_RET_ERRNO_NAME          "errno"
1950 #define SECCOMP_RET_USER_NOTIF_NAME     "user_notif"
1951 #define SECCOMP_RET_TRACE_NAME          "trace"
1952 #define SECCOMP_RET_LOG_NAME            "log"
1953 #define SECCOMP_RET_ALLOW_NAME          "allow"
1954
1955 static const char seccomp_actions_avail[] =
1956                                 SECCOMP_RET_KILL_PROCESS_NAME   " "
1957                                 SECCOMP_RET_KILL_THREAD_NAME    " "
1958                                 SECCOMP_RET_TRAP_NAME           " "
1959                                 SECCOMP_RET_ERRNO_NAME          " "
1960                                 SECCOMP_RET_USER_NOTIF_NAME     " "
1961                                 SECCOMP_RET_TRACE_NAME          " "
1962                                 SECCOMP_RET_LOG_NAME            " "
1963                                 SECCOMP_RET_ALLOW_NAME;
1964
1965 struct seccomp_log_name {
1966         u32             log;
1967         const char      *name;
1968 };
1969
1970 static const struct seccomp_log_name seccomp_log_names[] = {
1971         { SECCOMP_LOG_KILL_PROCESS, SECCOMP_RET_KILL_PROCESS_NAME },
1972         { SECCOMP_LOG_KILL_THREAD, SECCOMP_RET_KILL_THREAD_NAME },
1973         { SECCOMP_LOG_TRAP, SECCOMP_RET_TRAP_NAME },
1974         { SECCOMP_LOG_ERRNO, SECCOMP_RET_ERRNO_NAME },
1975         { SECCOMP_LOG_USER_NOTIF, SECCOMP_RET_USER_NOTIF_NAME },
1976         { SECCOMP_LOG_TRACE, SECCOMP_RET_TRACE_NAME },
1977         { SECCOMP_LOG_LOG, SECCOMP_RET_LOG_NAME },
1978         { SECCOMP_LOG_ALLOW, SECCOMP_RET_ALLOW_NAME },
1979         { }
1980 };
1981
1982 static bool seccomp_names_from_actions_logged(char *names, size_t size,
1983                                               u32 actions_logged,
1984                                               const char *sep)
1985 {
1986         const struct seccomp_log_name *cur;
1987         bool append_sep = false;
1988
1989         for (cur = seccomp_log_names; cur->name && size; cur++) {
1990                 ssize_t ret;
1991
1992                 if (!(actions_logged & cur->log))
1993                         continue;
1994
1995                 if (append_sep) {
1996                         ret = strscpy(names, sep, size);
1997                         if (ret < 0)
1998                                 return false;
1999
2000                         names += ret;
2001                         size -= ret;
2002                 } else
2003                         append_sep = true;
2004
2005                 ret = strscpy(names, cur->name, size);
2006                 if (ret < 0)
2007                         return false;
2008
2009                 names += ret;
2010                 size -= ret;
2011         }
2012
2013         return true;
2014 }
2015
2016 static bool seccomp_action_logged_from_name(u32 *action_logged,
2017                                             const char *name)
2018 {
2019         const struct seccomp_log_name *cur;
2020
2021         for (cur = seccomp_log_names; cur->name; cur++) {
2022                 if (!strcmp(cur->name, name)) {
2023                         *action_logged = cur->log;
2024                         return true;
2025                 }
2026         }
2027
2028         return false;
2029 }
2030
2031 static bool seccomp_actions_logged_from_names(u32 *actions_logged, char *names)
2032 {
2033         char *name;
2034
2035         *actions_logged = 0;
2036         while ((name = strsep(&names, " ")) && *name) {
2037                 u32 action_logged = 0;
2038
2039                 if (!seccomp_action_logged_from_name(&action_logged, name))
2040                         return false;
2041
2042                 *actions_logged |= action_logged;
2043         }
2044
2045         return true;
2046 }
2047
2048 static int read_actions_logged(struct ctl_table *ro_table, void __user *buffer,
2049                                size_t *lenp, loff_t *ppos)
2050 {
2051         char names[sizeof(seccomp_actions_avail)];
2052         struct ctl_table table;
2053
2054         memset(names, 0, sizeof(names));
2055
2056         if (!seccomp_names_from_actions_logged(names, sizeof(names),
2057                                                seccomp_actions_logged, " "))
2058                 return -EINVAL;
2059
2060         table = *ro_table;
2061         table.data = names;
2062         table.maxlen = sizeof(names);
2063         return proc_dostring(&table, 0, buffer, lenp, ppos);
2064 }
2065
2066 static int write_actions_logged(struct ctl_table *ro_table, void __user *buffer,
2067                                 size_t *lenp, loff_t *ppos, u32 *actions_logged)
2068 {
2069         char names[sizeof(seccomp_actions_avail)];
2070         struct ctl_table table;
2071         int ret;
2072
2073         if (!capable(CAP_SYS_ADMIN))
2074                 return -EPERM;
2075
2076         memset(names, 0, sizeof(names));
2077
2078         table = *ro_table;
2079         table.data = names;
2080         table.maxlen = sizeof(names);
2081         ret = proc_dostring(&table, 1, buffer, lenp, ppos);
2082         if (ret)
2083                 return ret;
2084
2085         if (!seccomp_actions_logged_from_names(actions_logged, table.data))
2086                 return -EINVAL;
2087
2088         if (*actions_logged & SECCOMP_LOG_ALLOW)
2089                 return -EINVAL;
2090
2091         seccomp_actions_logged = *actions_logged;
2092         return 0;
2093 }
2094
2095 static void audit_actions_logged(u32 actions_logged, u32 old_actions_logged,
2096                                  int ret)
2097 {
2098         char names[sizeof(seccomp_actions_avail)];
2099         char old_names[sizeof(seccomp_actions_avail)];
2100         const char *new = names;
2101         const char *old = old_names;
2102
2103         if (!audit_enabled)
2104                 return;
2105
2106         memset(names, 0, sizeof(names));
2107         memset(old_names, 0, sizeof(old_names));
2108
2109         if (ret)
2110                 new = "?";
2111         else if (!actions_logged)
2112                 new = "(none)";
2113         else if (!seccomp_names_from_actions_logged(names, sizeof(names),
2114                                                     actions_logged, ","))
2115                 new = "?";
2116
2117         if (!old_actions_logged)
2118                 old = "(none)";
2119         else if (!seccomp_names_from_actions_logged(old_names,
2120                                                     sizeof(old_names),
2121                                                     old_actions_logged, ","))
2122                 old = "?";
2123
2124         return audit_seccomp_actions_logged(new, old, !ret);
2125 }
2126
2127 static int seccomp_actions_logged_handler(struct ctl_table *ro_table, int write,
2128                                           void *buffer, size_t *lenp,
2129                                           loff_t *ppos)
2130 {
2131         int ret;
2132
2133         if (write) {
2134                 u32 actions_logged = 0;
2135                 u32 old_actions_logged = seccomp_actions_logged;
2136
2137                 ret = write_actions_logged(ro_table, buffer, lenp, ppos,
2138                                            &actions_logged);
2139                 audit_actions_logged(actions_logged, old_actions_logged, ret);
2140         } else
2141                 ret = read_actions_logged(ro_table, buffer, lenp, ppos);
2142
2143         return ret;
2144 }
2145
2146 static struct ctl_path seccomp_sysctl_path[] = {
2147         { .procname = "kernel", },
2148         { .procname = "seccomp", },
2149         { }
2150 };
2151
2152 static struct ctl_table seccomp_sysctl_table[] = {
2153         {
2154                 .procname       = "actions_avail",
2155                 .data           = (void *) &seccomp_actions_avail,
2156                 .maxlen         = sizeof(seccomp_actions_avail),
2157                 .mode           = 0444,
2158                 .proc_handler   = proc_dostring,
2159         },
2160         {
2161                 .procname       = "actions_logged",
2162                 .mode           = 0644,
2163                 .proc_handler   = seccomp_actions_logged_handler,
2164         },
2165         { }
2166 };
2167
2168 static int __init seccomp_sysctl_init(void)
2169 {
2170         struct ctl_table_header *hdr;
2171
2172         hdr = register_sysctl_paths(seccomp_sysctl_path, seccomp_sysctl_table);
2173         if (!hdr)
2174                 pr_warn("sysctl registration failed\n");
2175         else
2176                 kmemleak_not_leak(hdr);
2177
2178         return 0;
2179 }
2180
2181 device_initcall(seccomp_sysctl_init)
2182
2183 #endif /* CONFIG_SYSCTL */