seccomp: split filter prep from check and apply
[linux-block.git] / kernel / seccomp.c
1 /*
2  * linux/kernel/seccomp.c
3  *
4  * Copyright 2004-2005  Andrea Arcangeli <andrea@cpushare.com>
5  *
6  * Copyright (C) 2012 Google, Inc.
7  * Will Drewry <wad@chromium.org>
8  *
9  * This defines a simple but solid secure-computing facility.
10  *
11  * Mode 1 uses a fixed list of allowed system calls.
12  * Mode 2 allows user-defined system call filters in the form
13  *        of Berkeley Packet Filters/Linux Socket Filters.
14  */
15
16 #include <linux/atomic.h>
17 #include <linux/audit.h>
18 #include <linux/compat.h>
19 #include <linux/sched.h>
20 #include <linux/seccomp.h>
21 #include <linux/slab.h>
22 #include <linux/syscalls.h>
23
24 /* #define SECCOMP_DEBUG 1 */
25
26 #ifdef CONFIG_SECCOMP_FILTER
27 #include <asm/syscall.h>
28 #include <linux/filter.h>
29 #include <linux/ptrace.h>
30 #include <linux/security.h>
31 #include <linux/tracehook.h>
32 #include <linux/uaccess.h>
33
34 /**
35  * struct seccomp_filter - container for seccomp BPF programs
36  *
37  * @usage: reference count to manage the object lifetime.
38  *         get/put helpers should be used when accessing an instance
39  *         outside of a lifetime-guarded section.  In general, this
40  *         is only needed for handling filters shared across tasks.
41  * @prev: points to a previously installed, or inherited, filter
42  * @len: the number of instructions in the program
43  * @insnsi: the BPF program instructions to evaluate
44  *
45  * seccomp_filter objects are organized in a tree linked via the @prev
46  * pointer.  For any task, it appears to be a singly-linked list starting
47  * with current->seccomp.filter, the most recently attached or inherited filter.
48  * However, multiple filters may share a @prev node, by way of fork(), which
49  * results in a unidirectional tree existing in memory.  This is similar to
50  * how namespaces work.
51  *
52  * seccomp_filter objects should never be modified after being attached
53  * to a task_struct (other than @usage).
54  */
55 struct seccomp_filter {
56         atomic_t usage;
57         struct seccomp_filter *prev;
58         struct sk_filter *prog;
59 };
60
61 /* Limit any path through the tree to 256KB worth of instructions. */
62 #define MAX_INSNS_PER_PATH ((1 << 18) / sizeof(struct sock_filter))
63
64 /*
65  * Endianness is explicitly ignored and left for BPF program authors to manage
66  * as per the specific architecture.
67  */
68 static void populate_seccomp_data(struct seccomp_data *sd)
69 {
70         struct task_struct *task = current;
71         struct pt_regs *regs = task_pt_regs(task);
72         unsigned long args[6];
73
74         sd->nr = syscall_get_nr(task, regs);
75         sd->arch = syscall_get_arch();
76         syscall_get_arguments(task, regs, 0, 6, args);
77         sd->args[0] = args[0];
78         sd->args[1] = args[1];
79         sd->args[2] = args[2];
80         sd->args[3] = args[3];
81         sd->args[4] = args[4];
82         sd->args[5] = args[5];
83         sd->instruction_pointer = KSTK_EIP(task);
84 }
85
86 /**
87  *      seccomp_check_filter - verify seccomp filter code
88  *      @filter: filter to verify
89  *      @flen: length of filter
90  *
91  * Takes a previously checked filter (by sk_chk_filter) and
92  * redirects all filter code that loads struct sk_buff data
93  * and related data through seccomp_bpf_load.  It also
94  * enforces length and alignment checking of those loads.
95  *
96  * Returns 0 if the rule set is legal or -EINVAL if not.
97  */
98 static int seccomp_check_filter(struct sock_filter *filter, unsigned int flen)
99 {
100         int pc;
101         for (pc = 0; pc < flen; pc++) {
102                 struct sock_filter *ftest = &filter[pc];
103                 u16 code = ftest->code;
104                 u32 k = ftest->k;
105
106                 switch (code) {
107                 case BPF_LD | BPF_W | BPF_ABS:
108                         ftest->code = BPF_LDX | BPF_W | BPF_ABS;
109                         /* 32-bit aligned and not out of bounds. */
110                         if (k >= sizeof(struct seccomp_data) || k & 3)
111                                 return -EINVAL;
112                         continue;
113                 case BPF_LD | BPF_W | BPF_LEN:
114                         ftest->code = BPF_LD | BPF_IMM;
115                         ftest->k = sizeof(struct seccomp_data);
116                         continue;
117                 case BPF_LDX | BPF_W | BPF_LEN:
118                         ftest->code = BPF_LDX | BPF_IMM;
119                         ftest->k = sizeof(struct seccomp_data);
120                         continue;
121                 /* Explicitly include allowed calls. */
122                 case BPF_RET | BPF_K:
123                 case BPF_RET | BPF_A:
124                 case BPF_ALU | BPF_ADD | BPF_K:
125                 case BPF_ALU | BPF_ADD | BPF_X:
126                 case BPF_ALU | BPF_SUB | BPF_K:
127                 case BPF_ALU | BPF_SUB | BPF_X:
128                 case BPF_ALU | BPF_MUL | BPF_K:
129                 case BPF_ALU | BPF_MUL | BPF_X:
130                 case BPF_ALU | BPF_DIV | BPF_K:
131                 case BPF_ALU | BPF_DIV | BPF_X:
132                 case BPF_ALU | BPF_AND | BPF_K:
133                 case BPF_ALU | BPF_AND | BPF_X:
134                 case BPF_ALU | BPF_OR | BPF_K:
135                 case BPF_ALU | BPF_OR | BPF_X:
136                 case BPF_ALU | BPF_XOR | BPF_K:
137                 case BPF_ALU | BPF_XOR | BPF_X:
138                 case BPF_ALU | BPF_LSH | BPF_K:
139                 case BPF_ALU | BPF_LSH | BPF_X:
140                 case BPF_ALU | BPF_RSH | BPF_K:
141                 case BPF_ALU | BPF_RSH | BPF_X:
142                 case BPF_ALU | BPF_NEG:
143                 case BPF_LD | BPF_IMM:
144                 case BPF_LDX | BPF_IMM:
145                 case BPF_MISC | BPF_TAX:
146                 case BPF_MISC | BPF_TXA:
147                 case BPF_LD | BPF_MEM:
148                 case BPF_LDX | BPF_MEM:
149                 case BPF_ST:
150                 case BPF_STX:
151                 case BPF_JMP | BPF_JA:
152                 case BPF_JMP | BPF_JEQ | BPF_K:
153                 case BPF_JMP | BPF_JEQ | BPF_X:
154                 case BPF_JMP | BPF_JGE | BPF_K:
155                 case BPF_JMP | BPF_JGE | BPF_X:
156                 case BPF_JMP | BPF_JGT | BPF_K:
157                 case BPF_JMP | BPF_JGT | BPF_X:
158                 case BPF_JMP | BPF_JSET | BPF_K:
159                 case BPF_JMP | BPF_JSET | BPF_X:
160                         continue;
161                 default:
162                         return -EINVAL;
163                 }
164         }
165         return 0;
166 }
167
168 /**
169  * seccomp_run_filters - evaluates all seccomp filters against @syscall
170  * @syscall: number of the current system call
171  *
172  * Returns valid seccomp BPF response codes.
173  */
174 static u32 seccomp_run_filters(int syscall)
175 {
176         struct seccomp_filter *f;
177         struct seccomp_data sd;
178         u32 ret = SECCOMP_RET_ALLOW;
179
180         /* Ensure unexpected behavior doesn't result in failing open. */
181         if (WARN_ON(current->seccomp.filter == NULL))
182                 return SECCOMP_RET_KILL;
183
184         populate_seccomp_data(&sd);
185
186         /*
187          * All filters in the list are evaluated and the lowest BPF return
188          * value always takes priority (ignoring the DATA).
189          */
190         for (f = current->seccomp.filter; f; f = f->prev) {
191                 u32 cur_ret = SK_RUN_FILTER(f->prog, (void *)&sd);
192
193                 if ((cur_ret & SECCOMP_RET_ACTION) < (ret & SECCOMP_RET_ACTION))
194                         ret = cur_ret;
195         }
196         return ret;
197 }
198 #endif /* CONFIG_SECCOMP_FILTER */
199
200 static inline bool seccomp_may_assign_mode(unsigned long seccomp_mode)
201 {
202         if (current->seccomp.mode && current->seccomp.mode != seccomp_mode)
203                 return false;
204
205         return true;
206 }
207
208 static inline void seccomp_assign_mode(unsigned long seccomp_mode)
209 {
210         current->seccomp.mode = seccomp_mode;
211         set_tsk_thread_flag(current, TIF_SECCOMP);
212 }
213
214 #ifdef CONFIG_SECCOMP_FILTER
215 /**
216  * seccomp_prepare_filter: Prepares a seccomp filter for use.
217  * @fprog: BPF program to install
218  *
219  * Returns filter on success or an ERR_PTR on failure.
220  */
221 static struct seccomp_filter *seccomp_prepare_filter(struct sock_fprog *fprog)
222 {
223         struct seccomp_filter *filter;
224         unsigned long fp_size;
225         struct sock_filter *fp;
226         int new_len;
227         long ret;
228
229         if (fprog->len == 0 || fprog->len > BPF_MAXINSNS)
230                 return ERR_PTR(-EINVAL);
231         BUG_ON(INT_MAX / fprog->len < sizeof(struct sock_filter));
232         fp_size = fprog->len * sizeof(struct sock_filter);
233
234         /*
235          * Installing a seccomp filter requires that the task has
236          * CAP_SYS_ADMIN in its namespace or be running with no_new_privs.
237          * This avoids scenarios where unprivileged tasks can affect the
238          * behavior of privileged children.
239          */
240         if (!task_no_new_privs(current) &&
241             security_capable_noaudit(current_cred(), current_user_ns(),
242                                      CAP_SYS_ADMIN) != 0)
243                 return ERR_PTR(-EACCES);
244
245         fp = kzalloc(fp_size, GFP_KERNEL|__GFP_NOWARN);
246         if (!fp)
247                 return ERR_PTR(-ENOMEM);
248
249         /* Copy the instructions from fprog. */
250         ret = -EFAULT;
251         if (copy_from_user(fp, fprog->filter, fp_size))
252                 goto free_prog;
253
254         /* Check and rewrite the fprog via the skb checker */
255         ret = sk_chk_filter(fp, fprog->len);
256         if (ret)
257                 goto free_prog;
258
259         /* Check and rewrite the fprog for seccomp use */
260         ret = seccomp_check_filter(fp, fprog->len);
261         if (ret)
262                 goto free_prog;
263
264         /* Convert 'sock_filter' insns to 'sock_filter_int' insns */
265         ret = sk_convert_filter(fp, fprog->len, NULL, &new_len);
266         if (ret)
267                 goto free_prog;
268
269         /* Allocate a new seccomp_filter */
270         ret = -ENOMEM;
271         filter = kzalloc(sizeof(struct seccomp_filter),
272                          GFP_KERNEL|__GFP_NOWARN);
273         if (!filter)
274                 goto free_prog;
275
276         filter->prog = kzalloc(sk_filter_size(new_len),
277                                GFP_KERNEL|__GFP_NOWARN);
278         if (!filter->prog)
279                 goto free_filter;
280
281         ret = sk_convert_filter(fp, fprog->len, filter->prog->insnsi, &new_len);
282         if (ret)
283                 goto free_filter_prog;
284         kfree(fp);
285
286         atomic_set(&filter->usage, 1);
287         filter->prog->len = new_len;
288
289         sk_filter_select_runtime(filter->prog);
290
291         return filter;
292
293 free_filter_prog:
294         kfree(filter->prog);
295 free_filter:
296         kfree(filter);
297 free_prog:
298         kfree(fp);
299         return ERR_PTR(ret);
300 }
301
302 /**
303  * seccomp_prepare_user_filter - prepares a user-supplied sock_fprog
304  * @user_filter: pointer to the user data containing a sock_fprog.
305  *
306  * Returns 0 on success and non-zero otherwise.
307  */
308 static struct seccomp_filter *
309 seccomp_prepare_user_filter(const char __user *user_filter)
310 {
311         struct sock_fprog fprog;
312         struct seccomp_filter *filter = ERR_PTR(-EFAULT);
313
314 #ifdef CONFIG_COMPAT
315         if (is_compat_task()) {
316                 struct compat_sock_fprog fprog32;
317                 if (copy_from_user(&fprog32, user_filter, sizeof(fprog32)))
318                         goto out;
319                 fprog.len = fprog32.len;
320                 fprog.filter = compat_ptr(fprog32.filter);
321         } else /* falls through to the if below. */
322 #endif
323         if (copy_from_user(&fprog, user_filter, sizeof(fprog)))
324                 goto out;
325         filter = seccomp_prepare_filter(&fprog);
326 out:
327         return filter;
328 }
329
330 /**
331  * seccomp_attach_filter: validate and attach filter
332  * @flags:  flags to change filter behavior
333  * @filter: seccomp filter to add to the current process
334  *
335  * Returns 0 on success, -ve on error.
336  */
337 static long seccomp_attach_filter(unsigned int flags,
338                                   struct seccomp_filter *filter)
339 {
340         unsigned long total_insns;
341         struct seccomp_filter *walker;
342
343         /* Validate resulting filter length. */
344         total_insns = filter->prog->len;
345         for (walker = current->seccomp.filter; walker; walker = walker->prev)
346                 total_insns += walker->prog->len + 4;  /* 4 instr penalty */
347         if (total_insns > MAX_INSNS_PER_PATH)
348                 return -ENOMEM;
349
350         /*
351          * If there is an existing filter, make it the prev and don't drop its
352          * task reference.
353          */
354         filter->prev = current->seccomp.filter;
355         current->seccomp.filter = filter;
356
357         return 0;
358 }
359
360 /* get_seccomp_filter - increments the reference count of the filter on @tsk */
361 void get_seccomp_filter(struct task_struct *tsk)
362 {
363         struct seccomp_filter *orig = tsk->seccomp.filter;
364         if (!orig)
365                 return;
366         /* Reference count is bounded by the number of total processes. */
367         atomic_inc(&orig->usage);
368 }
369
370 static inline void seccomp_filter_free(struct seccomp_filter *filter)
371 {
372         if (filter) {
373                 sk_filter_free(filter->prog);
374                 kfree(filter);
375         }
376 }
377
378 /* put_seccomp_filter - decrements the ref count of tsk->seccomp.filter */
379 void put_seccomp_filter(struct task_struct *tsk)
380 {
381         struct seccomp_filter *orig = tsk->seccomp.filter;
382         /* Clean up single-reference branches iteratively. */
383         while (orig && atomic_dec_and_test(&orig->usage)) {
384                 struct seccomp_filter *freeme = orig;
385                 orig = orig->prev;
386                 seccomp_filter_free(freeme);
387         }
388 }
389
390 /**
391  * seccomp_send_sigsys - signals the task to allow in-process syscall emulation
392  * @syscall: syscall number to send to userland
393  * @reason: filter-supplied reason code to send to userland (via si_errno)
394  *
395  * Forces a SIGSYS with a code of SYS_SECCOMP and related sigsys info.
396  */
397 static void seccomp_send_sigsys(int syscall, int reason)
398 {
399         struct siginfo info;
400         memset(&info, 0, sizeof(info));
401         info.si_signo = SIGSYS;
402         info.si_code = SYS_SECCOMP;
403         info.si_call_addr = (void __user *)KSTK_EIP(current);
404         info.si_errno = reason;
405         info.si_arch = syscall_get_arch();
406         info.si_syscall = syscall;
407         force_sig_info(SIGSYS, &info, current);
408 }
409 #endif  /* CONFIG_SECCOMP_FILTER */
410
411 /*
412  * Secure computing mode 1 allows only read/write/exit/sigreturn.
413  * To be fully secure this must be combined with rlimit
414  * to limit the stack allocations too.
415  */
416 static int mode1_syscalls[] = {
417         __NR_seccomp_read, __NR_seccomp_write, __NR_seccomp_exit, __NR_seccomp_sigreturn,
418         0, /* null terminated */
419 };
420
421 #ifdef CONFIG_COMPAT
422 static int mode1_syscalls_32[] = {
423         __NR_seccomp_read_32, __NR_seccomp_write_32, __NR_seccomp_exit_32, __NR_seccomp_sigreturn_32,
424         0, /* null terminated */
425 };
426 #endif
427
428 int __secure_computing(int this_syscall)
429 {
430         int mode = current->seccomp.mode;
431         int exit_sig = 0;
432         int *syscall;
433         u32 ret;
434
435         switch (mode) {
436         case SECCOMP_MODE_STRICT:
437                 syscall = mode1_syscalls;
438 #ifdef CONFIG_COMPAT
439                 if (is_compat_task())
440                         syscall = mode1_syscalls_32;
441 #endif
442                 do {
443                         if (*syscall == this_syscall)
444                                 return 0;
445                 } while (*++syscall);
446                 exit_sig = SIGKILL;
447                 ret = SECCOMP_RET_KILL;
448                 break;
449 #ifdef CONFIG_SECCOMP_FILTER
450         case SECCOMP_MODE_FILTER: {
451                 int data;
452                 struct pt_regs *regs = task_pt_regs(current);
453                 ret = seccomp_run_filters(this_syscall);
454                 data = ret & SECCOMP_RET_DATA;
455                 ret &= SECCOMP_RET_ACTION;
456                 switch (ret) {
457                 case SECCOMP_RET_ERRNO:
458                         /* Set the low-order 16-bits as a errno. */
459                         syscall_set_return_value(current, regs,
460                                                  -data, 0);
461                         goto skip;
462                 case SECCOMP_RET_TRAP:
463                         /* Show the handler the original registers. */
464                         syscall_rollback(current, regs);
465                         /* Let the filter pass back 16 bits of data. */
466                         seccomp_send_sigsys(this_syscall, data);
467                         goto skip;
468                 case SECCOMP_RET_TRACE:
469                         /* Skip these calls if there is no tracer. */
470                         if (!ptrace_event_enabled(current, PTRACE_EVENT_SECCOMP)) {
471                                 syscall_set_return_value(current, regs,
472                                                          -ENOSYS, 0);
473                                 goto skip;
474                         }
475                         /* Allow the BPF to provide the event message */
476                         ptrace_event(PTRACE_EVENT_SECCOMP, data);
477                         /*
478                          * The delivery of a fatal signal during event
479                          * notification may silently skip tracer notification.
480                          * Terminating the task now avoids executing a system
481                          * call that may not be intended.
482                          */
483                         if (fatal_signal_pending(current))
484                                 break;
485                         if (syscall_get_nr(current, regs) < 0)
486                                 goto skip;  /* Explicit request to skip. */
487
488                         return 0;
489                 case SECCOMP_RET_ALLOW:
490                         return 0;
491                 case SECCOMP_RET_KILL:
492                 default:
493                         break;
494                 }
495                 exit_sig = SIGSYS;
496                 break;
497         }
498 #endif
499         default:
500                 BUG();
501         }
502
503 #ifdef SECCOMP_DEBUG
504         dump_stack();
505 #endif
506         audit_seccomp(this_syscall, exit_sig, ret);
507         do_exit(exit_sig);
508 #ifdef CONFIG_SECCOMP_FILTER
509 skip:
510         audit_seccomp(this_syscall, exit_sig, ret);
511 #endif
512         return -1;
513 }
514
515 long prctl_get_seccomp(void)
516 {
517         return current->seccomp.mode;
518 }
519
520 /**
521  * seccomp_set_mode_strict: internal function for setting strict seccomp
522  *
523  * Once current->seccomp.mode is non-zero, it may not be changed.
524  *
525  * Returns 0 on success or -EINVAL on failure.
526  */
527 static long seccomp_set_mode_strict(void)
528 {
529         const unsigned long seccomp_mode = SECCOMP_MODE_STRICT;
530         long ret = -EINVAL;
531
532         if (!seccomp_may_assign_mode(seccomp_mode))
533                 goto out;
534
535 #ifdef TIF_NOTSC
536         disable_TSC();
537 #endif
538         seccomp_assign_mode(seccomp_mode);
539         ret = 0;
540
541 out:
542
543         return ret;
544 }
545
546 #ifdef CONFIG_SECCOMP_FILTER
547 /**
548  * seccomp_set_mode_filter: internal function for setting seccomp filter
549  * @flags:  flags to change filter behavior
550  * @filter: struct sock_fprog containing filter
551  *
552  * This function may be called repeatedly to install additional filters.
553  * Every filter successfully installed will be evaluated (in reverse order)
554  * for each system call the task makes.
555  *
556  * Once current->seccomp.mode is non-zero, it may not be changed.
557  *
558  * Returns 0 on success or -EINVAL on failure.
559  */
560 static long seccomp_set_mode_filter(unsigned int flags,
561                                     const char __user *filter)
562 {
563         const unsigned long seccomp_mode = SECCOMP_MODE_FILTER;
564         struct seccomp_filter *prepared = NULL;
565         long ret = -EINVAL;
566
567         /* Validate flags. */
568         if (flags != 0)
569                 goto out;
570
571         /* Prepare the new filter before holding any locks. */
572         prepared = seccomp_prepare_user_filter(filter);
573         if (IS_ERR(prepared))
574                 return PTR_ERR(prepared);
575
576         if (!seccomp_may_assign_mode(seccomp_mode))
577                 goto out;
578
579         ret = seccomp_attach_filter(flags, prepared);
580         if (ret)
581                 goto out;
582         /* Do not free the successfully attached filter. */
583         prepared = NULL;
584
585         seccomp_assign_mode(seccomp_mode);
586 out:
587         seccomp_filter_free(prepared);
588         return ret;
589 }
590 #else
591 static inline long seccomp_set_mode_filter(unsigned int flags,
592                                            const char __user *filter)
593 {
594         return -EINVAL;
595 }
596 #endif
597
598 /* Common entry point for both prctl and syscall. */
599 static long do_seccomp(unsigned int op, unsigned int flags,
600                        const char __user *uargs)
601 {
602         switch (op) {
603         case SECCOMP_SET_MODE_STRICT:
604                 if (flags != 0 || uargs != NULL)
605                         return -EINVAL;
606                 return seccomp_set_mode_strict();
607         case SECCOMP_SET_MODE_FILTER:
608                 return seccomp_set_mode_filter(flags, uargs);
609         default:
610                 return -EINVAL;
611         }
612 }
613
614 SYSCALL_DEFINE3(seccomp, unsigned int, op, unsigned int, flags,
615                          const char __user *, uargs)
616 {
617         return do_seccomp(op, flags, uargs);
618 }
619
620 /**
621  * prctl_set_seccomp: configures current->seccomp.mode
622  * @seccomp_mode: requested mode to use
623  * @filter: optional struct sock_fprog for use with SECCOMP_MODE_FILTER
624  *
625  * Returns 0 on success or -EINVAL on failure.
626  */
627 long prctl_set_seccomp(unsigned long seccomp_mode, char __user *filter)
628 {
629         unsigned int op;
630         char __user *uargs;
631
632         switch (seccomp_mode) {
633         case SECCOMP_MODE_STRICT:
634                 op = SECCOMP_SET_MODE_STRICT;
635                 /*
636                  * Setting strict mode through prctl always ignored filter,
637                  * so make sure it is always NULL here to pass the internal
638                  * check in do_seccomp().
639                  */
640                 uargs = NULL;
641                 break;
642         case SECCOMP_MODE_FILTER:
643                 op = SECCOMP_SET_MODE_FILTER;
644                 uargs = filter;
645                 break;
646         default:
647                 return -EINVAL;
648         }
649
650         /* prctl interface doesn't have flags, so they are always zero. */
651         return do_seccomp(op, 0, uargs);
652 }