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