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