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