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