Skip to contentSkip to conversation

tracing: split out syscall_trace_enter construction

PATCH In review Will Drewry 31 participants 243 messages Apr 28, 2011 – Jun 9, 2011 1 message not in the archive Page 1 of 2

Subsystems (18)
lore
Share & tools
lore

Will Drewry

author reviewer
#0 lore raw

PATCH 2/7 tracing: split out syscall_trace_enter construction

perf appears to be the primary consumer of the CONFIG_FTRACE_SYSCALLS infrastructure. As such, many of the helpers that target perf can be split into a perf-focused helper and a generic CONFIG_FTRACE_SYSCALLS consumer interface.

This change splits out syscall_trace_enter construction from perf_syscall_enter for current into two helpers:
- ftrace_syscall_enter_state
- ftrace_syscall_enter_state_size

And adds another helper for completeness:
- ftrace_syscall_exit_state_size

These helpers allow for shared code between perf ftrace events and any other consumers of CONFIG_FTRACE_SYSCALLS events. The proposed seccomp_filter patches use this code.

---
 include/trace/syscall.h       |    4 ++
 kernel/trace/trace_syscalls.c |   96 +++++++++++++++++++++++++++++++++++------
 2 files changed, 86 insertions(+), 14 deletions(-)
include/trace/syscall.h +4 -0
index 31966a4..242ae04 100644
@@ -41,6 +41,10 @@ extern int reg_event_syscall_exit(struct ftrace_event_call *call);
 extern void unreg_event_syscall_exit(struct ftrace_event_call *call);
 extern int
 ftrace_format_syscall(struct ftrace_event_call *call, struct trace_seq *s);
+extern int ftrace_syscall_enter_state(u8 *buf, size_t available,
+				      struct trace_entry **entry);
+extern size_t ftrace_syscall_enter_state_size(int nb_args);
+extern size_t ftrace_syscall_exit_state_size(void);
 enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
 				      struct trace_event *event);
 enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
kernel/trace/trace_syscalls.c +82 -14

132 lines not on this page · raw message

Signature · 1 line
1.7.0.4
author reviewer
#1 lore raw

PATCH 3/7 seccomp_filter: Enable ftrace-based system call filtering

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all system calls are first checked against the bitmask to determine if they are allowed or denied. If allowed, the list of filters is checked for the given syscall number. If all filter predicates for the system call match or the system call was allowed without restriction, the process continues. Otherwise, it is killed and a KERN_INFO notification is posted.

The filter language itself is provided by the ftrace filter engine. Related patches tweak to the perf filter trace and free allow the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which predefines this information in syscall_metadata associated enter_event (and exit_event) structures.

The result is that a process may reduce its available interfaces to the kernel through prctl() without knowing the appropriate system call number a priori and with the flexibility of filtering based on register-stored arguments. (String checks suffer from TOCTOU issues and should be left to LSMs to provide policy for! Don't get greedy :)

A sample filterset for a process that only needs to interact over stdin and stdout and exit cleanly is shown below:
sys_read: fd == 0
sys_write: fd == 1
sys_exit_group: 1

The filters may be specified once prior to entering the reduced access state:
prctl(PR_SET_SECCOMP, 2, filters);
If prctl() is in the allowed bitmask, the process may futher reduce privileges by dropping system calls from the allowed set.

The only other twist is that it is possible to delay enforcement by one system call by supplying a "on_next_syscall: 1" 'filter'. This allows for a launcher process to fork(), prctl(), then execve() leaving the launched binary in a filtered state.

Implementation-wise, seccomp.c now uses seccomp_state struct which is managed using RCU primitives. It contains the system call bitmask and a linked list of seccomp_filters (which are also managed as an RCU list). All mutations (barring one optional bit flip) to the seccomp_state are always done on a duplicate of the current state value which is swapped on prior to use.

---
 include/linux/seccomp.h |   98 +++++++++++-
 include/trace/syscall.h |    2 +
 kernel/Makefile         |    1 +
 kernel/fork.c           |    8 +
 kernel/seccomp.c        |  144 +++++++++++++++--
 kernel/seccomp_filter.c |  428 +++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sys.c            |   11 +-
 kernel/trace/Kconfig    |   10 +
 8 files changed, 687 insertions(+), 15 deletions(-)
 create mode 100644 kernel/seccomp_filter.c
include/linux/seccomp.h +95 -3
index 167c333..16703c4 100644
@@ -4,10 +4,33 @@
 
 #ifdef CONFIG_SECCOMP
 
+#include <linux/list.h>
 #include <linux/thread_info.h>
+#include <linux/types.h>
 #include <asm/seccomp.h>
 
-typedef struct { int mode; } seccomp_t;
+/**
+ * struct seccomp_state - the state of a seccomp'ed process
+ *
+ * @mode:
+ *     if this is 1, the process is under standard seccomp rules
+ *             is 2, the process is only allowed to make system calls where
+ *                   the corresponding bit is set in bitmask and any
+ *                   associated filters evaluate successfully.
+ * @usage: number of references to the current instance.
+ * @bitmask: a mask of allowed or filtered system calls and additional flags.
+ * @filter_count: number of seccomp filters in @filters.
+ * @filters: list of seccomp_filter entries for  system calls.
+ */
+struct seccomp_state {
+	uint16_t mode;
+	atomic_t usage;
+	DECLARE_BITMAP(bitmask, NR_syscalls + 1);
+	int filter_count;
+	struct list_head filters;
+};
+
+typedef struct { struct seccomp_state *state; } seccomp_t;
 
 extern void __secure_computing(int);
 static inline void secure_computing(int this_syscall)
@@ -16,8 +39,14 @@ static inline void secure_computing(int this_syscall)
 		__secure_computing(this_syscall);
 }
 
+extern struct seccomp_state *seccomp_state_new(void);
+extern struct seccomp_state *seccomp_state_dup(const struct seccomp_state *);
+extern struct seccomp_state *get_seccomp_state(struct seccomp_state *);
+extern void put_seccomp_state(struct seccomp_state *);
 extern long prctl_get_seccomp(void);
-extern long prctl_set_seccomp(unsigned long);
+extern long prctl_set_seccomp(unsigned long, char *);
+
+#define SECCOMP_MAX_FILTER_LENGTH 16384
 
 #else /* CONFIG_SECCOMP */
 
@@ -27,16 +56,79 @@ typedef struct { } seccomp_t;
 
 #define secure_computing(x) do { } while (0)
 
+#define SECCOMP_MAX_FILTER_LENGTH 0
+
 static inline long prctl_get_seccomp(void)
 {
 	return -EINVAL;
 }
 
-static inline long prctl_set_seccomp(unsigned long arg2)
+static inline long prctl_set_seccomp(unsigned long arg2, unsigned char *filters)
 {
 	return -EINVAL;
 }
 
+static inline struct seccomp_state *seccomp_state_new(void)
+{
+	return NULL;
+}
+
+static inline struct seccomp_state *seccomp_state_dup(
+					const struct seccomp_state *state)
+{
+	return NULL;
+}
+
+static inline struct seccomp_state *get_seccomp_state(
+					struct seccomp_state *state)
+{
+	return NULL;
+}
+
+static inline void put_seccomp_state(struct seccomp_state *state)
+{
+}
+
 #endif /* CONFIG_SECCOMP */
 
+#if defined(CONFIG_SECCOMP) && defined(CONFIG_SECCOMP_FILTER)
+
+extern int seccomp_copy_all_filters(struct list_head *,
+				    const struct list_head *);
+extern void seccomp_drop_all_filters(struct seccomp_state *);
+
+extern int seccomp_parse_filters(struct seccomp_state *, char *);
+extern int seccomp_test_filters(struct seccomp_state *, int);
+
+extern int seccomp_show_filters(struct seccomp_state *, struct seq_file *);
+
+#else  /* CONFIG_SECCOMP && CONFIG_SECCOMP_FILTER */
+
+static inline int seccomp_test_filters(struct seccomp_state *state, int nr)
+{
+	return -EINVAL;
+}
+
+static inline int seccomp_parse_filters(struct seccomp_state *state,
+					char *filters)
+{
+	return -EINVAL;
+}
+
+static inline int seccomp_show_filters(struct seccomp_state *state,
+				       struct seq_file *m)
+{
+	return -EINVAL;
+}
+
+extern inline int seccomp_copy_all_filters(struct list_head *dst,
+					   const struct list_head *src)
+{
+	return 0;
+}
+
+static inline void seccomp_drop_all_filters(struct seccomp_state *state) { }
+
+#endif  /* CONFIG_SECCOMP && CONFIG_SECCOMP_FILTER */
+
 #endif /* _LINUX_SECCOMP_H */
include/trace/syscall.h +2 -0
index 242ae04..1f72fce 100644
@@ -35,6 +35,8 @@ struct syscall_metadata {
 extern unsigned long arch_syscall_addr(int nr);
 extern int init_syscall_trace(struct ftrace_event_call *call);
 
+extern struct syscall_metadata *syscall_nr_to_meta(int);
+
 extern int reg_event_syscall_enter(struct ftrace_event_call *call);
 extern void unreg_event_syscall_enter(struct ftrace_event_call *call);
 extern int reg_event_syscall_exit(struct ftrace_event_call *call);
kernel/Makefile +1 -0
index 85cbfb3..a4b21fb 100644
@@ -81,6 +81,7 @@ obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o
 obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
 obj-$(CONFIG_GENERIC_HARDIRQS) += irq/
 obj-$(CONFIG_SECCOMP) += seccomp.o
+obj-$(CONFIG_SECCOMP_FILTER) += seccomp_filter.o
 obj-$(CONFIG_RCU_TORTURE_TEST) += rcutorture.o
 obj-$(CONFIG_TREE_RCU) += rcutree.o
 obj-$(CONFIG_TREE_PREEMPT_RCU) += rcutree.o
kernel/fork.c +8 -0
index e7548de..bdcf70b 100644
@@ -34,6 +34,7 @@
 #include <linux/cgroup.h>
 #include <linux/security.h>
 #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
 #include <linux/swap.h>
 #include <linux/syscalls.h>
 #include <linux/jiffies.h>
@@ -169,6 +170,9 @@ void free_task(struct task_struct *tsk)
 	free_thread_info(tsk->stack);
 	rt_mutex_debug_task_free(tsk);
 	ftrace_graph_exit_task(tsk);
+#ifdef CONFIG_SECCOMP
+	put_seccomp_state(tsk->seccomp.state);
+#endif
 	free_task_struct(tsk);
 }
 EXPORT_SYMBOL(free_task);
@@ -280,6 +284,10 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
 	if (err)
 		goto out;
 
+#ifdef CONFIG_SECCOMP
+	tsk->seccomp.state = get_seccomp_state(orig->seccomp.state);
+#endif
+
 	setup_thread_stack(tsk, orig);
 	clear_user_return_notifier(tsk);
 	clear_tsk_need_resched(tsk);
kernel/seccomp.c +133 -11

188 lines not on this page · raw message

kernel/seccomp_filter.c new file +428 -0

428 lines not on this page · raw message

kernel/sys.c +10 -1
index af468ed..1d3f27e 100644
@@ -1620,6 +1620,7 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 {
 	struct task_struct *me = current;
 	unsigned char comm[sizeof(me->comm)];
+	char *seccomp_filter = NULL;
 	long error;
 
 	error = security_task_prctl(option, arg2, arg3, arg4, arg5);
@@ -1703,7 +1704,15 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 			error = prctl_get_seccomp();
 			break;
 		case PR_SET_SECCOMP:
-			error = prctl_set_seccomp(arg2);
+			if (arg3 && SECCOMP_MAX_FILTER_LENGTH) {
+				seccomp_filter = strndup_user(
+						   (char __user *)arg3,
+						   SECCOMP_MAX_FILTER_LENGTH);
+				if (!seccomp_filter)
+					return -ENOMEM;
+			}
+			error = prctl_set_seccomp(arg2, seccomp_filter);
+			kfree(seccomp_filter);
 			break;
 		case PR_GET_TSC:
 			error = GET_TSC_CTL(arg2);
kernel/trace/Kconfig +10 -0
index 61d7d59..e21b9eb 100644
@@ -240,6 +240,16 @@ config FTRACE_SYSCALLS
 	help
 	  Basic tracer to catch the syscall entry and exit events.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp trace event-based filtering"
+	depends on FTRACE_SYSCALLS
+	select CONFIG_SECCOMP
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.
+
+	  See Documentation/trace/seccomp_filter.txt for more detail.
+
 config TRACE_BRANCH_PROFILING
 	bool
 	select GENERIC_TRACER
Signature · 1 line
1.7.0.4
maintainer
#2 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

include/linux/seccomp.h line 19

Quoted 9 lines · Will Drewry
include/linux/seccomp.h +8 -1
-typedef struct { int mode; } seccomp_t;
+/**
+ * struct seccomp_state - the state of a seccomp'ed process
+ *
+ * @mode:
+ *     if this is 1, the process is under standard seccomp rules
+ *             is 2, the process is only allowed to make system calls where
+ *                   the corresponding bit is set in bitmask and any
+ *                   associated filters evaluate successfully.

I hate arbitrary numbers. This is not a big deal, but can we create an enum or define that puts names for the modes.

SECCOMP_MODE_BASIC
SECCOMP_MODE_FILTER

??

Quoted 46 lines

+ * @usage: number of references to the current instance.
+ * @bitmask: a mask of allowed or filtered system calls and additional flags.
+ * @filter_count: number of seccomp filters in @filters.
+ * @filters: list of seccomp_filter entries for system calls.
+ */

include/linux/seccomp.h +9 -0
+struct seccomp_state {
+	uint16_t mode;
+	atomic_t usage;
+	DECLARE_BITMAP(bitmask, NR_syscalls + 1);
+	int filter_count;
+	struct list_head filters;
+};
+
+typedef struct { struct seccomp_state *state; } seccomp_t;
 
 extern void __secure_computing(int);
 static inline void secure_computing(int this_syscall)
@@ -16,8 +39,14 @@ static inline void secure_computing(int this_syscall)
 		__secure_computing(this_syscall);
 }
 
 
 
kernel/fork.c +4 -0
index e7548de..bdcf70b 100644
@@ -34,6 +34,7 @@
 #include <linux/cgroup.h>
 #include <linux/security.h>
 #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
 #include <linux/swap.h>
 #include <linux/syscalls.h>
 #include <linux/jiffies.h>
@@ -169,6 +170,9 @@ void free_task(struct task_struct *tsk)
 	free_thread_info(tsk->stack);
 	rt_mutex_debug_task_free(tsk);
 	ftrace_graph_exit_task(tsk);
+#ifdef CONFIG_SECCOMP
+	put_seccomp_state(tsk->seccomp.state);
+#endif
 	free_task_struct(tsk);
 }
 EXPORT_SYMBOL(free_task);

kernel/fork.c static struct task_struct *dup_task_struct(struct task_struct *orig) · line 289

Quoted 6 lines
kernel/fork.c +3 -0
@@ -280,6 +284,10 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
 	if (err)
 		goto out;
 
+#ifdef CONFIG_SECCOMP
+	tsk->seccomp.state = get_seccomp_state(orig->seccomp.state);
+#endif

I wonder if we could macro these to get rid of the #ifdefs in fork.c.

#define put_seccomp_state(state) do { } while (0)
#define assign_seccomp_state(src, state) do { } while (0)

??

Quoted 22 lines
kernel/fork.c +1 -0
+
 	setup_thread_stack(tsk, orig);
 	clear_user_return_notifier(tsk);
 	clear_tsk_need_resched(tsk);
kernel/seccomp.c +2 -1
index 57d4b13..1bee87c 100644
@@ -8,10 +8,11 @@
 
 #include <linux/seccomp.h>
 #include <linux/sched.h>
+#include <linux/slab.h>
 #include <linux/compat.h>
 
 /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
+#define NR_SECCOMP_MODES 2
 
 /*
  * Secure computing mode 1 allows only read/write/exit/sigreturn.

kernel/seccomp.c static int mode1_syscalls_32[] = { · line 38

Quoted 8 lines
kernel/seccomp.c +2 -2
@@ -32,9 +33,11 @@ static int mode1_syscalls_32[] = {
 
 void __secure_computing(int this_syscall)
 {
-	int mode = current->seccomp.mode;
+	int mode = -1;
 	int * syscall;
-
+	/* Do we need an RCU read lock to access current's state? */

I'm actually confused to why you are using RCU. What are you protecting. Currently, I see the state is always accessed from current->seccomp. But current should not be fighting with itself.

Maybe I'm missing something.

-- Steve

Quoted 24 lines
kernel/seccomp.c +12 -0
+	if (current->seccomp.state)
+		mode = current->seccomp.state->mode;
 	switch (mode) {
 	case 1:
 		syscall = mode1_syscalls;
@@ -47,6 +50,16 @@ void __secure_computing(int this_syscall)
 				return;
 		} while (*++syscall);
 		break;
+	case 2:
+#ifdef CONFIG_COMPAT
+		if (is_compat_task())
+			/* XXX: No compat support yet. */
+			break;
+#endif
+		if (!seccomp_test_filters(current->seccomp.state,
+					  this_syscall))
+			return;
+		break;
 	default:
 		BUG();
 	}
@@ -57,30 +70,139 @@ void __secure_computing(int this_syscall)
 	do_exit(SIGKILL);
author reviewer
#3 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 15 lines · Steven Rostedt

include/linux/seccomp.h line 19

Quoted 9 lines · Will Drewry
include/linux/seccomp.h +8 -1
-typedef struct { int mode; } seccomp_t;
+/**
+ * struct seccomp_state - the state of a seccomp'ed process
+ *
+ * @mode:
+ *     if this is 1, the process is under standard seccomp rules
+ *             is 2, the process is only allowed to make system calls where
+ *                   the corresponding bit is set in bitmask and any
+ *                   associated filters evaluate successfully.

I hate arbitrary numbers. This is not a big deal, but can we create an enum or define that puts names for the modes.

Quoted 4 lines

SECCOMP_MODE_BASIC
SECCOMP_MODE_FILTER

??

Works for me.

Quoted 55 lines
Quoted 46 lines

+ * @usage: number of references to the current instance.
+ * @bitmask: a mask of allowed or filtered system calls and additional flags.
+ * @filter_count: number of seccomp filters in @filters.
+ * @filters: list of seccomp_filter entries for  system calls.
+ */

include/linux/seccomp.h +9 -0
+struct seccomp_state {
+     uint16_t mode;
+     atomic_t usage;
+     DECLARE_BITMAP(bitmask, NR_syscalls + 1);
+     int filter_count;
+     struct list_head filters;
+};
+
+typedef struct { struct seccomp_state *state; } seccomp_t;

 extern void __secure_computing(int);
 static inline void secure_computing(int this_syscall)

include/linux/seccomp.h +0 -0
@@ -16,8 +39,14 @@ static inline void secure_computing(int this_syscall)
               __secure_computing(this_syscall);
  }
 
 
 
kernel/fork.c +4 -0
index e7548de..bdcf70b 100644
@@ -34,6 +34,7 @@
  #include <linux/cgroup.h>
  #include <linux/security.h>
  #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
  #include <linux/swap.h>
  #include <linux/syscalls.h>
  #include <linux/jiffies.h>
@@ -169,6 +170,9 @@ void free_task(struct task_struct *tsk)
       free_thread_info(tsk->stack);
       rt_mutex_debug_task_free(tsk);
       ftrace_graph_exit_task(tsk);
+#ifdef CONFIG_SECCOMP
+     put_seccomp_state(tsk->seccomp.state);
+#endif
       free_task_struct(tsk);
  }
  EXPORT_SYMBOL(free_task);

kernel/fork.c static struct task_struct *dup_task_struct(struct task_struct *orig) · line 289

Quoted 6 lines
kernel/fork.c +3 -0
@@ -280,6 +284,10 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
       if (err)
               goto out;
 
+#ifdef CONFIG_SECCOMP
+     tsk->seccomp.state = get_seccomp_state(orig->seccomp.state);
+#endif

I wonder if we could macro these to get rid of the #ifdefs in fork.c.

Quoted 4 lines

#define put_seccomp_state(state)        do { } while (0) #define assign_seccomp_state(src, state) do { } while (0)

??

Makes sense to me. I'll add it to the next update.

Quoted 35 lines
Quoted 22 lines
kernel/fork.c +1 -0
+
       setup_thread_stack(tsk, orig);
       clear_user_return_notifier(tsk);
       clear_tsk_need_resched(tsk);
kernel/seccomp.c +2 -1
index 57d4b13..1bee87c 100644
@@ -8,10 +8,11 @@
 
  #include <linux/seccomp.h>
  #include <linux/sched.h>
+#include <linux/slab.h>
  #include <linux/compat.h>
 
  /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
+#define NR_SECCOMP_MODES 2
 
  /*
   * Secure computing mode 1 allows only read/write/exit/sigreturn.

kernel/seccomp.c static int mode1_syscalls_32[] = { · line 38

Quoted 8 lines
kernel/seccomp.c +2 -2
@@ -32,9 +33,11 @@ static int mode1_syscalls_32[] = {
 
  void __secure_computing(int this_syscall)
  {
-     int mode = current->seccomp.mode;
+     int mode = -1;
       int * syscall;
-
+     /* Do we need an RCU read lock to access current's state? */

I'm actually confused to why you are using RCU. What are you protecting. Currently, I see the state is always accessed from current->seccomp. But current should not be fighting with itself.

Quoted 1 line

Maybe I'm missing something.

I'm sure it's me that's missing something. I believe the seccomp pointer can be accessed from:
- current
- via /proc/<pid>/seccomp_filter (read-only)

Given those cases, would it make sense to ditch the RCU interface for it?

Thanks!
will

Quoted 28 lines
Quoted 25 lines
kernel/seccomp.c +2 -0
+     if (current->seccomp.state)
+             mode = current->seccomp.state->mode;
       switch (mode) {

      case 1:
              syscall = mode1_syscalls;

kernel/seccomp.c +10 -0
@@ -47,6 +50,16 @@ void __secure_computing(int this_syscall)
                               return;
               } while (*++syscall);
               break;
+     case 2:
+#ifdef CONFIG_COMPAT
+             if (is_compat_task())
+                     /* XXX: No compat support yet. */
+                     break;
+#endif
+             if (!seccomp_test_filters(current->seccomp.state,
+                                       this_syscall))
+                     return;
+             break;

      default:
              BUG();
      }

kernel/seccomp.c +0 -0
@@ -57,30 +70,139 @@ void __secure_computing(int this_syscall)
       do_exit(SIGKILL);
maintainer
#4 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 12 lines · Will Drewry
Quoted 12 lines
Quoted 7 lines

 void __secure_computing(int this_syscall)
 {
-     int mode = current->seccomp.mode;
+     int mode = -1;
      int * syscall;
-
+     /* Do we need an RCU read lock to access current's state? */

I'm actually confused to why you are using RCU. What are you protecting. Currently, I see the state is always accessed from current->seccomp. But current should not be fighting with itself.

Quoted 8 lines
Quoted 1 line

Maybe I'm missing something.

I'm sure it's me that's missing something. I believe the seccomp pointer can be accessed from:
- current
- via /proc/<pid>/seccomp_filter (read-only)

Given those cases, would it make sense to ditch the RCU interface for it?

ISTM you need them to protect the reader.

-serge

maintainer
#5 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

In reply to Will Drewry
Quoted 31 lines · Will Drewry
Quoted 31 lines
Quoted 18 lines
kernel/seccomp.c +2 -1
index 57d4b13..1bee87c 100644
@@ -8,10 +8,11 @@
 
 #include <linux/seccomp.h>
 #include <linux/sched.h>
+#include <linux/slab.h>
 #include <linux/compat.h>
 
 /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
+#define NR_SECCOMP_MODES 2
 
 /*
  * Secure computing mode 1 allows only read/write/exit/sigreturn.

kernel/seccomp.c static int mode1_syscalls_32[] = { · line 38

Quoted 8 lines
kernel/seccomp.c +2 -2
@@ -32,9 +33,11 @@ static int mode1_syscalls_32[] = {
 
 void __secure_computing(int this_syscall)
 {
-     int mode = current->seccomp.mode;
+     int mode = -1;
      int * syscall;
-
+     /* Do we need an RCU read lock to access current's state? */

I'm actually confused to why you are using RCU. What are you protecting. Currently, I see the state is always accessed from current->seccomp. But current should not be fighting with itself.

Quoted 8 lines
Quoted 1 line

Maybe I'm missing something.

I'm sure it's me that's missing something. I believe the seccomp pointer can be accessed from:
- current
- via /proc/<pid>/seccomp_filter (read-only)

Given those cases, would it make sense to ditch the RCU interface for it?

Looking at this in a bit more detail. I think you can ditch the rcu_readlocks where current accesses its own seccomp state. As current is the one that duplicates it (and ups the refcount) on fork, and current wont free it until after it performs a rcu_synchronization. No one else can free current's seccomp state while current has a reference to it.

You still need the rcu_readlocks on the readers for the proc system. Otherwise the handle can be freed while its still in use. With the rcu_readlocks, these readers will always get the refcount before current frees it. And then the dec_and_test should work as expected when the readers do the put.

-- Steve

author reviewer
#6 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 49 lines · Steven Rostedt
Quoted 31 lines · Will Drewry
Quoted 31 lines
Quoted 18 lines
kernel/seccomp.c +2 -1
index 57d4b13..1bee87c 100644
@@ -8,10 +8,11 @@
 
  #include <linux/seccomp.h>
  #include <linux/sched.h>
+#include <linux/slab.h>
  #include <linux/compat.h>
 
  /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
+#define NR_SECCOMP_MODES 2
 
  /*
   * Secure computing mode 1 allows only read/write/exit/sigreturn.

kernel/seccomp.c static int mode1_syscalls_32[] = { · line 38

Quoted 8 lines
kernel/seccomp.c +2 -2
@@ -32,9 +33,11 @@ static int mode1_syscalls_32[] = {
 
  void __secure_computing(int this_syscall)
  {
-     int mode = current->seccomp.mode;
+     int mode = -1;
       int * syscall;
-
+     /* Do we need an RCU read lock to access current's state? */

I'm actually confused to why you are using RCU. What are you protecting. Currently, I see the state is always accessed from current->seccomp. But current should not be fighting with itself.

Quoted 8 lines
Quoted 1 line

Maybe I'm missing something.

I'm sure it's me that's missing something.  I believe the seccomp pointer can be accessed from:
- current
- via /proc/<pid>/seccomp_filter (read-only)

Given those cases, would it make sense to ditch the RCU interface for it?

Looking at this in a bit more detail. I think you can ditch the rcu_readlocks where current accesses its own seccomp state. As current is the one that duplicates it (and ups the refcount) on fork, and current wont free it until after it performs a rcu_synchronization. No one else can free current's seccomp state while current has a reference to it.

Quoted 5 lines

You still need the rcu_readlocks on the readers for the proc system. Otherwise the handle can be freed while its still in use. With the rcu_readlocks, these readers will always get the refcount before current frees it. And then the dec_and_test should work as expected when the readers do the put.

Great, I'll do that!

#7 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

In reply to Will Drewry
Quoted 3 lines · Will Drewry

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all

Since you now use the filters. Why not using them to filter syscalls entirely rather than using a bitmap of allowed syscalls?

You have the "nr" field in syscall tracepoints.

author reviewer
#8 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 7 lines · Frederic Weisbecker
Quoted 3 lines · Will Drewry

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all

Since you now use the filters. Why not using them to filter syscalls entirely rather than using a bitmap of allowed syscalls?

The current approach just uses a linked list of filters. While a more efficient data structure could be used, the bitmask provides a quick binary decision, and optimizes for the relatively common case where there won't be many non-binary filters to evaluate so we don't have to walk the list for a larger number of yes/no decisions versus more complex predicates. Though that may be a short-sighted view! I'm happy to change it up.

Quoted 1 line

You have the "nr" field in syscall tracepoints.

I'n not sure I follow. Do you mean moving entirely to using the actual tracepoint infrastructure instead of using the seccomp hooks, or just looking up proper filter by syscall nr? If there's a sane and better way to do the latter, I'm all ears :) As far as using the tracepoints themselves, I looked to how the perf/ftrace interactions worked and while I could've registered with the syscalls tracepoints for enter and exit, it would mean later evaluation of the system call interception, possibly out-of-order with respect to other registered event sinks, and there is complexity in just killing current from within the notifier-like list registered syscall events (as Eric Paris ran into when expanding filtering into perf itself). To get around that, the tracepoint handler would have to pump the data somewhere else (like it does for perf), and it just seemed messy. I think it's doable, but I don't know that the pure syscall tracepoint infrastructure should be burdened with the added requirements that
come with seccomp-filtering. If I didn't properly understand the
code, though, please set me on the right path.

thanks!
will

#9 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 9 lines · Will Drewry
Quoted 7 lines · Frederic Weisbecker
Quoted 3 lines · Will Drewry

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all

Since you now use the filters. Why not using them to filter syscalls entirely rather than using a bitmap of allowed syscalls?

Quoted 7 lines

The current approach just uses a linked list of filters. While a more efficient data structure could be used, the bitmask provides a quick binary decision, and optimizes for the relatively common case where there won't be many non-binary filters to evaluate so we don't have to walk the list for a larger number of yes/no decisions versus more complex predicates. Though that may be a short-sighted view! I'm happy to change it up.

Well, using a hlist that points to the filters may be not that slower. Dunno, that needs to be measured perhaps.

No big deal for now.

Quoted 12 lines
Quoted 2 lines

You have the "nr" field in syscall tracepoints.

I'n not sure I follow. Do you mean moving entirely to using the actual tracepoint infrastructure instead of using the seccomp hooks, or just looking up proper filter by syscall nr? If there's a sane and better way to do the latter, I'm all ears :) As far as using the tracepoints themselves, I looked to how the perf/ftrace interactions worked and while I could've registered with the syscalls tracepoints for enter and exit, it would mean later evaluation of the system call interception, possibly out-of-order with respect to other registered event sinks, and there is complexity in just killing current from

Quoted 8 lines

within the notifier-like list registered syscall events (as Eric Paris ran into when expanding filtering into perf itself). To get around that, the tracepoint handler would have to pump the data somewhere else (like it does for perf), and it just seemed messy. I think it's doable, but I don't know that the pure syscall tracepoint infrastructure should be burdened with the added requirements that
come with seccomp-filtering. If I didn't properly understand the
code, though, please set me on the right path.

No, my bad I was confused. I always post questions that show my misunderstanding of a new (or not) patchset. It's like a tradition ;)

author reviewer
#10 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 18 lines · Frederic Weisbecker
Quoted 9 lines · Will Drewry
Quoted 7 lines · Frederic Weisbecker
Quoted 3 lines · Will Drewry

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all

Since you now use the filters. Why not using them to filter syscalls entirely rather than using a bitmap of allowed syscalls?

Quoted 7 lines

The current approach just uses a linked list of filters.  While a more efficient data structure could be used, the bitmask provides a quick binary decision, and optimizes for the relatively common case where there won't be many non-binary filters to evaluate so we don't have to walk the list for a larger number of yes/no decisions versus more complex predicates.  Though that may be a short-sighted view! I'm happy to change it up.

Quoted 4 lines

Well, using a hlist that points to the filters may be not that slower. Dunno, that needs to be measured perhaps.

No big deal for now.

Cool - that makes sense. I just haven't used hlist before and was reticent to dive in given how much other new territory this was. I'll check it out, though.

Quoted 21 lines
Quoted 12 lines
Quoted 2 lines

You have the "nr" field in syscall tracepoints.

I'n not sure I follow.  Do you mean moving entirely to using the actual tracepoint infrastructure instead of using the seccomp hooks, or just looking up proper filter by syscall nr?  If there's a sane and better way to do the latter, I'm all ears :)  As far as using the tracepoints themselves, I looked to how the perf/ftrace interactions worked and while I could've registered with the syscalls tracepoints for enter and exit, it would mean later evaluation of the system call interception, possibly out-of-order with respect to other registered event sinks, and there is complexity in just killing current from

Quoted 8 lines

within the notifier-like list registered syscall events (as Eric Paris ran into when expanding filtering into perf itself).  To get around that, the tracepoint handler would have to pump the data somewhere else (like it does for perf), and it just seemed messy.  I think it's doable, but I don't know that the pure syscall tracepoint infrastructure should be burdened with the added requirements that come with seccomp-filtering.   If I didn't properly understand the code, though, please set me on the right path.

Quoted 2 lines

No, my bad I was confused. I always post questions that show my misunderstanding of a new (or not) patchset. It's like a tradition ;)

Awesome - I was getting worried I'd missed something terribly obvious!

#11 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

In reply to Will Drewry
Quoted 29 lines · Will Drewry

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all system calls are first checked against the bitmask to determine if they are allowed or denied. If allowed, the list of filters is checked for the given syscall number. If all filter predicates for the system call match or the system call was allowed without restriction, the process continues. Otherwise, it is killed and a KERN_INFO notification is posted.

The filter language itself is provided by the ftrace filter engine. Related patches tweak to the perf filter trace and free allow the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which predefines this information in syscall_metadata associated enter_event (and exit_event) structures.

The result is that a process may reduce its available interfaces to the kernel through prctl() without knowing the appropriate system call number a priori and with the flexibility of filtering based on register-stored arguments. (String checks suffer from TOCTOU issues and should be left to LSMs to provide policy for! Don't get greedy :)

A sample filterset for a process that only needs to interact over stdin and stdout and exit cleanly is shown below:
sys_read: fd == 0
sys_write: fd == 1
sys_exit_group: 1

Quoted 3 lines

The filters may be specified once prior to entering the reduced access state:
prctl(PR_SET_SECCOMP, 2, filters);

Instead of having such multiline filter definition with syscall names prepended, it would be nicer to make the parsing simplier.

You could have either:

	prctl(PR_SET_SECCOMP, mode);
	/* Works only if we are in mode 2 */
	prctl(PR_SET_SECCOMP_FILTER, syscall_nr, filter);

or:
/*
* If mode == 2, set the filter to syscall_nr
* Recall this for each syscall that need a filter.
* If a filter was previously set on the targeted syscall,
* it will be overwritten.
*/
prctl(PR_SET_SECCOMP, mode, syscall_nr, filter);

One can erase a previous filter by setting the new filter "1".

Also, instead of having a bitmap of syscall to accept. You could simply set "0" as a filter to those you want to deactivate:

prctl(PR_SET_SECCOMP, 2, 1, 0); <- deactivate the syscall_nr 1

Hm?

#12 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 52 lines · Frederic Weisbecker
Quoted 29 lines · Will Drewry

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all system calls are first checked against the bitmask to determine if they are allowed or denied. If allowed, the list of filters is checked for the given syscall number. If all filter predicates for the system call match or the system call was allowed without restriction, the process continues. Otherwise, it is killed and a KERN_INFO notification is posted.

The filter language itself is provided by the ftrace filter engine. Related patches tweak to the perf filter trace and free allow the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which predefines this information in syscall_metadata associated enter_event (and exit_event) structures.

The result is that a process may reduce its available interfaces to the kernel through prctl() without knowing the appropriate system call number a priori and with the flexibility of filtering based on register-stored arguments. (String checks suffer from TOCTOU issues and should be left to LSMs to provide policy for! Don't get greedy :)

A sample filterset for a process that only needs to interact over stdin and stdout and exit cleanly is shown below:
sys_read: fd == 0
sys_write: fd == 1
sys_exit_group: 1

Quoted 3 lines

The filters may be specified once prior to entering the reduced access state:
prctl(PR_SET_SECCOMP, 2, filters);

Instead of having such multiline filter definition with syscall names prepended, it would be nicer to make the parsing simplier.

You could have either:

	prctl(PR_SET_SECCOMP, mode);
	/* Works only if we are in mode 2 */
	prctl(PR_SET_SECCOMP_FILTER, syscall_nr, filter);

or:
/*
* If mode == 2, set the filter to syscall_nr
* Recall this for each syscall that need a filter.
* If a filter was previously set on the targeted syscall,
* it will be overwritten.
*/
prctl(PR_SET_SECCOMP, mode, syscall_nr, filter);

Quoted 6 lines

One can erase a previous filter by setting the new filter "1".

Also, instead of having a bitmap of syscall to accept. You could simply set "0" as a filter to those you want to deactivate:

prctl(PR_SET_SECCOMP, 2, 1, 0); <- deactivate the syscall_nr 1

I meant "0" and not 0. Because a NULL filter would actually mean we don't have a filter, which would be the same as "1".

Quoted 2 lines

Hm?

author reviewer
#13 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

In reply to Frederic Weisbecker
Quoted 34 lines · Frederic Weisbecker
Quoted 29 lines · Will Drewry

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all system calls are first checked against the bitmask to determine if they are allowed or denied.  If allowed, the list of filters is checked for the given syscall number. If all filter predicates for the system call match or the system call was allowed without restriction, the process continues. Otherwise, it is killed and a KERN_INFO notification is posted.

The filter language itself is provided by the ftrace filter engine. Related patches tweak to the perf filter trace and free allow the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which predefines this information in syscall_metadata associated enter_event (and exit_event) structures.

The result is that a process may reduce its available interfaces to the kernel through prctl() without knowing the appropriate system call number a priori and with the flexibility of filtering based on register-stored arguments.  (String checks suffer from TOCTOU issues and should be left to LSMs to provide policy for! Don't get greedy :)

A sample filterset for a process that only needs to interact over stdin and stdout and exit cleanly is shown below:
  sys_read: fd == 0
  sys_write: fd == 1
  sys_exit_group: 1

Quoted 3 lines

The filters may be specified once prior to entering the reduced access state:
  prctl(PR_SET_SECCOMP, 2, filters);

Quoted 8 lines

Instead of having such multiline filter definition with syscall names prepended, it would be nicer to make the parsing simplier.

You could have either:

       prctl(PR_SET_SECCOMP, mode);
       /* Works only if we are in mode 2 */ prctl(PR_SET_SECCOMP_FILTER, syscall_nr, filter);

It'd need to be syscall_name instead of syscall_nr. Otherwise we're right back to where Adam's patch was 2+ years ago :) Using the event names from the syscalls infrastructure means the consumer of the interface doesn't need to be confident of the syscall number. That said, it would be nice to be able to specify the number as well. If there were no complaints, it'd be nice to support both, imo.

Quoted 9 lines

or:
       /*
        * If mode == 2, set the filter to syscall_nr
        * Recall this for each syscall that need a filter.
        * If a filter was previously set on the targeted syscall,
        * it will be overwritten.
        */
       prctl(PR_SET_SECCOMP, mode, syscall_nr, filter);

Quoted 8 lines

One can erase a previous filter by setting the new filter "1".

Also, instead of having a bitmap of syscall to accept. You could simply set "0" as a filter to those you want to deactivate:

prctl(PR_SET_SECCOMP, 2, 1, 0); <- deactivate the syscall_nr 1

Hm?

I like the simplicity in not needing to parse anything extra, but it does add the need for extra state - either a bit or a new field - to represent "enabled/enforcing".

The only way to do it without a third mode would be to take a blacklist model - where all syscalls are allowed by default and the caller has to enumerate them all and drop them. That would definitely not be the right approach :)

If a new bit of state was added, it could be used as:
prctl(PR_SET_SECCOMP, 2);
prctl(PR_SET_SECCOMP, 2, "sys_read", "fd == 1"); /* add a read filter */ prctl(PR_SET_SECCOMP, 2, "sys_write", "fd == 0"); /* add a read filter */
...
prctl(PR_SET_SECCOMP, 2, "sys_read", "0"); /* clear the sys_read
filters and block it */ (or NULL?)
prctl(PR_SET_SECCOMP, 2, "enable"); /* Start enforcing */ prctl(PR_SET_SECCOMP, 2, "sys_write", "0"); /* Reduce attack
surface on the fly */

As to the "0" filter instead of a bitmask, would it make sense to just cut over to an hlist now and drop the bitmask? It looks like perf uses that model, and I'd hope it wouldn't incur too much additional overhead. (The linked list approach now is certainly not scalable for a large number of filters!)

If that interface seems sane, I can certainly start exploring it and see if I hit any surprises (and put it in the next version of the patch :). I think it'll simplify a fair amount of the add/drop code!

thanks!
will

#14 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 7 lines · Will Drewry
Quoted 5 lines · Frederic Weisbecker

Instead of having such multiline filter definition with syscall names prepended, it would be nicer to make the parsing simplier.

You could have either:

Quoted 8 lines
Quoted 3 lines

       prctl(PR_SET_SECCOMP, mode);
       /* Works only if we are in mode 2 */ prctl(PR_SET_SECCOMP_FILTER, syscall_nr, filter);

It'd need to be syscall_name instead of syscall_nr. Otherwise we're right back to where Adam's patch was 2+ years ago :) Using the event names from the syscalls infrastructure means the consumer of the interface doesn't need to be confident of the syscall number.

Is it really a problem? There are libraries that can resolve that. Of course I can't recall their name.

Quoted 15 lines
Quoted 15 lines

or:
       /*
        * If mode == 2, set the filter to syscall_nr
        * Recall this for each syscall that need a filter.
        * If a filter was previously set on the targeted syscall,
        * it will be overwritten.
        */
       prctl(PR_SET_SECCOMP, mode, syscall_nr, filter);

One can erase a previous filter by setting the new filter "1".

Also, instead of having a bitmap of syscall to accept. You could simply set "0" as a filter to those you want to deactivate:

Quoted 7 lines
Quoted 3 lines

prctl(PR_SET_SECCOMP, 2, 1, 0); <- deactivate the syscall_nr 1

Hm?

I like the simplicity in not needing to parse anything extra, but it does add the need for extra state - either a bit or a new field - to represent "enabled/enforcing".

And by the way I'm really puzzled about these. I don't understand well why we need this.

As for the enable_on_next_syscall. The documentation says it's useful if you want the filter to only apply to the child. So if fork immediately follows, you will be able to fork but if the child doesn't have the right to exec, it won't be able to do so. Same for the mmap() that involves...

So I'm a bit confused about that.

But yeah if that's really needed, it looks to me better to reduce the parsing and cut it that way:

	prctl(PR_SET_SECCOMP, 2, syscall_name_or_nr, filter);
	prctl(PR_SECCOMP_APPLY_FILTERS, enable_on_next_syscall?)

or something...

Quoted 18 lines

The only way to do it without a third mode would be to take a blacklist model - where all syscalls are allowed by default and the caller has to enumerate them all and drop them. That would definitely not be the right approach :)

If a new bit of state was added, it could be used as:
prctl(PR_SET_SECCOMP, 2);
prctl(PR_SET_SECCOMP, 2, "sys_read", "fd == 1"); /* add a read filter */ prctl(PR_SET_SECCOMP, 2, "sys_write", "fd == 0"); /* add a read filter */
...
prctl(PR_SET_SECCOMP, 2, "sys_read", "0"); /* clear the sys_read
filters and block it */ (or NULL?)
prctl(PR_SET_SECCOMP, 2, "enable"); /* Start enforcing */ prctl(PR_SET_SECCOMP, 2, "sys_write", "0"); /* Reduce attack
surface on the fly */

Quoted 6 lines

As to the "0" filter instead of a bitmask, would it make sense to just cut over to an hlist now and drop the bitmask?
It looks like perf
uses that model, and I'd hope it wouldn't incur too much additional overhead. (The linked list approach now is certainly not scalable for a large number of filters!)

The linked list certainly doesn't scale there. But either a hlist for everything, or a hlist + bitmap to check if the syscall is enabled, why not. May be start with a pure hlist for any filters and if performance issues that really matter are pinpointed, then move the "1" and "0" implementation to a bitmap.

My guess is that doesn't really matter. If it's "1" then you can just have an empty set of filters for the syscall and it goes ahead quickly. If it's "0" then the app fails, which is not what I would call a fast path.

Quoted 3 lines

If that interface seems sane, I can certainly start exploring it and see if I hit any surprises (and put it in the next version of the patch :). I think it'll simplify a fair amount of the add/drop code!

Yup.

author reviewer
#15 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 12 lines · Frederic Weisbecker
Quoted 11 lines · Will Drewry
Quoted 8 lines · Frederic Weisbecker

Instead of having such multiline filter definition with syscall names prepended, it would be nicer to make the parsing simplier.

You could have either:

       prctl(PR_SET_SECCOMP, mode);
       /* Works only if we are in mode 2 */ prctl(PR_SET_SECCOMP_FILTER, syscall_nr, filter);

Quoted 6 lines
Quoted 4 lines

It'd need to be syscall_name instead of syscall_nr.  Otherwise we're right back to where Adam's patch was 2+ years ago :)  Using the event names from the syscalls infrastructure means the consumer of the interface doesn't need to be confident of the syscall number.

Is it really a problem?

I'd prefer using numbers myself since it gives more flexibility around filtering entries that haven't yet made it into ftrace syscalls hooks. However, I think there's some complexity in ensuring it matches the host kernel. (It would also allow compat_task support which doesn't seem to be possible now.)

Quoted 1 line

There are libraries that can resolve that. Of course I can't recall their name.

asm-generic/unistd.h will provide the mapping, if available. It would mean that any helper libraries would need to be matched to the locally running kernel.

If syscall names and numbers are supported, then it would mean that this change could do both what Adam's original bitmask patch did, by default, and when CONFIG_FTRACE_SYSCALLS are enabled, it could do name resolution and apply more complex filters based on the syscalls events.

Would that make sense? I wonder if the inconsistency between sometimes using names and filters and sometimes using numbers and 0|1 would become onerous if userspace applications started using this. Maybe something like
prctl(PR_SECCOMP_HAS_FILTERS);
would be desirable? I dunno.

Quoted 16 lines
Quoted 16 lines
Quoted 16 lines

or:
       /*
        * If mode == 2, set the filter to syscall_nr
        * Recall this for each syscall that need a filter.
        * If a filter was previously set on the targeted syscall,
        * it will be overwritten.
        */
       prctl(PR_SET_SECCOMP, mode, syscall_nr, filter);

One can erase a previous filter by setting the new filter "1".

Also, instead of having a bitmap of syscall to accept. You could simply set "0" as a filter to those you want to deactivate:

prctl(PR_SET_SECCOMP, 2, 1, 0); <- deactivate the syscall_nr 1

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

Hm?

I like the simplicity in not needing to parse anything extra, but it does add the need for extra state - either a bit or a new field - to represent "enabled/enforcing".

And by the way I'm really puzzled about these. I don't understand well why we need this.

Right now, if you are in seccomp mode !=0 , your system calls will be hooked (if TIF_SECCOMP is set too). The current patch begins filtering immediately. And once filtering is enabled, the process is not allowed to expand its access to the kernel system cals - only shrink it. An "enabled" bit would be needed to tell it that even though it is running in mode=2, it should/shouldn't kill the process for system call filter violations and it should allow filters to be added, not just dropped. It's why the current patch does it in one step: set the filters and the mode. While an enabled bit could be hidden behind whether TIF_SECCOMP is applied, I'm not sure if that would just be confusing. There'd still be a need to APPLY_FILTERS to get the TIF_SECCOMP flag set to start hooking the system calls.

Quoted 7 lines

As for the enable_on_next_syscall. The documentation says it's useful if you want the filter to only apply to the child. So if fork immediately follows, you will be able to fork but if the child doesn't have the right to exec, it won't be able to do so. Same for the mmap() that involves...

So I'm a bit confused about that.

Here's an example:
http://static.dataspill.org/seccomp_filter/v1/seccomp_launcher.c

You'd use it by calling fork() ... prctl(..., ON_NEXT_SYSCALL) then execve since you'll already have fork()d. It seems to work, but maybe I'm missing something :)

Quoted 7 lines

But yeah if that's really needed, it looks to me better to reduce the parsing and cut it that way:

       prctl(PR_SET_SECCOMP, 2, syscall_name_or_nr, filter); prctl(PR_SECCOMP_APPLY_FILTERS, enable_on_next_syscall?)

or something...

Cool - if there are any other flags, it could be something like:
prctl(PR_SECCOMP_SET_FLAGS, SECCOMP_ENFORCE|SECCOMP_DELAYED_ENFORCEMENT);

But only if there are other flags worth considering. I had a few others in mind, but now I've completely forgotten :/

Quoted 31 lines
Quoted 18 lines

The only way to do it without a third mode would be to take a blacklist model - where all syscalls are allowed by default and the caller has to enumerate them all and drop them. That would definitely not be the right approach :)

If a new bit of state was added,  it could be used as:
  prctl(PR_SET_SECCOMP, 2);
  prctl(PR_SET_SECCOMP, 2, "sys_read", "fd == 1");  /* add a read filter */ prctl(PR_SET_SECCOMP, 2, "sys_write", "fd == 0");  /* add a read filter */
  ...
  prctl(PR_SET_SECCOMP, 2, "sys_read", "0");  /* clear the sys_read filters and block it */  (or NULL?)
  prctl(PR_SET_SECCOMP, 2, "enable");  /* Start enforcing */ prctl(PR_SET_SECCOMP, 2, "sys_write", "0");  /* Reduce attack surface on the fly */

Quoted 6 lines

As to the "0" filter instead of a bitmask, would it make sense to just cut over to an hlist now and drop the bitmask?
It looks like perf
uses that model, and I'd hope it wouldn't incur too much additional overhead.  (The linked list approach now is certainly not scalable for a large number of filters!)

The linked list certainly doesn't scale there. But either a hlist for everything, or a hlist + bitmap to check if the syscall is enabled, why not. May be start with a pure hlist for any filters and if performance issues that really matter are pinpointed, then move the "1" and "0" implementation to a bitmap.

Quoted 4 lines

My guess is that doesn't really matter. If it's "1" then you can just have an empty set of filters for the syscall and it goes ahead quickly. If it's "0" then the app fails, which is not what I would call a fast path.

Sounds reasonable to me. I'll start to iterate on the suggested changes and see what emerges.

Quoted 5 lines
Quoted 3 lines

If that interface seems sane, I can certainly start exploring it and see if I hit any surprises (and put it in the next version of the patch :).  I think it'll simplify a fair amount of the add/drop code!

Yup.

Thanks!
will

#16 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 19 lines · Will Drewry
Quoted 17 lines · Frederic Weisbecker
Quoted 15 lines · Will Drewry
Quoted 8 lines · Frederic Weisbecker

Instead of having such multiline filter definition with syscall names prepended, it would be nicer to make the parsing simplier.

You could have either:

       prctl(PR_SET_SECCOMP, mode);
       /* Works only if we are in mode 2 */ prctl(PR_SET_SECCOMP_FILTER, syscall_nr, filter);

It'd need to be syscall_name instead of syscall_nr.  Otherwise we're right back to where Adam's patch was 2+ years ago :)  Using the event names from the syscalls infrastructure means the consumer of the interface doesn't need to be confident of the syscall number.

Quoted 7 lines
Quoted 1 line

Is it really a problem?

I'd prefer using numbers myself since it gives more flexibility around filtering entries that haven't yet made it into ftrace syscalls hooks. However, I think there's some complexity in ensuring it matches the host kernel. (It would also allow compat_task support which doesn't seem to be possible now.)

You'd have some problems with compat and syscall naming, I think some of them are not the same between compat architectures.

Note that your new prctl() request is turning syscall handler names (in-kernel API) into a user ABI. We won't be able to change the name of those kernel handlers after that. I'm not sure that's desired.

OTOH, syscall numbers are a user ABI,

Quoted 6 lines
Quoted 2 lines

There are libraries that can resolve that. Of course I can't recall their name.

asm-generic/unistd.h will provide the mapping, if available. It would mean that any helper libraries would need to be matched to the locally running kernel.

Yeah. But syscall numbers don't move inside a given architecture (could they?) Or if so then you'd a dynamic library.

Quoted 25 lines
Quoted 16 lines
Quoted 16 lines
Quoted 16 lines

or:
       /*
        * If mode == 2, set the filter to syscall_nr
        * Recall this for each syscall that need a filter.
        * If a filter was previously set on the targeted syscall,
        * it will be overwritten.
        */
       prctl(PR_SET_SECCOMP, mode, syscall_nr, filter);

One can erase a previous filter by setting the new filter "1".

Also, instead of having a bitmap of syscall to accept. You could simply set "0" as a filter to those you want to deactivate:

prctl(PR_SET_SECCOMP, 2, 1, 0); <- deactivate the syscall_nr 1

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

Hm?

I like the simplicity in not needing to parse anything extra, but it does add the need for extra state - either a bit or a new field - to represent "enabled/enforcing".

And by the way I'm really puzzled about these. I don't understand well why we need this.

Quoted 12 lines

Right now, if you are in seccomp mode !=0 , your system calls will be hooked (if TIF_SECCOMP is set too). The current patch begins filtering immediately. And once filtering is enabled, the process is not allowed to expand its access to the kernel system cals - only shrink it. An "enabled" bit would be needed to tell it that even though it is running in mode=2, it should/shouldn't kill the process for system call filter violations and it should allow filters to be added, not just dropped. It's why the current patch does it in one step: set the filters and the mode. While an enabled bit could be hidden behind whether TIF_SECCOMP is applied, I'm not sure if that would just be confusing. There'd still be a need to APPLY_FILTERS to get the TIF_SECCOMP flag set to start hooking the system calls.

It seems the filter is only ever needed for the childs, right? And moreover when they exec. So Steve's suggestion to apply the filters only after the next exec makes sense.

That would solve the problem of both ON_NEXT_SYSCALL and APPLY_FILTER.

I may be missing something obvious though. Do you see a limitation there?

Quoted 7 lines
Quoted 7 lines

As for the enable_on_next_syscall. The documentation says it's useful if you want the filter to only apply to the child. So if fork immediately follows, you will be able to fork but if the child doesn't have the right to exec, it won't be able to do so. Same for the mmap() that involves...

Quoted 8 lines
Quoted 1 line

So I'm a bit confused about that.

Here's an example:
http://static.dataspill.org/seccomp_filter/v1/seccomp_launcher.c

You'd use it by calling fork() ... prctl(..., ON_NEXT_SYSCALL) then execve since you'll already have fork()d. It seems to work, but maybe I'm missing something :)

Nope, I see.

Quoted 14 lines
Quoted 8 lines

But yeah if that's really needed, it looks to me better to reduce the parsing and cut it that way:

       prctl(PR_SET_SECCOMP, 2, syscall_name_or_nr, filter); prctl(PR_SECCOMP_APPLY_FILTERS, enable_on_next_syscall?)

or something...

Cool - if there are any other flags, it could be something like:
prctl(PR_SECCOMP_SET_FLAGS, SECCOMP_ENFORCE|SECCOMP_DELAYED_ENFORCEMENT);

But only if there are other flags worth considering. I had a few others in mind, but now I've completely forgotten :/

author reviewer
#17 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 28 lines · Frederic Weisbecker
Quoted 19 lines · Will Drewry
Quoted 17 lines · Frederic Weisbecker
Quoted 15 lines · Will Drewry
Quoted 8 lines · Frederic Weisbecker

Instead of having such multiline filter definition with syscall names prepended, it would be nicer to make the parsing simplier.

You could have either:

       prctl(PR_SET_SECCOMP, mode);
       /* Works only if we are in mode 2 */ prctl(PR_SET_SECCOMP_FILTER, syscall_nr, filter);

It'd need to be syscall_name instead of syscall_nr.  Otherwise we're right back to where Adam's patch was 2+ years ago :)  Using the event names from the syscalls infrastructure means the consumer of the interface doesn't need to be confident of the syscall number.

Quoted 7 lines
Quoted 1 line

Is it really a problem?

I'd prefer using numbers myself since it gives more flexibility around filtering entries that haven't yet made it into ftrace syscalls hooks. However, I think there's some complexity in ensuring it matches the host kernel.  (It would also allow compat_task support which doesn't seem to be possible now.)

Quoted 8 lines

You'd have some problems with compat and syscall naming, I think some of them are not the same between compat architectures.

Note that your new prctl() request is turning syscall handler names (in-kernel API) into a user ABI. We won't be able to change the name of those kernel handlers after that. I'm not sure that's desired.

OTOH, syscall numbers are a user ABI,

Makes sense. I don't mind going the syscall nr route and using a library for name resolution in userspace, but other users could just include the libc provided names. If it doesn't work, the SIGKILL will
make it apparent pretty quickly :p I don't think it would be a
problem and it makes the kernel side even simpler again.

Quoted 11 lines
Quoted 8 lines
Quoted 4 lines

There are libraries that can resolve that. Of course I can't recall their name.

asm-generic/unistd.h will provide the mapping, if available. It would mean that any helper libraries would need to be matched to the locally running kernel.

Yeah. But syscall numbers don't move inside a given architecture (could they?) Or if so then you'd a dynamic library.

Works for me.

Quoted 80 lines
Quoted 26 lines
Quoted 17 lines
Quoted 17 lines
Quoted 17 lines

or:
       /*
        * If mode == 2, set the filter to syscall_nr
        * Recall this for each syscall that need a filter.
        * If a filter was previously set on the targeted syscall,
        * it will be overwritten.
        */
       prctl(PR_SET_SECCOMP, mode, syscall_nr, filter);

One can erase a previous filter by setting the new filter "1".

Also, instead of having a bitmap of syscall to accept. You could simply set "0" as a filter to those you want to deactivate:

prctl(PR_SET_SECCOMP, 2, 1, 0); <- deactivate the syscall_nr 1

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

Hm?

I like the simplicity in not needing to parse anything extra, but it does add the need for extra state - either a bit or a new field - to represent "enabled/enforcing".

And by the way I'm really puzzled about these. I don't understand well why we need this.

Quoted 12 lines

Right now, if you are in seccomp mode !=0 , your system calls will be hooked (if TIF_SECCOMP is set too). The current patch begins filtering immediately.  And once filtering is enabled, the process is not allowed to expand its access to the kernel system cals - only shrink it.  An "enabled" bit would be needed to tell it that even though it is running in mode=2, it should/shouldn't kill the process for system call filter violations and it should allow filters to be added, not just dropped.  It's why the current patch does it in one step: set the filters and the mode.  While an enabled bit could be hidden behind whether TIF_SECCOMP is applied, I'm not sure if that would just be confusing.  There'd still be a need to APPLY_FILTERS to get the TIF_SECCOMP flag set to start hooking the system calls.

It seems the filter is only ever needed for the childs, right? And moreover when they exec. So Steve's suggestion to apply the filters only after the next exec makes sense.

That would solve the problem of both ON_NEXT_SYSCALL and APPLY_FILTER.

I may be missing something obvious though. Do you see a limitation there?

Quoted 7 lines
Quoted 7 lines

As for the enable_on_next_syscall. The documentation says it's useful if you want the filter to only apply to the child. So if fork immediately follows, you will be able to fork but if the child doesn't have the right to exec, it won't be able to do so. Same for the mmap() that involves...

Quoted 8 lines
Quoted 1 line

So I'm a bit confused about that.

Here's an example:
  http://static.dataspill.org/seccomp_filter/v1/seccomp_launcher.c

You'd use it by calling fork() ... prctl(..., ON_NEXT_SYSCALL) then execve since you'll already have fork()d.  It seems to work, but maybe I'm missing something :)

Nope, I see.

Quoted 14 lines
Quoted 8 lines

But yeah if that's really needed, it looks to me better to reduce the parsing and cut it that way:

       prctl(PR_SET_SECCOMP, 2, syscall_name_or_nr, filter); prctl(PR_SECCOMP_APPLY_FILTERS, enable_on_next_syscall?)

or something...

Cool - if there are any other flags, it could be something like:
  prctl(PR_SECCOMP_SET_FLAGS, SECCOMP_ENFORCE|SECCOMP_DELAYED_ENFORCEMENT);

But only if there are other flags worth considering. I had a few others in mind, but now I've completely forgotten :/

maintainer
#18 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

In reply to Will Drewry
Quoted 4 lines · Will Drewry

The only other twist is that it is possible to delay enforcement by one system call by supplying a "on_next_syscall: 1" 'filter'. This allows for a launcher process to fork(), prctl(), then execve() leaving the launched binary in a filtered state.

I wonder if the more "unixy" thing to do is, instead of on_next_sycall, have "enable_on_exec". Where the user could do multiple syscalls but the filter will not take place until an exec is made?

-- Steve

author reviewer
#19 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 10 lines · Steven Rostedt
Quoted 4 lines · Will Drewry

The only other twist is that it is possible to delay enforcement by one system call by supplying a "on_next_syscall: 1" 'filter'.  This allows for a launcher process to fork(), prctl(), then execve() leaving the launched binary in a filtered state.

I wonder if the more "unixy" thing to do is, instead of on_next_sycall, have "enable_on_exec". Where the user could do multiple syscalls but the filter will not take place until an exec is made?

That's what it was originally, but since ftrace syscalls doesn't wrap sys_execve on x86, I opted to just say "next syscall". But of course I can just check the _NR_execve == syscall_nr and do the right thing. Duh.

thanks!

maintainer
#20 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

In reply to Will Drewry

Quoting Will Drewry ([email protected]):

Thanks very much for going through with this, Will. I really hope to see this go upstream soon.

Quoted 48 lines

This change adds a new seccomp mode based on the work by [email protected]. This mode comes with a bitmask of NR_syscalls size and an optional linked list of seccomp_filter objects. When in mode 2, all system calls are first checked against the bitmask to determine if they are allowed or denied. If allowed, the list of filters is checked for the given syscall number. If all filter predicates for the system call match or the system call was allowed without restriction, the process continues. Otherwise, it is killed and a KERN_INFO notification is posted.

The filter language itself is provided by the ftrace filter engine. Related patches tweak to the perf filter trace and free allow the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which predefines this information in syscall_metadata associated enter_event (and exit_event) structures.

The result is that a process may reduce its available interfaces to the kernel through prctl() without knowing the appropriate system call number a priori and with the flexibility of filtering based on register-stored arguments. (String checks suffer from TOCTOU issues and should be left to LSMs to provide policy for! Don't get greedy :)

A sample filterset for a process that only needs to interact over stdin and stdout and exit cleanly is shown below:
sys_read: fd == 0
sys_write: fd == 1
sys_exit_group: 1

The filters may be specified once prior to entering the reduced access state:
prctl(PR_SET_SECCOMP, 2, filters);
If prctl() is in the allowed bitmask, the process may futher reduce privileges by dropping system calls from the allowed set.

The only other twist is that it is possible to delay enforcement by one system call by supplying a "on_next_syscall: 1" 'filter'. This allows for a launcher process to fork(), prctl(), then execve() leaving the launched binary in a filtered state.

Implementation-wise, seccomp.c now uses seccomp_state struct which is managed using RCU primitives. It contains the system call bitmask and a linked list of seccomp_filters (which are also managed as an RCU list). All mutations (barring one optional bit flip) to the seccomp_state are always done on a duplicate of the current state value which is swapped on prior to use.

...

kernel/seccomp.c static int mode1_syscalls_32[] = { · line 38

Quoted 7 lines

void __secure_computing(int this_syscall)
{

kernel/seccomp.c +2 -2
-	int mode = current->seccomp.mode;
+	int mode = -1;
 	int * syscall;
-
+	/* Do we need an RCU read lock to access current's state? */

Nope.

...

Quoted 98 lines
kernel/seccomp.c +73 -8
+struct seccomp_state *get_seccomp_state(struct seccomp_state *orig)
+{
+	if (!orig)
+		return NULL;
+	atomic_inc(&orig->usage);
+	return orig;
+}
+
+static void __put_seccomp_state(struct seccomp_state *orig)
+{
+	WARN_ON(atomic_read(&orig->usage));
+	seccomp_drop_all_filters(orig);
+	kfree(orig);
+}
+
+/* put_seccomp_state - decrements the reference count of @orig and may free. */
+void put_seccomp_state(struct seccomp_state *orig)
+{
+	if (!orig)
+		return;
+
+	if (atomic_dec_and_test(&orig->usage))
+		__put_seccomp_state(orig);
+}
+
 long prctl_get_seccomp(void)
 {
-	return current->seccomp.mode;
+	if (!current->seccomp.state)
+		return 0;
+	return current->seccomp.state->mode;
 }
 
-long prctl_set_seccomp(unsigned long seccomp_mode)
+long prctl_set_seccomp(unsigned long seccomp_mode, char *filters)
 {
 	long ret;
+	struct seccomp_state *state, *orig_state;
 
-	/* can set it only once to be even more secure */
+	rcu_read_lock();
+	orig_state = get_seccomp_state(rcu_dereference(current->seccomp.state));
+	rcu_read_unlock();
+
+	/* mode 1 can only be set once, but mode 2 may have access reduced. */
 	ret = -EPERM;
-	if (unlikely(current->seccomp.mode))
+	if (orig_state && orig_state->mode != 2 && seccomp_mode != 2)
 		goto out;
 
 	ret = -EINVAL;
-	if (seccomp_mode && seccomp_mode <= NR_SECCOMP_MODES) {
-		current->seccomp.mode = seccomp_mode;
-		set_thread_flag(TIF_SECCOMP);
+	if (!seccomp_mode || seccomp_mode > NR_SECCOMP_MODES)
+		goto out;
+
+	/* Prepare to modify the seccomp state by dropping the shared
+	 * reference after duplicating it.
+	 */
+	state = (orig_state ? seccomp_state_dup(orig_state) :
+			      seccomp_state_new());
+	if (!state) {
+		ret = -ENOMEM;
+		goto out;
+	}
+
+	ret = 0;
+	switch (seccomp_mode) {
+	case 1:
 #ifdef TIF_NOTSC
 		disable_TSC();
 #endif
+		state->mode = seccomp_mode;
+		set_thread_flag(TIF_SECCOMP);
 		ret = 0;
+		break;
+	case 2:
+		if (filters) {
+			ret = seccomp_parse_filters(state, filters);
+			/* No partial applications. */
+			if (ret)
+				goto free_state;
+		}
+
+		if (!state->mode) {
+			state->mode = seccomp_mode;
+			set_thread_flag(TIF_SECCOMP);
+		}
+		break;
+	default:
+		ret = -EINVAL;
 	}
 
- out:
+	rcu_assign_pointer(current->seccomp.state, state);
+	synchronize_rcu();
+	put_seccomp_state(orig_state);  /* for the get */

kernel/seccomp.c void __secure_computing(int this_syscall) · line 208

Quoted 10 lines
kernel/seccomp.c +8 -0
+
+out:
+	put_seccomp_state(orig_state);  /* for the task */
+	return ret;
+
+free_state:
+	put_seccomp_state(orig_state);  /* for the get */
+	put_seccomp_state(state);  /* drop the dup */
 	return ret;
 }

This looks exactly right. The only case where put_seccomp_state() might actually lead to freeing the state is where the current's state gets reassigned. So you need to synchronize_rcu() before that (as you do). The other cases will only decrement the usage counter, can race with a reader doing (inc; get) but not with a final free, which can only be done here.

(Rambling above is just me pursuading myself)

kernel/seccomp_filter.c

Quoted 1 line
kernel/seccomp_filter.c +0 -0

Unfortunately your use of filters doesn't seem exactly right.

Quoted 7 lines
kernel/seccomp_filter.c +7 -0
+/* seccomp_copy_all_filters - copies all filters from src to dst.
+ *
+ * @dst: the list_head for seccomp_filters to populate.
+ * @src: the list_head for seccomp_filters to copy from.
+ * Returns non-zero on failure.
+ */
+int seccomp_copy_all_filters(struct list_head *dst,

kernel/seccomp_filter.c line 291

Quoted 10 lines
kernel/seccomp_filter.c +10 -0
+			     const struct list_head *src)
+{
+	struct seccomp_filter *filter;
+	int ret = 0;
+	BUG_ON(!dst || !src);
+	if (list_empty(src))
+		goto done;
+	rcu_read_lock();
+	list_for_each_entry(filter, src, list) {
+		struct seccomp_filter *new_filter = copy_seccomp_filter(filter);

copy_seccomp_filter() causes kzalloc to be called. You can't do that under rcu_read_lock().

I actually thought you were going to be more extreme about the seccomp state than you are: I thought you were going to tie a filter list to seccomp state. So adding or removing a filter would have required duping the seccomp state, duping all the filters, making the change in the copy, and then swapping the new state into place. Slow in the hopefully rare update case, but safe.

You don't have to do that, but then I'm pretty sure you'll need to add reference counts to each filter and use rcu cycles to a reader from having the filter disappear mid-read.

-serge

maintainer
#21 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 11 lines · Serge E. Hallyn

...

kernel/seccomp.c static int mode1_syscalls_32[] = { · line 38

Quoted 7 lines

void __secure_computing(int this_syscall)
{

kernel/seccomp.c +2 -2
-	int mode = current->seccomp.mode;
+	int mode = -1;
 	int * syscall;
-
+	/* Do we need an RCU read lock to access current's state? */

Nope.

Correct.

Quoted 13 lines
Quoted 13 lines

- out:

kernel/seccomp.c +11 -0
+	rcu_assign_pointer(current->seccomp.state, state);
+	synchronize_rcu();
+	put_seccomp_state(orig_state);  /* for the get */
+
+out:
+	put_seccomp_state(orig_state);  /* for the task */
+	return ret;
+
+free_state:
+	put_seccomp_state(orig_state);  /* for the get */
+	put_seccomp_state(state);  /* drop the dup */
 	return ret;
Quoted 8 lines
Quoted 1 line

}

This looks exactly right. The only case where put_seccomp_state() might actually lead to freeing the state is where the current's state gets reassigned. So you need to synchronize_rcu() before that (as you do). The other cases will only decrement the usage counter, can race with a reader doing (inc; get) but not with a final free, which can only be done here.

Technically incorrect ;)

"final free, which can only be done here."

This is not the only place that a free will happen. But the code is correct none-the-less.

Reader on another CPU ups the orig_state refcount under rcu_readlock, but after it ups the refcount it releases the rcu_readlock and continues to read this state.

Current on this CPU calls this function does the synchronize_rcu() and calls put on the state. But since the reader still has a ref count on it, it does not get freed here.

When the reader is finally done with the state it calls the put() which does the final free on it.

The code still looks correct, I'm just nitpicking your analysis.

Quoted 2 lines

(Rambling above is just me pursuading myself)

Me rambling too.

Quoted 17 lines

kernel/seccomp_filter.c

Quoted 2 lines
kernel/seccomp_filter.c +0 -0

Unfortunately your use of filters doesn't seem exactly right.

Quoted 12 lines
kernel/seccomp_filter.c +12 -0
+/* seccomp_copy_all_filters - copies all filters from src to dst.
+ *
+ * @dst: the list_head for seccomp_filters to populate.
+ * @src: the list_head for seccomp_filters to copy from.
+ * Returns non-zero on failure.
+ */
+int seccomp_copy_all_filters(struct list_head *dst,
+			     const struct list_head *src)
+{
+	struct seccomp_filter *filter;
+	int ret = 0;
+	BUG_ON(!dst || !src);
Quoted 8 lines

kernel/seccomp_filter.c line 291

Quoted 5 lines
kernel/seccomp_filter.c +5 -0
+	if (list_empty(src))
+		goto done;
+	rcu_read_lock();
+	list_for_each_entry(filter, src, list) {
+		struct seccomp_filter *new_filter = copy_seccomp_filter(filter);

copy_seccomp_filter() causes kzalloc to be called. You can't do that under rcu_read_lock().

Unless you change the kzalloc to do GFP_ATOMIC. Not sure I'd recommend doing that.

Quoted 11 lines

I actually thought you were going to be more extreme about the seccomp state than you are: I thought you were going to tie a filter list to seccomp state. So adding or removing a filter would have required duping the seccomp state, duping all the filters, making the change in the copy, and then swapping the new state into place. Slow in the hopefully rare update case, but safe.

You don't have to do that, but then I'm pretty sure you'll need to add reference counts to each filter and use rcu cycles to a reader from having the filter disappear mid-read.

Or you can preallocate the new filters, call rcu_read_lock(), check if the number of old filters is the same or less, if more, call rcu_read_unlock, and try allocating more, and then call rcu_read_lock() again and repeat. Then just copy the filters to the preallocate ones. rcu_read_unlock() and then free any unused allocated filters.

Maybe a bit messy, but not that bad.

-- Steve

maintainer
#22 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 49 lines · Steven Rostedt
Quoted 11 lines · Serge E. Hallyn

...

kernel/seccomp.c static int mode1_syscalls_32[] = { · line 38

Quoted 7 lines

void __secure_computing(int this_syscall)
{

kernel/seccomp.c +2 -2
-	int mode = current->seccomp.mode;
+	int mode = -1;
 	int * syscall;
-
+	/* Do we need an RCU read lock to access current's state? */

Nope.

Correct.

Quoted 13 lines
Quoted 13 lines

- out:

kernel/seccomp.c +11 -0
+	rcu_assign_pointer(current->seccomp.state, state);
+	synchronize_rcu();
+	put_seccomp_state(orig_state);  /* for the get */
+
+out:
+	put_seccomp_state(orig_state);  /* for the task */
+	return ret;
+
+free_state:
+	put_seccomp_state(orig_state);  /* for the get */
+	put_seccomp_state(state);  /* drop the dup */
 	return ret;
Quoted 8 lines
Quoted 1 line

}

This looks exactly right. The only case where put_seccomp_state() might actually lead to freeing the state is where the current's state gets reassigned. So you need to synchronize_rcu() before that (as you do). The other cases will only decrement the usage counter, can race with a reader doing (inc; get) but not with a final free, which can only be done here.

Technically incorrect ;)

"final free, which can only be done here."

This is not the only place that a free will happen. But the code is correct none-the-less.

Reader on another CPU ups the orig_state refcount under rcu_readlock, but after it ups the refcount it releases the rcu_readlock and continues to read this state.

Quoted 8 lines

Current on this CPU calls this function does the synchronize_rcu() and calls put on the state. But since the reader still has a ref count on it, it does not get freed here.

When the reader is finally done with the state it calls the put() which does the final free on it.

The code still looks correct, I'm just nitpicking your analysis.

:) I appreciate the precision.

Quoted 45 lines
Quoted 1 line

(Rambling above is just me pursuading myself)

Me rambling too.

Quoted 17 lines

kernel/seccomp_filter.c

Quoted 2 lines
kernel/seccomp_filter.c +0 -0

Unfortunately your use of filters doesn't seem exactly right.

Quoted 12 lines
kernel/seccomp_filter.c +12 -0
+/* seccomp_copy_all_filters - copies all filters from src to dst.
+ *
+ * @dst: the list_head for seccomp_filters to populate.
+ * @src: the list_head for seccomp_filters to copy from.
+ * Returns non-zero on failure.
+ */
+int seccomp_copy_all_filters(struct list_head *dst,
+			     const struct list_head *src)
+{
+	struct seccomp_filter *filter;
+	int ret = 0;
+	BUG_ON(!dst || !src);
Quoted 8 lines

kernel/seccomp_filter.c line 291

Quoted 5 lines
kernel/seccomp_filter.c +5 -0
+	if (list_empty(src))
+		goto done;
+	rcu_read_lock();
+	list_for_each_entry(filter, src, list) {
+		struct seccomp_filter *new_filter = copy_seccomp_filter(filter);

copy_seccomp_filter() causes kzalloc to be called. You can't do that under rcu_read_lock().

Unless you change the kzalloc to do GFP_ATOMIC. Not sure I'd recommend doing that.

Quoted 11 lines

I actually thought you were going to be more extreme about the seccomp state than you are: I thought you were going to tie a filter list to seccomp state. So adding or removing a filter would have required duping the seccomp state, duping all the filters, making the change in the copy, and then swapping the new state into place. Slow in the hopefully rare update case, but safe.

You don't have to do that, but then I'm pretty sure you'll need to add reference counts to each filter and use rcu cycles to a reader from having the filter disappear mid-read.

Quoted 7 lines

Or you can preallocate the new filters, call rcu_read_lock(), check if the number of old filters is the same or less, if more, call rcu_read_unlock, and try allocating more, and then call rcu_read_lock() again and repeat. Then just copy the filters to the preallocate ones. rcu_read_unlock() and then free any unused allocated filters.

Maybe a bit messy, but not that bad.

Sounds good.

thanks,
-serge

author reviewer
#23 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 54 lines · Serge E. Hallyn
Quoted 53 lines · Steven Rostedt
Quoted 11 lines · Serge E. Hallyn

...

Quoted 7 lines

 void __secure_computing(int this_syscall)
 {
- int mode = current->seccomp.mode;
+ int mode = -1;
  int * syscall;
-
+ /* Do we need an RCU read lock to access current's state? */

Nope.

Correct.

Quoted 13 lines
Quoted 13 lines

- out:
+ rcu_assign_pointer(current->seccomp.state, state);
+ synchronize_rcu();
+ put_seccomp_state(orig_state);  /* for the get */

kernel/seccomp.c +8 -0
+
+out:
+ put_seccomp_state(orig_state);  /* for the task */
+ return ret;
+
+free_state:
+ put_seccomp_state(orig_state);  /* for the get */
+ put_seccomp_state(state);  /* drop the dup */

  return ret;

Quoted 8 lines
Quoted 1 line

 }

This looks exactly right.  The only case where put_seccomp_state() might actually lead to freeing the state is where the current's state gets reassigned.  So you need to synchronize_rcu() before that (as you do).  The other cases will only decrement the usage counter, can race with a reader doing (inc; get) but not with a final free, which can only be done here.

Technically incorrect ;)

"final free, which can only be done here."

This is not the only place that a free will happen. But the code is correct none-the-less.

Reader on another CPU ups the orig_state refcount under rcu_readlock, but after it ups the refcount it releases the rcu_readlock and continues to read this state.

Current on this CPU calls this function does the synchronize_rcu() and calls put on the state. But since the reader still has a ref count on it, it does not get freed here.

Quoted 39 lines
Quoted 4 lines

When the reader is finally done with the state it calls the put() which does the final free on it.

The code still looks correct, I'm just nitpicking your analysis.

:)  I appreciate the precision.

Quoted 32 lines
Quoted 1 line

(Rambling above is just me pursuading myself)

Me rambling too.

Quoted 17 lines

kernel/seccomp_filter.c

Quoted 2 lines
kernel/seccomp_filter.c +0 -0

Unfortunately your use of filters doesn't seem exactly right.

Quoted 12 lines
kernel/seccomp_filter.c +12 -0
+/* seccomp_copy_all_filters - copies all filters from src to dst.
+ *
+ * @dst: the list_head for seccomp_filters to populate.
+ * @src: the list_head for seccomp_filters to copy from.
+ * Returns non-zero on failure.
+ */
+int seccomp_copy_all_filters(struct list_head *dst,
+                      const struct list_head *src)
+{
+ struct seccomp_filter *filter;
+ int ret = 0;
+ BUG_ON(!dst || !src);
Quoted 8 lines
Quoted 5 lines

+ if (list_empty(src))
+         goto done;
+ rcu_read_lock();
+ list_for_each_entry(filter, src, list) {
+         struct seccomp_filter *new_filter = copy_seccomp_filter(filter);

copy_seccomp_filter() causes kzalloc to be called.  You can't do that under rcu_read_lock().

Unless you change the kzalloc to do GFP_ATOMIC. Not sure I'd recommend doing that.

Good to know! My question (below) is if I should even be using an RCU guard at all. I may have been a bit too overzealous.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

I actually thought you were going to be more extreme about the seccomp state than you are:  I thought you were going to tie a filter list to seccomp state.  So adding or removing a filter would have required duping the seccomp state, duping all the filters, making the change in the copy, and then swapping the new state into place.  Slow in the hopefully rare update case, but safe.

Hrm, I think I'm confused now! This is exactly what I *thought* the code was doing.

At present, seccomp_state can be shared across predecessor/ancestor relationships using refcounting in fork.c (get/put). However, the only way to change a given seccomp_state or its filters is either through the one-bit on_next_syscall change or through prctl_set_seccomp. In prctl_set_seccomp, it does:
state = (orig_state ? seccomp_state_dup(orig_state) :

                              seccomp_state_new());

operates on the new state and then rcu_assign_pointer()s it to the task. I didn't intentionally provide any way to drop filters from an existing state object nor change the filtered syscalls on an in-use object. That _dup call should hit the impromperly rcu_locked copy_all_filters returning duplicates of the original filters by reparsing the filter_string.

Did I accidentally provide a means to mutate a state object or filter list without dup()ing? :/

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

You don't have to do that, but then I'm pretty sure you'll need to add reference counts to each filter and use rcu cycles to a reader from having the filter disappear mid-read.

Right now, I don't think it is possible for seccomp_copy_all_filters() to be called with a src list that changes since every change is guarded by a seccomp_state_dup(). If that's not true, then I violated my own invariant :/ If that is the case, should I not treat the list as an RCU list? There should never be any simultaneous reader/writers, just a single reader/writer or multiple readers.

Quoted 10 lines
Quoted 8 lines

Or you can preallocate the new filters, call rcu_read_lock(), check if the number of old filters is the same or less, if more, call rcu_read_unlock, and try allocating more, and then call rcu_read_lock() again and repeat. Then just copy the filters to the preallocate ones. rcu_read_unlock() and then free any unused allocated filters.

Maybe a bit messy, but not that bad.

Sounds good.

I'd prefer a heavy-weight copy ;)

I think I'm a bit lost -- am I missing something obvious here? I was hoping by using a swapped-in-seccomp_state-pointer, locking and consistency internal to the state objects would be a tad easier - though expensive.

thanks!
will

maintainer
#24 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 11 lines · Will Drewry

Good to know! My question (below) is if I should even be using an RCU guard at all. I may have been a bit too overzealous.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

I actually thought you were going to be more extreme about the seccomp state than you are: I thought you were going to tie a filter list to seccomp state. So adding or removing a filter would have required duping the seccomp state, duping all the filters, making the change in the copy, and then swapping the new state into place. Slow in the hopefully rare update case, but safe.

Quoted 2 lines

Hrm, I think I'm confused now! This is exactly what I *thought* the code was doing.

I guess my thought by looking at the code is the call_rcu() to free the filters in drop_matching_filters().

Also, you have seccomp_drop_all_filters() as a standalone function that is even exported to modules.

This to me, seems that the filters can disappear at any time. Because the freeing is done with a rcu_call() the access to the filters needs a ref count.

Quoted 15 lines

At present, seccomp_state can be shared across predecessor/ancestor relationships using refcounting in fork.c (get/put). However, the only way to change a given seccomp_state or its filters is either through the one-bit on_next_syscall change or through prctl_set_seccomp. In prctl_set_seccomp, it does:
state = (orig_state ? seccomp_state_dup(orig_state) :

                              seccomp_state_new());

operates on the new state and then rcu_assign_pointer()s it to the task. I didn't intentionally provide any way to drop filters from an existing state object nor change the filtered syscalls on an in-use object. That _dup call should hit the impromperly rcu_locked copy_all_filters returning duplicates of the original filters by reparsing the filter_string.

Quoted 2 lines

Did I accidentally provide a means to mutate a state object or filter list without dup()ing? :/

That seccomp_drop_all_filters() looks like you can.

Quoted 11 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

You don't have to do that, but then I'm pretty sure you'll need to add reference counts to each filter and use rcu cycles to a reader from having the filter disappear mid-read.

Right now, I don't think it is possible for seccomp_copy_all_filters() to be called with a src list that changes since every change is guarded by a seccomp_state_dup(). If that's not true, then I violated my own invariant :/ If that is the case, should I not treat the list as an RCU list? There should never be any simultaneous reader/writers, just a single reader/writer or multiple readers.

Again, that seccomp_copy_all_filters() is called free standing (exported to modules). Which to me means that it can be called by anyone at anytime. There is no protection of this src list.

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines

Or you can preallocate the new filters, call rcu_read_lock(), check if the number of old filters is the same or less, if more, call rcu_read_unlock, and try allocating more, and then call rcu_read_lock() again and repeat. Then just copy the filters to the preallocate ones. rcu_read_unlock() and then free any unused allocated filters.

Maybe a bit messy, but not that bad.

Quoted 8 lines
Quoted 1 line

Sounds good.

I'd prefer a heavy-weight copy ;)

I think I'm a bit lost -- am I missing something obvious here? I was hoping by using a swapped-in-seccomp_state-pointer, locking and consistency internal to the state objects would be a tad easier - though expensive.

Perhaps, but those free standing functions (the ones that are exported to modules) seem like they can destroy state.

Your code would have been correct if you could call kzalloc under rcu_read_lock() (which you can on some kernel configurations but not all). The issue is that you need to pull out that allocation from the rcu_read_lock() because rcu_read_lock assumes you can't preempt, and that allocation can schedule out. The access to the filters must be done under rcu_read_lock(), other than that, you're fine.

-- Steve

author reviewer
#25 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 76 lines · Steven Rostedt
Quoted 11 lines · Will Drewry

Good to know! My question (below) is if I should even be using an RCU guard at all. I may have been a bit too overzealous.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

I actually thought you were going to be more extreme about the seccomp state than you are:  I thought you were going to tie a filter list to seccomp state.  So adding or removing a filter would have required duping the seccomp state, duping all the filters, making the change in the copy, and then swapping the new state into place.  Slow in the hopefully rare update case, but safe.

Quoted 2 lines

Hrm, I think I'm confused now!  This is exactly what I *thought* the code was doing.

I guess my thought by looking at the code is the call_rcu() to free the filters in drop_matching_filters().

Also, you have seccomp_drop_all_filters() as a standalone function that is even exported to modules.

This to me, seems that the filters can disappear at any time. Because the freeing is done with a rcu_call() the access to the filters needs a ref count.

Quoted 15 lines

At present, seccomp_state can be shared across predecessor/ancestor relationships using refcounting in fork.c  (get/put). However, the only way to change a given seccomp_state or its filters is either through the one-bit on_next_syscall change or through prctl_set_seccomp.  In prctl_set_seccomp, it does:
state = (orig_state ? seccomp_state_dup(orig_state) :
                              seccomp_state_new()); operates on the new state and then rcu_assign_pointer()s it to the task.  I didn't intentionally provide any way to drop filters from an existing state object nor change the filtered syscalls on an in-use object.  That _dup call should hit the impromperly rcu_locked copy_all_filters returning duplicates of the original filters by reparsing the filter_string.

Quoted 2 lines

Did I accidentally provide a means to mutate a state object or filter list without dup()ing? :/

That seccomp_drop_all_filters() looks like you can.

Quoted 11 lines
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

You don't have to do that, but then I'm pretty sure you'll need to add reference counts to each filter and use rcu cycles to a reader from having the filter disappear mid-read.

Right now, I don't think it is possible for seccomp_copy_all_filters() to be called with a src list that changes since every change is guarded by a seccomp_state_dup(). If that's not true, then I violated my own invariant :/  If that is the case, should I not treat the list as an RCU list?  There should never be any simultaneous reader/writers, just a single reader/writer or multiple readers.

Again, that seccomp_copy_all_filters() is called free standing (exported to modules). Which to me means that it can be called by anyone at anytime. There is no protection of this src list.

Quoted 14 lines
Quoted 11 lines
Quoted 9 lines

Or you can preallocate the new filters, call rcu_read_lock(), check if the number of old filters is the same or less, if more, call rcu_read_unlock, and try allocating more, and then call rcu_read_lock() again and repeat. Then just copy the filters to the preallocate ones. rcu_read_unlock() and then free any unused allocated filters.

Maybe a bit messy, but not that bad.

Sounds good.

I'd prefer a heavy-weight copy ;)

Quoted 7 lines
Quoted 4 lines

I think I'm a bit lost -- am I missing something obvious here?  I was hoping by using a swapped-in-seccomp_state-pointer, locking and consistency internal to the state objects would be a tad easier - though expensive.

Perhaps, but those free standing functions (the ones that are exported to modules) seem like they can destroy state.

My intent was to make them available for use by seccomp.c during state teardown/dup. I don't think there's benefit to exposing them outside of that. Would dropping the export, and adding an local seccomp.h with the shared functions in them resolve that more cleanly?

Quoted 6 lines

Your code would have been correct if you could call kzalloc under rcu_read_lock() (which you can on some kernel configurations but not all). The issue is that you need to pull out that allocation from the rcu_read_lock() because rcu_read_lock assumes you can't preempt, and that allocation can schedule out. The access to the filters must be done under rcu_read_lock(), other than that, you're fine.

That makes sense. I think I'd prefer to not share those functions rather than guard the list just in case a future consumer of the interface comes along. Would that make sense to you? Since I don't see any other users right now other than seccomp.c, it might make sense to tackle the impact when an actual need arises.

I'll go whichever way pointed on this, though.
thanks again,
will

maintainer
#26 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 4 lines · Will Drewry

My intent was to make them available for use by seccomp.c during state teardown/dup. I don't think there's benefit to exposing them outside of that. Would dropping the export, and adding an local seccomp.h with the shared functions in them resolve that more cleanly?

And add a clear comment explaining :)

Quoted 7 lines
Quoted 6 lines

Your code would have been correct if you could call kzalloc under rcu_read_lock() (which you can on some kernel configurations but not all). The issue is that you need to pull out that allocation from the rcu_read_lock() because rcu_read_lock assumes you can't preempt, and that allocation can schedule out. The access to the filters must be done under rcu_read_lock(), other than that, you're fine.

Quoted 7 lines

That makes sense. I think I'd prefer to not share those functions rather than guard the list just in case a future consumer of the interface comes along. Would that make sense to you? Since I don't see any other users right now other than seccomp.c, it might make sense to tackle the impact when an actual need arises.

I'll go whichever way pointed on this, though.

Complicating the locking for nonexistent users doesn't seem like the right way.

-serge

maintainer
#27 lore raw

Re: [PATCH 3/7] seccomp_filter: Enable ftrace-based system call filtering

Quoted 7 lines · Serge E. Hallyn
Quoted 4 lines · Will Drewry

My intent was to make them available for use by seccomp.c during state teardown/dup. I don't think there's benefit to exposing them outside of that. Would dropping the export, and adding an local seccomp.h with the shared functions in them resolve that more cleanly?

And add a clear comment explaining :)

Yes that always helps.

Quoted 14 lines
Quoted 14 lines
Quoted 7 lines

Your code would have been correct if you could call kzalloc under rcu_read_lock() (which you can on some kernel configurations but not all). The issue is that you need to pull out that allocation from the rcu_read_lock() because rcu_read_lock assumes you can't preempt, and that allocation can schedule out. The access to the filters must be done under rcu_read_lock(), other than that, you're fine.

That makes sense. I think I'd prefer to not share those functions rather than guard the list just in case a future consumer of the interface comes along. Would that make sense to you? Since I don't see any other users right now other than seccomp.c, it might make sense to tackle the impact when an actual need arises.

Quoted 4 lines
Quoted 1 line

I'll go whichever way pointed on this, though.

Complicating the locking for nonexistent users doesn't seem like the right way.

I agree.

-- Steve

author reviewer
#28 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

This change adds a new seccomp mode based on the work by
agl at chromium.org in [1]. This new mode, "filter mode", provides a hash table of seccomp_filter objects. When in the new mode (2), all system calls are checked against the filters - first by system call number, then by a filter string. If an entry exists for a given system call and all filter predicates evaluate to true, then the task may proceed. Otherwise, the task is killed (as per seccomp_mode == 1).

Filter string parsing and evaluation is handled by the ftrace filter engine. Related patches tweak to the perf filter trace and free allow the call to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which already predefines this information in syscall_metadata associated enter_event (and exit_event) structures. If CONFIG_FTRACE and CONFIG_FTRACE_SYSCALLS are not compiled in, only "1" filter strings will be allowed.

The net result is a process may have its system calls filtered using the ftrace filter engine's inherent understanding of systems calls. A logical ruleset for a process that only needs stdin/stdout may be:
sys_read: fd == 0
sys_write: fd == 1 || fd == 2
sys_exit: 1

The set of filters is specified through the PR_SET_SECCOMP path in prctl(). For example:
prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 0"); prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd == 1 || fd == 2"); prctl(PR_SET_SECCOMP_FILTER, __NR_exit, "1"); prctl(PR_SET_SECCOMP, 2, 0);

v2: - changed to use the existing syscall number ABI.
- prctl changes to minimize parsing in the kernel:
prctl(PR_SET_SECCOMP, {0 | 1 | 2 }, { 0 | ON_EXEC }); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 5"); prctl(PR_CLEAR_SECCOMP_FILTER, __NR_read); prctl(PR_GET_SECCOMP_FILTER, __NR_read, buf, bufsize);
- defined PR_SECCOMP_MODE_STRICT and ..._FILTER
- added flags
- provide a default fail syscall_nr_to_meta in ftrace
- provides fallback for unhooked system calls
- use -ENOSYS and ERR_PTR(-ENOSYS) for stubbed functionality
- added kernel/seccomp.h to share seccomp.c/seccomp_filter.c
- moved to a hlist and 4 bit hash of linked lists
- added support to operate without CONFIG_FTRACE_SYSCALLS
- moved Kconfig support next to SECCOMP
(should this be done in per-platform patches?)
- made Kconfig entries dependent on EXPERIMENTAL
- added macros to avoid ifdefs from kernel/fork.c
- added compat task/filter matching
- drop seccomp.h inclusion in sched.h and drop seccomp_t
- added Filtering to "show" output
- added on_exec state dup'ing when enabling after a fast-path accept.

---
 arch/arm/Kconfig        |   10 +
 arch/microblaze/Kconfig |   10 +
 arch/mips/Kconfig       |   10 +
 arch/powerpc/Kconfig    |   10 +
 arch/s390/Kconfig       |   10 +
 arch/sh/Kconfig         |   10 +
 arch/sparc/Kconfig      |   10 +
 arch/x86/Kconfig        |   10 +
 include/linux/prctl.h   |    9 +
 include/linux/sched.h   |    5 +-
 include/linux/seccomp.h |  116 +++++++++-
 include/trace/syscall.h |    7 +
 kernel/Makefile         |    3 +
 kernel/fork.c           |    3 +
 kernel/seccomp.c        |  228 +++++++++++++++++-
 kernel/seccomp.h        |   74 ++++++
 kernel/seccomp_filter.c |  581 +++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sys.c            |   15 +-
 18 files changed, 1100 insertions(+), 21 deletions(-)
 create mode 100644 kernel/seccomp.h
 create mode 100644 kernel/seccomp_filter.c
arch/arm/Kconfig +10 -0
index 377a7a5..22e1668 100644
@@ -1664,6 +1664,16 @@ config SECCOMP
 	  and the task is only allowed to execute a few safe syscalls
 	  defined by each seccomp mode.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 config CC_STACKPROTECTOR
 	bool "Enable -fstack-protector buffer overflow detection (EXPERIMENTAL)"
 	depends on EXPERIMENTAL
arch/microblaze/Kconfig +10 -0
index eccdefe..7641ee9 100644
@@ -129,6 +129,16 @@ config SECCOMP
 
 	  If unsure, say Y. Only embedded should say N here.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 endmenu
 
 menu "Advanced setup"
arch/mips/Kconfig +10 -0
index 8e256cc..fe4cbda 100644
@@ -2245,6 +2245,16 @@ config SECCOMP
 
 	  If unsure, say Y. Only embedded should say N here.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 config USE_OF
 	bool "Flattened Device Tree support"
 	select OF
arch/powerpc/Kconfig +10 -0
index 8f4d50b..83499e4 100644
@@ -605,6 +605,16 @@ config SECCOMP
 
 	  If unsure, say Y. Only embedded should say N here.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 endmenu
 
 config ISA_DMA_API
arch/s390/Kconfig +10 -0
index 2508a6f..2777515 100644
@@ -614,6 +614,16 @@ config SECCOMP
 
 	  If unsure, say Y.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 endmenu
 
 menu "Power Management"
arch/sh/Kconfig +10 -0
index 4b89da2..00c1521 100644
@@ -676,6 +676,16 @@ config SECCOMP
 
 	  If unsure, say N.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 config SMP
 	bool "Symmetric multi-processing support"
 	depends on SYS_SUPPORTS_SMP
arch/sparc/Kconfig +10 -0
index e560d10..5b42255 100644
@@ -270,6 +270,16 @@ config SECCOMP
 
 	  If unsure, say Y. Only embedded should say N here.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 config HOTPLUG_CPU
 	bool "Support for hot-pluggable CPUs"
 	depends on SPARC64 && SMP
arch/x86/Kconfig +10 -0
index cc6c53a..d6d44d9 100644
@@ -1485,6 +1485,16 @@ config SECCOMP
 
 	  If unsure, say Y. Only embedded should say N here.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	depends on SECCOMP && EXPERIMENTAL
+	help
+	  Per-process, inherited system call filtering using shared code
+	  across seccomp and ftrace_syscalls.  If CONFIG_FTRACE_SYSCALLS
+	  is not available, enhanced filters will not be available.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 config CC_STACKPROTECTOR
 	bool "Enable -fstack-protector buffer overflow detection (EXPERIMENTAL)"
 	---help---
include/linux/prctl.h +9 -0
index a3baeb2..379b391 100644
@@ -63,6 +63,15 @@
 /* Get/set process seccomp mode */
 #define PR_GET_SECCOMP	21
 #define PR_SET_SECCOMP	22
+# define PR_SECCOMP_MODE_NONE	0
+# define PR_SECCOMP_MODE_STRICT	1
+# define PR_SECCOMP_MODE_FILTER	2
+# define PR_SECCOMP_FLAG_FILTER_ON_EXEC	(1 << 1)
+
+/* Get/set process seccomp filters */
+#define PR_GET_SECCOMP_FILTER	35
+#define PR_SET_SECCOMP_FILTER	36
+#define PR_CLEAR_SECCOMP_FILTER	37
 
 /* Get/set the capability bounding set (as per security/commoncap.c) */
 #define PR_CAPBSET_READ 23
include/linux/sched.h +3 -2
index 18d63ce..27eacf9 100644
@@ -77,7 +77,6 @@ struct sched_param {
 #include <linux/percpu.h>
 #include <linux/topology.h>
 #include <linux/proportions.h>
-#include <linux/seccomp.h>
 #include <linux/rcupdate.h>
 #include <linux/rculist.h>
 #include <linux/rtmutex.h>
@@ -1190,6 +1189,8 @@ enum perf_event_task_context {
 	perf_nr_task_contexts,
 };
 
+struct seccomp_state;
+
 struct task_struct {
 	volatile long state;	/* -1 unrunnable, 0 runnable, >0 stopped */
 	void *stack;
@@ -1374,7 +1375,7 @@ struct task_struct {
 	uid_t loginuid;
 	unsigned int sessionid;
 #endif
-	seccomp_t seccomp;
+	struct seccomp_state *seccomp;
 
 /* Thread group tracking */
    	u32 parent_exec_id;
include/linux/seccomp.h +112 -4

151 lines not on this page · raw message

include/trace/syscall.h +7 -0
index 242ae04..e061ad0 100644
@@ -35,6 +35,8 @@ struct syscall_metadata {
 extern unsigned long arch_syscall_addr(int nr);
 extern int init_syscall_trace(struct ftrace_event_call *call);
 
+extern struct syscall_metadata *syscall_nr_to_meta(int);
+
 extern int reg_event_syscall_enter(struct ftrace_event_call *call);
 extern void unreg_event_syscall_enter(struct ftrace_event_call *call);
 extern int reg_event_syscall_exit(struct ftrace_event_call *call);
@@ -49,6 +51,11 @@ enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
 				      struct trace_event *event);
 enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
 				     struct trace_event *event);
+#else
+static inline struct syscall_metadata *syscall_nr_to_meta(int nr)
+{
+	return NULL;
+}
 #endif
 
 #ifdef CONFIG_PERF_EVENTS
kernel/Makefile +3 -0
index 85cbfb3..84e7dfb 100644
@@ -81,6 +81,9 @@ obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o
 obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
 obj-$(CONFIG_GENERIC_HARDIRQS) += irq/
 obj-$(CONFIG_SECCOMP) += seccomp.o
+ifeq ($(CONFIG_SECCOMP_FILTER),y)
+obj-$(CONFIG_SECCOMP) += seccomp_filter.o
+endif
 obj-$(CONFIG_RCU_TORTURE_TEST) += rcutorture.o
 obj-$(CONFIG_TREE_RCU) += rcutree.o
 obj-$(CONFIG_TREE_PREEMPT_RCU) += rcutree.o
kernel/fork.c +3 -0
index e7548de..46987d4 100644
@@ -34,6 +34,7 @@
 #include <linux/cgroup.h>
 #include <linux/security.h>
 #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
 #include <linux/swap.h>
 #include <linux/syscalls.h>
 #include <linux/jiffies.h>
@@ -169,6 +170,7 @@ void free_task(struct task_struct *tsk)
 	free_thread_info(tsk->stack);
 	rt_mutex_debug_task_free(tsk);
 	ftrace_graph_exit_task(tsk);
+	put_tsk_seccomp_state(tsk);
 	free_task_struct(tsk);
 }
 EXPORT_SYMBOL(free_task);
@@ -280,6 +282,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
 	if (err)
 		goto out;
 
+	inherit_tsk_seccomp_state(tsk, orig);
 	setup_thread_stack(tsk, orig);
 	clear_user_return_notifier(tsk);
 	clear_tsk_need_resched(tsk);
kernel/seccomp.c +215 -13

274 lines not on this page · raw message

kernel/seccomp.h new file +74 -0

74 lines not on this page · raw message

kernel/seccomp_filter.c new file +581 -0

581 lines not on this page · raw message

kernel/sys.c +13 -2
index af468ed..d29003a 100644
@@ -1698,12 +1698,23 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 		case PR_SET_ENDIAN:
 			error = SET_ENDIAN(me, arg2);
 			break;
-
 		case PR_GET_SECCOMP:
 			error = prctl_get_seccomp();
 			break;
 		case PR_SET_SECCOMP:
-			error = prctl_set_seccomp(arg2);
+			error = prctl_set_seccomp(arg2, arg3);
+			break;
+		case PR_SET_SECCOMP_FILTER:
+			error = prctl_set_seccomp_filter(arg2,
+							 (char __user *) arg3);
+			break;
+		case PR_CLEAR_SECCOMP_FILTER:
+			error = prctl_clear_seccomp_filter(arg2);
+			break;
+		case PR_GET_SECCOMP_FILTER:
+			error = prctl_get_seccomp_filter(arg2,
+							 (char __user *) arg3,
+							 arg4);
 			break;
 		case PR_GET_TSC:
 			error = GET_TSC_CTL(arg2);
Signature · 1 line
1.7.0.4
#29 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Ok, i like the direction here, but i think the ABI should be done differently.

In this patch the ftrace event filter mechanism is used:

Quoted 30 lines · Will Drewry
kernel/seccomp_filter.c new file +30 -0
+static struct seccomp_filter *alloc_seccomp_filter(int syscall_nr,
+						   const char *filter_string)
+{
+	int err = -ENOMEM;
+	struct seccomp_filter *filter = kzalloc(sizeof(struct seccomp_filter),
+						GFP_KERNEL);
+	if (!filter)
+		goto fail;
+
+	INIT_HLIST_NODE(&filter->node);
+	filter->syscall_nr = syscall_nr;
+	filter->data = syscall_nr_to_meta(syscall_nr);
+
+	/* Treat a filter of SECCOMP_WILDCARD_FILTER as a wildcard and skip
+	 * using a predicate at all.
+	 */
+	if (!strcmp(SECCOMP_WILDCARD_FILTER, filter_string))
+		goto out;
+
+	/* Argument-based filtering only works on ftrace-hooked syscalls. */
+	if (!filter->data) {
+		err = -ENOSYS;
+		goto fail;
+	}
+
+#ifdef CONFIG_FTRACE_SYSCALLS
+	err = ftrace_parse_filter(&filter->event_filter,
+				  filter->data->enter_event->event.type,
+				  filter_string);
+	if (err)

kernel/seccomp_filter.c line 119

Quoted 10 lines
kernel/seccomp_filter.c new file +10 -0
+		goto fail;
+#endif
+
+out:
+	return filter;
+
+fail:
+	kfree(filter);
+	return ERR_PTR(err);
+}

Via a prctl() ABI:

Quoted 15 lines
kernel/sys.c +3 -2
@@ -1698,12 +1698,23 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 		case PR_SET_ENDIAN:
 			error = SET_ENDIAN(me, arg2);
 			break;
-
 		case PR_GET_SECCOMP:
 			error = prctl_get_seccomp();
 			break;
 		case PR_SET_SECCOMP:
-			error = prctl_set_seccomp(arg2);
+			error = prctl_set_seccomp(arg2, arg3);
+			break;
+		case PR_SET_SECCOMP_FILTER:

kernel/sys.c SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3, · line 1717

Quoted 10 lines
kernel/sys.c +10 -0
+			error = prctl_set_seccomp_filter(arg2,
+							 (char __user *) arg3);
+			break;
+		case PR_CLEAR_SECCOMP_FILTER:
+			error = prctl_clear_seccomp_filter(arg2);
+			break;
+		case PR_GET_SECCOMP_FILTER:
+			error = prctl_get_seccomp_filter(arg2,
+							 (char __user *) arg3,
+							 arg4);

To restrict execution to system calls.

Two observations:

1) We already have a specific ABI for this: you can set filters for events via an event fd.

Why not extend that mechanism instead and improve *both* your sandboxing bits and the events code? This new seccomp code has a lot more to do with trace event filters than the minimal old seccomp code ...

kernel/trace/trace_event_filter.c is 2000 lines of tricky code that interprets the ASCII filter expressions. kernel/seccomp.c is 86 lines of mostly trivial code.

2) Why should this concept not be made available wider, to allow the restriction of not just system calls but other security relevant components of the kernel as well?

This too, if you approach the problem via the events code, will be a natural end result, while if you approach it from the seccomp prctl angle it will be a limited hack only.

Note, the end result will be the same - just using a different ABI.

So i really think the ABI itself should be closer related to the event code. What this "seccomp" code does is that it uses specific syscall events to restrict execution of certain event generating codepaths, such as system calls.

Thanks,

Ingo

#30 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Hi,

Quoted 6 lines · Ingo Molnar

1) We already have a specific ABI for this: you can set filters for events via an event fd.

Why not extend that mechanism instead and improve *both* your sandboxing bits and the events code? This new seccomp code has a lot more to do with trace event filters than the minimal old seccomp code ...

Would this require privileges to get the event fd to start with? If so, I would prefer to avoid that, since using prctl() as shown in the patch set won't require any privs.

-Kees

Signature · 2 lines
Kees Cook
Ubuntu Security Team
#31 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 11 lines · Kees Cook

Hi,

Quoted 6 lines · Ingo Molnar

1) We already have a specific ABI for this: you can set filters for events via an event fd.

Why not extend that mechanism instead and improve *both* your sandboxing bits and the events code? This new seccomp code has a lot more to do with trace event filters than the minimal old seccomp code ...

Would this require privileges to get the event fd to start with? [...]

No special privileges with the default perf_events_paranoid value.

Quoted 2 lines

[...] If so, I would prefer to avoid that, since using prctl() as shown in the patch set won't require any privs.

and we could also explicitly allow syscall events without any privileges, regardless of the setting of 'perf_events_paranoid' config value.

Obviously a sandboxing host process wants to run with as low privileges as it can.

Thanks,

Ingo

maintainer
#32 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Ingo Molnar
Quoted 4 lines · Ingo Molnar

2) Why should this concept not be made available wider, to allow the restriction of not just system calls but other security relevant components of the kernel as well?

Because the aim of this is to reduce the attack surface of the syscall interface.

LSM is the correct level of abstraction for general security mediation, because it allows you to take into account all relevant security information in a race-free context.

Quoted 3 lines

This too, if you approach the problem via the events code, will be a natural end result, while if you approach it from the seccomp prctl angle it will be a limited hack only.

I'd say it's a well-defined and readily understandable feature.

- James

Signature · 2 lines
James Morris
<[email protected]>
#33 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 8 lines · James Morris
Quoted 3 lines · Ingo Molnar

2) Why should this concept not be made available wider, to allow the restriction of not just system calls but other security relevant components of the kernel as well?

Because the aim of this is to reduce the attack surface of the syscall interface.

What i suggest achieves the same, my argument is that we could aim it to be even more flexible and even more useful.

Quoted 3 lines

LSM is the correct level of abstraction for general security mediation, because it allows you to take into account all relevant security information in a race-free context.

I don't care about LSM though, i find it poorly designed.

The approach implemented here, the ability for *unprivileged code* to define (the seeds of ...) flexible security policies, in a proper Linuxish way, which is inherited along the task parent/child hieararchy and which allows nesting etc. is a *lot* more flexible.

What Will implemented here is pretty huge in my opinion: it turns security from a root-only kind of weird hack into an essential component of its APIs, available to *any* app not just the select security policy/mechanism chosen by the distributor ...

If implemented properly this could replace LSM in the long run.

As a prctl() hack bound to seccomp (which, by all means, is a natural extension to the current seccomp ABI, so perfectly fine if we only want that scope), that is much less likely to happen.

And if we merge the seccomp interface prematurely then interest towards a more flexible approach will disappear, so either we do it properly now or it will take some time for someone to come around and do it ...

Also note that i do not consider the perf events ABI itself cast into stone - and we could very well add a new system call for this, independent of perf events. I just think that the seccomp scope itself is exciting but looks limited to what the real potential of this could be.

Quoted 5 lines
Quoted 3 lines

This too, if you approach the problem via the events code, will be a natural end result, while if you approach it from the seccomp prctl angle it will be a limited hack only.

I'd say it's a well-defined and readily understandable feature.

Note, it was me who suggested this very event-filter-engine design a year ago, when the first submission still used a crude bitmap of allowed seccomp syscalls:

http://lwn.net/Articles/332974/

Funnily enough, back then you wrote this:

" I'm concerned that we're seeing yet another security scheme being designed on
the fly, without a well-formed threat model, and without taking into account lessons learned from the seemingly endless parade of similar, failed schemes. "

so when and how did your opinion of this scheme turn from it being an "endless parade of failed schemes" to it being a "well-defined and readily understandable feature"? :-)

The idea itself has not changed since last year, what happened is that the filter engine got a couple of new features and Will has separated it out and has implemented a working prototype for sandboxing.

What i do here is to suggest *further* steps down the same road, now that we see that this scheme can indeed be used to implement sandboxing ... I think it's a valid line of inquiry.

Thanks,

Ingo

author reviewer
#34 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

[Thanks to everyone for the continued feedback and insights - I appreciate it!]

Quoted 37 lines · Ingo Molnar
Quoted 8 lines · James Morris
Quoted 3 lines · Ingo Molnar

2) Why should this concept not be made available wider, to allow the ? ?restriction of not just system calls but other security relevant components ? ?of the kernel as well?

Because the aim of this is to reduce the attack surface of the syscall interface.

What i suggest achieves the same, my argument is that we could aim it to be even more flexible and even more useful.

Quoted 3 lines

LSM is the correct level of abstraction for general security mediation, because it allows you to take into account all relevant security information in a race-free context.

I don't care about LSM though, i find it poorly designed.

The approach implemented here, the ability for *unprivileged code* to define (the seeds of ...) flexible security policies, in a proper Linuxish way, which is inherited along the task parent/child hieararchy and which allows nesting etc. is a *lot* more flexible.

What Will implemented here is pretty huge in my opinion: it turns security from a root-only kind of weird hack into an essential component of its APIs, available to *any* app not just the select security policy/mechanism chosen by the distributor ...

If implemented properly this could replace LSM in the long run.

As a prctl() hack bound to seccomp (which, by all means, is a natural extension to the current seccomp ABI, so perfectly fine if we only want that scope), that is much less likely to happen.

Quoted 8 lines

And if we merge the seccomp interface prematurely then interest towards a more flexible approach will disappear, so either we do it properly now or it will take some time for someone to come around and do it ...

Also note that i do not consider the perf events ABI itself cast into stone - and we could very well add a new system call for this, independent of perf events. I just think that the seccomp scope itself is exciting but looks limited to what the real potential of this could be.

I agree with you on many of these points! However, I don't think that the views around LSMs, perf/ftrace infrastructure, or the current seccomp filtering implementation are necessarily in conflict. Here is my understanding of how the different worlds fit together and where I see this patchset living, along with where I could see future work going. Perhaps I'm being a trifle naive, but here goes anyway:

1. LSMs provide a global mechanism for hooking "security relevant" events at a point where all the incoming user-sourced data has been preprocessed and moved into userspace. The hooks are called every time one of those boundaries are crossed.
2. Perf and the ftrace infrastructure provide global function tracing and system call hooks with direct access to the caller's registers (and memory).
3. seccomp (as it exists today) provides a global system call entry hook point with a binary per-process decision about whether to provide "secure computing" behavior.

When I boil that down to abstractions, I see:
A. Globally scoped: LSMs, ftrace/perf
B. Locally/process scoped: seccomp

The result of that logical equivalence is that I see room for:
I. A per-process, locally scoped security event hooking interface (the proposed changes in this patchset)
II. A globally scoped security event hooking interface _prior_ to argument processing
III. A globally scoped security event hooking interface _post_ argument processing

II and III could be reduced further if I assume that ftrace/perf provides (II) and a simple intermediary layer (hook entry/exit) provides the argument processing steps that then call out a global security policy system.

The driving motivation for this patchset is kernel attack surface reduction, but that need arises because we lack a process-scoped mechanism for making security decisions -- everything is global:
creds/DAC, containers, LSM, etc. Adding ftrace filtering to agl's
original bitmask-seccomp proposal opens up the process-local security world. At present, it can limit the attack surface with simple binary filters or apply limited security policy through the use of filter strings.

Based on your mails, I see two main deficiencies in my proposed patchset:
a. Deep argument analysis: Any arguments that live in user memory needs to be copied into the kernel, then checked, and substituted for the actual system call, then have the original pointers restored (when applicable) on system call exit. There is a large overhead here and the LSM hooks provide much of this support on a global level. b. Lack of support for non-system call events.

For (a), if the long term view of ftrace/perf & LSMs is that LSM-like functionality will live on top of the ftrace/perf infrastructure, then adding support for the intermediary layer to analyze arguments will come with time. It's also likely that for process-local stuff (e.g.,) a new predicate could be added to callback to a userspace supervisor, or even a more generic ability for modules to register new predicates/functions in the filtering engine itself -- like "fd == 1 && check_path(path) == '/etc/safe.conf'" or "check_xattr(path, expected)". Of course, I'm just making stuff up right now :)

For (b), we could just add a field we don't use right now in the prctl interface:
prctl(PR_SET_SECCOMP_FILTER, int event_type, int
event_or_syscall_nr, char *filter)
[or something similar]

Then we can add process-local/scoped supported event types somewhere down the road without an ABI change.

Tying it all together, it'd look like:
* Now -- add process-scoped security support: secocmp filter with support for "future" event types
* Soon -- expand ftrace syscall hooks to hook more system calls
* Later -- expand ftrace filter language to support either deep argument analysis and/or custom registered predicates
* Later, later -- implement a LSM-like hooking layer for "interesting" event types on top of the ftrace hooks

That would yield process-scoped security controls and global security controls and the ability to continue to create new and interesting security modules.

All that said, I'm in over my head. I've focused primarily on the process-scoped security. I think James, some of the LSM authors, and out-of-tree security system maintainers would be good to help guide direction toward the security view you have in mind to ensure the flexibility desired exists. And that's even assuming this sketch is even vaguely interesting...

[snip]

Quoted 3 lines

What i do here is to suggest *further* steps down the same road, now that we see that this scheme can indeed be used to implement sandboxing ... I think it's a valid line of inquiry.

I certainly agree that it's a valid line of inquiry, but I worry about the massive scope expansion. I know it hurts my head, but I'm hoping the brain-dump above frames up how I think about this patch and your line of inquiry. ftrace hooking and the perf code certainly look a lot like LSMs if I squint hard :) But there is a substantial amount of work to merge the worlds, and (thankfully) I don't think that future directly impacts process-scoped security mechanisms even if they can interact nicely.

thanks!
will

#35 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 7 lines · Will Drewry

I agree with you on many of these points! However, I don't think that the views around LSMs, perf/ftrace infrastructure, or the current seccomp filtering implementation are necessarily in conflict. Here is my understanding of how the different worlds fit together and where I see this patchset living, along with where I could see future work going. Perhaps I'm being a trifle naive, but here goes anyway:

Quoted 8 lines

1. LSMs provide a global mechanism for hooking "security relevant" events at a point where all the incoming user-sourced data has been preprocessed and moved into userspace. The hooks are called every time one of those boundaries are crossed.

2. Perf and the ftrace infrastructure provide global function tracing and system call hooks with direct access to the caller's registers (and memory).

No, perf events are not just global but per task as well. Nor are events limited to 'tracing' (generating a flow of events into a trace buffer) - they can just be themselves as well and count and generate callbacks.

The generic NMI watchdog uses that kind of event model for example, see kernel/watchdog.c and how it makes use of struct perf_event abstractions to do per CPU events (with no buffrs), or how kernel/hw_breakpoint.c uses it for per task events and integrates it with the ptrace hw-breakpoints code.

Ideally Peter's one particular suggestion is right IMO and we'd want to be able for a perf_event to just be a list of callbacks, attached to a task and barely more than a discoverable, named notifier chain in its slimmest form.

In practice it's fatter than that right now, but we should definitely factor out that aspect of it more clearly, both code-wise and API-wise. kernel/watchdog.c and kernel/hw_breakpoint.c shows that such factoring out is possible and desirable.

Quoted 7 lines

3. seccomp (as it exists today) provides a global system call entry hook point with a binary per-process decision about whether to provide "secure computing" behavior.

When I boil that down to abstractions, I see:
A. Globally scoped: LSMs, ftrace/perf
B. Locally/process scoped: seccomp

Ok, i see where you got the idea that you needed to cut your surface of abstraction at the filter engine / syscall enumeration level - i think you were thinking of it in the ftrace model of tracepoints, not in the perf model of events.

No, events are generic and as such per task as well, not just global.

I've replied to your other mail with more specific suggestions of how we could provide your feature using abstractions that share code more widely. Talking specifics will i hope help move the discussion forward! :-)

Thanks,

Ingo

author reviewer
#36 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 15 lines · Ingo Molnar
Quoted 11 lines · Will Drewry

I agree with you on many of these points! ?However, I don't think that the views around LSMs, perf/ftrace infrastructure, or the current seccomp filtering implementation are necessarily in conflict. ?Here is my understanding of how the different worlds fit together and where I see this patchset living, along with where I could see future work going. ?Perhaps I'm being a trifle naive, but here goes anyway:

1. LSMs provide a global mechanism for hooking "security relevant" events at a point where all the incoming user-sourced data has been preprocessed and moved into userspace. ?The hooks are called every time one of those boundaries are crossed.

Quoted 7 lines
Quoted 3 lines

2. Perf and the ftrace infrastructure provide global function tracing and system call hooks with direct access to the caller's registers (and memory).

No, perf events are not just global but per task as well. Nor are events limited to 'tracing' (generating a flow of events into a trace buffer) - they can just be themselves as well and count and generate callbacks.

I was looking at the perf_sysenter_enable() call, but clearly there is more going on :)

Quoted 27 lines

The generic NMI watchdog uses that kind of event model for example, see kernel/watchdog.c and how it makes use of struct perf_event abstractions to do per CPU events (with no buffrs), or how kernel/hw_breakpoint.c uses it for per task events and integrates it with the ptrace hw-breakpoints code.

Ideally Peter's one particular suggestion is right IMO and we'd want to be able for a perf_event to just be a list of callbacks, attached to a task and barely more than a discoverable, named notifier chain in its slimmest form.

In practice it's fatter than that right now, but we should definitely factor out that aspect of it more clearly, both code-wise and API-wise. kernel/watchdog.c and kernel/hw_breakpoint.c shows that such factoring out is possible and desirable.

Quoted 7 lines

3. seccomp (as it exists today) provides a global system call entry hook point with a binary per-process decision about whether to provide "secure computing" behavior.

When I boil that down to abstractions, I see:
A. Globally scoped: LSMs, ftrace/perf
B. Locally/process scoped: seccomp

Ok, i see where you got the idea that you needed to cut your surface of abstraction at the filter engine / syscall enumeration level - i think you were thinking of it in the ftrace model of tracepoints, not in the perf model of events.

Quoted 5 lines

No, events are generic and as such per task as well, not just global.

I've replied to your other mail with more specific suggestions of how we could provide your feature using abstractions that share code more widely. Talking specifics will i hope help move the discussion forward! :-)

Agreed. I'll digest both the watchdog code as well as your other comments and follow up when I have a fuller picture in my head.

(I have a few initial comments I'll post in response to your other mail.)

Thanks!
will

maintainer
#37 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Ingo Molnar
Quoted 9 lines · Ingo Molnar

Funnily enough, back then you wrote this:

" I'm concerned that we're seeing yet another security scheme being designed on
the fly, without a well-formed threat model, and without taking into account lessons learned from the seemingly endless parade of similar, failed schemes. "

so when and how did your opinion of this scheme turn from it being an "endless parade of failed schemes" to it being a "well-defined and readily understandable feature"? :-)

When it was defined in a way which limited its purpose to reducing the attack surface of the sycall interface.

- James

Signature · 2 lines
James Morris
<[email protected]>
#38 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 7 lines · James Morris
Quoted 6 lines · Ingo Molnar

Funnily enough, back then you wrote this:

" I'm concerned that we're seeing yet another security scheme being designed on
the fly, without a well-formed threat model, and without taking into account lessons learned from the seemingly endless parade of similar, failed schemes. "

Quoted 6 lines
Quoted 3 lines

so when and how did your opinion of this scheme turn from it being an "endless parade of failed schemes" to it being a "well-defined and readily understandable feature"? :-)

When it was defined in a way which limited its purpose to reducing the attack surface of the sycall interface.

Let me outline a simple example of a new filter expression based security feature that could be implemented outside the narrow system call boundary you find acceptable, and please tell what is bad about it.

Say i'm a user-space sandbox developer who wants to enforce that sandboxed code should only be allowed to open files in /home/sandbox/, /lib/ and /usr/lib/.

It is a simple and sensible security feature, agreed? It allows most code to run well and link to countless libraries - but no access to other files is allowed.

I would also like my sandbox app to be able to install this policy without having to be root. I do not want the sandbox app to have permission to create labels on /lib and /usr/lib and what not.

Firstly, using the filter code i deny the various link creation syscalls so that sandboxed code cannot escape for example by creating a symlink to outside the permitted VFS namespace. (Note: we opt-in to syscalls, that way new syscalls added by new kernels are denied by defalt. The current symlink creation syscalls are not opted in to.)

But the next step, actually checking filenames, poses a big hurdle: i cannot implement the filename checking at the sys_open() syscall level in a secure
way: because the pathname is passed to sys_open() by pointer, and if i check it at the generic sys_open() syscall level, another thread in the sandbox might modify the underlying filename *after* i've checked it.

But if i had a VFS event at the fs/namei.c::getname() level, i would have access to a central point where the VFS string becomes stable to the kernel and can be checked (and denied if necessary).

A sidenote, and not surprisingly, the audit subsystem already has an event callback there:

        audit_getname(result);

Unfortunately this audit callback cannot be used for my purposes, because the event is single-purpose for auditd and because it allows no feedback (no deny/accept discretion for the security policy).

But if had this simple event there:

	err = event_vfs_getname(result);

I could implement this new filename based sandboxing policy, using a filter like this installed on the vfs::getname event and inherited by all sandboxed tasks (which cannot uninstall the filter, obviously):

"

	if (strstr(name, ".."))
		return -EACCESS;

	if (!strncmp(name, "/home/sandbox/", 14) &&
	    !strncmp(name, "/lib/", 5) &&
	    !strncmp(name, "/usr/lib/", 9))
		return -EACCESS;

"

#
# Note1: Obviously the filter engine would be extended to allow such simple string
# match functions. )
#
# Note2: ".." is disallowed so that sandboxed code cannot escape the restrictions
# using "/..".
#

This kind of flexible and dynamic sandboxing would allow a wide range of file ops within the sandbox, while still isolating it from files not included in the specified VFS namespace.

( Note that there are tons of other examples as well, for useful security features
that are best done using events outside the syscall boundary. )

The security event filters code tied to seccomp and syscalls at the moment is useful, but limited in its future potential.

So i argue that it should go slightly further and should become:

- unprivileged: application-definable, allowing the embedding of security policy in *apps* as well, not just the system

- flexible: can be added/removed runtime unprivileged, and cheaply so

- transparent: does not impact executing code that meets the policy

- nestable: it is inherited by child tasks and is fundamentally stackable,
multiple policies will have the combined effect and they are transparent to each other. So if a child task within a sandbox adds *more* checks then those add to the already existing set of checks. We only narrow permissions, never extend them.

- generic: allowing observation and (safe) control of security relevant
parameters not just at the system call boundary but at other relevant places of kernel execution as well: which points/callbacks could also be used for other types of event extraction such as perf. It could even be shared with audit ...

I argue that this is the LSM and audit subsystems designed right: in the long run it could allow everything that LSM does at the moment - and so much more
...

And you argue that allowing this would be bad, if it was extended like that then you'd consider it a failed scheme? Why?

Thanks,

Ingo

maintainer
#39 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 1 line · Ingo Molnar
        err = event_vfs_getname(result);

I really think we should not do this. Events like we have them should be inactive, totally passive entities, only observe but not affect execution (other than the bare minimal time delay introduced by observance).

If you want another entity that is more active, please invent a new name for it and create a new subsystem for them, now you could have these active entities also have an (automatic) passive event side, but that's some detail.

#40 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 6 lines · Peter Zijlstra
Quoted 1 line · Ingo Molnar
        err = event_vfs_getname(result);

I really think we should not do this. Events like we have them should be inactive, totally passive entities, only observe but not affect execution (other than the bare minimal time delay introduced by observance).

Well, this patchset already demonstrates that we can use a single event callback for a rather useful purpose.

Either it makes sense to do, in which case we should share facilities as much as possible, or it makes no sense, in which case we should not merge it at all.

Quoted 3 lines

If you want another entity that is more active, please invent a new name for it and create a new subsystem for them, now you could have these active entities also have an (automatic) passive event side, but that's some detail.

Why should we have two callbacks next to each other:

	event_vfs_getname(result);
	result = check_event_vfs_getname(result);

if one could do it all?

Thanks,

Ingo

maintainer
#41 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 11 lines · Ingo Molnar
Quoted 6 lines · Peter Zijlstra
Quoted 1 line · Ingo Molnar
        err = event_vfs_getname(result);

I really think we should not do this. Events like we have them should be inactive, totally passive entities, only observe but not affect execution (other than the bare minimal time delay introduced by observance).

Well, this patchset already demonstrates that we can use a single event callback for a rather useful purpose.

Can and should are two distinct things.

Quoted 2 lines

Either it makes sense to do, in which case we should share facilities as much as possible, or it makes no sense, in which case we should not merge it at all.

And I'm arguing we should _not_. Observing is radically different from Affecting, at the very least the two things should have different permission schemes. We should not confuse these two matters.

Quoted 10 lines
Quoted 3 lines

If you want another entity that is more active, please invent a new name for it and create a new subsystem for them, now you could have these active entities also have an (automatic) passive event side, but that's some detail.

Why should we have two callbacks next to each other:

	event_vfs_getname(result);
	result = check_event_vfs_getname(result);

if one could do it all?

Did you actually read the bit where I said that check_event_* (although I still think that name sucks) could imply a matching event_*?

maintainer
#42 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 3 lines · Peter Zijlstra
Quoted 3 lines
      event_vfs_getname(result);
      result = check_event_vfs_getname(result); 

Another fundamental difference is how to treat the callback chains for these two.

Observers won't have a return value and are assumed to never fail, therefore we can always call every entry on the callback list.

Active things otoh do have a return value, and thus we need to have semantics that define what to do with that during callback iteration, when to continue and when to break. Thus for active elements its impossible to guarantee all entries will indeed be called.

#43 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 8 lines · Peter Zijlstra
Quoted 3 lines · Peter Zijlstra
Quoted 3 lines
      event_vfs_getname(result);
      result = check_event_vfs_getname(result); 

Another fundamental difference is how to treat the callback chains for these two.

Quoted 7 lines

Observers won't have a return value and are assumed to never fail, therefore we can always call every entry on the callback list.

Active things otoh do have a return value, and thus we need to have semantics that define what to do with that during callback iteration, when to continue and when to break. Thus for active elements its impossible to guarantee all entries will indeed be called.

I think the sanest semantics is to run all active callbacks as well.

For example if this is used for three stacked security policies - as if 3 LSM modules were stacked at once. We'd call all three, and we'd determine that at least one failed - and we'd return a failure.

Even if the first one failed already we'd still want to trigger *all* the failures, because security policies like to know when they have triggered a failure (regardless of other active policies) and want to see that failure event (if they are logging such events).

So to me this looks pretty similar to observer callbacks as well, it's the natural extension to an observer callback chain.

Observer callbacks are simply constant functions (to the caller), those which never return failure and which never modify any of the parameters.

It's as if you argued that there should be separate syscalls/facilities for handling readonly files versus handling read/write files.

Thanks,

Ingo

maintainer
#44 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 5 lines · Ingo Molnar

I think the sanest semantics is to run all active callbacks as well.

For example if this is used for three stacked security policies - as if 3 LSM modules were stacked at once. We'd call all three, and we'd determine that at least one failed - and we'd return a failure.

But that only works for boolean functions where you can return the multi-bit-or of the result. What if you need to return the specific error code.

Also, there's bound to be other cases where people will want to employ this, look at all the various notifier chain muck we've got, it already deals with much of this -- simply because users need it.

Then there's the whole indirection argument, if you don't need indirection, its often better to not use it, I myself much prefer code to look like:

   foo1(bar);
   foo2(bar);
   foo3(bar);

Than:

   foo_notifier(bar);

Simply because its much clearer who all are involved without me having to grep around to see who registers for foo_notifier and wth they do with it. It also makes it much harder to sneak in another user, whereas its nearly impossible to find new notifier users.

Its also much faster, no extra memory accesses, no indirect function calls, no other muck.

#45 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 10 lines · Peter Zijlstra
Quoted 5 lines · Ingo Molnar

I think the sanest semantics is to run all active callbacks as well.

For example if this is used for three stacked security policies - as if 3 LSM modules were stacked at once. We'd call all three, and we'd determine that at least one failed - and we'd return a failure.

But that only works for boolean functions where you can return the multi-bit-or of the result. What if you need to return the specific error code.

Do you mean that one filter returns -EINVAL while the other -EACCES?

Seems like a non-problem to me, we'd return the first nonzero value.

Quoted 3 lines

Also, there's bound to be other cases where people will want to employ this, look at all the various notifier chain muck we've got, it already deals with much of this -- simply because users need it.

Do you mean it would be easy to abuse it? What kind of abuse are you most worried about?

Quoted 12 lines

Then there's the whole indirection argument, if you don't need indirection, its often better to not use it, I myself much prefer code to look like:

   foo1(bar);
   foo2(bar);
   foo3(bar);

Than:

   foo_notifier(bar);
Quoted 7 lines

Simply because its much clearer who all are involved without me having to grep around to see who registers for foo_notifier and wth they do with it. It also makes it much harder to sneak in another user, whereas its nearly impossible to find new notifier users.

Its also much faster, no extra memory accesses, no indirect function calls, no other muck.

But i suspect this question has been settled, given the fact that even pure observer events need and already process a chain of events? Am i missing something about your argument?

Thanks,

Ingo

maintainer
#46 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Cut the microblaze list since its bouncy.

Quoted 9 lines · Ingo Molnar
Quoted 7 lines · Peter Zijlstra
Quoted 5 lines · Ingo Molnar

I think the sanest semantics is to run all active callbacks as well.

For example if this is used for three stacked security policies - as if 3 LSM modules were stacked at once. We'd call all three, and we'd determine that at least one failed - and we'd return a failure.

Quoted 7 lines
Quoted 3 lines

But that only works for boolean functions where you can return the multi-bit-or of the result. What if you need to return the specific error code.

Do you mean that one filter returns -EINVAL while the other -EACCES?

Seems like a non-problem to me, we'd return the first nonzero value.

Assuming the first is -EINVAL, what then is the value in computing the -EACCESS? Sounds like a massive waste of time to me.

Quoted 6 lines
Quoted 3 lines

Also, there's bound to be other cases where people will want to employ this, look at all the various notifier chain muck we've got, it already deals with much of this -- simply because users need it.

Do you mean it would be easy to abuse it? What kind of abuse are you most worried about?

I'm not worried about abuse, I'm saying that going by the existing notifier pattern always visiting all entries on the callback list is undesired.

Quoted 17 lines
Quoted 17 lines

Then there's the whole indirection argument, if you don't need indirection, its often better to not use it, I myself much prefer code to look like:

   foo1(bar);
   foo2(bar);
   foo3(bar);

Than:

   foo_notifier(bar);

Simply because its much clearer who all are involved without me having to grep around to see who registers for foo_notifier and wth they do with it. It also makes it much harder to sneak in another user, whereas its nearly impossible to find new notifier users.

Quoted 6 lines
Quoted 2 lines

Its also much faster, no extra memory accesses, no indirect function calls, no other muck.

But i suspect this question has been settled, given the fact that even pure observer events need and already process a chain of events? Am i missing something about your argument?

I'm saying that there's reasons to not use notifiers passive or active.

Mostly the whole notifier/indirection muck comes up once you want modules to make use of the thing, because then you need dynamic management of the callback list.

(Then again, I'm fairly glad we don't have explicit callbacks in kernel/cpu.c for all the cpu-hotplug callbacks :-)

Anyway, I oppose for the existing events to gain an active role.

#47 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 16 lines · Peter Zijlstra

Cut the microblaze list since its bouncy.

Quoted 13 lines · Ingo Molnar
Quoted 10 lines · Peter Zijlstra
Quoted 5 lines · Ingo Molnar

I think the sanest semantics is to run all active callbacks as well.

For example if this is used for three stacked security policies - as if 3 LSM modules were stacked at once. We'd call all three, and we'd determine that at least one failed - and we'd return a failure.

But that only works for boolean functions where you can return the multi-bit-or of the result. What if you need to return the specific error code.

Quoted 6 lines
Quoted 3 lines

Do you mean that one filter returns -EINVAL while the other -EACCES?

Seems like a non-problem to me, we'd return the first nonzero value.

Assuming the first is -EINVAL, what then is the value in computing the -EACCESS? Sounds like a massive waste of time to me.

No, because the common case is no rejection - this is a security mechanism. So in the normal case we would execute all 3 anyway, just to determine that all return 0.

Are you really worried about the abnormal case of one of them returning an error and us calculating all 3 return values?

Quoted 10 lines
Quoted 6 lines
Quoted 3 lines

Also, there's bound to be other cases where people will want to employ this, look at all the various notifier chain muck we've got, it already deals with much of this -- simply because users need it.

Do you mean it would be easy to abuse it? What kind of abuse are you most worried about?

I'm not worried about abuse, I'm saying that going by the existing notifier pattern always visiting all entries on the callback list is undesired.

That is because many notifier chains are used in an 'event consuming' manner - they are responding to things like hardware events and are called in an interrupt-handler alike fashion most of the time.

Quoted 24 lines
Quoted 17 lines
Quoted 17 lines

Then there's the whole indirection argument, if you don't need indirection, its often better to not use it, I myself much prefer code to look like:

   foo1(bar);
   foo2(bar);
   foo3(bar);

Than:

   foo_notifier(bar);

Simply because its much clearer who all are involved without me having to grep around to see who registers for foo_notifier and wth they do with it. It also makes it much harder to sneak in another user, whereas its nearly impossible to find new notifier users.

Quoted 6 lines
Quoted 2 lines

Its also much faster, no extra memory accesses, no indirect function calls, no other muck.

But i suspect this question has been settled, given the fact that even pure observer events need and already process a chain of events? Am i missing something about your argument?

Quoted 5 lines

I'm saying that there's reasons to not use notifiers passive or active.

Mostly the whole notifier/indirection muck comes up once you want modules to make use of the thing, because then you need dynamic management of the callback list.

But your argument assumes that we'd have a chain of functions to call, like regular notifiers.

While the natural model here would be to have a list of registered event structs for that point, with different filters but basically the same callback mechanism (a call into the filter engine in essence).

Also note that the common case would be no event registered - and we'd automatically optimize that case via the existing jump labels optimization.

Quoted 4 lines

(Then again, I'm fairly glad we don't have explicit callbacks in kernel/cpu.c for all the cpu-hotplug callbacks :-)

Anyway, I oppose for the existing events to gain an active role.

Why if 'being active' is optional and useful?

Thanks,

Ingo

maintainer
#48 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 1 line · Ingo Molnar

this is a security mechanism

Who says? and why would you want to unify two separate concepts only to them limit it to security that just doesn't make sense.

Either you provide a full on replacement for notifier chain like things or you don't, only extending trace events in this fashion for security is like way weird.

Plus see the arguments Eric made about stacking stuff, not only security schemes will have those problems.

#49 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 4 lines · Peter Zijlstra
Quoted 1 line · Ingo Molnar

this is a security mechanism

Who says? [...]

Kernel developers/maintainers of the affected code.

We have security hooks all around the kernel, which can deny/accept execution at various key points, but we do not have 'execute arbitrary user-space defined (safe) scripts' callbacks in general.

But yes, if a particular callback point is defined widely enough to allow much bigger intervention into the flow of execution, then more is possible as well.

Quoted 2 lines

[...] and why would you want to unify two separate concepts only to them limit it to security that just doesn't make sense.

I don't limit them to security - the callbacks themselves are either for passive observation or, at most, for security accept/deny callbacks.

It's decided by the subsystem maintainers what kind of user-space control power (or observation power) they want to allow, not me.

I would just like to not stop the facility itself at the 'observe only' level, like you suggest.

Thanks,

Ingo

maintainer
#50 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Ingo Molnar
Quoted 33 lines · Ingo Molnar
Quoted 24 lines
Quoted 17 lines
Quoted 17 lines

Then there's the whole indirection argument, if you don't need indirection, its often better to not use it, I myself much prefer code to look like:

   foo1(bar);
   foo2(bar);
   foo3(bar);

Than:

   foo_notifier(bar);

Simply because its much clearer who all are involved without me having to grep around to see who registers for foo_notifier and wth they do with it. It also makes it much harder to sneak in another user, whereas its nearly impossible to find new notifier users.

Quoted 6 lines
Quoted 2 lines

Its also much faster, no extra memory accesses, no indirect function calls, no other muck.

But i suspect this question has been settled, given the fact that even pure observer events need and already process a chain of events? Am i missing something about your argument?

Quoted 5 lines

I'm saying that there's reasons to not use notifiers passive or active.

Mostly the whole notifier/indirection muck comes up once you want modules to make use of the thing, because then you need dynamic management of the callback list.

But your argument assumes that we'd have a chain of functions to call, like regular notifiers.

Quoted 6 lines

While the natural model here would be to have a list of registered event structs for that point, with different filters but basically the same callback mechanism (a call into the filter engine in essence).

Also note that the common case would be no event registered - and we'd automatically optimize that case via the existing jump labels optimization.

I agree that I prefer the "notifier" type over having direct function calls. Yes, it's easier to read and figure out what functions are called, but notifiers can be optimized for the default case where nothing is called (jump-label nop).

Quoted 7 lines
Quoted 5 lines

(Then again, I'm fairly glad we don't have explicit callbacks in kernel/cpu.c for all the cpu-hotplug callbacks :-)

Anyway, I oppose for the existing events to gain an active role.

Why if 'being active' is optional and useful?

I'm a bit nervous about the 'active' role of (trace_)events, because of the way multiple callbacks can be registered. How would:

	err = event_x();
	if (err == -EACCESS) {

be handled? Would we need a way to prioritize which call back gets the return value? One way I guess would be to add a check_event option, where you pass in an ENUM of the event you want:

	event_x();
	err = check_event_x(MYEVENT);

If something registered itself as "MYEVENT" to event_x, then you get the return code of MYEVENT. If the MYEVENT was not registered, a -ENODEV or something could be returned. I'm sure we could even optimize it such a way if no active events have been registered to event_x, that check_event_x() will return -ENODEV without any branches.

-- Steve

#51 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 7 lines · Steven Rostedt

I'm a bit nervous about the 'active' role of (trace_)events, because of the way multiple callbacks can be registered. How would:

	err = event_x();
	if (err == -EACCESS) {

be handled? [...]

The default behavior would be something obvious: to trigger all callbacks and use the first non-zero return value.

Quoted 4 lines

[...] Would we need a way to prioritize which call back gets the return value? One way I guess would be to add a check_event option, where you pass in an ENUM of the event you want:

Quoted 8 lines
	event_x();
	err = check_event_x(MYEVENT);

If something registered itself as "MYEVENT" to event_x, then you get the return code of MYEVENT. If the MYEVENT was not registered, a -ENODEV or something could be returned. I'm sure we could even optimize it such a way if no active events have been registered to event_x, that check_event_x() will return -ENODEV without any branches.

I would keep it simple and extensible - that way we can complicate it when the need arises! :)

Thanks,

Ingo

maintainer
#52 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 5 lines · Ingo Molnar
Quoted 3 lines · Steven Rostedt

I'm a bit nervous about the 'active' role of (trace_)events, because of the way multiple callbacks can be registered. How would:

Quoted 7 lines
Quoted 4 lines
	err = event_x();
	if (err == -EACCESS) {

be handled? [...]

The default behavior would be something obvious: to trigger all callbacks and use the first non-zero return value.

But how do we know which callback that was from? There's no ordering of what callbacks are called first.

Quoted 8 lines
Quoted 8 lines

[...] Would we need a way to prioritize which call back gets the return value? One way I guess would be to add a check_event option, where you pass in an ENUM of the event you want:

	event_x();
	err = check_event_x(MYEVENT);
Quoted 8 lines
Quoted 5 lines

If something registered itself as "MYEVENT" to event_x, then you get the return code of MYEVENT. If the MYEVENT was not registered, a -ENODEV or something could be returned. I'm sure we could even optimize it such a way if no active events have been registered to event_x, that check_event_x() will return -ENODEV without any branches.

I would keep it simple and extensible - that way we can complicate it when the need arises! :)

The above is rather trivial to implement. I don't think it complicates anything.

-- Steve

#53 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 9 lines · Steven Rostedt
Quoted 8 lines · Ingo Molnar
Quoted 6 lines · Steven Rostedt

I'm a bit nervous about the 'active' role of (trace_)events, because of the way multiple callbacks can be registered. How would:

	err = event_x();
	if (err == -EACCESS) {
Quoted 7 lines
Quoted 4 lines
Quoted 1 line

be handled? [...]

The default behavior would be something obvious: to trigger all callbacks and use the first non-zero return value.

But how do we know which callback that was from? There's no ordering of what callbacks are called first.

We do not have to know that - nor do the calling sites care in general. Do you have some specific usecase in mind where the identity of the callback that generates a match matters?

Thanks,

Ingo

maintainer
#54 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 16 lines · Ingo Molnar
Quoted 14 lines · Steven Rostedt
Quoted 12 lines · Ingo Molnar
Quoted 7 lines · Steven Rostedt

I'm a bit nervous about the 'active' role of (trace_)events, because of the way multiple callbacks can be registered. How would:

	err = event_x();
	if (err == -EACCESS) {

be handled? [...]

The default behavior would be something obvious: to trigger all callbacks and use the first non-zero return value.

Quoted 6 lines
Quoted 2 lines

But how do we know which callback that was from? There's no ordering of what callbacks are called first.

We do not have to know that - nor do the calling sites care in general. Do you have some specific usecase in mind where the identity of the callback that generates a match matters?

Maybe I'm confused. I was thinking that these event_*() are what we currently call trace_*(), but the event_*(), I assume, can return a value if a call back returns one.

Thus, we now have the ability to dynamically attach function calls to arbitrary points in the kernel that can have an affect on the code that called it. Right now, we only have the ability to attach function calls to these locations that have passive affects (tracing/profiling).

But you say, "nor do the calling sites care in general". Then what do these calling sites do with the return code? Are we limiting these actions to security only? Or can we have some other feature. I can envision that we can make the Linux kernel quite dynamic here with "self modifying code". That is, anywhere we have "hooks", perhaps we could replace them with dynamic switches (jump labels). Maybe events would not be the best use, but they could be a generic one.

Knowing what callback returned the result would be beneficial. Right now, you are saying if the call back return anything, just abort the call, not knowing what callback was called.

-- Steve

#55 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 20 lines · Steven Rostedt
Quoted 19 lines · Ingo Molnar
Quoted 16 lines · Steven Rostedt
Quoted 5 lines · Ingo Molnar
Quoted 3 lines · Steven Rostedt

I'm a bit nervous about the 'active' role of (trace_)events, because of the way multiple callbacks can be registered. How would:

Quoted 7 lines
Quoted 4 lines
	err = event_x();
	if (err == -EACCESS) {

be handled? [...]

The default behavior would be something obvious: to trigger all callbacks and use the first non-zero return value.

But how do we know which callback that was from? There's no ordering of what callbacks are called first.

Quoted 7 lines
Quoted 3 lines

We do not have to know that - nor do the calling sites care in general. Do you have some specific usecase in mind where the identity of the callback that generates a match matters?

Maybe I'm confused. I was thinking that these event_*() are what we currently call trace_*(), but the event_*(), I assume, can return a value if a call back returns one.

Yeah - and the call site can treat it as:

- Ugh, if i get an error i need to abort whatever i was about to do

or (more advanced future use):

- If i get a positive value i need to re-evaluate the parameters that were passed in, they were changed

Quoted 4 lines

Thus, we now have the ability to dynamically attach function calls to arbitrary points in the kernel that can have an affect on the code that called it. Right now, we only have the ability to attach function calls to these locations that have passive affects (tracing/profiling).

Well, they can only have the effect that the calling site accepts and handles. So the 'effect' is not arbitrary and not defined by the callbacks, it is controlled and handled by the calling code.

We do not want invisible side-effects, opaque hooks, etc.

Instead of that we want (this is the getname() example i cited in the thread) explicit effects, like:

if (event_vfs_getname(result))

	return ERR_PTR(-EPERM);
Quoted 3 lines

But you say, "nor do the calling sites care in general". Then what do these calling sites do with the return code? Are we limiting these actions to security only? Or can we have some other feature. [...]

Yeah, not just security. One other example that came up recently is whether to panic the box on certain (bad) events such as NMI errors. This too could be made flexible via the event filter code: we already capture many events, so places that might conceivably do some policy could do so based on a filter condition.

Quoted 4 lines

[...] I can envision that we can make the Linux kernel quite dynamic here with "self modifying code". That is, anywhere we have "hooks", perhaps we could replace them with dynamic switches (jump labels). Maybe events would not be the best use, but they could be a generic one.

events and explicit function calls and explicit side-effects are pretty much the only thing that are acceptable. We do not want opaque hooks and arbitrary side-effects.

Quoted 3 lines

Knowing what callback returned the result would be beneficial. Right now, you are saying if the call back return anything, just abort the call, not knowing what callback was called.

Yeah, and that's a feature: that way a number of conditions can be attached. Multiple security frameworks may have effect on a task or multiple tools might set policy action on a given event.

Thanks,

Ingo

author reviewer
#56 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 31 lines · Ingo Molnar
Quoted 20 lines · Steven Rostedt
Quoted 19 lines · Ingo Molnar
Quoted 16 lines · Steven Rostedt
Quoted 5 lines · Ingo Molnar
Quoted 3 lines · Steven Rostedt

I'm a bit nervous about the 'active' role of (trace_)events, because of the way multiple callbacks can be registered. How would:

Quoted 7 lines
Quoted 4 lines

? ? ? err = event_x();
? ? ? if (err == -EACCESS) {

be handled? [...]

The default behavior would be something obvious: to trigger all callbacks and use the first non-zero return value.

But how do we know which callback that was from? There's no ordering of what callbacks are called first.

Quoted 7 lines
Quoted 3 lines

We do not have to know that - nor do the calling sites care in general. Do you have some specific usecase in mind where the identity of the callback that generates a match matters?

Maybe I'm confused. I was thinking that these event_*() are what we currently call trace_*(), but the event_*(), I assume, can return a value if a call back returns one.

Quoted 8 lines

Yeah - and the call site can treat it as:

?- Ugh, if i get an error i need to abort whatever i was about to do

or (more advanced future use):

?- If i get a positive value i need to re-evaluate the parameters that were ? passed in, they were changed

Do event_* that return non-void exist in the tree at all now? I've looked at the various tracepoint macros as well as some of the other handlers (trace_function, perf_tp_event, etc) and I'm not seeing any places where a return value is honored nor could be. At best, the perf_tp_event can be short-circuited it in the hlist_for_each, but it'd still need a way to bubble up a failure and result in not calling the trace/event that the hook precedes.

Am I missing something really obvious? I don't feel I've gotten a good handle on exactly how all the tracing code gets triggered, so perhaps I'm still a level (or three) too shallow. (I can see the asm hooks for trace functions and I can see where that translates to registered calls - like trace_function - but I don't see how the hooked calls can be trivially aborted).

As is, I'm not sure how the perf and ftrace infrastructure could be reused cleanly without a fair number of hacks to the interface and a good bit of reworking. I can already see a number of challenges around reusing the sys_perf_event_open interface and the fact that reimplementing something even as simple as seccomp mode=1 seems to require a fair amount of tweaking to avoid from being leaky. (E.g., enabling all TRACE_EVENT()s for syscalls will miss unhooked syscalls so either acceptance matching needs to be propagated up the stack along with some seccomp-like task modality or seccomp-on-perf would have to depend on sys_enter events with syscall number predicate matching and fail when a filter discard applies to all active events.)

At present, I'm leaning back towards the v2 series (plus the requested minor changes) for the benefit of code clarity and its fail-secure behavior. Even just considering the reduced case of seccomp mode 1 being implemented on the shared infrastructure, I feel like I missing something that makes it viable. Any clues?

If not, I don't think a seccomp mode 2 interface via prctl would be intractable if the long term movement is to a ftrace/perf backend - it just means that the in-kernel code would change to wrap whatever the final design ended up being.

Thanks and sorry if I'm being dense!

Quoted 21 lines
Quoted 4 lines

Thus, we now have the ability to dynamically attach function calls to arbitrary points in the kernel that can have an affect on the code that called it. Right now, we only have the ability to attach function calls to these locations that have passive affects (tracing/profiling).

Well, they can only have the effect that the calling site accepts and handles. So the 'effect' is not arbitrary and not defined by the callbacks, it is controlled and handled by the calling code.

We do not want invisible side-effects, opaque hooks, etc.

Instead of that we want (this is the getname() example i cited in the thread) explicit effects, like:

?if (event_vfs_getname(result))
? ? ? ?return ERR_PTR(-EPERM);

Quoted 3 lines

But you say, "nor do the calling sites care in general". Then what do these calling sites do with the return code? Are we limiting these actions to security only? Or can we have some other feature. [...]

Quoted 5 lines

Yeah, not just security. One other example that came up recently is whether to panic the box on certain (bad) events such as NMI errors. This too could be made flexible via the event filter code: we already capture many events, so places that might conceivably do some policy could do so based on a filter condition.

This sounds great - I just wish I could figure out how it'd work :)

Quoted 21 lines
Quoted 4 lines

[...] I can envision that we can make the Linux kernel quite dynamic here with "self modifying code". That is, anywhere we have "hooks", perhaps we could replace them with dynamic switches (jump labels). Maybe events would not be the best use, but they could be a generic one.

events and explicit function calls and explicit side-effects are pretty much the only thing that are acceptable. We do not want opaque hooks and arbitrary side-effects.

Quoted 3 lines

Knowing what callback returned the result would be beneficial. Right now, you are saying if the call back return anything, just abort the call, not knowing what callback was called.

Yeah, and that's a feature: that way a number of conditions can be attached. Multiple security frameworks may have effect on a task or multiple tools might set policy action on a given event.

Thanks,

? ? ? ?Ingo

maintainer
#57 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 7 lines · Will Drewry

Do event_* that return non-void exist in the tree at all now? I've looked at the various tracepoint macros as well as some of the other handlers (trace_function, perf_tp_event, etc) and I'm not seeing any places where a return value is honored nor could be. At best, the perf_tp_event can be short-circuited it in the hlist_for_each, but it'd still need a way to bubble up a failure and result in not calling the trace/event that the hook precedes.

No, none of the current trace hooks have return values. That was what I was talking about how to implement in my previous emails.

-- Steve

author reviewer
#58 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 10 lines · Steven Rostedt
Quoted 7 lines · Will Drewry

Do event_* that return non-void exist in the tree at all now? ?I've looked at the various tracepoint macros as well as some of the other handlers (trace_function, perf_tp_event, etc) and I'm not seeing any places where a return value is honored nor could be. ?At best, the perf_tp_event can be short-circuited it in the hlist_for_each, but it'd still need a way to bubble up a failure and result in not calling the trace/event that the hook precedes.

Quoted 2 lines

No, none of the current trace hooks have return values. That was what I was talking about how to implement in my previous emails.

Led on by complete ignorance, I think I'm finally beginning to untwist the different pieces of the tracing infrastructure. Unfortunately, that means I took a few wrong turns along the way...

I think function tracing looks something like this:

ftrace_call has been injected into at a specific callsite. Upon hit:
1. ftrace_call triggers
2. does some checks then calls ftrace_trace_function (via mcount instrs)
3. ftrace_trace_function may be a single func or a list. For a list it will be: ftrace_list_func
4. ftrace_list_func calls each registered hook for that function in a while loop ignoring return values
5. registered hook funcs may then track the call, farm it out to specific sub-handlers, etc.

This seems to be a red herring for my use case :/ though this helped me understand your back and forth (Ingo & Steve) regarding dynamic versus explicit events.

System call tracing is done via kernel/tracepoint.c events fed in via arch/[arch]/kernel/ptrace.c where it calls trace_sys_enter. This yields direct sys_enter and sys_exit event sources (and an event class to hook up per-system call events). This means that ftrace_syscall_enter() does the event prep prior to doing a filter check comparing the ftrace_event object for the given syscall_nr to the event data. perf_sysenter_enter() is similar but it pushes the info over to perf_tp_event to be matched not against the global syscall event entry, but against any sub-event in the linked list on that syscall's event.

Is that roughly an accurate representation of the two? I wish I hadn't gotten distracted along the function path, but at least I learned something (and it is relevant to the larger scope of this thread's discussion).

After doing that digging, it looks like providing hook call pre-emption and return value propagation will be a unique and fun task for each tracer and event subsystem. If I look solely at tracepoints, a generic change would be to make the trace_##subsys function return an int (which I think was the event_vfs_getname proposal?). The other option is to change the trace_sys_enter proto to include a 'int *retcode'.

That change would allow the propagation of some sort of policy information. To put it to use, seccomp mode 1 could be implemented on top of trace_syscalls. The following changes would need to happen:
1. dummy metadata should be inserted for all unhooked system calls
2. perf_trace_buf_submit would need to return an int or a new TRACE_REG_SECCOMP_REGISTER handler would need to be setup in syscall_enter_register.
3. If perf is abused, a "kill/fail_on_discard" bit would be added to event->attrs.
4. perf_trace_buf_submit/perf_tp_event will return 0 for no matches, 'n' for the number of event matches, and -EACCES/? if a 'fail_on_discard' event is seen.
5. perf_syscall_enter would set *retcode = perf_trace_buf_submit()'s retcode
6. trace_sys_enter() would need to be moved to be the first entry arch/../kernel/ptrace.c for incoming syscalls
7. if trace_sys_enter() yields a negative return code, then do_exit(SIGKILL) the process and return.

Entering into seccomp mode 1 would require adding a "0" filter for every system call number (which is why we need a dummy event call for them since failing to check the bitmask can't be flagged fail_on_discard) with the fail_on_discard bit. For the three calls that are allowed, a '1' filter would be set.

That would roughly implement seccomp mode 1. It's pretty ugly and the fact that every system call that's disallowed has to be blacklisted is not ideal. An alternate model would be to just use the seccomp mode as we do today and let secure_computing() handle the return code of "# of matches". If it the # of matches is 0, it terminates. A 'fail_on_discard' bit then would only be good to stop further tracepoint callback evaluation. This approach would also *almost* nix the need to provide dummy syscall hooks. (Since sigreturn isn't hooked on x86 because it uses ptregs fixup, a dummy would still be needed to apply a "1" filter to.)

Even with that tweak to move to a whitelist model, the perf event evaluation and tracepoint callback ordering is still not guaranteed. Without changing tracepoint itself, all other TPs will still execute. And for perf events, it'll be first-come-first-serve until a fail_on_discard is hit.

After using seccomp mode=1 as the sample case to reduce scope, it's possible to ignore it for now :) and look at the seccomp-filter/mode=2 case. The same mechanism could be used to inject more expressive filters. This would be done over the sys_perf_event_open() interface assuming the new attr is added to stop perf event list enumeration. Assuming a whitelist model, a call to prctl(PR_SET_SECCOMP, 2) would be needed (maybe with the ON_EXEC flag option too to mirror the event->attr on-exec bit). That would yield the ability to register perf events for system calls then use ioctl() to SET_FILTER on them.

Reducing the privileges of the filters after installation could be done with another attribute bit like 'set_filter_ands'. If that is also set on the event, and a filter is installed to ensure that sys_perf_event_open is blocked, then it should be reasonably sane.

I'd need to add a PERF_EVENT_IOC_GET_FILTER handler to allow extracting the settings.

Clearly, I haven't written the code for that yet, though making the change for a single platform shouldn't be too much code.

So that leaves me with some questions:
- Is this the type of reuse that was being encouraged?
- Does it really make sense to cram this through the perf interface and events? While the changed attributes are innocuous and potentially reusable, it seems that a large amount of the perf facilities are exposed that could have weird side effects, but I'm sure I still don't fully grok the perf infrastructure.
- Does extending one tracepoint to provide return values via a pointer make sense? I'd hesitate to make all tracepoint hooks return an int by default.
- If all tracepoints returned an int, what would the standard value look like - or would it need to be per tracepoint impl?
- How is ambiguity resolved if multiple perf_events are registered for a syscall with different filters? Maybe a 'stop_on_match'? though ordering is still a problem then.
- Is there a way to affect a task-wide change without a seccomp flag (or new task_struct entry) via the existing sys_perf_event_open syscall? I considered suggesting a attr bit call 'secure_computing' that when an event with the bit is enabled, it automagically forces the task into seccomp enforcement mode, but that, again, seemed hackish.

While I like the idea of sharing the tracepoints infrastructure and the trace_syscalls hooks as well as using a pre-existing interface with very minor changes, I'm worried that the complexity of the interface and of the infrastructure might undermine the ability to continue meeting the desired security goals. I had originally stayed very close to the seccomp world because of how trivial it is to review the code and verify its accuracy/effectiveness. This approach leaves a lot of gaps for kernel code to seep through and a fair amount of ambiguity in what locked down syscall filters might look like.

To me, the best part of the above is that it shows that even if we go with a prctl SET_SECCOMP_FILTER-style interface, it is completely certain that if a perf/ftrace-based security infrastructure is on our future, it will be entirely compatible -- even if the prctl() interface is just the "simpler" interface at that point somewhere down the road.

Regardless, I'll hack up a proof of concept based on the outline above. Perhaps something more elegant will emerge once I start tweaking the source, but I'm still seeing too many gaps to be comfortable so far.

[[There is a whole other approach to this too. We could continue with the prctl() interface and mirror the trace_sys_enter model for
secure_computing(). Instead of keeping a seccomp_t-based hlist of
events, they could be stored in a new hlist for seccomp_events in struct ftrace_event_call. The ftrace filters would be installed there and the seccomp_syscall_enter() function could do the checks and pass up some state data on the task's seccomp_t that indicates it needs to do_exit(). That would likely reduce the amount of code in seccomp_filter.c pretty seriously (though not entirely beneficially).]]

Thanks again for all the feedback and insights! I really hope we can come to an agreeable approach for implementing kernel attack surface reduction.
will

author reviewer
#59 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 180 lines · Will Drewry
Quoted 10 lines · Steven Rostedt
Quoted 7 lines · Will Drewry

Do event_* that return non-void exist in the tree at all now? ?I've looked at the various tracepoint macros as well as some of the other handlers (trace_function, perf_tp_event, etc) and I'm not seeing any places where a return value is honored nor could be. ?At best, the perf_tp_event can be short-circuited it in the hlist_for_each, but it'd still need a way to bubble up a failure and result in not calling the trace/event that the hook precedes.

Quoted 2 lines

No, none of the current trace hooks have return values. That was what I was talking about how to implement in my previous emails.

Led on by complete ignorance, I think I'm finally beginning to untwist the different pieces of the tracing infrastructure. ?Unfortunately, that means I took a few wrong turns along the way...

I think function tracing looks something like this:

ftrace_call has been injected into at a specific callsite. ?Upon hit:
1. ftrace_call triggers
2. does some checks then calls ftrace_trace_function (via mcount instrs)
3. ftrace_trace_function may be a single func or a list. For a list it will be: ftrace_list_func
4. ftrace_list_func calls each registered hook for that function in a while loop ignoring return values
5. registered hook funcs may then track the call, farm it out to specific sub-handlers, etc.

This seems to be a red herring for my use case :/ though this helped me understand your back and forth (Ingo & Steve) regarding dynamic versus explicit events.

System call tracing is done via kernel/tracepoint.c events fed in via arch/[arch]/kernel/ptrace.c where it calls trace_sys_enter. ?This yields direct sys_enter and sys_exit event sources (and an event class to hook up per-system call events). ?This means that ftrace_syscall_enter() does the event prep prior to doing a filter check comparing the ftrace_event object for the given syscall_nr to the event data. ?perf_sysenter_enter() is similar but it pushes the info over to perf_tp_event to be matched not against the global syscall event entry, but against any sub-event in the linked list on that syscall's event.

Is that roughly an accurate representation of the two? ?I wish I hadn't gotten distracted along the function path, but at least I learned something (and it is relevant to the larger scope of this thread's discussion).

After doing that digging, it looks like providing hook call pre-emption and return value propagation will be a unique and fun task for each tracer and event subsystem. ?If I look solely at tracepoints, a generic change would be to make the trace_##subsys function return an int (which I think was the event_vfs_getname proposal?). ?The other option is to change the trace_sys_enter proto to include a 'int *retcode'.

That change would allow the propagation of some sort of policy information. ?To put it to use, seccomp mode 1 could be implemented on top of trace_syscalls. ?The following changes would need to happen:
1. dummy metadata should be inserted for all unhooked system calls
2. perf_trace_buf_submit would need to return an int or a new TRACE_REG_SECCOMP_REGISTER handler would need to be setup in syscall_enter_register.
3. If perf is abused, a "kill/fail_on_discard" bit would be added to event->attrs.
4. perf_trace_buf_submit/perf_tp_event will return 0 for no matches, 'n' for the number of event matches, and -EACCES/? if a 'fail_on_discard' event is seen.
5. perf_syscall_enter would set *retcode = perf_trace_buf_submit()'s retcode
6. trace_sys_enter() would need to be moved to be the first entry arch/../kernel/ptrace.c for incoming syscalls
7. if trace_sys_enter() yields a negative return code, then do_exit(SIGKILL) the process and return.

Entering into seccomp mode 1 would require adding a ?"0" filter for every system call number (which is why we need a dummy event call for them since failing to check the bitmask can't be flagged fail_on_discard) with the fail_on_discard bit. ?For the three calls that are allowed, a '1' filter would be set.

That would roughly implement seccomp mode 1. ?It's pretty ugly and the fact that every system call that's disallowed has to be blacklisted is not ideal. ?An alternate model would be to just use the seccomp mode as we do today and let secure_computing() handle the return code of "# of matches". ?If it the # of matches is 0, it terminates. A 'fail_on_discard' bit then would only be good to stop further tracepoint callback evaluation. ?This approach would also *almost* nix the need to provide dummy syscall hooks. ?(Since sigreturn isn't hooked on x86 because it uses ptregs fixup, a dummy would still be needed to apply a "1" filter to.)

Even with that tweak to move to a whitelist model, the perf event evaluation and tracepoint callback ordering is still not guaranteed. Without changing tracepoint itself, all other TPs will still execute. And for perf events, it'll be first-come-first-serve until a fail_on_discard is hit.

After using seccomp mode=1 as the sample case to reduce scope, it's possible to ignore it for now :) and look at the seccomp-filter/mode=2 case. ?The same mechanism could be used to inject more expressive filters. ?This would be done over the sys_perf_event_open() interface assuming the new attr is added to stop perf event list enumeration. Assuming a whitelist model, a call to prctl(PR_SET_SECCOMP, 2) would be needed (maybe with the ON_EXEC flag option too to mirror the event->attr on-exec bit). That would yield the ability to register perf events for system calls then use ioctl() to SET_FILTER on them.

Reducing the privileges of the filters after installation could be done with another attribute bit like 'set_filter_ands'. ?If that is also set on the event, and a filter is installed to ensure that sys_perf_event_open is blocked, then it should be reasonably sane.

I'd need to add a PERF_EVENT_IOC_GET_FILTER handler to allow extracting the settings.

Clearly, I haven't written the code for that yet, though making the change for a single platform shouldn't be too much code.

So that leaves me with some questions:
- Is this the type of reuse that was being encouraged?
- Does it really make sense to cram this through the perf interface and events? ?While the changed attributes are innocuous and potentially reusable, it seems that a large amount of the perf facilities are exposed that could have weird side effects, but I'm sure I still don't fully grok the perf infrastructure.
- Does extending one tracepoint to provide return values via a pointer make sense? I'd hesitate to make all tracepoint hooks return an int by default.
- If all tracepoints returned an int, what would the standard value look like - or would it need to be per tracepoint impl?
- How is ambiguity resolved if multiple perf_events are registered for a syscall with different filters? ?Maybe a 'stop_on_match'? though ordering is still a problem then.
- Is there a way to affect a task-wide change without a seccomp flag (or new task_struct entry) via the existing sys_perf_event_open syscall? ?I considered suggesting a attr bit call 'secure_computing' that when an event with the bit is enabled, it automagically forces the task into seccomp enforcement mode, but that, again, seemed hackish.

While I like the idea of sharing the tracepoints infrastructure and the trace_syscalls hooks as well as using a pre-existing interface with very minor changes, I'm worried that the complexity of the interface and of the infrastructure might undermine the ability to continue meeting the desired security goals. ?I had originally stayed very close to the seccomp world because of how trivial it is to review the code and verify its accuracy/effectiveness. ?This approach leaves a lot of gaps for kernel code to seep through and a fair amount of ambiguity in what locked down syscall filters might look like.

To me, the best part of the above is that it shows that even if we go with a prctl SET_SECCOMP_FILTER-style interface, it is completely certain that if a perf/ftrace-based security infrastructure is on our future, it will be entirely compatible -- even if the prctl() interface is just the "simpler" interface at that point somewhere down the road.

Regardless, I'll hack up a proof of concept based on the outline above. Perhaps something more elegant will emerge once I start tweaking the source, but I'm still seeing too many gaps to be comfortable so far.

[[There is a whole other approach to this too. We could continue with the prctl() interface and mirror the trace_sys_enter model for secure_computing(). ? Instead of keeping a seccomp_t-based hlist of events, they could be stored in a new hlist for seccomp_events in struct ftrace_event_call. ?The ftrace filters would be installed there and the seccomp_syscall_enter() function could do the checks and pass up some state data on the task's seccomp_t that indicates it needs to do_exit(). ?That would likely reduce the amount of code in seccomp_filter.c pretty seriously (though not entirely beneficially).]]

Quoted 3 lines

Thanks again for all the feedback and insights! I really hope we can come to an agreeable approach for implementing kernel attack surface reduction.

Just a quick follow up. I have a PoC of the perf-based system call filtering code in place which uses seccomp.mode as a task_context flag, adds require_secure and err_on_discard perf_event_attrs, and enforces these new events terminate the process in perf_syscall_enter via a return value on perf_buf_submit. This lets a call like:

LD_LIBRARY_PATH=/host/home/wad/kernel.uml/tests/ /host/home/wad/kernel.uml/tests/perf record \
-S \
-e 'syscalls:sys_enter_access' \
-e 'syscalls:sys_enter_brk' \
-e 'syscalls:sys_enter_close' \
-e 'syscalls:sys_enter_exit_group' \
-e 'syscalls:sys_enter_fcntl64' \
-e 'syscalls:sys_enter_fstat64' \
-e 'syscalls:sys_enter_getdents64' \
-e 'syscalls:sys_enter_getpid' \
-e 'syscalls:sys_enter_getuid' \
-e 'syscalls:sys_enter_ioctl' \
-e 'syscalls:sys_enter_lstat64' \
-e 'syscalls:sys_enter_mmap_pgoff' \
-e 'syscalls:sys_enter_mprotect' \
-e 'syscalls:sys_enter_munmap' \
-e 'syscalls:sys_enter_open' \
-e 'syscalls:sys_enter_read' \
-e 'syscalls:sys_enter_stat64' \
-e 'syscalls:sys_enter_time' \
-e 'syscalls:sys_enter_newuname' \
-e 'syscalls:sys_enter_write' --filter "fd == 1" \
/bin/ls

run successfully while omitting a syscall or passing in --filter "fd == 0" properly terminates it. (ignoring the need for execve and set_thread_area for PoC purposes).

The change avoids defining a new trace call type or a huge number of internal changes and hides seccomp.mode=2 from ABI-exposure in prctl, but the attack surface is non-trivial to verify, and I'm not sure if this ABI change makes sense. It amounts to:

 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-)

And can be found here: http://static.dataspill.org/perf_secure/v1/

If there is any interest at all, I can post it properly to this giant CC list. However, it's unclear to me where this thread stands. I also see a completely independent path for implementing system call filtering now, but I'll hold off posting that patch until I see where this goes.

Any guidance will be appreciated - thanks again!
will

maintainer
#60 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

#61 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

Amen. We have enough crap to cleanup in perf/ftrace already, so we really do not need security magic added to it.

Thanks,

tglx

author reviewer
#62 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 10 lines · Thomas Gleixner
Quoted 8 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
?include/linux/ftrace_event.h ?| ? ?4 +-
?include/linux/perf_event.h ? ?| ? 10 +++++---
?kernel/perf_event.c ? ? ? ? ? | ? 49 +++++++++++++++++++++++++++++++++++++---
?kernel/seccomp.c ? ? ? ? ? ? ?| ? ?8 ++++++
?kernel/trace/trace_syscalls.c | ? 27 +++++++++++++++++-----

?5 files changed, 82 insertions(+), 16 deletions(-)

Quoted 5 lines
Quoted 2 lines

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

Amen. We have enough crap to cleanup in perf/ftrace already, so we really do not need security magic added to it.

Thanks for the quick responses!

I agree, but I'm left a little bit lost now w.r.t. the comments around reusing the ABI. If perf doesn't make sense (which certainly seems wrong from a security interface perspective), then the preexisting ABIs I know of for this case are as follows:
- /sys/kernel/debug/tracing/*
- prctl(PR_SET_SECCOMP* (or /proc/...)

Both would require expansion. The latter was reused by the original patch series. The former doesn't expose much in the way of per-task event filtering -- ftrace_pids doesn't translate well to ftrace_syscall_enter-based enforcement. I'd expect we'd need ftrace_event_call->task_events (like ->perf_events), and either explore them in ftrace_syscall_enter or add a new tracepoint handler, ftrace_task_syscall_enter, via something like TRACE_REG_TASK_REGISTER.
It could then do whatever it wanted with the successful or
unsuccessful matching against predicates, stacking or not, which could be used for a seccomp-like mechanism. However, bubbling that change up to the non-existent interfaces in debug/tracing could be a challenge too (Registration would require an alternate flow like perf to call TRACE_REG_*? Do they become tracing/events/subsystem/event/task/<tid>/<filter_string_N>? ...?).

This is all just a matter of programming... but at this point, I'm not seeing the clear shared path forward. Even with per-task ftrace access in debug/tracing, that would introduce a reasonably large change to the system and add a new ABI, albeit in debug/tracing. If the above (or whatever the right approach is) comes into existence, then any prctl(PR_SET_SECCOMP) ABI could have the backend implementation to modify the same data. I'm not putting it like this to say that I'm designing to be obsolete, but to show that the defined interface wouldn't conflict if ftrace does overlap more in the future.
Given the importance of a clearly defined interface for security
functionality, I'd be surprised to see all the pieces come together in the near future in such a way that a transition would be immediately possible -- I'm not even sure what the ftrace roadmap really is!

Would it be more desirable to put a system call filtering interface on a miscdev (like /dev/syscall_filter) instead of in /proc or prctl (and not reuse seccomp at all)? I'm not clear what the onus is to justify a change in the different ABI areas, but I see system call filtering as an important piece of system security and would like to determine if there is a viable path forward, or if this will need to be revisited in another 2 years.

thanks again!
will

#63 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Peter Zijlstra
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

I'd object to invisible side-effects as well, and vehemently so. But note how intelligently it's used here: it's explicit in the code, it's used explicitly in kernel/seccomp.c and the event generation place in kernel/trace/trace_syscalls.c.

So this is a really flexible solution IMO and does not extend events with some invisible 'active' role. It extends the *call site* with an open-coded active role - which active role btw. already pre-existed.

Thanks,

Ingo

#64 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 14 lines · Ingo Molnar
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

Quoted 8 lines

I'd object to invisible side-effects as well, and vehemently so. But note how intelligently it's used here: it's explicit in the code, it's used explicitly in kernel/seccomp.c and the event generation place in kernel/trace/trace_syscalls.c.

So this is a really flexible solution IMO and does not extend events with some invisible 'active' role. It extends the *call site* with an open-coded active role - which active role btw. already pre-existed.

Also see my other mail - i think this seccomp code is too tied in to the perf core and ABI - but this is fixable IMO.

The fundamental notion that a generator subsystem of events can use filter results as well (such as kernel/trace/trace_syscalls.c.) for its own purposes is pretty robust though.

Thanks,

Ingo

#65 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Ingo Molnar
Quoted 13 lines · Ingo Molnar
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

Quoted 8 lines

I'd object to invisible side-effects as well, and vehemently so. But note how intelligently it's used here: it's explicit in the code, it's used explicitly in kernel/seccomp.c and the event generation place in kernel/trace/trace_syscalls.c.

So this is a really flexible solution IMO and does not extend events with some invisible 'active' role. It extends the *call site* with an open-coded active role - which active role btw. already pre-existed.

We do _NOT_ make any decision based on the trace point so what's the "pre-existing" active role in the syscall entry code?

I'm all for code reuse and reuse of interfaces, but this is completely wrong. Instrumentation and security decisions are two fundamentally different things and we want them kept separate. Instrumentation is not meant to make decisions. Just because we can does not mean that it is a good idea.

So what the current approach does is:

- abuse the existing ftrace syscall hook by adding a return value to the tracepoint.

So we need to propagate that for every tracepoint just because we have a single user.

- abuse the perf per task mechanism

Just because we have per task context in perf does not mean that we pull everything and the world which requires per task context into perf. The security folks have per task context already so security related stuff wants to go there.

- abuse the perf/ftrace interfaces

One of the arguments was that perf and ftrace have permission which are not available from the existing security interfaces. That's not at all a good reason to abuse these interfaces. Let the security folks sort out the problem on their end and do not impose any expectations on perf/ftrace which we have to carry around forever.

Yes, it can be made working with a relatively small patch, but it has a very nasty side effect:

You add another user space visible ABI to the existing perf/ftrace mess which needs to be supported forever.

Brilliant, we have already two ABIs (perf/ftrace) to support and at the same time we urgently need to solve the problem of better integration of those two. So adding a third completely unrelated component with a guaranteed ABI is just making this even more complex.

We can factor out the filtering code and let the security dudes reuse it for their own purposes. That makes them to have their own interfaces and does not impose any restrictions upon the tracing/perf ones. And really security stuff wants to be integrated into the existing security frameworks and not duct taped into perf/trace just because it's a conveniant hack around limitiations of the existing security stuff.

You really should stop to see everything as a nail just because the only tool you have handy is the perf hammer. perf is about instrumentation and we don't want to violate the oldest principle of unix to have simple tools which do one thing and do it good.

Even swiss army knifes have the restriction that you can use only one tool at a time unless you want to stick the corkscrew through your palm when you try to cut bread.

Thanks,

tglx

#66 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 19 lines · Thomas Gleixner
Quoted 18 lines · Ingo Molnar
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

I'd object to invisible side-effects as well, and vehemently so. But note how intelligently it's used here: it's explicit in the code, it's used explicitly in kernel/seccomp.c and the event generation place in kernel/trace/trace_syscalls.c.

Quoted 6 lines
Quoted 3 lines

So this is a really flexible solution IMO and does not extend events with some invisible 'active' role. It extends the *call site* with an open-coded active role - which active role btw. already pre-existed.

We do _NOT_ make any decision based on the trace point so what's the "pre-existing" active role in the syscall entry code?

The seccomp code we are discussing in this thread.

Quoted 5 lines

I'm all for code reuse and reuse of interfaces, but this is completely wrong. Instrumentation and security decisions are two fundamentally different things and we want them kept separate. Instrumentation is not meant to make decisions. Just because we can does not mean that it is a good idea.

Instrumentation does not 'make decisions': the calling site, which is already emitting both the event and wants to do decisions based on the data that also generates the event wants to do decisions.

Those decisions *will be made* and you cannot prevent that, the only open question is can it reuse code intelligently, which code it is btw. already calling for observation reasons?

( Note that pure observers wont be affected and note that pure
observation call sites are not affected either. )

Quoted 7 lines

So what the current approach does is:

- abuse the existing ftrace syscall hook by adding a return value to the tracepoint.

So we need to propagate that for every tracepoint just because we have a single user.

This is a technical criticism i share with you and i think it can be fixed - i outlined it to Will yesterday.

And no, if done cleanly it's not 'abuse' to reuse code. Could we wait for the first clean iteration of this patch instead of rushing judgement prematurely?

Quoted 6 lines

- abuse the perf per task mechanism

Just because we have per task context in perf does not mean that we pull everything and the world which requires per task context into perf. The security folks have per task context already so security related stuff wants to go there.

We do not pull 'everything and the world' in, but code that wants to process events in places that already emit events surely sounds related to me :-)

Quoted 8 lines

- abuse the perf/ftrace interfaces

One of the arguments was that perf and ftrace have permission which are not available from the existing security interfaces. That's not at all a good reason to abuse these interfaces. Let the security folks sort out the problem on their end and do not impose any expectations on perf/ftrace which we have to carry around forever.

Quoted 5 lines

Yes, it can be made working with a relatively small patch, but it has a very nasty side effect:

You add another user space visible ABI to the existing perf/ftrace mess which needs to be supported forever.

What mess? I'm not aware of a mess - other than the ftrace API which is not used by this patch.

Quoted 4 lines

Brilliant, we have already two ABIs (perf/ftrace) to support and at the same time we urgently need to solve the problem of better integration of those two. So adding a third completely unrelated component with a guaranteed ABI is just making this even more complex.

So your solution is to add yet another ABI for seccomp and to keep seccomp a limited hack forever, just because you are not interested in security?

I think we want fewer ABIs and more flexible/reusable facilities.

Quoted 7 lines

We can factor out the filtering code and let the security dudes reuse it for their own purposes. That makes them to have their own interfaces and does not impose any restrictions upon the tracing/perf ones. And really security stuff wants to be integrated into the existing security frameworks and not duct taped into perf/trace just because it's a conveniant hack around limitiations of the existing security stuff.

You are missing what i tried to point out in earlier discussions:
from a security design POV this isnt just about the system call boundary. If this seccomp variant is based on events then it could grow proper security checks in other places as well, in places where we have some sort of object observation event anyway.

So this is opens up possibilities to reuse and unify code on a very broad basis.

Quoted 4 lines

You really should stop to see everything as a nail just because the only tool you have handy is the perf hammer. perf is about instrumentation and we don't want to violate the oldest principle of unix to have simple tools which do one thing and do it good.

That is one of the most misunderstood principles of Unix.

The original Unix tool landscape was highly *integrated* and *unified*, into a very tight codebase that was maintained together. Yes, there were different, atomic, simple commands but it was all done together and it was a coherent whole and pleasant to use!

People misunderstood this as a license to fragment the heck out functionality and build 'simple and stupid' tools that fit nowhere really and use different, incompatible principles not synced with each other. That is wrong and harmful.

So yes, over-integration is obviously wrong - but so is needless fragmentation.

Anyway, i still reserve judgement on this seccomp bit but the patches so far looked very promising with a very surprisingly small diffstat.

If anything then that should tell you something that events and seccomp are not just casually related ...

Quoted 3 lines

Even swiss army knifes have the restriction that you can use only one tool at a time unless you want to stick the corkscrew through your palm when you try to cut bread.

I'm not sure what you are arguing here - do you pine for the DOS days where you could only use one command at a time?

Thanks,

Ingo

maintainer
#67 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 4 lines · Ingo Molnar
Quoted 2 lines

We do _NOT_ make any decision based on the trace point so what's the "pre-existing" active role in the syscall entry code?

The seccomp code we are discussing in this thread.

That isn't pre-existing, that's proposed.

But face it, you can argue until you're blue in the face, but both tglx and I will NAK any and all patches that extend perf/ftrace beyond the passive observing role.

Your arguments appear to be as non-persuasive to us as ours are to you, so please drop this endeavor and let the security folks sort it on their own and let's get back to doing useful work.

#68 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 1 line · Peter Zijlstra

But face it, you can argue until you're blue in the face,

That is not a technical argument though - and i considered and answered every valid technical argument made by you and Thomas. You were either not able to or not willing to counter them.

Quoted 2 lines

[...] but both tglx and I will NAK any and all patches that extend perf/ftrace beyond the passive observing role.

The thing is, perf is *already* well beyond the 'passive observer'
role: we already generate lots of 'action' in response to events. We generate notification signals, we write events - all of which can (and does) modify program behavior.

So what's your point? There's no "passive observer" role really - it's apparently just that you dislike this use of instrumentation while you approve of other uses.

Thanks,

Ingo

#69 lore raw

PATCH 3/5 v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Ingo Molnar
Quoted 20 lines · Ingo Molnar
Quoted 19 lines · Thomas Gleixner
Quoted 18 lines · Ingo Molnar
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

I'd object to invisible side-effects as well, and vehemently so. But note how intelligently it's used here: it's explicit in the code, it's used explicitly in kernel/seccomp.c and the event generation place in kernel/trace/trace_syscalls.c.

Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

So this is a really flexible solution IMO and does not extend events with some invisible 'active' role. It extends the *call site* with an open-coded active role - which active role btw. already pre-existed.

We do _NOT_ make any decision based on the trace point so what's the "pre-existing" active role in the syscall entry code?

The seccomp code we are discussing in this thread.

That's proposed code and has absolutely nothing to do with the existing trace point semantics.

Quoted 9 lines
Quoted 5 lines

I'm all for code reuse and reuse of interfaces, but this is completely wrong. Instrumentation and security decisions are two fundamentally different things and we want them kept separate. Instrumentation is not meant to make decisions. Just because we can does not mean that it is a good idea.

Instrumentation does not 'make decisions': the calling site, which is already emitting both the event and wants to do decisions based on the data that also generates the event wants to do decisions.

You can repeat that as often as you want, it does not make it more true. Fact is that the decision is made in the middle of the perf code.

Review

Quoted 8 lines
(quoted diff) +8 -0
+     /* Transition the task if required. */
+     if (ctx->type == task_context && event->attr.require_secure) {
+#ifdef CONFIG_SECCOMP
+		/* Don't allow perf events to escape mode = 1. */
+		   if (!current->seccomp.mode)
+			current->seccomp.mode = 2;
+#endif
+	}

and further down

Quoted 6 lines
(quoted diff) +2 -0
+   	    if (event->attr.err_on_discard)
+		ok = -EACCES;

Those decisions *will be made* and you cannot prevent that, the only open question is can it reuse code intelligently, which code it is btw. already calling for observation reasons?

The tracepoint is called for observation reasons and now you make it a decision function. That's what I call abuse.

Quoted 2 lines

( Note that pure observers wont be affected and note that pure
observation call sites are not affected either. )

Hahaha, they still have to run through the additional code when seccomp is enabled and we still have to propagate the return value down to the point where the tracepoint itself is. You call that not affected?

Quoted 8 lines
Quoted 7 lines

So what the current approach does is:

- abuse the existing ftrace syscall hook by adding a return value to the tracepoint.

So we need to propagate that for every tracepoint just because we have a single user.

Quoted 6 lines

This is a technical criticism i share with you and i think it can be fixed - i outlined it to Will yesterday.

And no, if done cleanly it's not 'abuse' to reuse code. Could we wait for the first clean iteration of this patch instead of rushing judgement prematurely?

There is no way to do it cleanly. It always comes for the price that you add additional code into the tracing code path. And there are other people who try hard to remove stuff to recude the overhead which is caused by instrumentation.

Quoted 10 lines
Quoted 6 lines

- abuse the perf per task mechanism

Just because we have per task context in perf does not mean that we pull everything and the world which requires per task context into perf. The security folks have per task context already so security related stuff wants to go there.

We do not pull 'everything and the world' in, but code that wants to process events in places that already emit events surely sounds related to me :-)

We have enough places where different independent parts of the kernel want to hook into for obvious reasons.

We have notifiers for those where performance does not matter much and we have separate calls into the independent functions where it matters or where we need to evaluate the results in specific ways.

So now you turn instrumentation into a security mechanism, which "works" nicely for a particular purpose, i.e. decision on a particular syscall number. Now, how do you make that work when a decision has to be made on more than a simple match, e.g. syscall number + arguments ?

Not at all, unless you add more complexity and arbitrary callbacks into the instrumentation code.

Quoted 8 lines
Quoted 4 lines

Brilliant, we have already two ABIs (perf/ftrace) to support and at the same time we urgently need to solve the problem of better integration of those two. So adding a third completely unrelated component with a guaranteed ABI is just making this even more complex.

So your solution is to add yet another ABI for seccomp and to keep seccomp a limited hack forever, just because you are not interested in security?

Well, I'm interested in security, but I'm neither interested in security decisions inside instrumentation code nor in security models which are limited hacks by definition unless you want to add callback complexities to the instrumentation code.

It all looks nice and charming with this minimalistic use case, but add real features to it and it gets messy in a split second and you can't hold that off once you started to allow A. And you clearly stated that you want to have more trace point based security features than the simple syscall number filtering.

Quoted 1 line

I think we want fewer ABIs and more flexible/reusable facilities.

I'm all for that, but security and instrumentation are different beasts.

Quoted 8 lines
Quoted 7 lines

We can factor out the filtering code and let the security dudes reuse it for their own purposes. That makes them to have their own interfaces and does not impose any restrictions upon the tracing/perf ones. And really security stuff wants to be integrated into the existing security frameworks and not duct taped into perf/trace just because it's a conveniant hack around limitiations of the existing security stuff.

Quoted 5 lines

You are missing what i tried to point out in earlier discussions:
from a security design POV this isnt just about the system call boundary. If this seccomp variant is based on events then it could grow proper security checks in other places as well, in places where we have some sort of object observation event anyway.

Right, that requires callbacks and more stuff to do object based observation and ties a trace point into a place where it might not make sense after a while, but the security decision wants to stay at that place. The syscall example is so tempting because it's simplistic and easy to solve, but every extension to that model is going to create a nightmare.

You are duct taping stuff together which has totally different semantics and requirements. And your only argument is reuse of existing code. That's a good argument in principle, but there is a fundamental difference between intelligent reuse and enforcing it just for reuse sake.

Quoted 2 lines

So this is opens up possibilities to reuse and unify code on a very broad basis.

By making a total mess out of it?

Quoted 2 lines

So yes, over-integration is obviously wrong - but so is needless fragmentation.

Right. And this falls into the category of over-integration. We have people working on security and they are working on stacked security models, so where is the justification to start another security framework inside the instrumentation code which is completely non interoperable with the existing ones?

Quoted 2 lines

If anything then that should tell you something that events and seccomp are not just casually related ...

They happen to have the hook at the same point in the source and for pure coincidence it works because the problem to solve is extremly simplistic. And that's why the diffstat is minimalistic, but that does not prove anything.

Thanks,

tglx

#70 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Hi,

Quoted 39 lines · Thomas Gleixner
Quoted 20 lines · Ingo Molnar
Quoted 19 lines · Thomas Gleixner
Quoted 18 lines · Ingo Molnar
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Will Drewry
 include/linux/ftrace_event.h  |    4 +-
 include/linux/perf_event.h    |   10 +++++---
 kernel/perf_event.c           |   49 +++++++++++++++++++++++++++++++++++++---
 kernel/seccomp.c              |    8 ++++++
 kernel/trace/trace_syscalls.c |   27 +++++++++++++++++-----
 5 files changed, 82 insertions(+), 16 deletions(-) 

I strongly oppose to the perf core being mixed with any sekurity voodoo (or any other active role for that matter).

I'd object to invisible side-effects as well, and vehemently so. But note how intelligently it's used here: it's explicit in the code, it's used explicitly in kernel/seccomp.c and the event generation place in kernel/trace/trace_syscalls.c.

Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

So this is a really flexible solution IMO and does not extend events with some invisible 'active' role. It extends the *call site* with an open-coded active role - which active role btw. already pre-existed.

We do _NOT_ make any decision based on the trace point so what's the "pre-existing" active role in the syscall entry code?

The seccomp code we are discussing in this thread.

That's proposed code and has absolutely nothing to do with the existing trace point semantics.

Quoted 6 lines
Quoted 5 lines

I'm all for code reuse and reuse of interfaces, but this is completely wrong. Instrumentation and security decisions are two fundamentally different things and we want them kept separate. Instrumentation is not meant to make decisions. Just because we can does not mean that it is a good idea.

Quoted 6 lines
Quoted 3 lines

Instrumentation does not 'make decisions': the calling site, which is already emitting both the event and wants to do decisions based on the data that also generates the event wants to do decisions.

You can repeat that as often as you want, it does not make it more true. Fact is that the decision is made in the middle of the perf code.

Can we just go back to the original spec? A lot of people were excited about the prctl() API as done in Will's earlier patchset, we don't lose the extremely useful "enable_on_exec" feature, and we can get away from all this disagreement.

-Kees

Signature · 2 lines
Kees Cook
Ubuntu Security Team
#71 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 5 lines · Kees Cook

Can we just go back to the original spec? A lot of people were excited about the prctl() API as done in Will's earlier patchset, we don't lose the extremely useful "enable_on_exec" feature, and we can get away from all this disagreement.

.. and quite frankly, I'm not even convinced about the original simpler spec.

Security is a morass. People come up with cool ideas every day, and nobody actually uses them - or if they use them, they are just a maintenance nightmare.

Quite frankly, limiting pathname access by some prefix is "cool", but it's basically useless.

That's not where security problems are.

Security problems are in the odd corners - ioctl's, /proc files, random small interfaces that aren't just about file access.

And who would *use* this thing in real life? Nobody. In order to sell me on a new security interface, give me a real actual use case that is security-conscious and relevant to real users.

For things like web servers that actually want to limit filename lookup, we'd be <i>much</i> better off with a few new flags to pathname lookup that say "don't follow symlinks" and "don't follow '..'". Things like that can actually be beneficial to security-conscious programming, with very little overhead. Some of those things currently look up pathnames one component at a time, because they can't afford to not do so. That's a *much* better model for the whole "only limit to this subtree" case that was quoted sometime early in this thread.

And per-system-call permissions are very dubious. What system calls don't you want to succeed? That ioctl? You just made it impossible to do a modern graphical application. Yet the kind of thing where we would _want_ to help users is in making it easier to sandbox something like the adobe flash player. But without accelerated direct rendering, that's not going to fly, is it?

So I'm sorry for throwing cold water on you guys, but the whole "let's come up with a new security gadget" thing just makes me go "oh no, not again".

Linus

#72 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 6 lines · Linus Torvalds

And per-system-call permissions are very dubious. What system calls don't you want to succeed? That ioctl? You just made it impossible to do a modern graphical application. Yet the kind of thing where we would _want_ to help users is in making it easier to sandbox something like the adobe flash player. But without accelerated direct rendering, that's not going to fly, is it?

I was under the impression that Will had a very specific application in mind which actually works today and uses the inferior version of seccomp.

Will, mind filling us in on that?

I'd agree that adding any of this without a real serious app making real use of it would be pointless. I discussed this under the impression that the app existed :-)

I also got the very distinct impression from the various iterations that a real usecase existed behind it - all the fixes and considerations looked very realistic, not designed up for security's sake.

Quoted 3 lines

So I'm sorry for throwing cold water on you guys, but the whole "let's come up with a new security gadget" thing just makes me go "oh no, not again".

Fair enough :-)

Thanks,

Ingo

author reviewer
#73 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 10 lines · Ingo Molnar
Quoted 6 lines · Linus Torvalds

And per-system-call permissions are very dubious. What system calls don't you want to succeed? That ioctl? You just made it impossible to do a modern graphical application. Yet the kind of thing where we would _want_ to help users is in making it easier to sandbox something like the adobe flash player. But without accelerated direct rendering, that's not going to fly, is it?

Quoted 5 lines

I was under the impression that Will had a very specific application in mind which actually works today and uses the inferior version of seccomp.

Will, mind filling us in on that?

With pleasure! I'll be a bit overly verbose to ensure I'm covering my bases, I hope it's not too tedious.

Support for using system call filtering will be added to the Chromium browser if it is accepted here. At present, Chromium separates the processing of untrusted input (html, javascript, images) into standalone renderer processes. In an effort to reduce the risks associated with processing the data we put those renderers in a chroot with a private VFS and PID namespace. This limits the ability for a compromised renderer to signal() another process outside of the "sandbox" or access files it shouldn't.

Ideally, the only exposed surface to the renderer would be the IPC mechanism, memory allocation, etc. That isn't possible today though [*]. The renderer gets the whole syscall ABI. In many cases, adding support for (all of the) LSMs to the sandboxing methodology would help mitigate the exposure. There would be the code paths that handle the user input prior to calling the LSM hooks, but after that point, the renderer could be denied, shutdown, etc. Unfortunately, there's no one-to-one mapping from system calls to LSM hooks (nor do all stock kernels from distros come with a pre-chosen and configured LSM).

To supply some concreteness, the perf_counter_open() system call comes to mind. It suffered from a stack-based buffer overflow when processing the user-supplied arguments, and there was no effective mechanism, LSM or otherwise, to prevent its access. In my usecase, if only a whitelist of required system calls was made available to the Chromium renderer processes, then the addition of a bug like perf_counter_open()'s to the kernel would not have provided a direct means to escape the user-level sandboxing and execute arbitrary code in the kernel.

As I mentioned, if it is possible to expand seccomp to provide a system call access mechanism (bitmask, whatever), I will expand the Chromium sandbox to make use of it on every linux distro that ships with it enabled. In addition, my immediate work focus is on Chromium OS. I would like to apply system call filtering to every daemon in the distribution alongside additional security defenses. Also, I am aware of many server-side uses but can't promise immediate deployment in the same fashion.

[It's also worth noting that as more browser plugins, like Adobe Flash, migrate to the Pepper API (chrome,mozilla), they will no longer need direct hardware access (ioctl()s, fs, etc). All system access will be brokered via the browser which lets them be sandboxed entirely -- including system call filtering is supported by the host platform.]

[*] it is possible to do crazy, on-the-fly syscall rewriting with seccomp(1) and a trusted thread, but the performance cost is huge, the portability is nil (pure asm), and the risk of a security bug is high.

Quoted 9 lines

I'd agree that adding any of this without a real serious app making real use of it would be pointless. I discussed this under the impression that the app existed :-)

I also got the very distinct impression from the various iterations that a real usecase existed behind it - all the fixes and considerations looked very realistic, not designed up for security's sake.

Quoted 5 lines
Quoted 3 lines

So I'm sorry for throwing cold water on you guys, but the whole "let's come up with a new security gadget" thing just makes me go "oh no, not again".

Fair enough :-)

I don't want to boil the ocean and certainly am not interested in reliving the LSM-wars. I want the missing piece of the puzzle when it comes to reducing exposed kernel code. seccomp.mode=1 is so close, but its overly restrictive nature has made it implausible for nearly all real-world uses. A slight expansion to allow a system call bitmask or simple filters would be sufficient for Chromium OS, Chromium, qemu, and lxc use, among others.

Thanks for reading and replying!
will

#74 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Linus Torvalds

Hi Linus,

Quoted 10 lines · Linus Torvalds

And who would *use* this thing in real life? Nobody. In order to sell me on a new security interface, give me a real actual use case that is security-conscious and relevant to real users.
[...]
And per-system-call permissions are very dubious. What system calls don't you want to succeed? That ioctl? You just made it impossible to do a modern graphical application. Yet the kind of thing where we would _want_ to help users is in making it easier to sandbox something like the adobe flash player. But without accelerated direct rendering, that's not going to fly, is it?

Uhm, what? Chrome would use it. And LXC would. Those were stated very early on as projects extremely interested in syscall filtering. And that's just the start, I can easily imagine Apache modules enforcing a very narrow band of syscalls, or just about anything else that could be in a position of running potentially malicious code. This could be very far-reaching, IMO.

-Kees

Signature · 2 lines
Kees Cook
Ubuntu Security Team
#75 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 3 lines · Kees Cook

Uhm, what? Chrome would use it. And LXC would. Those were stated very early on as projects extremely interested in syscall filtering.

.. and I seriously doubt it is workable.

Or at least it needs some actual working proof-of-concept thing. Exactly because of issues like direct rendering etc, that require some of the nastier system calls to work at all.

As to your example of apache modules - last I saw, most of those were written in high-level scripting languages that almost invariably end up using quite a bit of the system call interfaces. And more importantly, almost nobody does unportable code.

So hey, I'm willing to be convinced. But I'll need more than people _saying_ that they'd be interested. Because judging by past performance, nobody ever uses esoteric cool new features.

Linus

#76 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 10 lines · Linus Torvalds
Quoted 3 lines · Kees Cook

Uhm, what? Chrome would use it. And LXC would. Those were stated very early on as projects extremely interested in syscall filtering.

.. and I seriously doubt it is workable.

Or at least it needs some actual working proof-of-concept thing. Exactly because of issues like direct rendering etc, that require some of the nastier system calls to work at all.

Btw., Will's patch in this thread (which i think he tested with real code) implements an approach which detaches the concept from a rigid notion of 'syscall filtering' and opens it up for things like reliable pathname checks, memory object checks, etc. - without having to change the ABI.

If we go for syscall filtering as per bitmask, then we've pretty much condemned this to be limited to the syscall boundary alone.

So this sandboxing concept looked flexible enough to me to work itself up the security concept food chain *embedded in apps*.

<flame>

IMHO the key design mistake of LSM is that it detaches security policy from applications: you need to be admin to load policies, you need to be root to use/configure an LSM. Dammit, you need to be root to add labels to files!

This not only makes the LSM policies distro specific (and needlessly forked and detached from real security), but also gives the message that:

'to ensure your security you need to be privileged'

which is the anti-concept of good security IMO.

So why not give unprivileged security policy facilities and let *Apps* shape their own security models. Yes, they will mess up initially and will reinvent the wheel. But socially IMO it will work a *lot* better in the long run: it's not imposed on them *externally*, it's something they can use and grow gradually. They will experience the security holes first hand and they will be *able to do something strategic about them* if we give them the right facilities.

At least the Chrome browser project appears to be intent on following such an approach. I consider a more bazaar alike approach more healthy, and it very much needs kernel help as LSMs are isolated from apps right now.

The thing is, we cannot possibly make the LSM situation much worse than it is today: i see *ALL* of the LSMs focused on all the wrong things!

But yes, i can understand that you are deeply sceptical.

</flame>

Thanks,

Ingo

#77 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 13 lines · Ingo Molnar <mingo <at> elte.hu> writes:

<flame>

IMHO the key design mistake of LSM is that it detaches security policy from applications: you need to be admin to load policies, you need to be root to use/configure an LSM. Dammit, you need to be root to add labels to files!

This not only makes the LSM policies distro specific (and needlessly forked and detached from real security), but also gives the message that:

'to ensure your security you need to be privileged'

Quoted 7 lines

which is the anti-concept of good security IMO.

[....]
</flame>

Thanks,
Ingo

Hello!
An incomplete idea I had some time ago:

Couldn't the security information (like the selinux profiles) be part of the binaries?

Each source package should deliver it's own security information and this should be better than adding it later, because the developer of the program knows, what his program should be allowed to do. Moreover, if the developer changes something, he can/must add the security information altogether.

Of course these information has to be signed in some way to avoid tampering.

Just an idea...

#78 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Linus Torvalds
Quoted 5 lines · Linus Torvalds

As to your example of apache modules - last I saw, most of those were written in high-level scripting languages that almost invariably end up using quite a bit of the system call interfaces. And more importantly, almost nobody does unportable code.

Well, there's a difference between frameworks and applications. At least in GNOME e.g. we've been generally good at picking up and transparently taking advantage of Linux-specific stuff where possible like splice() in g_file_copy(), and in this cycle I'll probably end up using signalfd() to fix a long standing race condition.

Quoted 3 lines

So hey, I'm willing to be convinced. But I'll need more than people _saying_ that they'd be interested. Because judging by past performance, nobody ever uses esoteric cool new features.

I'm curious which features you feel are esoteric and cool but unused?

#79 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 2 lines · Colin Walters

I'm curious which features you feel are esoteric and cool but unused?

Just about anything linux-specific. Ranging from the totally new concepts (epoll/clone/splice/signalfd) to just simple cleanups and extensions of reasonably standard stuff (sync_file_range/sendpage).

Sure, there's almost always *somebody* who uses them, but they are seldom actually worth it.

The one thing that works well is when you expose it as a standard interface. So futexes are linux-specific, but they are exposed as the standard pthreads condition variables etc to apps - very few actually use them as futexes. But because glibc uses them for the pthreads synchronization, I think they ended up being used inside glibc for low-level stuff too, so I think futexes ended up being an unqualified success - much better than the standard interface.

The "it can be used in standard libraries" ends up being a very powerful thing. It doesn't have to be libc - if something like a glib or a big graphical interface uses them, they can get very popular. But if you have to have actual config options (autoconf or similar) to enable the feature on Linux, along with a compatibility case (because older kernels don't even support it, so it's not even "linux", it's "linux newer than xyz"), then very very few applications end up using it.

And security issues in particular are often *very* subtle. For example, something like a system call filter sounds like an obviously safe thing: it can only limit what you do, right?

Except no, not right at all. Imagine that you're limiting a suid application, and the one operation you limit is "setuid()". Imagine that the suid application explicitly drops privileges in order to run safely as the user. Imagine, further, that it doesn't even check the return value, because it *knows* that if it is root, it will succeed, and if it isn't root, then it wasn't suid to begin with and doesn't need to do anything about it.

Unlikely? Hell no. That's standard practice. And if you allow filter setup that survives fork+exec, you just opened a HUGE security hole.

Fixable? Yes, easily. And I haven't looked at the current patches, but I would not be AT ALL surprised if they had exactly the above huge security hole.

My point being that (a) I'm very dubious about new non-standard features, because historically they seldom get used very widely and
(b) I'm doubly dubious about security things because it turns out it's damn easy to get it wrong in all kinds of small subtle details.

Linus

#80 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 7 lines · Linus Torvalds
Quoted 2 lines · Colin Walters

I'm curious which features you feel are esoteric and cool but unused?

Just about anything linux-specific. Ranging from the totally new concepts (epoll/clone/splice/signalfd) to just simple cleanups and extensions of reasonably standard stuff (sync_file_range/sendpage).

epoll's very widely used via frameworks I'd say; at least the Apache runtime uses it, libevent does, and apparently the Sun JDK does:
http://www.google.com/codesearch/p?hl=en#ih5hvYJNSIA/src/solaris/classes/sun/nio/ch/EPollPort.java&q=epoll&sa=N&cd=32&ct=rc
And here's an entry on that: http://blogs.oracle.com/alanb/entry/epoll

(Why doesn't glib? It's hard since the priority design was kind of a
mistake: https://bugzilla.gnome.org/show_bug.cgi?id=156048 )

Quoted 3 lines

The "it can be used in standard libraries" ends up being a very powerful thing. It doesn't have to be libc - if something like a glib or a big graphical interface uses them, they can get very popular.

Right, that's the distinction I was trying to make.

Quoted 8 lines

But
if you have to have actual config options (autoconf or similar) to enable the feature on Linux, along with a compatibility case (because older kernels don't even support it, so it's not even "linux", it's "linux newer than xyz"), then very very few applications end up using it.

From my experience as a framework developer, it hasn't been hard at

all to keep track of new Linux features, we talk about them a lot =) The fallback code is often obvious, like for splice(), though for signalfd it's going to much more messy to keep around the legacy helper thread case.

Quoted 2 lines

Unlikely? Hell no. That's standard practice. And if you allow filter setup that survives fork+exec, you just opened a HUGE security hole.

Oh definitely, setuid and process inheritance has been a source of many problems over the years, and I agree it'd be very dangerous for the syscall filters to stay open across execve. Of course in practice glibc secure mode exists to mitigate these things too; it could abort if one was in place in that case.

But I was more curious about your views on Linux-specific interfaces, and you answered that; thanks!

author reviewer
#81 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Linus Torvalds
Quoted 40 lines · Linus Torvalds
Quoted 2 lines · Colin Walters

I'm curious which features you feel are esoteric and cool but unused?

Just about anything linux-specific. Ranging from the totally new concepts (epoll/clone/splice/signalfd) to just simple cleanups and extensions of reasonably standard stuff (sync_file_range/sendpage).

Sure, there's almost always *somebody* who uses them, but they are seldom actually worth it.

The one thing that works well is when you expose it as a standard interface. So futexes are linux-specific, but they are exposed as the standard pthreads condition variables etc to apps - very few actually use them as futexes. But because glibc uses them for the pthreads synchronization, I think they ended up being used inside glibc for low-level stuff too, so I think futexes ended up being an unqualified success - much better than the standard interface.

The "it can be used in standard libraries" ends up being a very powerful thing. It doesn't have to be libc - if something like a glib or a big graphical interface uses them, they can get very popular. But if you have to have actual config options (autoconf or similar) to enable the feature on Linux, along with a compatibility case (because older kernels don't even support it, so it's not even "linux", it's "linux newer than xyz"), then very very few applications end up using it.

And security issues in particular are often *very* subtle. For example, something like a system call filter sounds like an obviously safe thing: it can only limit what you do, right?

Except no, not right at all. Imagine that you're limiting a suid application, and the one operation you limit is "setuid()". Imagine that the suid application explicitly drops privileges in order to run safely as the user. Imagine, further, that it doesn't even check the return value, because it *knows* that if it is root, it will succeed, and if it isn't root, then it wasn't suid to begin with and doesn't need to do anything about it.

Quoted 6 lines

Unlikely? Hell no. That's standard practice. And if you allow filter setup that survives fork+exec, you just opened a HUGE security hole.

Fixable? Yes, easily. And I haven't looked at the current patches, but I would not be AT ALL surprised if they had exactly the above huge security hole.

FWIW, none of the patches deal with privilege escalation via setuid files or file capabilities.

Quoted 4 lines

My point being that (a) I'm very dubious about new non-standard features, because historically they seldom get used very widely and
(b) I'm doubly dubious about security things because it turns out it's damn easy to get it wrong in all kinds of small subtle details.

I agree with both points, so I'm being a bit hypocritical, I suspect.

At present, I'm not aware of any platforms that support system call restriction in a non-platform-specific fashion: mac has seatbelt, freebsd has things like capsicum, linux has seccomp :) This led me to the proposal around expanding seccomp since it was already a Linux-ism for this functionality and, ideally, could be minimal to help limit
the subtle-bug-exposure. However, any form of kernel attack surface
reduction would be great, but I'm unaware of any that integrate with glibc smoothly (even if some do have nicer programming interfaces).

I've used system call filtering in the past with good effect in server environments, and I believe the Chromium renderer example is a robust for Linux desktops, even without glibc integration. If the Linux-specific, non-automatic (glibc) interface is a no-go, then I'll go back to the drawing board. I'm not sure how to avoid something Linux-specific in general, even if it's just adding syscall hooks to LSMs, though it could be possible to share interfaces with some other platform's implementation of a broader security system that includes kernel exposure minimization (like capsicum) which could be built-on what existing substrate is available or a new one, as Ingo proposes.

thanks!
will

#82 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 3 lines · Will Drewry

FWIW, none of the patches deal with privilege escalation via setuid files or file capabilities.

That is NOT AT ALL what I'm talking about.

I'm talking about the "setuid()" system call (and all its cousins:
setgit/setreuid etc). And the whole thread has been about filtering system calls, no?

Do a google code search for setuid.

In good code, it will look something like

  uid = getuid();

  if (setuid(uid)) {
    fprintf(stderr, "Unable to drop provileges\n");
    exit(1);
  }

but I guarantee you that there are cases where people just blindly drop privileges. google code search found me at least the "heirloom" source code doing exactly that.

And if you filter system calls, it's entirely possible that you can attack suid executables through such a vector. Your "limit system calls for security" security suddenly turned into "avoid the system call that made things secure"!

See what I'm saying?

Linus

author reviewer
#83 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 26 lines · Linus Torvalds
Quoted 3 lines · Will Drewry

FWIW, none of the patches deal with privilege escalation via setuid files or file capabilities.

That is NOT AT ALL what I'm talking about.

I'm talking about the "setuid()" system call (and all its cousins:
setgit/setreuid etc). And the whole thread has been about filtering system calls, no?

Do a google code search for setuid.

In good code, it will look something like

 uid = getuid();

 if (setuid(uid)) {
   fprintf(stderr, "Unable to drop provileges\n"); exit(1);
 }

but I guarantee you that there are cases where people just blindly drop privileges. google code search found me at least the "heirloom" source code doing exactly that.

Quoted 6 lines

And if you filter system calls, it's entirely possible that you can attack suid executables through such a vector. Your "limit system calls for security" security suddenly turned into "avoid the system call that made things secure"!

See what I'm saying?

Absolutely - that was what I meant :/ The patches do not currently check creds at creation or again at use, which would lead to unprivileged filters being used in a privileged context. Right now, though, if setuid() is not allowed by the seccomp-filter, the process will be immediately killed with do_exit(SIGKILL) on call -- thus avoiding a silent failure. I mentioned file capabilities because they can have setuid-like side effects, too. As long as system call rejection results in a process death, I *think* it helps with some of this complexity, but I haven't fully vetted the patches for these scenarios to be 100% confident.

Sorry I wasn't clear!
will

author reviewer
#84 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 35 lines · Will Drewry
Quoted 26 lines · Linus Torvalds
Quoted 3 lines · Will Drewry

FWIW, none of the patches deal with privilege escalation via setuid files or file capabilities.

That is NOT AT ALL what I'm talking about.

I'm talking about the "setuid()" system call (and all its cousins:
setgit/setreuid etc). And the whole thread has been about filtering system calls, no?

Do a google code search for setuid.

In good code, it will look something like

 uid = getuid();

 if (setuid(uid)) {
   fprintf(stderr, "Unable to drop provileges\n"); exit(1);
 }

but I guarantee you that there are cases where people just blindly drop privileges. google code search found me at least the "heirloom" source code doing exactly that.

Quoted 6 lines

And if you filter system calls, it's entirely possible that you can attack suid executables through such a vector. Your "limit system calls for security" security suddenly turned into "avoid the system call that made things secure"!

See what I'm saying?

Quoted 10 lines

Absolutely - that was what I meant :/  The patches do not currently check creds at creation or again at use, which would lead to unprivileged filters being used in a privileged context.  Right now, though, if setuid() is not allowed by the seccomp-filter, the process will be immediately killed with do_exit(SIGKILL) on call -- thus avoiding a silent failure. I mentioned file capabilities because they can have setuid-like side effects, too.  As long as system call rejection results in a process death, I *think* it helps with some of this complexity, but I haven't fully vetted the patches for these scenarios to be 100% confident.

Bah - by "setuid-like side effects", I meant suid executable-like side effects. And I blocking even outside of those scenarios, I think immediate process-death helps resolves coding mistakes leading to filtering setuid() calls prior to use.

cheers,
will

#85 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Will Drewry
Quoted 7 lines · Will Drewry

Absolutely - that was what I meant :/  The patches do not currently check creds at creation or again at use, which would lead to unprivileged filters being used in a privileged context.  Right now, though, if setuid() is not allowed by the seccomp-filter, the process will be immediately killed with do_exit(SIGKILL) on call -- thus avoiding a silent failure.

Umm.

You do realize that there is a reason we don't allow random kill() system calls to succeed without privileges either?

So no, "we kill it with sigkill" is not safe *either*. It now is potentially a way to kill privileged processes that you didn't have permission to kill.

My point is that it all sounds designed for well-behaved processes. "kill it if it does something bad" sounds like a *wonderful* idea if you're doing a sandbox.

But it is suddenly potentially deadly if that capability is used by a malicious user for a process that isn't ready for it.

One option is to just not ever allow execve() from inside a restricted environment.

Linus

author reviewer
#86 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 14 lines · Linus Torvalds
Quoted 7 lines · Will Drewry

Absolutely - that was what I meant :/  The patches do not currently check creds at creation or again at use, which would lead to unprivileged filters being used in a privileged context.  Right now, though, if setuid() is not allowed by the seccomp-filter, the process will be immediately killed with do_exit(SIGKILL) on call -- thus avoiding a silent failure.

Umm.

You do realize that there is a reason we don't allow random kill() system calls to succeed without privileges either?

Quoted 7 lines

So no, "we kill it with sigkill" is not safe *either*. It now is potentially a way to kill privileged processes that you didn't have permission to kill.

My point is that it all sounds designed for well-behaved processes. "kill it if it does something bad" sounds like a *wonderful* idea if you're doing a sandbox.

Yeah - we end up in a weird place, because for many suid executables, the failure would be immediate (at priv drop), but it introduces bugs that will be less obvious in more complex scenarios.

Quoted 5 lines

But it is suddenly potentially deadly if that capability is used by a malicious user for a process that isn't ready for it.

One option is to just not ever allow execve() from inside a restricted environment.

That'd certainly be fine with me. Another option could be adding a cred checking (from set to use) or execve time checking or ..., but simple works for me. I'm not hung up on the implementation details specifically if the end result is that the syscalls can be _safely_ whitelisted.

Thanks!

#87 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 5 lines · Will Drewry
Quoted 3 lines

One option is to just not ever allow execve() from inside a restricted environment.

That'd certainly be fine with me.

So if it ends up being purely a "internal to the process" thing, then I'm much happier about it - it not only limits the scope of things sufficiently that I don't worry too much about security issues, but it makes it very clear that it's about a process going into "lock-down" mode on its own.

It also gets rid of all configuration - one of the things that makes most security frameworks (look at selinux, but also just ACL's etc) such a crazy rats nest is the whole "set up for other processes". If it's designed very much to be about just the "self" process (after initialization etc), then I think that avoids pretty much all the serious issues.

A lot of server processes could probably use it as a way to say "Hey, I guarantee that I will only open new files read-only, and will only write to the socket that was already opened for me by the accept", and explicitly limit their worker threads that way.

If that is really sufficient for some chrome sandboxing, then hey, that's all fine.

Sometimes limiting yourself (rather than looking for some bigger "generic" solution) is the right answer.

Linus

#88 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 6 lines · Linus Torvalds

It also gets rid of all configuration - one of the things that makes most security frameworks (look at selinux, but also just ACL's etc) such a crazy rats nest is the whole "set up for other processes". If it's designed very much to be about just the "self" process (after initialization etc), then I think that avoids pretty much all the serious issues.

That's how the event filters work currently: even when inherited they get removed when exec-ing a setuid task, so they cannot leak into privileged context and cannot modify execution there.

Inheritance works when requested, covering only same-credential child tasks, not privileged successors.

Thanks,

Ingo

#89 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 9 lines · Ingo Molnar
Quoted 6 lines · Linus Torvalds

It also gets rid of all configuration - one of the things that makes most security frameworks (look at selinux, but also just ACL's etc) such a crazy rats nest is the whole "set up for other processes". If it's designed very much to be about just the "self" process (after initialization etc), then I think that avoids pretty much all the serious issues.

Quoted 6 lines

That's how the event filters work currently: even when inherited they get removed when exec-ing a setuid task, so they cannot leak into privileged context and cannot modify execution there.

Inheritance works when requested, covering only same-credential child tasks, not privileged successors.

this is a very reasonable default, but there should be some way of saying that you want the restrictions to carry over to the suid task (I really know what I'm doing switch)

David Lang

#90 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 15 lines · On Thu, May 26, 2011 at 3:05 PM, <[email protected]> wrote:
Quoted 13 lines · Ingo Molnar
Quoted 6 lines · Linus Torvalds

It also gets rid of all configuration - one of the things that makes most security frameworks (look at selinux, but also just ACL's etc) such a crazy rats nest is the whole "set up for other processes". If it's designed very much to be about just the "self" process (after initialization etc), then I think that avoids pretty much all the serious issues.

That's how the event filters work currently: even when inherited they get removed when exec-ing a setuid task, so they cannot leak into privileged context and cannot modify execution there.

Quoted 6 lines
Quoted 2 lines

Inheritance works when requested, covering only same-credential child tasks, not privileged successors.

this is a very reasonable default, but there should be some way of saying that you want the restrictions to carry over to the suid task (I really know what I'm doing switch)

You mean the "i'm a hacker and want to be able to learn about tasks I shouldn't be able to learn about" switch? No. You either get out of the way on SUID or refuse to launch SUID apps. Those are the only reasonable choices.

#91 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to [email protected]
Quoted 15 lines · * [email protected] <[email protected]> wrote:
Quoted 13 lines · Ingo Molnar
Quoted 6 lines · Linus Torvalds

It also gets rid of all configuration - one of the things that makes most security frameworks (look at selinux, but also just ACL's etc) such a crazy rats nest is the whole "set up for other processes". If it's designed very much to be about just the "self" process (after initialization etc), then I think that avoids pretty much all the serious issues.

That's how the event filters work currently: even when inherited they get removed when exec-ing a setuid task, so they cannot leak into privileged context and cannot modify execution there.

Quoted 6 lines
Quoted 2 lines

Inheritance works when requested, covering only same-credential child tasks, not privileged successors.

this is a very reasonable default, but there should be some way of saying that you want the restrictions to carry over to the suid task (I really know what I'm doing switch)

Unless you mean that root should be able to do it it's a security hole both for events and for filters:

- for example we dont want really finegrained events to be used to BTS hw-trace sshd and thus enable it to discover cryptographic properties of the private key sshd is using.

- we do not want to *modify* the execution flow of a setuid program, that can lead to exploits: by pushing the privileged codepath into a condition that can never occur on a normal system - and thus can push it into doing something it was not intended to do.

data damage could be done as well: for example if the privileged code is logging into a system file then modifying execution can damage the log file.

So it's not a good idea in general to allow unprivileged code to modify the execution of privileged code. In fact it's not a good idea to allow it to simply *observe* privileged code. It must remain a black box with very few information leaking outwards.

Thanks,

Ingo

#92 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 36 lines · Ingo Molnar
Quoted 15 lines · * [email protected] <[email protected]> wrote:
Quoted 13 lines · Ingo Molnar
Quoted 6 lines · Linus Torvalds

It also gets rid of all configuration - one of the things that makes most security frameworks (look at selinux, but also just ACL's etc) such a crazy rats nest is the whole "set up for other processes". If it's designed very much to be about just the "self" process (after initialization etc), then I think that avoids pretty much all the serious issues.

That's how the event filters work currently: even when inherited they get removed when exec-ing a setuid task, so they cannot leak into privileged context and cannot modify execution there.

Quoted 6 lines
Quoted 2 lines

Inheritance works when requested, covering only same-credential child tasks, not privileged successors.

this is a very reasonable default, but there should be some way of saying that you want the restrictions to carry over to the suid task (I really know what I'm doing switch)

Unless you mean that root should be able to do it it's a security hole both for events and for filters:

- for example we dont want really finegrained events to be used to BTS hw-trace sshd and thus enable it to discover cryptographic properties of the private key sshd is using.

- we do not want to *modify* the execution flow of a setuid program, that can lead to exploits: by pushing the privileged codepath into a condition that can never occur on a normal system - and thus can push it into doing something it was not intended to do.

Quoted 8 lines

data damage could be done as well: for example if the privileged code is logging into a system file then modifying execution can damage the log file.

So it's not a good idea in general to allow unprivileged code to modify the execution of privileged code. In fact it's not a good idea to allow it to simply *observe* privileged code. It must remain a black box with very few information leaking outwards.

I was thinking of the use case of the real sysadmin (i.e. root) wanting to be able to constrain things. I can see why you would not want to allow normal users to do this.

David Lang

author reviewer
#93 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Linus Torvalds
Quoted 20 lines · Linus Torvalds
Quoted 5 lines · Will Drewry
Quoted 3 lines

One option is to just not ever allow execve() from inside a restricted environment.

That'd certainly be fine with me.

So if it ends up being purely a "internal to the process" thing, then I'm much happier about it - it not only limits the scope of things sufficiently that I don't worry too much about security issues, but it makes it very clear that it's about a process going into "lock-down" mode on its own.

It also gets rid of all configuration - one of the things that makes most security frameworks (look at selinux, but also just ACL's etc) such a crazy rats nest is the whole "set up for other processes". If it's designed very much to be about just the "self" process (after initialization etc), then I think that avoids pretty much all the serious issues.

Quoted 7 lines

A lot of server processes could probably use it as a way to say "Hey, I guarantee that I will only open new files read-only, and will only write to the socket that was already opened for me by the accept", and explicitly limit their worker threads that way.

If that is really sufficient for some chrome sandboxing, then hey, that's all fine.

It adds some hoops, but less than exist today.

Quoted 2 lines

Sometimes limiting yourself (rather than looking for some bigger "generic" solution) is the right answer.

I will very happily validate usage and repost with a self-limited patch series. Doing so makes the change much more explicitly an expansion of seccomp, which keeps things sane.

Thanks!
will

author reviewer
#94 lore raw

PATCH v3 1/13 tracing: split out filter initialization and clean up.

Moves the perf-specific profile event allocation and freeing code into kernel/perf_event.c where it is called from and two symbols are exported via ftrace_event.h for instantiating struct event_filters without requiring a change to the core tracing code.

The change allows globally registered ftrace events to be used in event_filter structs. perf is the current consumer, but a possible future consumer is a system call filtering using the secure computing hooks (and the existing syscalls subsystem events).

---
 include/linux/ftrace_event.h       |    9 +++--
 kernel/perf_event.c                |    7 +++-
 kernel/trace/trace_events_filter.c |   60 ++++++++++++++++++++++--------------
 3 files changed, 48 insertions(+), 28 deletions(-)
include/linux/ftrace_event.h +6 -3
index 22b32af..fea9d98 100644
@@ -216,6 +216,12 @@ extern int filter_current_check_discard(struct ring_buffer *buffer,
 					void *rec,
 					struct ring_buffer_event *event);
 
+extern void ftrace_free_filter(struct event_filter *filter);
+extern int ftrace_parse_filter(struct event_filter **filter,
+			       int event_id,
+			       const char *filter_str);
+extern const char *ftrace_get_filter_string(const struct event_filter *filter);
+
 enum {
 	FILTER_OTHER = 0,
 	FILTER_STATIC_STRING,
@@ -266,9 +272,6 @@ extern int  perf_trace_init(struct perf_event *event);
 extern void perf_trace_destroy(struct perf_event *event);
 extern int  perf_trace_add(struct perf_event *event, int flags);
 extern void perf_trace_del(struct perf_event *event, int flags);
-extern int  ftrace_profile_set_filter(struct perf_event *event, int event_id,
-				     char *filter_str);
-extern void ftrace_profile_free_filter(struct perf_event *event);
 extern void *perf_trace_buf_prepare(int size, unsigned short type,
 				    struct pt_regs *regs, int *rctxp);
 
kernel/perf_event.c +5 -2
index 8e81a98..1da45e7 100644
@@ -5588,7 +5588,8 @@ static int perf_event_set_filter(struct perf_event *event, void __user *arg)
 	if (IS_ERR(filter_str))
 		return PTR_ERR(filter_str);
 
-	ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
+	ret = ftrace_parse_filter(&event->filter, event->attr.config,
+				  filter_str);
 
 	kfree(filter_str);
 	return ret;
@@ -5596,7 +5597,9 @@ static int perf_event_set_filter(struct perf_event *event, void __user *arg)
 
 static void perf_event_free_filter(struct perf_event *event)
 {
-	ftrace_profile_free_filter(event);
+	struct event_filter *filter = event->filter;
+	event->filter = NULL;
+	ftrace_free_filter(filter);
 }
 
 #else
kernel/trace/trace_events_filter.c +37 -23

105 lines not on this page · raw message

Signature · 1 line
1.7.0.4
author reviewer
#95 lore raw

PATCH v3 2/13 tracing: split out syscall_trace_enter construction

In reply to Will Drewry

perf appears to be the primary consumer of the CONFIG_FTRACE_SYSCALLS infrastructure. As such, many the helpers target at perf can be split into a peerf-focused helper and a generic CONFIG_FTRACE_SYSCALLS consumer interface.

This change splits out syscall_trace_enter construction from perf_syscall_enter for current into two helpers:
- ftrace_syscall_enter_state
- ftrace_syscall_enter_state_size

And adds another helper for completeness:
- ftrace_syscall_exit_state_size

These helpers allow for shared code between perf ftrace events and any other consumers of CONFIG_FTRACE_SYSCALLS events. The proposed seccomp_filter patches use this code.

---
 include/trace/syscall.h       |    4 ++
 kernel/trace/trace_syscalls.c |   96 +++++++++++++++++++++++++++++++++++------
 2 files changed, 86 insertions(+), 14 deletions(-)
include/trace/syscall.h +4 -0
index 31966a4..242ae04 100644
@@ -41,6 +41,10 @@ extern int reg_event_syscall_exit(struct ftrace_event_call *call);
 extern void unreg_event_syscall_exit(struct ftrace_event_call *call);
 extern int
 ftrace_format_syscall(struct ftrace_event_call *call, struct trace_seq *s);
+extern int ftrace_syscall_enter_state(u8 *buf, size_t available,
+				      struct trace_entry **entry);
+extern size_t ftrace_syscall_enter_state_size(int nb_args);
+extern size_t ftrace_syscall_exit_state_size(void);
 enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
 				      struct trace_event *event);
 enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
kernel/trace/trace_syscalls.c +82 -14

132 lines not on this page · raw message

Signature · 1 line
1.7.0.4
#96 lore raw
Quoted 17 lines · Will Drewry

perf appears to be the primary consumer of the CONFIG_FTRACE_SYSCALLS infrastructure. As such, many the helpers target at perf can be split into a peerf-focused helper and a generic CONFIG_FTRACE_SYSCALLS consumer interface.

This change splits out syscall_trace_enter construction from perf_syscall_enter for current into two helpers:
- ftrace_syscall_enter_state
- ftrace_syscall_enter_state_size

And adds another helper for completeness:
- ftrace_syscall_exit_state_size

These helpers allow for shared code between perf ftrace events and any other consumers of CONFIG_FTRACE_SYSCALLS events. The proposed seccomp_filter patches use this code.

Quoted 5 lines
---
 include/trace/syscall.h       |    4 ++
 kernel/trace/trace_syscalls.c |   96 +++++++++++++++++++++++++++++++++++------
 2 files changed, 86 insertions(+), 14 deletions(-)

So, looking at the diffstat comparison again:

       bitmask (2009):  6 files changed,  194 insertions(+), 22 deletions(-)

filter engine (2010): 18 files changed, 1100 insertions(+), 21 deletions(-)
event filters (2011): 5 files changed, 82 insertions(+), 16 deletions(-)

you went back to the middle solution again which is the worst of them
- why?

If you want this to be a stupid, limited hack then go for the v1 bitmask.

If you agree with my observation that filters allow the clean user-space implementation of LSM equivalent security solutions (of which sandboxes are just a *narrow special case*) then please use the main highlevel abstraction we have defined around them: event filters.

Now, my observation was not uncontested so let me try to sum up the rather large discussion that erupted around it, as i see it.

I saw four main counter arguments:

- "Sandboxing is special and should stay separate from LSMs."

I think this is a technically bogus argument, see:

         https://lkml.org/lkml/2011/5/26/85

That answer of mine went unchallenged.

- "Events should only be observers."

Even ignoring the question of why on earth it should be a problem for a willing call-site to use event filtering results sensibly, this argument misses the plain fact that events are *already* active participants, see:

         http://www.spinics.net/lists/mips/msg41075.html

That answer of mine went unchallenged too.

- "This feature is too simplistic."

That's wrong i think, the feature is highly flexible:

         http://www.mail-archive.com/[email protected]/msg51387.html

This reply of mine went unchallenged as well.

- "Is this feature actually useful enough for applications, does it justify the complexity?"

This is the *only* valid technical counter-argument i saw, and it's a crutial one that is not fully answered yet. Since i think the feature is an LSM equivalent i think it's at least as useful as any LSM is.

- [ if i missed any important argument then someone please insert it

     here. ]

But what you do here is to use the filter engine directly which is both a limited hack *and* complex (beyond the linecount it doubles our ABI exposure, amongst other things), so i find that approach rather counter-productive, now that i've seen the real thing.

Will this feature be just another example of the LSM status quo dragging down a newcomer into the mud, until it's just as sucky and limited as any existing LSMs? That would be a sad outcome!

Thanks,

Ingo

ps. Please start a new discussion thread for the next iteration!
This one is *way* too deep already.

author reviewer
#97 lore raw
Quoted 26 lines · Ingo Molnar
Quoted 17 lines · Will Drewry

perf appears to be the primary consumer of the CONFIG_FTRACE_SYSCALLS infrastructure.  As such, many the helpers target at perf can be split into a peerf-focused helper and a generic CONFIG_FTRACE_SYSCALLS consumer interface.

This change splits out syscall_trace_enter construction from perf_syscall_enter for current into two helpers:
- ftrace_syscall_enter_state
- ftrace_syscall_enter_state_size

And adds another helper for completeness:
- ftrace_syscall_exit_state_size

These helpers allow for shared code between perf ftrace events and any other consumers of CONFIG_FTRACE_SYSCALLS events.  The proposed seccomp_filter patches use this code.

Quoted 5 lines

---
 include/trace/syscall.h       |    4 ++ kernel/trace/trace_syscalls.c |   96 +++++++++++++++++++++++++++++++++++------

 2 files changed, 86 insertions(+), 14 deletions(-)
Quoted 8 lines

So, looking at the diffstat comparison again:

      bitmask (2009):  6 files changed,  194 insertions(+), 22 deletions(-) filter engine (2010): 18 files changed, 1100 insertions(+), 21 deletions(-) event filters (2011):  5 files changed,   82 insertions(+), 16 deletions(-)

you went back to the middle solution again which is the worst of them
- why?

In short, design for the future and implement now. I'll elaborate a bit more below.

Quoted 2 lines

If you want this to be a stupid, limited hack then go for the v1 bitmask.

I only aim for the finest!

(bitmasks were bad for the other consumers of this patch series:
socketcall mulitplexing issues and ioctl # filtering).

Quoted 5 lines

If you agree with my observation that filters allow the clean user-space implementation of LSM equivalent security solutions (of which sandboxes are just a *narrow special case*) then please use the main highlevel abstraction we have defined around them: event filters.

I agree that LSM-equivalent security solutions can be moved over to an ftrace based infrastructure. However, LSMs and seccomp have different semantics. Reducing the kernel attack surface in a "sandboxing"-sort-of-way requires a default-deny interface that is resilient to kernel changes (like new system calls) without immediately degrading robustness. LSMs provide a fail-open mechanism for taking an active role in kernel-defined pinch points. It is possible to implement a default-deny LSM, but it requires a "hook" for every security event and the addition of a security event results in a hole in the not-so-default-deny infrastructure. ftrace + event filters are the same.

Based on my observations while exploring the code, it appears that the LSM security_* calls could easily become active trace events and the LSM infrastructure moved over to use those as tracepoints or via event_filters. There will be a need for new predicates for the various new types (inode *, etc), and so on. However, the trace_sys_enter/__secure_computing model will still be a special case.
Even if they fed into security event subsystem or something like
that, the absence of filters on a traced process would need to default-deny as well as when there are no active matches. So while a brand-new shared ABI may be possible (security_event_open, active_event_open, ?), there will still be trickiness in making the behaviors not have implicit side effects and ensure that newly added system calls, for instance, that lack the macro wrapper don't poke a hole in the "sandbox" model. There are a lot of options for designing it though. Like making TIF_SECCOMP mean that any security_* filter failure or match count of 0 == process death. It's just that designing this new approach will be incredibly hairy, and we really lack many of the concrete requirements that would be needed, in my opinion.

Quoted 5 lines

Now, my observation was not uncontested so let me try to sum up the rather large discussion that erupted around it, as i see it.

I saw four main counter arguments:

Quoted 7 lines

 - "Sandboxing is special and should stay separate from LSMs."

  I think this is a technically bogus argument, see:

        https://lkml.org/lkml/2011/5/26/85

  That answer of mine went unchallenged.

I may have spoken to this above. I dunno.

Quoted 11 lines

 - "Events should only be observers."

  Even ignoring the question of why on earth it should be a problem for a willing call-site to use event filtering results sensibly, this argument misses the plain fact that events are *already* active participants, see:

        http://www.spinics.net/lists/mips/msg41075.html

  That answer of mine went unchallenged too.

Quoted 7 lines

 - "This feature is too simplistic."

  That's wrong i think, the feature is highly flexible:

        http://www.mail-archive.com/[email protected]/msg51387.html

  This reply of mine went unchallenged as well.

Well I did only implement a PoC. It couldn't handle attack surface reduction after-the-fact, nor did I add a GET_FILTER call, etc. The code was minimal in many ways because the functionality was too.

Quoted 10 lines

 - "Is this feature actually useful enough for applications, does it justify the complexity?"

 This is the *only* valid technical counter-argument i saw, and it's a crutial one that is not fully answered yet. Since i think the feature is an LSM equivalent i think it's at least as useful as any LSM is.

 - [ if i missed any important argument then someone please insert it here. ]

Quoted 8 lines

But what you do here is to use the filter engine directly which is both a limited hack *and* complex (beyond the linecount it doubles our ABI exposure, amongst other things), so i find that approach rather counter-productive, now that i've seen the real thing.

Will this feature be just another example of the LSM status quo dragging down a newcomer into the mud, until it's just as sucky and limited as any existing LSMs? That would be a sad outcome!

I hope not. I believe it will be easy to move the backend of seccomp_filter over to a per-task ftrace event filter infrastructure when that comes in the future. But for now, I'm trying to meet the needs of possible consumers now: chromium, qemu, lxc, and lay groundwork for a ftrace-future.

If this is a total fail, then perhaps we should have a separate discussion over how we can tackle a lot of these needs. I was hoping that we could push some of that off to the LinuxSecuritySummit -- I've proposed/requested a QA panel on this topic :) But I'd love to not wait until then for everything.

Quoted 2 lines

ps. Please start a new discussion thread for the next iteration! This one is *way* too deep already.

Sorry - will do!

thanks!
will

#98 lore raw
Quoted 6 lines · Will Drewry
Quoted 5 lines

If you agree with my observation that filters allow the clean user-space implementation of LSM equivalent security solutions (of which sandboxes are just a *narrow special case*) then please use the main highlevel abstraction we have defined around them:
event filters.

Quoted 6 lines

I agree that LSM-equivalent security solutions can be moved over to an ftrace based infrastructure. However, LSMs and seccomp have different semantics. Reducing the kernel attack surface in a "sandboxing"-sort-of-way requires a default-deny interface that is resilient to kernel changes (like new system calls) without immediately degrading robustness. [...]

Correct. Because seccomp is the user of those syscall-surface events it can use them in such a way - i see no problem there: unknown or not permitted syscalls get denied for seccomp-mode-2 tasks.

Quoted 6 lines

[...] LSMs provide a fail-open mechanism for taking an active role in kernel-defined pinch points. It is possible to implement a default-deny LSM, but it requires a "hook" for every security event and the addition of a security event results in a hole in the not-so-default-deny infrastructure. ftrace + event filters are the same.

Well, i only suggested that it's LSM-equivalent security functionality, i did not suggest that you should implement an LSM in security/. I do not think the LSM modularization is particularly well fit for seccomp.

Quoted 7 lines

Based on my observations while exploring the code, it appears that the LSM security_* calls could easily become active trace events and the LSM infrastructure moved over to use those as tracepoints or via event_filters. There will be a need for new predicates for the various new types (inode *, etc), and so on. However, the trace_sys_enter/__secure_computing model will still be a special case.

Yes, and that special event will not go away!

I did not suggest to *replace* those events with the security events. I suggested to *combine* them - or at least have a model that smoothly extends to those events as well and does not limit itself to the syscall surface alone.

We'll want to have both.

But by hardcoding to only those events, and creating a syscall-numbering special ABI, a wall will be risen between this implementation and any future enhancement to cover other events. My suggestion would be to use the event filter approach - that way there's not a wall but an open door towards future extensions ;-)

Thanks,

Ingo

author reviewer
#99 lore raw
Quoted 3 lines · Ingo Molnar

* Will Drewry <[email protected]> wrote:

[...]

Quoted 16 lines
Quoted 8 lines

Based on my observations while exploring the code, it appears that the LSM security_* calls could easily become active trace events and the LSM infrastructure moved over to use those as tracepoints or via event_filters.  There will be a need for new predicates for the various new types (inode *, etc), and so on.  However, the trace_sys_enter/__secure_computing model will still be a special case.

Yes, and that special event will not go away!

I did not suggest to *replace* those events with the security events. I suggested to *combine* them - or at least have a model that smoothly extends to those events as well and does not limit itself to the syscall surface alone.

Quoted 7 lines

We'll want to have both.

But by hardcoding to only those events, and creating a syscall-numbering special ABI, a wall will be risen between this implementation and any future enhancement to cover other events. My suggestion would be to use the event filter approach - that way there's not a wall but an open door towards future extensions ;-)

Yeah, I can definitely see that. We could have the prctl interface take in the event id, but that introduces dependency on CONFIG_PERF_EVENTS in addition
(to get the id exported) and means we'll have much more limited coverage of syscalls until the syscall wrapping matures.

Could this be resolved in the proposed change by supporting both mechanisms? Or is that just asking for trouble?

E.g., it could be an extra field:
prctl(PR_SET_SECCOMP_FILTER, PR_SECCOMP_FILTER_TYPE_EVENT, event_id,
filter_string);
prctl(PR_SET_SECCOMP_FILTER, PR_SECCOMP_FILTER_TYPE_SYSCALL,
__NR_somesyscall, filter_string);
[and the same for CLEAR_FILTER and GET_FILTER]

or even reserve negative values for event ids and positive for syscalls (which feels more hackish). Adding event_id support wouldn't be much more additional code (since it's just a layer of dereferencing). Since there will likely be syscall-indexed entry behavior no matter what (like there is for ftrace/perf_sysenter), it won't necessarily be a large diversion in the future either.

If not, seccomp_filter could depend on both FTRACE_SYSCALLS and exported PERF_EVENTS (or make "id"s not perf_event specific), then it could just use the sys_enter event ids. Doing so does have some other properties that I'm not as fond of, like requiring debugfs to be compiled in, mounted, and readable by the caller in order to construct a filterset, so I can still see some benefit for the syscall number use in some cases (much easier to deploy on a server without debugfs access, etc). Right now, having both interfaces doesn't really give us anything, but having the field set aside for future exploration isn't necessarily a bad thing!

What do you think? Would a change to support both be too crazy/dumb or just crazy/dumb enough? Or do you see another path that could avoid isolating any current work from a more fruitful future?

thanks!
will

author reviewer
#100 lore raw

PATCH v3 3/13 seccomp_filters: new mode with configurable syscall filters

In reply to Will Drewry

This change adds a new seccomp mode which specifies the allowed system calls dynamically. When in the new mode (2), all system calls are checked against process-defined filters - first by system call number, then by a filter string. If an entry exists for a given system call and all filter predicates evaluate to true, then the task may proceed. Otherwise, the task is killed.

Filter string parsing and evaluation is handled by the ftrace filter engine. Related patches tweak to the perf filter trace and free allowing the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which already populates this information in syscall_metadata associated enter_event (and exit_event) structures. If CONFIG_FTRACE_SYSCALLS is not compiled in, only filter strings of "1" will be allowed.

The net result is a process may have its system calls filtered using the ftrace filter engine's inherent understanding of systems calls. The set of filters is specified through the PR_SET_SECCOMP_FILTER argument in prctl(). For example, a filterset for a process, like pdftotext, that should only process read-only input could (roughly) look like:
sprintf(rdonly, "flags == %u", O_RDONLY|O_LARGEFILE); prctl(PR_SET_SECCOMP_FILTER, __NR_open, rdonly); prctl(PR_SET_SECCOMP_FILTER, __NR__llseek, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_brk, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_close, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_exit_group, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_fstat64, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_mmap2, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_munmap, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_write, "(fd == 1 | fd == 2)"); prctl(PR_SET_SECCOMP, 2);

Subsequent calls to PR_SET_SECCOMP_FILTER for the same system call will be &&'d together to ensure that attack surface may only be reduced:
prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd != 2");

With the earlier example, the active filter becomes:
"(fd == 1 || fd == 2) && fd != 2"

The patch also adds PR_CLEAR_SECCOMP_FILTER and PR_GET_SECCOMP_FILTER. The latter returns the current filter for a system call to userspace:

  prctl(PR_GET_SECCOMP_FILTER, __NR_write, buf, bufsize);

while the former clears any filters for a given system call changing it back to a defaulty deny:

  prctl(PR_CLEAR_SECCOMP_FILTER, __NR_write);

v3: - always block execve calls (as per linus torvalds)
- add __NR_seccomp_execve(_32) to seccomp-supporting arches
- ensure compat tasks can't reach ftrace:syscalls
- dropped new defines for seccomp modes.
- two level array instead of hlists (sugg. by olof johansson)
- added generic Kconfig entry that is not connected.
- dropped internal seccomp.h
- move prctl helpers to seccomp_filter
- killed seccomp_t typedef (as per checkpatch)
v2: - changed to use the existing syscall number ABI.
- prctl changes to minimize parsing in the kernel:
prctl(PR_SET_SECCOMP, {0 | 1 | 2 }, { 0 | ON_EXEC }); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 5"); prctl(PR_CLEAR_SECCOMP_FILTER, __NR_read); prctl(PR_GET_SECCOMP_FILTER, __NR_read, buf, bufsize);
- defined PR_SECCOMP_MODE_STRICT and ..._FILTER
- added flags
- provide a default fail syscall_nr_to_meta in ftrace
- provides fallback for unhooked system calls
- use -ENOSYS and ERR_PTR(-ENOSYS) for stubbed functionality
- added kernel/seccomp.h to share seccomp.c/seccomp_filter.c
- moved to a hlist and 4 bit hash of linked lists
- added support to operate without CONFIG_FTRACE_SYSCALLS
- moved Kconfig support next to SECCOMP
- made Kconfig entries dependent on EXPERIMENTAL
- added macros to avoid ifdefs from kernel/fork.c
- added compat task/filter matching
- drop seccomp.h inclusion in sched.h and drop seccomp_t
- added Filtering to "show" output
- added on_exec state dup'ing when enabling after a fast-path accept.

---
 include/linux/prctl.h   |    5 +
 include/linux/sched.h   |    2 +-
 include/linux/seccomp.h |   98 ++++++-
 include/trace/syscall.h |    7 +
 kernel/Makefile         |    3 +
 kernel/fork.c           |    3 +
 kernel/seccomp.c        |   38 ++-
 kernel/seccomp_filter.c |  784 +++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sys.c            |   13 +-
 security/Kconfig        |   17 +
 10 files changed, 954 insertions(+), 16 deletions(-)
 create mode 100644 kernel/seccomp_filter.c
include/linux/prctl.h +5 -0
index a3baeb2..44723ce 100644
@@ -64,6 +64,11 @@
 #define PR_GET_SECCOMP	21
 #define PR_SET_SECCOMP	22
 
+/* Get/set process seccomp filters */
+#define PR_GET_SECCOMP_FILTER	35
+#define PR_SET_SECCOMP_FILTER	36
+#define PR_CLEAR_SECCOMP_FILTER	37
+
 /* Get/set the capability bounding set (as per security/commoncap.c) */
 #define PR_CAPBSET_READ 23
 #define PR_CAPBSET_DROP 24
include/linux/sched.h +1 -1
index 18d63ce..3f0bc8d 100644
@@ -1374,7 +1374,7 @@ struct task_struct {
 	uid_t loginuid;
 	unsigned int sessionid;
 #endif
-	seccomp_t seccomp;
+	struct seccomp_struct seccomp;
 
 /* Thread group tracking */
    	u32 parent_exec_id;
include/linux/seccomp.h +93 -5

132 lines not on this page · raw message

include/trace/syscall.h +7 -0
index 242ae04..e061ad0 100644
@@ -35,6 +35,8 @@ struct syscall_metadata {
 extern unsigned long arch_syscall_addr(int nr);
 extern int init_syscall_trace(struct ftrace_event_call *call);
 
+extern struct syscall_metadata *syscall_nr_to_meta(int);
+
 extern int reg_event_syscall_enter(struct ftrace_event_call *call);
 extern void unreg_event_syscall_enter(struct ftrace_event_call *call);
 extern int reg_event_syscall_exit(struct ftrace_event_call *call);
@@ -49,6 +51,11 @@ enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
 				      struct trace_event *event);
 enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
 				     struct trace_event *event);
+#else
+static inline struct syscall_metadata *syscall_nr_to_meta(int nr)
+{
+	return NULL;
+}
 #endif
 
 #ifdef CONFIG_PERF_EVENTS
kernel/Makefile +3 -0
index 85cbfb3..84e7dfb 100644
@@ -81,6 +81,9 @@ obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o
 obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
 obj-$(CONFIG_GENERIC_HARDIRQS) += irq/
 obj-$(CONFIG_SECCOMP) += seccomp.o
+ifeq ($(CONFIG_SECCOMP_FILTER),y)
+obj-$(CONFIG_SECCOMP) += seccomp_filter.o
+endif
 obj-$(CONFIG_RCU_TORTURE_TEST) += rcutorture.o
 obj-$(CONFIG_TREE_RCU) += rcutree.o
 obj-$(CONFIG_TREE_PREEMPT_RCU) += rcutree.o
kernel/fork.c +3 -0
index e7548de..6f835e0 100644
@@ -34,6 +34,7 @@
 #include <linux/cgroup.h>
 #include <linux/security.h>
 #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
 #include <linux/swap.h>
 #include <linux/syscalls.h>
 #include <linux/jiffies.h>
@@ -169,6 +170,7 @@ void free_task(struct task_struct *tsk)
 	free_thread_info(tsk->stack);
 	rt_mutex_debug_task_free(tsk);
 	ftrace_graph_exit_task(tsk);
+	put_tsk_seccomp(tsk);
 	free_task_struct(tsk);
 }
 EXPORT_SYMBOL(free_task);
@@ -280,6 +282,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
 	if (err)
 		goto out;
 
+	inherit_tsk_seccomp(tsk, orig);
 	setup_thread_stack(tsk, orig);
 	clear_user_return_notifier(tsk);
 	clear_tsk_need_resched(tsk);
kernel/seccomp.c +29 -9
index 57d4b13..0a942be 100644
@@ -2,16 +2,20 @@
  * linux/kernel/seccomp.c
  *
  * Copyright 2004-2005  Andrea Arcangeli <[email protected]>
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
  *
  * This defines a simple but solid secure-computing mode.
  */
 
 #include <linux/seccomp.h>
 #include <linux/sched.h>
+#include <linux/slab.h>
 #include <linux/compat.h>
+#include <linux/unistd.h>
+#include <linux/ftrace_event.h>
 
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
 /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
 
 /*
  * Secure computing mode 1 allows only read/write/exit/sigreturn.
@@ -32,10 +36,9 @@ static int mode1_syscalls_32[] = {
 
 void __secure_computing(int this_syscall)
 {
-	int mode = current->seccomp.mode;
 	int * syscall;
 
-	switch (mode) {
+	switch (current->seccomp.mode) {
 	case 1:
 		syscall = mode1_syscalls;
 #ifdef CONFIG_COMPAT
@@ -47,6 +50,17 @@ void __secure_computing(int this_syscall)
 				return;
 		} while (*++syscall);
 		break;
+#ifdef CONFIG_SECCOMP_FILTER
+	case 2:
+		if (this_syscall >= NR_syscalls || this_syscall < 0)
+			break;
+
+		if (!seccomp_test_filters(this_syscall))
+			return;
+
+		seccomp_filter_log_failure(this_syscall);
+		break;
+#endif
 	default:
 		BUG();
 	}
@@ -71,16 +85,22 @@ long prctl_set_seccomp(unsigned long seccomp_mode)
 	if (unlikely(current->seccomp.mode))
 		goto out;
 
-	ret = -EINVAL;
-	if (seccomp_mode && seccomp_mode <= NR_SECCOMP_MODES) {
-		current->seccomp.mode = seccomp_mode;
-		set_thread_flag(TIF_SECCOMP);
+	ret = 0;
+	switch (seccomp_mode) {
+	case 1:
 #ifdef TIF_NOTSC
 		disable_TSC();
 #endif
-		ret = 0;
+#ifdef CONFIG_SECCOMP_FILTER
+	case 2:
+#endif
+		current->seccomp.mode = seccomp_mode;
+		set_thread_flag(TIF_SECCOMP);
+		break;
+	default:
+		ret = -EINVAL;
 	}
 
- out:
+out:
 	return ret;
 }
kernel/seccomp_filter.c new file +784 -0

784 lines not on this page · raw message

kernel/sys.c +12 -1
index af468ed..ed60d06 100644
@@ -1698,13 +1698,24 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 		case PR_SET_ENDIAN:
 			error = SET_ENDIAN(me, arg2);
 			break;
-
 		case PR_GET_SECCOMP:
 			error = prctl_get_seccomp();
 			break;
 		case PR_SET_SECCOMP:
 			error = prctl_set_seccomp(arg2);
 			break;
+		case PR_SET_SECCOMP_FILTER:
+			error = prctl_set_seccomp_filter(arg2,
+							 (char __user *) arg3);
+			break;
+		case PR_CLEAR_SECCOMP_FILTER:
+			error = prctl_clear_seccomp_filter(arg2);
+			break;
+		case PR_GET_SECCOMP_FILTER:
+			error = prctl_get_seccomp_filter(arg2,
+							 (char __user *) arg3,
+							 arg4);
+			break;
 		case PR_GET_TSC:
 			error = GET_TSC_CTL(arg2);
 			break;
security/Kconfig +17 -0
index 95accd4..c76adf2 100644
@@ -2,6 +2,10 @@
 # Security configuration
 #
 
+# Make seccomp filter Kconfig switch below available
+config HAVE_SECCOMP_FILTER
+       bool
+
 menu "Security options"
 
 config KEYS
@@ -82,6 +86,19 @@ config SECURITY_DMESG_RESTRICT
 
 	  If you are unsure how to answer this question, answer N.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	select SECCOMP
+	depends on HAVE_SECCOMP_FILTER && EXPERIMENTAL
+	help
+	  This kernel feature expands CONFIG_SECCOMP to allow computing
+	  in environments with reduced kernel access dictated by the
+	  application itself through prctl calls.  If
+	  CONFIG_FTRACE_SYSCALLS is available, then system call
+	  argument-based filtering predicates may be used.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 config SECURITY
 	bool "Enable different security models"
 	depends on SYSFS
Signature · 1 line
1.7.0.4
#101 lore raw

Re: [PATCH v3 03/13] seccomp_filters: new mode with configurable syscall filters

Quoted 6 lines · Will Drewry

This change adds a new seccomp mode which specifies the allowed system calls dynamically. When in the new mode (2), all system calls are checked against process-defined filters - first by system call number, then by a filter string. If an entry exists for a given system call and all filter predicates evaluate to true, then the task may proceed. Otherwise, the task is killed.

A few questions below -- I can't say that I understand the RCU usage.

Thanx, Paul

Quoted 821 lines

Filter string parsing and evaluation is handled by the ftrace filter engine. Related patches tweak to the perf filter trace and free allowing the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which already populates this information in syscall_metadata associated enter_event (and exit_event) structures. If CONFIG_FTRACE_SYSCALLS is not compiled in, only filter strings of "1" will be allowed.

The net result is a process may have its system calls filtered using the ftrace filter engine's inherent understanding of systems calls. The set of filters is specified through the PR_SET_SECCOMP_FILTER argument in prctl(). For example, a filterset for a process, like pdftotext, that should only process read-only input could (roughly) look like:
sprintf(rdonly, "flags == %u", O_RDONLY|O_LARGEFILE); prctl(PR_SET_SECCOMP_FILTER, __NR_open, rdonly); prctl(PR_SET_SECCOMP_FILTER, __NR__llseek, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_brk, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_close, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_exit_group, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_fstat64, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_mmap2, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_munmap, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_write, "(fd == 1 | fd == 2)"); prctl(PR_SET_SECCOMP, 2);

Subsequent calls to PR_SET_SECCOMP_FILTER for the same system call will be &&'d together to ensure that attack surface may only be reduced:
prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd != 2");

With the earlier example, the active filter becomes:
"(fd == 1 || fd == 2) && fd != 2"

The patch also adds PR_CLEAR_SECCOMP_FILTER and PR_GET_SECCOMP_FILTER. The latter returns the current filter for a system call to userspace:

  prctl(PR_GET_SECCOMP_FILTER, __NR_write, buf, bufsize);

while the former clears any filters for a given system call changing it back to a defaulty deny:

  prctl(PR_CLEAR_SECCOMP_FILTER, __NR_write);

v3: - always block execve calls (as per linus torvalds)
- add __NR_seccomp_execve(_32) to seccomp-supporting arches
- ensure compat tasks can't reach ftrace:syscalls
- dropped new defines for seccomp modes.
- two level array instead of hlists (sugg. by olof johansson)
- added generic Kconfig entry that is not connected.
- dropped internal seccomp.h
- move prctl helpers to seccomp_filter
- killed seccomp_t typedef (as per checkpatch)
v2: - changed to use the existing syscall number ABI.
- prctl changes to minimize parsing in the kernel:
prctl(PR_SET_SECCOMP, {0 | 1 | 2 }, { 0 | ON_EXEC }); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 5"); prctl(PR_CLEAR_SECCOMP_FILTER, __NR_read); prctl(PR_GET_SECCOMP_FILTER, __NR_read, buf, bufsize);
- defined PR_SECCOMP_MODE_STRICT and ..._FILTER
- added flags
- provide a default fail syscall_nr_to_meta in ftrace
- provides fallback for unhooked system calls
- use -ENOSYS and ERR_PTR(-ENOSYS) for stubbed functionality
- added kernel/seccomp.h to share seccomp.c/seccomp_filter.c
- moved to a hlist and 4 bit hash of linked lists
- added support to operate without CONFIG_FTRACE_SYSCALLS
- moved Kconfig support next to SECCOMP
- made Kconfig entries dependent on EXPERIMENTAL
- added macros to avoid ifdefs from kernel/fork.c
- added compat task/filter matching
- drop seccomp.h inclusion in sched.h and drop seccomp_t
- added Filtering to "show" output
- added on_exec state dup'ing when enabling after a fast-path accept.

---
 include/linux/prctl.h   |    5 +
 include/linux/sched.h   |    2 +-
 include/linux/seccomp.h |   98 ++++++-
 include/trace/syscall.h |    7 +
 kernel/Makefile         |    3 +
 kernel/fork.c           |    3 +
 kernel/seccomp.c        |   38 ++-
 kernel/seccomp_filter.c |  784 +++++++++++++++++++++++++++++++++++++++++++++++
 kernel/sys.c            |   13 +-
 security/Kconfig        |   17 +
 10 files changed, 954 insertions(+), 16 deletions(-)
 create mode 100644 kernel/seccomp_filter.c
include/linux/prctl.h +5 -0
index a3baeb2..44723ce 100644
@@ -64,6 +64,11 @@
 #define PR_GET_SECCOMP	21
 #define PR_SET_SECCOMP	22
 
+/* Get/set process seccomp filters */
+#define PR_GET_SECCOMP_FILTER	35
+#define PR_SET_SECCOMP_FILTER	36
+#define PR_CLEAR_SECCOMP_FILTER	37
+
 /* Get/set the capability bounding set (as per security/commoncap.c) */
 #define PR_CAPBSET_READ 23
 #define PR_CAPBSET_DROP 24
include/linux/sched.h +1 -1
index 18d63ce..3f0bc8d 100644
@@ -1374,7 +1374,7 @@ struct task_struct {
 	uid_t loginuid;
 	unsigned int sessionid;
 #endif
-	seccomp_t seccomp;
+	struct seccomp_struct seccomp;
 
 /* Thread group tracking */
    	u32 parent_exec_id;
include/linux/seccomp.h +93 -5
index 167c333..f4434ca 100644
@@ -1,13 +1,33 @@
 #ifndef _LINUX_SECCOMP_H
 #define _LINUX_SECCOMP_H
 
+struct seq_file;
 
 #ifdef CONFIG_SECCOMP
 
+#include <linux/errno.h>
 #include <linux/thread_info.h>
+#include <linux/types.h>
 #include <asm/seccomp.h>
 
-typedef struct { int mode; } seccomp_t;
+struct seccomp_filters;
+/**
+ * struct seccomp_struct - the state of a seccomp'ed process
+ *
+ * @mode:
+ *     if this is 1, the process is under standard seccomp rules
+ *             is 2, the process is only allowed to make system calls where
+ *                   associated filters evaluate successfully.
+ * @filters: Metadata for filters if using CONFIG_SECCOMP_FILTER.
+ *           filters assignment/use should be RCU-protected and its contents
+ *           should never be modified when attached to a seccomp_struct.
+ */
+struct seccomp_struct {
+	uint16_t mode;
+#ifdef CONFIG_SECCOMP_FILTER
+	struct seccomp_filters *filters;
+#endif
+};
 
 extern void __secure_computing(int);
 static inline void secure_computing(int this_syscall)
@@ -16,15 +36,14 @@ static inline void secure_computing(int this_syscall)
 		__secure_computing(this_syscall);
 }
 
-extern long prctl_get_seccomp(void);
 extern long prctl_set_seccomp(unsigned long);
+extern long prctl_get_seccomp(void);
 
 #else /* CONFIG_SECCOMP */
 
 #include <linux/errno.h>
 
-typedef struct { } seccomp_t;
-
+struct seccomp_struct { };
 #define secure_computing(x) do { } while (0)
 
 static inline long prctl_get_seccomp(void)
@@ -32,11 +51,80 @@ static inline long prctl_get_seccomp(void)
 	return -EINVAL;
 }
 
-static inline long prctl_set_seccomp(unsigned long arg2)
+static inline long prctl_set_seccomp(unsigned long a2);
 {
 	return -EINVAL;
 }
 
 #endif /* CONFIG_SECCOMP */
 
+#ifdef CONFIG_SECCOMP_FILTER
+
+#define inherit_tsk_seccomp(_child, _orig) do { \
+	_child->seccomp.mode = _orig->seccomp.mode; \
+	_child->seccomp.filters = get_seccomp_filters(_orig->seccomp.filters); \
+	} while (0)
+#define put_tsk_seccomp(_tsk) put_seccomp_filters(_tsk->seccomp.filters)
+
+extern int seccomp_show_filters(struct seccomp_filters *filters,
+				struct seq_file *);
+extern long seccomp_set_filter(int, char *);
+extern long seccomp_clear_filter(int);
+extern long seccomp_get_filter(int, char *, unsigned long);
+
+extern long prctl_set_seccomp_filter(unsigned long, char __user *);
+extern long prctl_get_seccomp_filter(unsigned long, char __user *,
+				     unsigned long);
+extern long prctl_clear_seccomp_filter(unsigned long);
+
+extern struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *);
+extern void put_seccomp_filters(struct seccomp_filters *);
+
+extern int seccomp_test_filters(int);
+extern void seccomp_filter_log_failure(int);
+
+#else  /* CONFIG_SECCOMP_FILTER */
+
+struct seccomp_filters { };
+#define inherit_tsk_seccomp(_child, _orig) do { } while (0)
+#define put_tsk_seccomp(_tsk) do { } while (0)
+
+static inline int seccomp_show_filters(struct seccomp_filters *filters,
+				       struct seq_file *m)
+{
+	return -ENOSYS;
+}
+
+static inline long seccomp_set_filter(int syscall_nr, char *filter)
+{
+	return -ENOSYS;
+}
+
+static inline long seccomp_clear_filter(int syscall_nr)
+{
+	return -ENOSYS;
+}
+
+static inline long seccomp_get_filter(int syscall_nr,
+				      char *buf, unsigned long available)
+{
+	return -ENOSYS;
+}
+
+static inline long prctl_set_seccomp_filter(unsigned long a2, char __user *a3)
+{
+	return -ENOSYS;
+}
+
+static inline long prctl_clear_seccomp_filter(unsigned long a2)
+{
+	return -ENOSYS;
+}
+
+static inline long prctl_get_seccomp_filter(unsigned long a2, char __user *a3,
+					    unsigned long a4)
+{
+	return -ENOSYS;
+}
+#endif  /* CONFIG_SECCOMP_FILTER */
 #endif /* _LINUX_SECCOMP_H */
include/trace/syscall.h +7 -0
index 242ae04..e061ad0 100644
@@ -35,6 +35,8 @@ struct syscall_metadata {
 extern unsigned long arch_syscall_addr(int nr);
 extern int init_syscall_trace(struct ftrace_event_call *call);
 
+extern struct syscall_metadata *syscall_nr_to_meta(int);
+
 extern int reg_event_syscall_enter(struct ftrace_event_call *call);
 extern void unreg_event_syscall_enter(struct ftrace_event_call *call);
 extern int reg_event_syscall_exit(struct ftrace_event_call *call);
@@ -49,6 +51,11 @@ enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
 				      struct trace_event *event);
 enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
 				     struct trace_event *event);
+#else
+static inline struct syscall_metadata *syscall_nr_to_meta(int nr)
+{
+	return NULL;
+}
 #endif
 
 #ifdef CONFIG_PERF_EVENTS
kernel/Makefile +3 -0
index 85cbfb3..84e7dfb 100644
@@ -81,6 +81,9 @@ obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o
 obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
 obj-$(CONFIG_GENERIC_HARDIRQS) += irq/
 obj-$(CONFIG_SECCOMP) += seccomp.o
+ifeq ($(CONFIG_SECCOMP_FILTER),y)
+obj-$(CONFIG_SECCOMP) += seccomp_filter.o
+endif
 obj-$(CONFIG_RCU_TORTURE_TEST) += rcutorture.o
 obj-$(CONFIG_TREE_RCU) += rcutree.o
 obj-$(CONFIG_TREE_PREEMPT_RCU) += rcutree.o
kernel/fork.c +3 -0
index e7548de..6f835e0 100644
@@ -34,6 +34,7 @@
 #include <linux/cgroup.h>
 #include <linux/security.h>
 #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
 #include <linux/swap.h>
 #include <linux/syscalls.h>
 #include <linux/jiffies.h>
@@ -169,6 +170,7 @@ void free_task(struct task_struct *tsk)
 	free_thread_info(tsk->stack);
 	rt_mutex_debug_task_free(tsk);
 	ftrace_graph_exit_task(tsk);
+	put_tsk_seccomp(tsk);
 	free_task_struct(tsk);
 }
 EXPORT_SYMBOL(free_task);
@@ -280,6 +282,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
 	if (err)
 		goto out;
 
+	inherit_tsk_seccomp(tsk, orig);
 	setup_thread_stack(tsk, orig);
 	clear_user_return_notifier(tsk);
 	clear_tsk_need_resched(tsk);
kernel/seccomp.c +29 -9
index 57d4b13..0a942be 100644
@@ -2,16 +2,20 @@
  * linux/kernel/seccomp.c
  *
  * Copyright 2004-2005  Andrea Arcangeli <[email protected]>
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
  *
  * This defines a simple but solid secure-computing mode.
  */
 
 #include <linux/seccomp.h>
 #include <linux/sched.h>
+#include <linux/slab.h>
 #include <linux/compat.h>
+#include <linux/unistd.h>
+#include <linux/ftrace_event.h>
 
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
 /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
 
 /*
  * Secure computing mode 1 allows only read/write/exit/sigreturn.
@@ -32,10 +36,9 @@ static int mode1_syscalls_32[] = {
 
 void __secure_computing(int this_syscall)
 {
-	int mode = current->seccomp.mode;
 	int * syscall;
 
-	switch (mode) {
+	switch (current->seccomp.mode) {
 	case 1:
 		syscall = mode1_syscalls;
 #ifdef CONFIG_COMPAT
@@ -47,6 +50,17 @@ void __secure_computing(int this_syscall)
 				return;
 		} while (*++syscall);
 		break;
+#ifdef CONFIG_SECCOMP_FILTER
+	case 2:
+		if (this_syscall >= NR_syscalls || this_syscall < 0)
+			break;
+
+		if (!seccomp_test_filters(this_syscall))
+			return;
+
+		seccomp_filter_log_failure(this_syscall);
+		break;
+#endif
 	default:
 		BUG();
 	}
@@ -71,16 +85,22 @@ long prctl_set_seccomp(unsigned long seccomp_mode)
 	if (unlikely(current->seccomp.mode))
 		goto out;
 
-	ret = -EINVAL;
-	if (seccomp_mode && seccomp_mode <= NR_SECCOMP_MODES) {
-		current->seccomp.mode = seccomp_mode;
-		set_thread_flag(TIF_SECCOMP);
+	ret = 0;
+	switch (seccomp_mode) {
+	case 1:
 #ifdef TIF_NOTSC
 		disable_TSC();
 #endif
-		ret = 0;
+#ifdef CONFIG_SECCOMP_FILTER
+	case 2:
+#endif
+		current->seccomp.mode = seccomp_mode;
+		set_thread_flag(TIF_SECCOMP);
+		break;
+	default:
+		ret = -EINVAL;
 	}
 
- out:
+out:
 	return ret;
 }
kernel/seccomp_filter.c new file +405 -0
new file mode 100644
index 0000000..9782f25
@@ -0,0 +1,784 @@
+/* filter engine-based seccomp system call filtering
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
+ */
+
+#include <linux/compat.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/ftrace_event.h>
+#include <linux/seccomp.h>
+#include <linux/seq_file.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/uaccess.h>
+
+#include <asm/syscall.h>
+#include <trace/syscall.h>
+
+
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
+
+#define SECCOMP_FILTER_ALLOW "1"
+#define SECCOMP_ACTION_DENY 0xffff
+#define SECCOMP_ACTION_ALLOW 0xfffe
+
+/**
+ * struct seccomp_filters - container for seccomp filterset
+ *
+ * @syscalls: array of 16-bit indices into @event_filters by syscall_nr
+ *            May also be SECCOMP_ACTION_DENY or SECCOMP_ACTION_ALLOW
+ * @event_filters: array of pointers to ftrace event objects
+ * @count: size of @event_filters
+ * @flags: anonymous struct to wrap filters-specific flags
+ * @usage: reference count to simplify use.
+ */
+struct seccomp_filters {
+	uint16_t syscalls[NR_syscalls];
+	struct event_filter **event_filters;
+	uint16_t count;
+	struct {
+		uint32_t compat:1,
+			 __reserved:31;
+	} flags;
+	atomic_t usage;
+};
+
+/* Handle ftrace symbol non-existence */
+#ifdef CONFIG_FTRACE_SYSCALLS
+#define create_event_filter(_ef_pptr, _event_type, _str) \
+	ftrace_parse_filter(_ef_pptr, _event_type, _str)
+#define get_filter_string(_ef) ftrace_get_filter_string(_ef)
+#define free_event_filter(_f) ftrace_free_filter(_f)
+
+#else
+
+#define create_event_filter(_ef_pptr, _event_type, _str) (-ENOSYS)
+#define get_filter_string(_ef) (NULL)
+#define free_event_filter(_f) do { } while (0)
+#endif
+
+/**
+ * seccomp_filters_new - allocates a new filters object
+ * @count: count to allocate for the event_filters array
+ *
+ * Returns ERR_PTR on error or an allocated object.
+ */
+static struct seccomp_filters *seccomp_filters_new(uint16_t count)
+{
+	struct seccomp_filters *f;
+
+	if (count >= SECCOMP_ACTION_ALLOW)
+		return ERR_PTR(-EINVAL);
+
+	f = kzalloc(sizeof(struct seccomp_filters), GFP_KERNEL);
+	if (!f)
+		return ERR_PTR(-ENOMEM);
+
+	/* Lazy SECCOMP_ACTION_DENY assignment. */
+	memset(f->syscalls, 0xff, sizeof(f->syscalls));
+	atomic_set(&f->usage, 1);
+
+	f->event_filters = NULL;
+	f->count = count;
+	if (!count)
+		return f;
+
+	f->event_filters = kzalloc(count * sizeof(struct event_filter *),
+				   GFP_KERNEL);
+	if (!f->event_filters) {
+		kfree(f);
+		f = ERR_PTR(-ENOMEM);
+	}
+	return f;
+}
+
+/**
+ * seccomp_filters_free - cleans up the filter list and frees the table
+ * @filters: NULL or live object to be completely destructed.
+ */
+static void seccomp_filters_free(struct seccomp_filters *filters)
+{
+	uint16_t count = 0;
+	if (!filters)
+		return;
+	while (count < filters->count) {
+		struct event_filter *f = filters->event_filters[count];
+		free_event_filter(f);
+		count++;
+	}
+	kfree(filters->event_filters);
+	kfree(filters);
+}
+
+static void __put_seccomp_filters(struct seccomp_filters *orig)
+{
+	WARN_ON(atomic_read(&orig->usage));
+	seccomp_filters_free(orig);
+}
+
+#define seccomp_filter_allow(_id) ((_id) == SECCOMP_ACTION_ALLOW)
+#define seccomp_filter_deny(_id) ((_id) == SECCOMP_ACTION_DENY)
+#define seccomp_filter_dynamic(_id) \
+	(!seccomp_filter_allow(_id) && !seccomp_filter_deny(_id))
+static inline uint16_t seccomp_filter_id(const struct seccomp_filters *f,
+					 int syscall_nr)
+{
+	if (!f)
+		return SECCOMP_ACTION_DENY;
+	return f->syscalls[syscall_nr];
+}
+
+static inline struct event_filter *seccomp_dynamic_filter(
+		const struct seccomp_filters *filters, uint16_t id)
+{
+	if (!seccomp_filter_dynamic(id))
+		return NULL;
+	return filters->event_filters[id];
+}
+
+static inline void set_seccomp_filter_id(struct seccomp_filters *filters,
+					 int syscall_nr, uint16_t id)
+{
+	filters->syscalls[syscall_nr] = id;
+}
+
+static inline void set_seccomp_filter(struct seccomp_filters *filters,
+				      int syscall_nr, uint16_t id,
+				      struct event_filter *dynamic_filter)
+{
+	filters->syscalls[syscall_nr] = id;
+	if (seccomp_filter_dynamic(id))
+		filters->event_filters[id] = dynamic_filter;
+}
+
+static struct event_filter *alloc_event_filter(int syscall_nr,
+					       const char *filter_string)
+{
+	struct syscall_metadata *data;
+	struct event_filter *filter = NULL;
+	int err;
+
+	data = syscall_nr_to_meta(syscall_nr);
+	/* Argument-based filtering only works on ftrace-hooked syscalls. */
+	err = -ENOSYS;
+	if (!data)
+		goto fail;
+	err = create_event_filter(&filter,
+				  data->enter_event->event.type,
+				  filter_string);
+	if (err)
+		goto fail;
+
+	return filter;
+fail:
+	kfree(filter);
+	return ERR_PTR(err);
+}
+
+/**
+ * seccomp_filters_copy - copies filters from src to dst.
+ *
+ * @dst: seccomp_filters to populate.
+ * @src: table to read from.
+ * @skip: specifies an entry, by system call, to skip.
+ *
+ * Returns non-zero on failure.
+ * Both the source and the destination should have no simultaneous
+ * writers, and dst should be exclusive to the caller.
+ * If @skip is < 0, it is ignored.
+ */
+static int seccomp_filters_copy(struct seccomp_filters *dst,
+				const struct seccomp_filters *src,
+				int skip)
+{
+	int id = 0, ret = 0, nr;
+	memcpy(&dst->flags, &src->flags, sizeof(src->flags));
+	memcpy(dst->syscalls, src->syscalls, sizeof(dst->syscalls));
+	if (!src->count)
+		goto done;
+	for (nr = 0; nr < NR_syscalls; ++nr) {
+		struct event_filter *filter;
+		const char *str;
+		uint16_t src_id = seccomp_filter_id(src, nr);
+		if (nr == skip) {
+			set_seccomp_filter(dst, nr, SECCOMP_ACTION_DENY,
+					   NULL);
+			continue;
+		}
+		if (!seccomp_filter_dynamic(src_id))
+			continue;
+		if (id >= dst->count) {
+			ret = -EINVAL;
+			goto done;
+		}
+		str = get_filter_string(seccomp_dynamic_filter(src, src_id));
+		filter = alloc_event_filter(nr, str);
+		if (IS_ERR(filter)) {
+			ret = PTR_ERR(filter);
+			goto done;
+		}
+		set_seccomp_filter(dst, nr, id, filter);
+		id++;
+	}
+
+done:
+	return ret;
+}
+
+/**
+ * seccomp_extend_filter - appends more text to a syscall_nr's filter
+ * @filters: unattached filter object to operate on
+ * @syscall_nr: syscall number to update filters for
+ * @filter_string: string to append to the existing filter
+ *
+ * The new string will be &&'d to the original filter string to ensure that it
+ * always matches the existing predicates or less:
+ *   (old_filter) && @filter_string
+ * A new seccomp_filters instance is returned on success and a ERR_PTR on
+ * failure.
+ */
+static int seccomp_extend_filter(struct seccomp_filters *filters,
+				 int syscall_nr, char *filter_string)
+{
+	struct event_filter *filter;
+	uint16_t id = seccomp_filter_id(filters, syscall_nr);
+	char *merged = NULL;
+	int ret = -EINVAL, expected;
+
+	/* No extending with a "1". */
+	if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string))
+		goto out;
+
+	filter = seccomp_dynamic_filter(filters, id);
+	ret = -ENOENT;
+	if (!filter)
+		goto out;
+
+	merged = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+	ret = -ENOMEM;
+	if (!merged)
+		goto out;
+
+	expected = snprintf(merged, SECCOMP_MAX_FILTER_LENGTH, "(%s) && %s",
+			    get_filter_string(filter), filter_string);
+	ret = -E2BIG;
+	if (expected >= SECCOMP_MAX_FILTER_LENGTH || expected < 0)
+		goto out;
+
+	/* Free the old filter */
+	free_event_filter(filter);
+	set_seccomp_filter(filters, syscall_nr, id, NULL);
+
+	/* Replace it */
+	filter = alloc_event_filter(syscall_nr, merged);
+	if (IS_ERR(filter)) {
+		ret = PTR_ERR(filter);
+		goto out;
+	}
+	set_seccomp_filter(filters, syscall_nr, id, filter);
+	ret = 0;
+
+out:
+	kfree(merged);
+	return ret;
+}
+
+/**
+ * seccomp_add_filter - adds a filter for an unfiltered syscall
+ * @filters: filters object to add a filter/action to
+ * @syscall_nr: system call number to add a filter for
+ * @filter_string: the filter string to apply
+ *
+ * Returns 0 on success and non-zero otherwise.
+ */
+static int seccomp_add_filter(struct seccomp_filters *filters, int syscall_nr,
+			      char *filter_string)
+{
+	struct event_filter *filter;
+	int ret = 0;
+
+	if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string)) {
+		set_seccomp_filter(filters, syscall_nr,
+				   SECCOMP_ACTION_ALLOW, NULL);
+		goto out;
+	}
+
+	filter = alloc_event_filter(syscall_nr, filter_string);
+	if (IS_ERR(filter)) {
+		ret = PTR_ERR(filter);
+		goto out;
+	}
+	/* Always add to the last slot available since additions are
+	 * are only done one at a time.
+	 */
+	set_seccomp_filter(filters, syscall_nr, filters->count - 1, filter);
+out:
+	return ret;
+}
+
+/* Wrap optional ftrace syscall support. Returns 1 on match or 0 otherwise. */
+static int filter_match_current(struct event_filter *event_filter)
+{
+	int err = 0;
+#ifdef CONFIG_FTRACE_SYSCALLS
+	uint8_t syscall_state[64];
+
+	memset(syscall_state, 0, sizeof(syscall_state));
+
+	/* The generic tracing entry can remain zeroed. */
+	err = ftrace_syscall_enter_state(syscall_state, sizeof(syscall_state),
+					 NULL);
+	if (err)
+		return 0;
+
+	err = filter_match_preds(event_filter, syscall_state);
+#endif
+	return err;
+}
+
+static const char *syscall_nr_to_name(int syscall)
+{
+	const char *syscall_name = "unknown";
+	struct syscall_metadata *data = syscall_nr_to_meta(syscall);
+	if (data)
+		syscall_name = data->name;
+	return syscall_name;
+}
+
+static void filters_set_compat(struct seccomp_filters *filters)
+{
+#ifdef CONFIG_COMPAT
+	if (is_compat_task())
+		filters->flags.compat = 1;
+#endif
+}
+
+static inline int filters_compat_mismatch(struct seccomp_filters *filters)
+{
+	int ret = 0;
+	if (!filters)
+		return 0;
+#ifdef CONFIG_COMPAT
+	if (!!(is_compat_task()) == filters->flags.compat)
+		ret = 1;
+#endif
+	return ret;
+}
+
+static inline int syscall_is_execve(int syscall)
+{
+	int nr = __NR_execve;
+#ifdef CONFIG_COMPAT
+	if (is_compat_task())
+		nr = __NR_seccomp_execve_32;
+#endif
+	return syscall == nr;
+}
+
+#ifndef KSTK_EIP
+#define KSTK_EIP(x) 0L
+#endif
+
+void seccomp_filter_log_failure(int syscall)
+{
+	pr_info("%s[%d]: system call %d (%s) blocked at 0x%lx\n",
+		current->comm, task_pid_nr(current), syscall,
+		syscall_nr_to_name(syscall), KSTK_EIP(current));
+}
+
+/* put_seccomp_state - decrements the reference count of @orig and may free. */
+void put_seccomp_filters(struct seccomp_filters *orig)

kernel/seccomp_filter.c line 415

Quoted 10 lines
kernel/seccomp_filter.c new file +10 -0
+{
+	if (!orig)
+		return;
+
+	if (atomic_dec_and_test(&orig->usage))
+		__put_seccomp_filters(orig);
+}
+
+/* get_seccomp_state - increments the reference count of @orig */
+struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *orig)

Nit: the name does not match the comment.

kernel/seccomp_filter.c line 420

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+{
+	if (!orig)
+		return NULL;
+	atomic_inc(&orig->usage);
+	return orig;

This is called in an RCU read-side critical section. What exactly is RCU protecting? I would expect an rcu_dereference() or one of the RCU list-traversal primitives somewhere, either here or at the caller.

Quoted 179 lines
kernel/seccomp_filter.c new file +179 -0
+}
+
+/**
+ * seccomp_test_filters - tests 'current' against the given syscall
+ * @state: seccomp_state of current to use.
+ * @syscall: number of the system call to test
+ *
+ * Returns 0 on ok and non-zero on error/failure.
+ */
+int seccomp_test_filters(int syscall)
+{
+	uint16_t id;
+	struct event_filter *filter;
+	struct seccomp_filters *filters;
+	int ret = -EACCES;
+
+	rcu_read_lock();
+	filters = get_seccomp_filters(current->seccomp.filters);
+	rcu_read_unlock();
+
+	if (!filters)
+		goto out;
+
+	if (filters_compat_mismatch(filters)) {
+		pr_info("%s[%d]: seccomp_filter compat() mismatch.\n",
+			current->comm, task_pid_nr(current));
+		goto out;
+	}
+
+	/* execve is never allowed. */
+	if (syscall_is_execve(syscall))
+		goto out;
+
+	ret = 0;
+	id = seccomp_filter_id(filters, syscall);
+	if (seccomp_filter_allow(id))
+		goto out;
+
+	ret = -EACCES;
+	if (!seccomp_filter_dynamic(id))
+		goto out;
+
+	filter = seccomp_dynamic_filter(filters, id);
+	if (filter && filter_match_current(filter))
+		ret = 0;
+out:
+	put_seccomp_filters(filters);
+	return ret;
+}
+
+/**
+ * seccomp_show_filters - prints the current filter state to a seq_file
+ * @filters: properly get()'d filters object
+ * @m: the prepared seq_file to receive the data
+ *
+ * Returns 0 on a successful write.
+ */
+int seccomp_show_filters(struct seccomp_filters *filters, struct seq_file *m)
+{
+	int syscall;
+	seq_printf(m, "Mode: %d\n", current->seccomp.mode);
+	if (!filters)
+		goto out;
+
+	for (syscall = 0; syscall < NR_syscalls; ++syscall) {
+		uint16_t id = seccomp_filter_id(filters, syscall);
+		const char *filter_string = SECCOMP_FILTER_ALLOW;
+		if (seccomp_filter_deny(id))
+			continue;
+		seq_printf(m, "%d (%s): ",
+			      syscall,
+			      syscall_nr_to_name(syscall));
+		if (seccomp_filter_dynamic(id))
+			filter_string = get_filter_string(
+					  seccomp_dynamic_filter(filters, id));
+		seq_printf(m, "%s\n", filter_string);
+	}
+out:
+	return 0;
+}
+EXPORT_SYMBOL_GPL(seccomp_show_filters);
+
+/**
+ * seccomp_get_filter - copies the filter_string into "buf"
+ * @syscall_nr: system call number to look up
+ * @buf: destination buffer
+ * @bufsize: available space in the buffer.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Looks up the filter for the given system call number on current.  If found,
+ * the string length of the NUL-terminated buffer is returned and < 0 is
+ * returned on error. The NUL byte is not included in the length.
+ */
+long seccomp_get_filter(int syscall_nr, char *buf, unsigned long bufsize)
+{
+	struct seccomp_filters *filters;
+	struct event_filter *filter;
+	long ret = -EINVAL;
+	uint16_t id;
+
+	if (bufsize > SECCOMP_MAX_FILTER_LENGTH)
+		bufsize = SECCOMP_MAX_FILTER_LENGTH;
+
+	rcu_read_lock();
+	filters = get_seccomp_filters(current->seccomp.filters);
+	rcu_read_unlock();
+
+	if (!filters)
+		goto out;
+
+	ret = -ENOENT;
+	id = seccomp_filter_id(filters, syscall_nr);
+	if (seccomp_filter_deny(id))
+		goto out;
+
+	if (seccomp_filter_allow(id)) {
+		ret = strlcpy(buf, SECCOMP_FILTER_ALLOW, bufsize);
+		goto copied;
+	}
+
+	filter = seccomp_dynamic_filter(filters, id);
+	if (!filter)
+		goto out;
+	ret = strlcpy(buf, get_filter_string(filter), bufsize);
+
+copied:
+	if (ret >= bufsize) {
+		ret = -ENOSPC;
+		goto out;
+	}
+	/* Zero out any remaining buffer, just in case. */
+	memset(buf + ret, 0, bufsize - ret);
+out:
+	put_seccomp_filters(filters);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_get_filter);
+
+/**
+ * seccomp_clear_filter: clears the seccomp filter for a syscall.
+ * @syscall_nr: the system call number to clear filters for.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Returns 0 on success.
+ */
+long seccomp_clear_filter(int syscall_nr)
+{
+	struct seccomp_filters *filters = NULL, *orig_filters;
+	uint16_t id;
+	int ret = -EINVAL;
+
+	rcu_read_lock();
+	orig_filters = get_seccomp_filters(current->seccomp.filters);
+	rcu_read_unlock();
+
+	if (!orig_filters)
+		goto out;
+
+	if (filters_compat_mismatch(orig_filters))
+		goto out;
+
+	id = seccomp_filter_id(orig_filters, syscall_nr);
+	if (seccomp_filter_deny(id))
+		goto out;
+
+	/* Create a new filters object for the task */
+	if (seccomp_filter_dynamic(id))
+		filters = seccomp_filters_new(orig_filters->count - 1);
+	else
+		filters = seccomp_filters_new(orig_filters->count);
+
+	if (IS_ERR(filters)) {
+		ret = PTR_ERR(filters);

kernel/seccomp_filter.c line 609

Quoted 10 lines
kernel/seccomp_filter.c new file +10 -0
+		goto out;
+	}
+
+	/* Copy, but drop the requested entry. */
+	ret = seccomp_filters_copy(filters, orig_filters, syscall_nr);
+	if (ret)
+		goto out;
+	get_seccomp_filters(filters);  /* simplify the out: path */
+
+	rcu_assign_pointer(current->seccomp.filters, filters);

What prevents two copies of seccomp_clear_filter() from running concurrently?

Quoted 70 lines
kernel/seccomp_filter.c new file +70 -0
+	synchronize_rcu();
+	put_seccomp_filters(orig_filters);  /* for the task */
+out:
+	put_seccomp_filters(orig_filters);  /* for the get */
+	put_seccomp_filters(filters);  /* for the extra get */
+	return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_clear_filter);
+
+/**
+ * seccomp_set_filter: - Adds/extends a seccomp filter for a syscall.
+ * @syscall_nr: system call number to apply the filter to.
+ * @filter: ftrace filter string to apply.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * New filters may be added for system calls when the current task is
+ * not in a secure computing mode (seccomp).  Otherwise, existing filters may
+ * be extended.
+ *
+ * Returns 0 on success or an errno on failure.
+ */
+long seccomp_set_filter(int syscall_nr, char *filter)
+{
+	struct seccomp_filters *filters = NULL, *orig_filters = NULL;
+	uint16_t id;
+	long ret = -EINVAL;
+	uint16_t filters_needed;
+
+	if (!filter)
+		goto out;
+
+	filter = strstrip(filter);
+	/* Disallow empty strings. */
+	if (filter[0] == 0)
+		goto out;
+
+	rcu_read_lock();
+	orig_filters = get_seccomp_filters(current->seccomp.filters);
+	rcu_read_unlock();
+
+	/* After the first call, compatibility mode is selected permanently. */
+	ret = -EACCES;
+	if (filters_compat_mismatch(orig_filters))
+		goto out;
+
+	filters_needed = orig_filters ? orig_filters->count : 0;
+	id = seccomp_filter_id(orig_filters, syscall_nr);
+	if (seccomp_filter_deny(id)) {
+		/* Don't allow DENYs to be changed when in a seccomp mode */
+		ret = -EACCES;
+		if (current->seccomp.mode)
+			goto out;
+		filters_needed++;
+	}
+
+	filters = seccomp_filters_new(filters_needed);
+	if (IS_ERR(filters)) {
+		ret = PTR_ERR(filters);
+		goto out;
+	}
+
+	filters_set_compat(filters);
+	if (orig_filters) {
+		ret = seccomp_filters_copy(filters, orig_filters, -1);
+		if (ret)
+			goto out;
+	}

kernel/seccomp_filter.c line 689

Quoted 10 lines
kernel/seccomp_filter.c new file +10 -0
+
+	if (seccomp_filter_deny(id))
+		ret = seccomp_add_filter(filters, syscall_nr, filter);
+	else
+		ret = seccomp_extend_filter(filters, syscall_nr, filter);
+	if (ret)
+		goto out;
+	get_seccomp_filters(filters);  /* simplify the error paths */
+
+	rcu_assign_pointer(current->seccomp.filters, filters);

Again, what prevents two copies of seccomp_set_filter() from running concurrently?

Quoted 168 lines
kernel/seccomp_filter.c new file +95 -0
+	synchronize_rcu();
+	put_seccomp_filters(orig_filters);  /* for the task */
+out:
+	put_seccomp_filters(orig_filters);  /* for the get */
+	put_seccomp_filters(filters);  /* for get or task, on err */
+	return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_set_filter);
+
+long prctl_set_seccomp_filter(unsigned long syscall_nr,
+			      char __user *user_filter)
+{
+	int nr;
+	long ret;
+	char *filter = NULL;
+
+	ret = -EINVAL;
+	if (syscall_nr >= NR_syscalls)
+		goto out;
+
+	ret = -EFAULT;
+	if (!user_filter)
+		goto out;
+
+	filter = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+	ret = -ENOMEM;
+	if (!filter)
+		goto out;
+
+	ret = -EFAULT;
+	if (strncpy_from_user(filter, user_filter,
+			      SECCOMP_MAX_FILTER_LENGTH - 1) < 0)
+		goto out;
+
+	nr = (int) syscall_nr;
+	ret = seccomp_set_filter(nr, filter);
+
+out:
+	kfree(filter);
+	return ret;
+}
+
+long prctl_clear_seccomp_filter(unsigned long syscall_nr)
+{
+	int nr = -1;
+	long ret;
+
+	ret = -EINVAL;
+	if (syscall_nr >= NR_syscalls)
+		goto out;
+
+	nr = (int) syscall_nr;
+	ret = seccomp_clear_filter(nr);
+
+out:
+	return ret;
+}
+
+long prctl_get_seccomp_filter(unsigned long syscall_nr, char __user *dst,
+			      unsigned long available)
+{
+	int ret, nr;
+	unsigned long copied;
+	char *buf = NULL;
+	ret = -EINVAL;
+	if (!available)
+		goto out;
+	/* Ignore extra buffer space. */
+	if (available > SECCOMP_MAX_FILTER_LENGTH)
+		available = SECCOMP_MAX_FILTER_LENGTH;
+
+	ret = -EINVAL;
+	if (syscall_nr >= NR_syscalls)
+		goto out;
+	nr = (int) syscall_nr;
+
+	ret = -ENOMEM;
+	buf = kmalloc(available, GFP_KERNEL);
+	if (!buf)
+		goto out;
+
+	ret = seccomp_get_filter(nr, buf, available);
+	if (ret < 0)
+		goto out;
+
+	/* Include the NUL byte in the copy. */
+	copied = copy_to_user(dst, buf, ret + 1);
+	ret = -ENOSPC;
+	if (copied)
+		goto out;
+	ret = 0;
+out:
+	kfree(buf);
+	return ret;
+}
kernel/sys.c +12 -1
index af468ed..ed60d06 100644
@@ -1698,13 +1698,24 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 		case PR_SET_ENDIAN:
 			error = SET_ENDIAN(me, arg2);
 			break;
-
 		case PR_GET_SECCOMP:
 			error = prctl_get_seccomp();
 			break;
 		case PR_SET_SECCOMP:
 			error = prctl_set_seccomp(arg2);
 			break;
+		case PR_SET_SECCOMP_FILTER:
+			error = prctl_set_seccomp_filter(arg2,
+							 (char __user *) arg3);
+			break;
+		case PR_CLEAR_SECCOMP_FILTER:
+			error = prctl_clear_seccomp_filter(arg2);
+			break;
+		case PR_GET_SECCOMP_FILTER:
+			error = prctl_get_seccomp_filter(arg2,
+							 (char __user *) arg3,
+							 arg4);
+			break;
 		case PR_GET_TSC:
 			error = GET_TSC_CTL(arg2);
 			break;
security/Kconfig +17 -0
index 95accd4..c76adf2 100644
@@ -2,6 +2,10 @@
 # Security configuration
 #
 
+# Make seccomp filter Kconfig switch below available
+config HAVE_SECCOMP_FILTER
+       bool
+
 menu "Security options"
 
 config KEYS
@@ -82,6 +86,19 @@ config SECURITY_DMESG_RESTRICT
 
 	  If you are unsure how to answer this question, answer N.
 
+config SECCOMP_FILTER
+	bool "Enable seccomp-based system call filtering"
+	select SECCOMP
+	depends on HAVE_SECCOMP_FILTER && EXPERIMENTAL
+	help
+	  This kernel feature expands CONFIG_SECCOMP to allow computing
+	  in environments with reduced kernel access dictated by the
+	  application itself through prctl calls.  If
+	  CONFIG_FTRACE_SYSCALLS is available, then system call
+	  argument-based filtering predicates may be used.
+
+	  See Documentation/prctl/seccomp_filter.txt for more detail.
+
 config SECURITY
 	bool "Enable different security models"
 	depends on SYSFS
Signature · 7 lines
1.7.0.4

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/
author reviewer
#102 lore raw

Re: [PATCH v3 03/13] seccomp_filters: new mode with configurable syscall filters

Quoted 837 lines · Paul E. McKenney
Quoted 6 lines · Will Drewry

This change adds a new seccomp mode which specifies the allowed system calls dynamically.  When in the new mode (2), all system calls are checked against process-defined filters - first by system call number, then by a filter string.  If an entry exists for a given system call and all filter predicates evaluate to true, then the task may proceed. Otherwise, the task is killed.

A few questions below -- I can't say that I understand the RCU usage.

                                                       Thanx, Paul

Quoted 825 lines

Filter string parsing and evaluation is handled by the ftrace filter engine.  Related patches tweak to the perf filter trace and free allowing the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which already populates this information in syscall_metadata associated enter_event (and exit_event) structures. If CONFIG_FTRACE_SYSCALLS is not compiled in, only filter strings of "1" will be allowed.

The net result is a process may have its system calls filtered using the ftrace filter engine's inherent understanding of systems calls.  The set of filters is specified through the PR_SET_SECCOMP_FILTER argument in prctl(). For example, a filterset for a process, like pdftotext, that should only process read-only input could (roughly) look like:
  sprintf(rdonly, "flags == %u", O_RDONLY|O_LARGEFILE); prctl(PR_SET_SECCOMP_FILTER, __NR_open, rdonly); prctl(PR_SET_SECCOMP_FILTER, __NR__llseek, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_brk, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_close, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_exit_group, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_fstat64, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_mmap2, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_munmap, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_write, "(fd == 1 | fd == 2)"); prctl(PR_SET_SECCOMP, 2);

Subsequent calls to PR_SET_SECCOMP_FILTER for the same system call will be &&'d together to ensure that attack surface may only be reduced:
  prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd != 2");

With the earlier example, the active filter becomes:
  "(fd == 1 || fd == 2) && fd != 2"

The patch also adds PR_CLEAR_SECCOMP_FILTER and PR_GET_SECCOMP_FILTER. The latter returns the current filter for a system call to userspace:

  prctl(PR_GET_SECCOMP_FILTER, __NR_write, buf, bufsize);

while the former clears any filters for a given system call changing it back to a defaulty deny:

  prctl(PR_CLEAR_SECCOMP_FILTER, __NR_write);

v3: - always block execve calls (as per linus torvalds)
    - add __NR_seccomp_execve(_32) to seccomp-supporting arches
    - ensure compat tasks can't reach ftrace:syscalls
    - dropped new defines for seccomp modes.
    - two level array instead of hlists (sugg. by olof johansson)
    - added generic Kconfig entry that is not connected.
    - dropped internal seccomp.h
    - move prctl helpers to seccomp_filter
    - killed seccomp_t typedef (as per checkpatch)
v2: - changed to use the existing syscall number ABI.
    - prctl changes to minimize parsing in the kernel:
      prctl(PR_SET_SECCOMP, {0 | 1 | 2 }, { 0 | ON_EXEC }); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 5"); prctl(PR_CLEAR_SECCOMP_FILTER, __NR_read); prctl(PR_GET_SECCOMP_FILTER, __NR_read, buf, bufsize);
    - defined PR_SECCOMP_MODE_STRICT and ..._FILTER
    - added flags
    - provide a default fail syscall_nr_to_meta in ftrace
    - provides fallback for unhooked system calls
    - use -ENOSYS and ERR_PTR(-ENOSYS) for stubbed functionality
    - added kernel/seccomp.h to share seccomp.c/seccomp_filter.c
    - moved to a hlist and 4 bit hash of linked lists
    - added support to operate without CONFIG_FTRACE_SYSCALLS
    - moved Kconfig support next to SECCOMP
    - made Kconfig entries dependent on EXPERIMENTAL
    - added macros to avoid ifdefs from kernel/fork.c
    - added compat task/filter matching
    - drop seccomp.h inclusion in sched.h and drop seccomp_t
    - added Filtering to "show" output
    - added on_exec state dup'ing when enabling after a fast-path accept.

---
 include/linux/prctl.h   |    5 +
 include/linux/sched.h   |    2 +-
 include/linux/seccomp.h |   98 ++++++-
 include/trace/syscall.h |    7 +
 kernel/Makefile         |    3 +
 kernel/fork.c           |    3 +
 kernel/seccomp.c        |   38 ++-
 kernel/seccomp_filter.c |  784 +++++++++++++++++++++++++++++++++++++++++++++++ kernel/sys.c            |   13 +-
 security/Kconfig        |   17 +

 10 files changed, 954 insertions(+), 16 deletions(-)

 create mode 100644 kernel/seccomp_filter.c

include/linux/prctl.h +5 -0
index a3baeb2..44723ce 100644
@@ -64,6 +64,11 @@
  #define PR_GET_SECCOMP       21
  #define PR_SET_SECCOMP       22
 
+/* Get/set process seccomp filters */
+#define PR_GET_SECCOMP_FILTER        35
+#define PR_SET_SECCOMP_FILTER        36
+#define PR_CLEAR_SECCOMP_FILTER      37
+
  /* Get/set the capability bounding set (as per security/commoncap.c) */
  #define PR_CAPBSET_READ 23
  #define PR_CAPBSET_DROP 24
include/linux/sched.h +1 -1
index 18d63ce..3f0bc8d 100644
@@ -1374,7 +1374,7 @@ struct task_struct {
       uid_t loginuid;
       unsigned int sessionid;
  #endif
-     seccomp_t seccomp;
+     struct seccomp_struct seccomp;
 
  /* Thread group tracking */
       u32 parent_exec_id;
include/linux/seccomp.h +93 -5
index 167c333..f4434ca 100644
@@ -1,13 +1,33 @@
  #ifndef _LINUX_SECCOMP_H
  #define _LINUX_SECCOMP_H
 
+struct seq_file;
 
  #ifdef CONFIG_SECCOMP
 
+#include <linux/errno.h>
  #include <linux/thread_info.h>
+#include <linux/types.h>
  #include <asm/seccomp.h>
 
-typedef struct { int mode; } seccomp_t;
+struct seccomp_filters;
+/**
+ * struct seccomp_struct - the state of a seccomp'ed process
+ *
+ * @mode:
+ *     if this is 1, the process is under standard seccomp rules
+ *             is 2, the process is only allowed to make system calls where
+ *                   associated filters evaluate successfully.
+ * @filters: Metadata for filters if using CONFIG_SECCOMP_FILTER.
+ *           filters assignment/use should be RCU-protected and its contents
+ *           should never be modified when attached to a seccomp_struct.
+ */
+struct seccomp_struct {
+     uint16_t mode;
+#ifdef CONFIG_SECCOMP_FILTER
+     struct seccomp_filters *filters;
+#endif
+};
 
  extern void __secure_computing(int);
  static inline void secure_computing(int this_syscall)
@@ -16,15 +36,14 @@ static inline void secure_computing(int this_syscall)
               __secure_computing(this_syscall);
  }
 
-extern long prctl_get_seccomp(void);
  extern long prctl_set_seccomp(unsigned long);
+extern long prctl_get_seccomp(void);
 
  #else /* CONFIG_SECCOMP */
 
  #include <linux/errno.h>
 
-typedef struct { } seccomp_t;
-
+struct seccomp_struct { };
  #define secure_computing(x) do { } while (0)
 
  static inline long prctl_get_seccomp(void)
@@ -32,11 +51,80 @@ static inline long prctl_get_seccomp(void)
       return -EINVAL;
  }
 
-static inline long prctl_set_seccomp(unsigned long arg2)
+static inline long prctl_set_seccomp(unsigned long a2);
  {
       return -EINVAL;
  }
 
  #endif /* CONFIG_SECCOMP */
 
+#ifdef CONFIG_SECCOMP_FILTER
+
+#define inherit_tsk_seccomp(_child, _orig) do { \
+     _child->seccomp.mode = _orig->seccomp.mode; \
+     _child->seccomp.filters = get_seccomp_filters(_orig->seccomp.filters); \
+     } while (0)
+#define put_tsk_seccomp(_tsk) put_seccomp_filters(_tsk->seccomp.filters)
+
+extern int seccomp_show_filters(struct seccomp_filters *filters,
+                             struct seq_file *);
+extern long seccomp_set_filter(int, char *);
+extern long seccomp_clear_filter(int);
+extern long seccomp_get_filter(int, char *, unsigned long);
+
+extern long prctl_set_seccomp_filter(unsigned long, char __user *);
+extern long prctl_get_seccomp_filter(unsigned long, char __user *,
+                                  unsigned long);
+extern long prctl_clear_seccomp_filter(unsigned long);
+
+extern struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *);
+extern void put_seccomp_filters(struct seccomp_filters *);
+
+extern int seccomp_test_filters(int);
+extern void seccomp_filter_log_failure(int);
+
+#else  /* CONFIG_SECCOMP_FILTER */
+
+struct seccomp_filters { };
+#define inherit_tsk_seccomp(_child, _orig) do { } while (0)
+#define put_tsk_seccomp(_tsk) do { } while (0)
+
+static inline int seccomp_show_filters(struct seccomp_filters *filters,
+                                    struct seq_file *m)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_set_filter(int syscall_nr, char *filter)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_clear_filter(int syscall_nr)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_get_filter(int syscall_nr,
+                                   char *buf, unsigned long available)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_set_seccomp_filter(unsigned long a2, char __user *a3)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_clear_seccomp_filter(unsigned long a2)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_get_seccomp_filter(unsigned long a2, char __user *a3,
+                                         unsigned long a4)
+{
+     return -ENOSYS;
+}
+#endif  /* CONFIG_SECCOMP_FILTER */
  #endif /* _LINUX_SECCOMP_H */
include/trace/syscall.h +7 -0
index 242ae04..e061ad0 100644
@@ -35,6 +35,8 @@ struct syscall_metadata {
  extern unsigned long arch_syscall_addr(int nr);
  extern int init_syscall_trace(struct ftrace_event_call *call);
 
+extern struct syscall_metadata *syscall_nr_to_meta(int);
+
  extern int reg_event_syscall_enter(struct ftrace_event_call *call);
  extern void unreg_event_syscall_enter(struct ftrace_event_call *call);
  extern int reg_event_syscall_exit(struct ftrace_event_call *call);
@@ -49,6 +51,11 @@ enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
                                     struct trace_event *event);
  enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
                                    struct trace_event *event);
+#else
+static inline struct syscall_metadata *syscall_nr_to_meta(int nr)
+{
+     return NULL;
+}
  #endif
 
  #ifdef CONFIG_PERF_EVENTS
kernel/Makefile +0 -0
index 85cbfb3..84e7dfb 100644
@@ -81,6 +81,9 @@ obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o

 obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
 obj-$(CONFIG_GENERIC_HARDIRQS) += irq/
 obj-$(CONFIG_SECCOMP) += seccomp.o

kernel/Makefile +3 -0
+ifeq ($(CONFIG_SECCOMP_FILTER),y)
+obj-$(CONFIG_SECCOMP) += seccomp_filter.o
+endif

 obj-$(CONFIG_RCU_TORTURE_TEST) += rcutorture.o
 obj-$(CONFIG_TREE_RCU) += rcutree.o
 obj-$(CONFIG_TREE_PREEMPT_RCU) += rcutree.o

kernel/fork.c +3 -0
index e7548de..6f835e0 100644
@@ -34,6 +34,7 @@
  #include <linux/cgroup.h>
  #include <linux/security.h>
  #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
  #include <linux/swap.h>
  #include <linux/syscalls.h>
  #include <linux/jiffies.h>
@@ -169,6 +170,7 @@ void free_task(struct task_struct *tsk)
       free_thread_info(tsk->stack);
       rt_mutex_debug_task_free(tsk);
       ftrace_graph_exit_task(tsk);
+     put_tsk_seccomp(tsk);
       free_task_struct(tsk);
  }
  EXPORT_SYMBOL(free_task);
@@ -280,6 +282,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
       if (err)
               goto out;
 
+     inherit_tsk_seccomp(tsk, orig);
       setup_thread_stack(tsk, orig);
       clear_user_return_notifier(tsk);
       clear_tsk_need_resched(tsk);
kernel/seccomp.c +6 -3
index 57d4b13..0a942be 100644
@@ -2,16 +2,20 @@
   * linux/kernel/seccomp.c
   *
   * Copyright 2004-2005  Andrea Arcangeli <[email protected]>
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
   *
   * This defines a simple but solid secure-computing mode.
   */
 
  #include <linux/seccomp.h>
  #include <linux/sched.h>
+#include <linux/slab.h>
  #include <linux/compat.h>
+#include <linux/unistd.h>
+#include <linux/ftrace_event.h>
 
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
  /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
 
  /*
   * Secure computing mode 1 allows only read/write/exit/sigreturn.
@@ -32,10 +36,9 @@ static int mode1_syscalls_32[] = {
 
  void __secure_computing(int this_syscall)
  {
-     int mode = current->seccomp.mode;
       int * syscall;
 
-     switch (mode) {
+     switch (current->seccomp.mode) {

      case 1:
              syscall = mode1_syscalls;
 #ifdef CONFIG_COMPAT

kernel/seccomp.c +11 -0
@@ -47,6 +50,17 @@ void __secure_computing(int this_syscall)
                               return;
               } while (*++syscall);
               break;
+#ifdef CONFIG_SECCOMP_FILTER
+     case 2:
+             if (this_syscall >= NR_syscalls || this_syscall < 0)
+                     break;
+
+             if (!seccomp_test_filters(this_syscall))
+                     return;
+
+             seccomp_filter_log_failure(this_syscall);
+             break;
+#endif

      default:
              BUG();
      }

kernel/seccomp.c +12 -6
@@ -71,16 +85,22 @@ long prctl_set_seccomp(unsigned long seccomp_mode)
       if (unlikely(current->seccomp.mode))
               goto out;
 
-     ret = -EINVAL;
-     if (seccomp_mode && seccomp_mode <= NR_SECCOMP_MODES) {
-             current->seccomp.mode = seccomp_mode;
-             set_thread_flag(TIF_SECCOMP);
+     ret = 0;
+     switch (seccomp_mode) {
+     case 1:
  #ifdef TIF_NOTSC
               disable_TSC();
  #endif
-             ret = 0;
+#ifdef CONFIG_SECCOMP_FILTER
+     case 2:
+#endif
+             current->seccomp.mode = seccomp_mode;
+             set_thread_flag(TIF_SECCOMP);
+             break;
+     default:
+             ret = -EINVAL;
       }
 
- out:
+out:
       return ret;
  }
kernel/seccomp_filter.c new file +409 -0
new file mode 100644
index 0000000..9782f25
@@ -0,0 +1,784 @@
+/* filter engine-based seccomp system call filtering
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
+ */
+
+#include <linux/compat.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/ftrace_event.h>
+#include <linux/seccomp.h>
+#include <linux/seq_file.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/uaccess.h>
+
+#include <asm/syscall.h>
+#include <trace/syscall.h>
+
+
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
+
+#define SECCOMP_FILTER_ALLOW "1"
+#define SECCOMP_ACTION_DENY 0xffff
+#define SECCOMP_ACTION_ALLOW 0xfffe
+
+/**
+ * struct seccomp_filters - container for seccomp filterset
+ *
+ * @syscalls: array of 16-bit indices into @event_filters by syscall_nr
+ *            May also be SECCOMP_ACTION_DENY or SECCOMP_ACTION_ALLOW
+ * @event_filters: array of pointers to ftrace event objects
+ * @count: size of @event_filters
+ * @flags: anonymous struct to wrap filters-specific flags
+ * @usage: reference count to simplify use.
+ */
+struct seccomp_filters {
+     uint16_t syscalls[NR_syscalls];
+     struct event_filter **event_filters;
+     uint16_t count;
+     struct {
+             uint32_t compat:1,
+                      __reserved:31;
+     } flags;
+     atomic_t usage;
+};
+
+/* Handle ftrace symbol non-existence */
+#ifdef CONFIG_FTRACE_SYSCALLS
+#define create_event_filter(_ef_pptr, _event_type, _str) \
+     ftrace_parse_filter(_ef_pptr, _event_type, _str)
+#define get_filter_string(_ef) ftrace_get_filter_string(_ef)
+#define free_event_filter(_f) ftrace_free_filter(_f)
+
+#else
+
+#define create_event_filter(_ef_pptr, _event_type, _str) (-ENOSYS)
+#define get_filter_string(_ef) (NULL)
+#define free_event_filter(_f) do { } while (0)
+#endif
+
+/**
+ * seccomp_filters_new - allocates a new filters object
+ * @count: count to allocate for the event_filters array
+ *
+ * Returns ERR_PTR on error or an allocated object.
+ */
+static struct seccomp_filters *seccomp_filters_new(uint16_t count)
+{
+     struct seccomp_filters *f;
+
+     if (count >= SECCOMP_ACTION_ALLOW)
+             return ERR_PTR(-EINVAL);
+
+     f = kzalloc(sizeof(struct seccomp_filters), GFP_KERNEL);
+     if (!f)
+             return ERR_PTR(-ENOMEM);
+
+     /* Lazy SECCOMP_ACTION_DENY assignment. */
+     memset(f->syscalls, 0xff, sizeof(f->syscalls));
+     atomic_set(&f->usage, 1);
+
+     f->event_filters = NULL;
+     f->count = count;
+     if (!count)
+             return f;
+
+     f->event_filters = kzalloc(count * sizeof(struct event_filter *),
+                                GFP_KERNEL);
+     if (!f->event_filters) {
+             kfree(f);
+             f = ERR_PTR(-ENOMEM);
+     }
+     return f;
+}
+
+/**
+ * seccomp_filters_free - cleans up the filter list and frees the table
+ * @filters: NULL or live object to be completely destructed.
+ */
+static void seccomp_filters_free(struct seccomp_filters *filters)
+{
+     uint16_t count = 0;
+     if (!filters)
+             return;
+     while (count < filters->count) {
+             struct event_filter *f = filters->event_filters[count];
+             free_event_filter(f);
+             count++;
+     }
+     kfree(filters->event_filters);
+     kfree(filters);
+}
+
+static void __put_seccomp_filters(struct seccomp_filters *orig)
+{
+     WARN_ON(atomic_read(&orig->usage));
+     seccomp_filters_free(orig);
+}
+
+#define seccomp_filter_allow(_id) ((_id) == SECCOMP_ACTION_ALLOW)
+#define seccomp_filter_deny(_id) ((_id) == SECCOMP_ACTION_DENY)
+#define seccomp_filter_dynamic(_id) \
+     (!seccomp_filter_allow(_id) && !seccomp_filter_deny(_id))
+static inline uint16_t seccomp_filter_id(const struct seccomp_filters *f,
+                                      int syscall_nr)
+{
+     if (!f)
+             return SECCOMP_ACTION_DENY;
+     return f->syscalls[syscall_nr];
+}
+
+static inline struct event_filter *seccomp_dynamic_filter(
+             const struct seccomp_filters *filters, uint16_t id)
+{
+     if (!seccomp_filter_dynamic(id))
+             return NULL;
+     return filters->event_filters[id];
+}
+
+static inline void set_seccomp_filter_id(struct seccomp_filters *filters,
+                                      int syscall_nr, uint16_t id)
+{
+     filters->syscalls[syscall_nr] = id;
+}
+
+static inline void set_seccomp_filter(struct seccomp_filters *filters,
+                                   int syscall_nr, uint16_t id,
+                                   struct event_filter *dynamic_filter)
+{
+     filters->syscalls[syscall_nr] = id;
+     if (seccomp_filter_dynamic(id))
+             filters->event_filters[id] = dynamic_filter;
+}
+
+static struct event_filter *alloc_event_filter(int syscall_nr,
+                                            const char *filter_string)
+{
+     struct syscall_metadata *data;
+     struct event_filter *filter = NULL;
+     int err;
+
+     data = syscall_nr_to_meta(syscall_nr);
+     /* Argument-based filtering only works on ftrace-hooked syscalls. */
+     err = -ENOSYS;
+     if (!data)
+             goto fail;
+     err = create_event_filter(&filter,
+                               data->enter_event->event.type,
+                               filter_string);
+     if (err)
+             goto fail;
+
+     return filter;
+fail:
+     kfree(filter);
+     return ERR_PTR(err);
+}
+
+/**
+ * seccomp_filters_copy - copies filters from src to dst.
+ *
+ * @dst: seccomp_filters to populate.
+ * @src: table to read from.
+ * @skip: specifies an entry, by system call, to skip.
+ *
+ * Returns non-zero on failure.
+ * Both the source and the destination should have no simultaneous
+ * writers, and dst should be exclusive to the caller.
+ * If @skip is < 0, it is ignored.
+ */
+static int seccomp_filters_copy(struct seccomp_filters *dst,
+                             const struct seccomp_filters *src,
+                             int skip)
+{
+     int id = 0, ret = 0, nr;
+     memcpy(&dst->flags, &src->flags, sizeof(src->flags));
+     memcpy(dst->syscalls, src->syscalls, sizeof(dst->syscalls));
+     if (!src->count)
+             goto done;
+     for (nr = 0; nr < NR_syscalls; ++nr) {
+             struct event_filter *filter;
+             const char *str;
+             uint16_t src_id = seccomp_filter_id(src, nr);
+             if (nr == skip) {
+                     set_seccomp_filter(dst, nr, SECCOMP_ACTION_DENY,
+                                        NULL);
+                     continue;
+             }
+             if (!seccomp_filter_dynamic(src_id))
+                     continue;
+             if (id >= dst->count) {
+                     ret = -EINVAL;
+                     goto done;
+             }
+             str = get_filter_string(seccomp_dynamic_filter(src, src_id));
+             filter = alloc_event_filter(nr, str);
+             if (IS_ERR(filter)) {
+                     ret = PTR_ERR(filter);
+                     goto done;
+             }
+             set_seccomp_filter(dst, nr, id, filter);
+             id++;
+     }
+
+done:
+     return ret;
+}
+
+/**
+ * seccomp_extend_filter - appends more text to a syscall_nr's filter
+ * @filters: unattached filter object to operate on
+ * @syscall_nr: syscall number to update filters for
+ * @filter_string: string to append to the existing filter
+ *
+ * The new string will be &&'d to the original filter string to ensure that it
+ * always matches the existing predicates or less:
+ *   (old_filter) && @filter_string
+ * A new seccomp_filters instance is returned on success and a ERR_PTR on
+ * failure.
+ */
+static int seccomp_extend_filter(struct seccomp_filters *filters,
+                              int syscall_nr, char *filter_string)
+{
+     struct event_filter *filter;
+     uint16_t id = seccomp_filter_id(filters, syscall_nr);
+     char *merged = NULL;
+     int ret = -EINVAL, expected;
+
+     /* No extending with a "1". */
+     if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string))
+             goto out;
+
+     filter = seccomp_dynamic_filter(filters, id);
+     ret = -ENOENT;
+     if (!filter)
+             goto out;
+
+     merged = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+     ret = -ENOMEM;
+     if (!merged)
+             goto out;
+
+     expected = snprintf(merged, SECCOMP_MAX_FILTER_LENGTH, "(%s) && %s",
+                         get_filter_string(filter), filter_string);
+     ret = -E2BIG;
+     if (expected >= SECCOMP_MAX_FILTER_LENGTH || expected < 0)
+             goto out;
+
+     /* Free the old filter */
+     free_event_filter(filter);
+     set_seccomp_filter(filters, syscall_nr, id, NULL);
+
+     /* Replace it */
+     filter = alloc_event_filter(syscall_nr, merged);
+     if (IS_ERR(filter)) {
+             ret = PTR_ERR(filter);
+             goto out;
+     }
+     set_seccomp_filter(filters, syscall_nr, id, filter);
+     ret = 0;
+
+out:
+     kfree(merged);
+     return ret;
+}
+
+/**
+ * seccomp_add_filter - adds a filter for an unfiltered syscall
+ * @filters: filters object to add a filter/action to
+ * @syscall_nr: system call number to add a filter for
+ * @filter_string: the filter string to apply
+ *
+ * Returns 0 on success and non-zero otherwise.
+ */
+static int seccomp_add_filter(struct seccomp_filters *filters, int syscall_nr,
+                           char *filter_string)
+{
+     struct event_filter *filter;
+     int ret = 0;
+
+     if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string)) {
+             set_seccomp_filter(filters, syscall_nr,
+                                SECCOMP_ACTION_ALLOW, NULL);
+             goto out;
+     }
+
+     filter = alloc_event_filter(syscall_nr, filter_string);
+     if (IS_ERR(filter)) {
+             ret = PTR_ERR(filter);
+             goto out;
+     }
+     /* Always add to the last slot available since additions are
+      * are only done one at a time.
+      */
+     set_seccomp_filter(filters, syscall_nr, filters->count - 1, filter);
+out:
+     return ret;
+}
+
+/* Wrap optional ftrace syscall support. Returns 1 on match or 0 otherwise. */
+static int filter_match_current(struct event_filter *event_filter)
+{
+     int err = 0;
+#ifdef CONFIG_FTRACE_SYSCALLS
+     uint8_t syscall_state[64];
+
+     memset(syscall_state, 0, sizeof(syscall_state));
+
+     /* The generic tracing entry can remain zeroed. */
+     err = ftrace_syscall_enter_state(syscall_state, sizeof(syscall_state),
+                                      NULL);
+     if (err)
+             return 0;
+
+     err = filter_match_preds(event_filter, syscall_state);
+#endif
+     return err;
+}
+
+static const char *syscall_nr_to_name(int syscall)
+{
+     const char *syscall_name = "unknown";
+     struct syscall_metadata *data = syscall_nr_to_meta(syscall);
+     if (data)
+             syscall_name = data->name;
+     return syscall_name;
+}
+
+static void filters_set_compat(struct seccomp_filters *filters)
+{
+#ifdef CONFIG_COMPAT
+     if (is_compat_task())
+             filters->flags.compat = 1;
+#endif
+}
+
+static inline int filters_compat_mismatch(struct seccomp_filters *filters)
+{
+     int ret = 0;
+     if (!filters)
+             return 0;
+#ifdef CONFIG_COMPAT
+     if (!!(is_compat_task()) == filters->flags.compat)
+             ret = 1;
+#endif
+     return ret;
+}
+
+static inline int syscall_is_execve(int syscall)
+{
+     int nr = __NR_execve;
+#ifdef CONFIG_COMPAT
+     if (is_compat_task())
+             nr = __NR_seccomp_execve_32;
+#endif
+     return syscall == nr;
+}
+
+#ifndef KSTK_EIP
+#define KSTK_EIP(x) 0L
+#endif
+
+void seccomp_filter_log_failure(int syscall)
+{
+     pr_info("%s[%d]: system call %d (%s) blocked at 0x%lx\n",
+             current->comm, task_pid_nr(current), syscall,
+             syscall_nr_to_name(syscall), KSTK_EIP(current));
+}
+
+/* put_seccomp_state - decrements the reference count of @orig and may free. */
+void put_seccomp_filters(struct seccomp_filters *orig)
+{
+     if (!orig)
+             return;
+
Quoted 8 lines

kernel/seccomp_filter.c line 415

Quoted 6 lines
kernel/seccomp_filter.c new file +6 -0
+     if (atomic_dec_and_test(&orig->usage))
+             __put_seccomp_filters(orig);
+}
+
+/* get_seccomp_state - increments the reference count of @orig */
+struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *orig)

Nit: the name does not match the comment.

Will fix it here and above. Thanks!

Quoted 9 lines

kernel/seccomp_filter.c line 420

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+{
+     if (!orig)
+             return NULL;
+     atomic_inc(&orig->usage);
+     return orig;

This is called in an RCU read-side critical section.  What exactly is RCU protecting?  I would expect an rcu_dereference() or one of the RCU list-traversal primitives somewhere, either here or at the caller.

Ah, I spaced on rcu_dereference(). The goal was to make the assignment and replacement of the seccomp_filters pointer RCU-protected (in seccomp_state) so there's no concern over it being replaced partial on platforms where pointer assignments are non-atomic
- such as via /proc/<pid>/seccomp_filters access or a call via the exported symbols. Object lifetime is managed by reference counting so that I don't have to worry about extending the RCU read-side critical section by much or deal with pre-allocations.

I'll add rcu_dereference() to all the get_seccomp_filters() uses where it makes sense, so that it is called safely. Just to make sure, does it make sense to continue to rcu protect the specific pointer?

Quoted 184 lines
Quoted 184 lines
kernel/seccomp_filter.c new file +184 -0
+}
+
+/**
+ * seccomp_test_filters - tests 'current' against the given syscall
+ * @state: seccomp_state of current to use.
+ * @syscall: number of the system call to test
+ *
+ * Returns 0 on ok and non-zero on error/failure.
+ */
+int seccomp_test_filters(int syscall)
+{
+     uint16_t id;
+     struct event_filter *filter;
+     struct seccomp_filters *filters;
+     int ret = -EACCES;
+
+     rcu_read_lock();
+     filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!filters)
+             goto out;
+
+     if (filters_compat_mismatch(filters)) {
+             pr_info("%s[%d]: seccomp_filter compat() mismatch.\n",
+                     current->comm, task_pid_nr(current));
+             goto out;
+     }
+
+     /* execve is never allowed. */
+     if (syscall_is_execve(syscall))
+             goto out;
+
+     ret = 0;
+     id = seccomp_filter_id(filters, syscall);
+     if (seccomp_filter_allow(id))
+             goto out;
+
+     ret = -EACCES;
+     if (!seccomp_filter_dynamic(id))
+             goto out;
+
+     filter = seccomp_dynamic_filter(filters, id);
+     if (filter && filter_match_current(filter))
+             ret = 0;
+out:
+     put_seccomp_filters(filters);
+     return ret;
+}
+
+/**
+ * seccomp_show_filters - prints the current filter state to a seq_file
+ * @filters: properly get()'d filters object
+ * @m: the prepared seq_file to receive the data
+ *
+ * Returns 0 on a successful write.
+ */
+int seccomp_show_filters(struct seccomp_filters *filters, struct seq_file *m)
+{
+     int syscall;
+     seq_printf(m, "Mode: %d\n", current->seccomp.mode);
+     if (!filters)
+             goto out;
+
+     for (syscall = 0; syscall < NR_syscalls; ++syscall) {
+             uint16_t id = seccomp_filter_id(filters, syscall);
+             const char *filter_string = SECCOMP_FILTER_ALLOW;
+             if (seccomp_filter_deny(id))
+                     continue;
+             seq_printf(m, "%d (%s): ",
+                           syscall,
+                           syscall_nr_to_name(syscall));
+             if (seccomp_filter_dynamic(id))
+                     filter_string = get_filter_string(
+                                       seccomp_dynamic_filter(filters, id));
+             seq_printf(m, "%s\n", filter_string);
+     }
+out:
+     return 0;
+}
+EXPORT_SYMBOL_GPL(seccomp_show_filters);
+
+/**
+ * seccomp_get_filter - copies the filter_string into "buf"
+ * @syscall_nr: system call number to look up
+ * @buf: destination buffer
+ * @bufsize: available space in the buffer.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Looks up the filter for the given system call number on current.  If found,
+ * the string length of the NUL-terminated buffer is returned and < 0 is
+ * returned on error. The NUL byte is not included in the length.
+ */
+long seccomp_get_filter(int syscall_nr, char *buf, unsigned long bufsize)
+{
+     struct seccomp_filters *filters;
+     struct event_filter *filter;
+     long ret = -EINVAL;
+     uint16_t id;
+
+     if (bufsize > SECCOMP_MAX_FILTER_LENGTH)
+             bufsize = SECCOMP_MAX_FILTER_LENGTH;
+
+     rcu_read_lock();
+     filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!filters)
+             goto out;
+
+     ret = -ENOENT;
+     id = seccomp_filter_id(filters, syscall_nr);
+     if (seccomp_filter_deny(id))
+             goto out;
+
+     if (seccomp_filter_allow(id)) {
+             ret = strlcpy(buf, SECCOMP_FILTER_ALLOW, bufsize);
+             goto copied;
+     }
+
+     filter = seccomp_dynamic_filter(filters, id);
+     if (!filter)
+             goto out;
+     ret = strlcpy(buf, get_filter_string(filter), bufsize);
+
+copied:
+     if (ret >= bufsize) {
+             ret = -ENOSPC;
+             goto out;
+     }
+     /* Zero out any remaining buffer, just in case. */
+     memset(buf + ret, 0, bufsize - ret);
+out:
+     put_seccomp_filters(filters);
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_get_filter);
+
+/**
+ * seccomp_clear_filter: clears the seccomp filter for a syscall.
+ * @syscall_nr: the system call number to clear filters for.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Returns 0 on success.
+ */
+long seccomp_clear_filter(int syscall_nr)
+{
+     struct seccomp_filters *filters = NULL, *orig_filters;
+     uint16_t id;
+     int ret = -EINVAL;
+
+     rcu_read_lock();
+     orig_filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!orig_filters)
+             goto out;
+
+     if (filters_compat_mismatch(orig_filters))
+             goto out;
+
+     id = seccomp_filter_id(orig_filters, syscall_nr);
+     if (seccomp_filter_deny(id))
+             goto out;
+
+     /* Create a new filters object for the task */
+     if (seccomp_filter_dynamic(id))
+             filters = seccomp_filters_new(orig_filters->count - 1);
+     else
+             filters = seccomp_filters_new(orig_filters->count);
+
+     if (IS_ERR(filters)) {
+             ret = PTR_ERR(filters);
+             goto out;
+     }
+
+     /* Copy, but drop the requested entry. */
+     ret = seccomp_filters_copy(filters, orig_filters, syscall_nr);
Quoted 8 lines

kernel/seccomp_filter.c line 609

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+     if (ret)
+             goto out;
+     get_seccomp_filters(filters);  /* simplify the out: path */
+
+     rcu_assign_pointer(current->seccomp.filters, filters);

What prevents two copies of seccomp_clear_filter() from running concurrently?

Nothing - the last one wins assignment, but the objects themselves should be internally consistent to the parallel calls. If that's a concern, a per-task writer mutex could be used just to ensure simultaneous calls to clear and set are performed serially. Would that make more sense?

Quoted 75 lines
Quoted 75 lines
kernel/seccomp_filter.c new file +75 -0
+     synchronize_rcu();
+     put_seccomp_filters(orig_filters);  /* for the task */
+out:
+     put_seccomp_filters(orig_filters);  /* for the get */
+     put_seccomp_filters(filters);  /* for the extra get */
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_clear_filter);
+
+/**
+ * seccomp_set_filter: - Adds/extends a seccomp filter for a syscall.
+ * @syscall_nr: system call number to apply the filter to.
+ * @filter: ftrace filter string to apply.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * New filters may be added for system calls when the current task is
+ * not in a secure computing mode (seccomp).  Otherwise, existing filters may
+ * be extended.
+ *
+ * Returns 0 on success or an errno on failure.
+ */
+long seccomp_set_filter(int syscall_nr, char *filter)
+{
+     struct seccomp_filters *filters = NULL, *orig_filters = NULL;
+     uint16_t id;
+     long ret = -EINVAL;
+     uint16_t filters_needed;
+
+     if (!filter)
+             goto out;
+
+     filter = strstrip(filter);
+     /* Disallow empty strings. */
+     if (filter[0] == 0)
+             goto out;
+
+     rcu_read_lock();
+     orig_filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     /* After the first call, compatibility mode is selected permanently. */
+     ret = -EACCES;
+     if (filters_compat_mismatch(orig_filters))
+             goto out;
+
+     filters_needed = orig_filters ? orig_filters->count : 0;
+     id = seccomp_filter_id(orig_filters, syscall_nr);
+     if (seccomp_filter_deny(id)) {
+             /* Don't allow DENYs to be changed when in a seccomp mode */
+             ret = -EACCES;
+             if (current->seccomp.mode)
+                     goto out;
+             filters_needed++;
+     }
+
+     filters = seccomp_filters_new(filters_needed);
+     if (IS_ERR(filters)) {
+             ret = PTR_ERR(filters);
+             goto out;
+     }
+
+     filters_set_compat(filters);
+     if (orig_filters) {
+             ret = seccomp_filters_copy(filters, orig_filters, -1);
+             if (ret)
+                     goto out;
+     }
+
+     if (seccomp_filter_deny(id))
+             ret = seccomp_add_filter(filters, syscall_nr, filter);
+     else
+             ret = seccomp_extend_filter(filters, syscall_nr, filter);
Quoted 8 lines

kernel/seccomp_filter.c line 689

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+     if (ret)
+             goto out;
+     get_seccomp_filters(filters);  /* simplify the error paths */
+
+     rcu_assign_pointer(current->seccomp.filters, filters);

Again, what prevents two copies of seccomp_set_filter() from running concurrently?

Same deal - nothing, but I'd be happy to add a guard if it makes sense.

Thanks!

Quoted 169 lines
Quoted 168 lines
kernel/seccomp_filter.c new file +95 -0
+     synchronize_rcu();
+     put_seccomp_filters(orig_filters);  /* for the task */
+out:
+     put_seccomp_filters(orig_filters);  /* for the get */
+     put_seccomp_filters(filters);  /* for get or task, on err */
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_set_filter);
+
+long prctl_set_seccomp_filter(unsigned long syscall_nr,
+                           char __user *user_filter)
+{
+     int nr;
+     long ret;
+     char *filter = NULL;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+
+     ret = -EFAULT;
+     if (!user_filter)
+             goto out;
+
+     filter = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+     ret = -ENOMEM;
+     if (!filter)
+             goto out;
+
+     ret = -EFAULT;
+     if (strncpy_from_user(filter, user_filter,
+                           SECCOMP_MAX_FILTER_LENGTH - 1) < 0)
+             goto out;
+
+     nr = (int) syscall_nr;
+     ret = seccomp_set_filter(nr, filter);
+
+out:
+     kfree(filter);
+     return ret;
+}
+
+long prctl_clear_seccomp_filter(unsigned long syscall_nr)
+{
+     int nr = -1;
+     long ret;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+
+     nr = (int) syscall_nr;
+     ret = seccomp_clear_filter(nr);
+
+out:
+     return ret;
+}
+
+long prctl_get_seccomp_filter(unsigned long syscall_nr, char __user *dst,
+                           unsigned long available)
+{
+     int ret, nr;
+     unsigned long copied;
+     char *buf = NULL;
+     ret = -EINVAL;
+     if (!available)
+             goto out;
+     /* Ignore extra buffer space. */
+     if (available > SECCOMP_MAX_FILTER_LENGTH)
+             available = SECCOMP_MAX_FILTER_LENGTH;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+     nr = (int) syscall_nr;
+
+     ret = -ENOMEM;
+     buf = kmalloc(available, GFP_KERNEL);
+     if (!buf)
+             goto out;
+
+     ret = seccomp_get_filter(nr, buf, available);
+     if (ret < 0)
+             goto out;
+
+     /* Include the NUL byte in the copy. */
+     copied = copy_to_user(dst, buf, ret + 1);
+     ret = -ENOSPC;
+     if (copied)
+             goto out;
+     ret = 0;
+out:
+     kfree(buf);
+     return ret;
+}
kernel/sys.c +0 -0
index af468ed..ed60d06 100644
@@ -1698,13 +1698,24 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,

              case PR_SET_ENDIAN:
                      error = SET_ENDIAN(me, arg2);
                      break;
-
              case PR_GET_SECCOMP:
                      error = prctl_get_seccomp();
                      break;
              case PR_SET_SECCOMP:
                      error = prctl_set_seccomp(arg2);
                      break;
+             case PR_SET_SECCOMP_FILTER:
+                     error = prctl_set_seccomp_filter(arg2,
+                                                      (char __user *) arg3);
+                     break;
+             case PR_CLEAR_SECCOMP_FILTER:
+                     error = prctl_clear_seccomp_filter(arg2);
+                     break;
+             case PR_GET_SECCOMP_FILTER:
+                     error = prctl_get_seccomp_filter(arg2,
+                                                      (char __user *) arg3,
+                                                      arg4);
+                     break;
              case PR_GET_TSC:
                      error = GET_TSC_CTL(arg2);
                      break;

security/Kconfig +4 -0
index 95accd4..c76adf2 100644
@@ -2,6 +2,10 @@
  # Security configuration
  #
 
+# Make seccomp filter Kconfig switch below available
+config HAVE_SECCOMP_FILTER
+       bool
+

 menu "Security options"

 config KEYS

security/Kconfig +0 -0
@@ -82,6 +86,19 @@ config SECURITY_DMESG_RESTRICT
 

        If you are unsure how to answer this question, answer N.

security/Kconfig +13 -0
+config SECCOMP_FILTER
+     bool "Enable seccomp-based system call filtering"
+     select SECCOMP
+     depends on HAVE_SECCOMP_FILTER && EXPERIMENTAL
+     help
+       This kernel feature expands CONFIG_SECCOMP to allow computing
+       in environments with reduced kernel access dictated by the
+       application itself through prctl calls.  If
+       CONFIG_FTRACE_SYSCALLS is available, then system call
+       argument-based filtering predicates may be used.
+
+       See Documentation/prctl/seccomp_filter.txt for more detail.
+

 config SECURITY
      bool "Enable different security models"
      depends on SYSFS
--
1.7.0.4

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/

#103 lore raw

Re: [PATCH v3 03/13] seccomp_filters: new mode with configurable syscall filters

Quoted 869 lines · Will Drewry
Quoted 837 lines · Paul E. McKenney
Quoted 6 lines · Will Drewry

This change adds a new seccomp mode which specifies the allowed system calls dynamically.  When in the new mode (2), all system calls are checked against process-defined filters - first by system call number, then by a filter string.  If an entry exists for a given system call and all filter predicates evaluate to true, then the task may proceed. Otherwise, the task is killed.

A few questions below -- I can't say that I understand the RCU usage.

                                                       Thanx, Paul

Quoted 825 lines

Filter string parsing and evaluation is handled by the ftrace filter engine.  Related patches tweak to the perf filter trace and free allowing the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which already populates this information in syscall_metadata associated enter_event (and exit_event) structures. If CONFIG_FTRACE_SYSCALLS is not compiled in, only filter strings of "1" will be allowed.

The net result is a process may have its system calls filtered using the ftrace filter engine's inherent understanding of systems calls.  The set of filters is specified through the PR_SET_SECCOMP_FILTER argument in prctl(). For example, a filterset for a process, like pdftotext, that should only process read-only input could (roughly) look like:
  sprintf(rdonly, "flags == %u", O_RDONLY|O_LARGEFILE); prctl(PR_SET_SECCOMP_FILTER, __NR_open, rdonly); prctl(PR_SET_SECCOMP_FILTER, __NR__llseek, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_brk, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_close, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_exit_group, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_fstat64, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_mmap2, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_munmap, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_write, "(fd == 1 | fd == 2)"); prctl(PR_SET_SECCOMP, 2);

Subsequent calls to PR_SET_SECCOMP_FILTER for the same system call will be &&'d together to ensure that attack surface may only be reduced:
  prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd != 2");

With the earlier example, the active filter becomes:
  "(fd == 1 || fd == 2) && fd != 2"

The patch also adds PR_CLEAR_SECCOMP_FILTER and PR_GET_SECCOMP_FILTER. The latter returns the current filter for a system call to userspace:

  prctl(PR_GET_SECCOMP_FILTER, __NR_write, buf, bufsize);

while the former clears any filters for a given system call changing it back to a defaulty deny:

  prctl(PR_CLEAR_SECCOMP_FILTER, __NR_write);

v3: - always block execve calls (as per linus torvalds)
    - add __NR_seccomp_execve(_32) to seccomp-supporting arches
    - ensure compat tasks can't reach ftrace:syscalls
    - dropped new defines for seccomp modes.
    - two level array instead of hlists (sugg. by olof johansson)
    - added generic Kconfig entry that is not connected.
    - dropped internal seccomp.h
    - move prctl helpers to seccomp_filter
    - killed seccomp_t typedef (as per checkpatch)
v2: - changed to use the existing syscall number ABI.
    - prctl changes to minimize parsing in the kernel:
      prctl(PR_SET_SECCOMP, {0 | 1 | 2 }, { 0 | ON_EXEC }); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 5"); prctl(PR_CLEAR_SECCOMP_FILTER, __NR_read); prctl(PR_GET_SECCOMP_FILTER, __NR_read, buf, bufsize);
    - defined PR_SECCOMP_MODE_STRICT and ..._FILTER
    - added flags
    - provide a default fail syscall_nr_to_meta in ftrace
    - provides fallback for unhooked system calls
    - use -ENOSYS and ERR_PTR(-ENOSYS) for stubbed functionality
    - added kernel/seccomp.h to share seccomp.c/seccomp_filter.c
    - moved to a hlist and 4 bit hash of linked lists
    - added support to operate without CONFIG_FTRACE_SYSCALLS
    - moved Kconfig support next to SECCOMP
    - made Kconfig entries dependent on EXPERIMENTAL
    - added macros to avoid ifdefs from kernel/fork.c
    - added compat task/filter matching
    - drop seccomp.h inclusion in sched.h and drop seccomp_t
    - added Filtering to "show" output
    - added on_exec state dup'ing when enabling after a fast-path accept.

---
 include/linux/prctl.h   |    5 +
 include/linux/sched.h   |    2 +-
 include/linux/seccomp.h |   98 ++++++-
 include/trace/syscall.h |    7 +
 kernel/Makefile         |    3 +
 kernel/fork.c           |    3 +
 kernel/seccomp.c        |   38 ++-
 kernel/seccomp_filter.c |  784 +++++++++++++++++++++++++++++++++++++++++++++++ kernel/sys.c            |   13 +-
 security/Kconfig        |   17 +

 10 files changed, 954 insertions(+), 16 deletions(-)

 create mode 100644 kernel/seccomp_filter.c

include/linux/prctl.h +5 -0
index a3baeb2..44723ce 100644
@@ -64,6 +64,11 @@
  #define PR_GET_SECCOMP       21
  #define PR_SET_SECCOMP       22
 
+/* Get/set process seccomp filters */
+#define PR_GET_SECCOMP_FILTER        35
+#define PR_SET_SECCOMP_FILTER        36
+#define PR_CLEAR_SECCOMP_FILTER      37
+
  /* Get/set the capability bounding set (as per security/commoncap.c) */
  #define PR_CAPBSET_READ 23
  #define PR_CAPBSET_DROP 24
include/linux/sched.h +1 -1
index 18d63ce..3f0bc8d 100644
@@ -1374,7 +1374,7 @@ struct task_struct {
       uid_t loginuid;
       unsigned int sessionid;
  #endif
-     seccomp_t seccomp;
+     struct seccomp_struct seccomp;
 
  /* Thread group tracking */
       u32 parent_exec_id;
include/linux/seccomp.h +93 -5
index 167c333..f4434ca 100644
@@ -1,13 +1,33 @@
  #ifndef _LINUX_SECCOMP_H
  #define _LINUX_SECCOMP_H
 
+struct seq_file;
 
  #ifdef CONFIG_SECCOMP
 
+#include <linux/errno.h>
  #include <linux/thread_info.h>
+#include <linux/types.h>
  #include <asm/seccomp.h>
 
-typedef struct { int mode; } seccomp_t;
+struct seccomp_filters;
+/**
+ * struct seccomp_struct - the state of a seccomp'ed process
+ *
+ * @mode:
+ *     if this is 1, the process is under standard seccomp rules
+ *             is 2, the process is only allowed to make system calls where
+ *                   associated filters evaluate successfully.
+ * @filters: Metadata for filters if using CONFIG_SECCOMP_FILTER.
+ *           filters assignment/use should be RCU-protected and its contents
+ *           should never be modified when attached to a seccomp_struct.
+ */
+struct seccomp_struct {
+     uint16_t mode;
+#ifdef CONFIG_SECCOMP_FILTER
+     struct seccomp_filters *filters;
+#endif
+};
 
  extern void __secure_computing(int);
  static inline void secure_computing(int this_syscall)
@@ -16,15 +36,14 @@ static inline void secure_computing(int this_syscall)
               __secure_computing(this_syscall);
  }
 
-extern long prctl_get_seccomp(void);
  extern long prctl_set_seccomp(unsigned long);
+extern long prctl_get_seccomp(void);
 
  #else /* CONFIG_SECCOMP */
 
  #include <linux/errno.h>
 
-typedef struct { } seccomp_t;
-
+struct seccomp_struct { };
  #define secure_computing(x) do { } while (0)
 
  static inline long prctl_get_seccomp(void)
@@ -32,11 +51,80 @@ static inline long prctl_get_seccomp(void)
       return -EINVAL;
  }
 
-static inline long prctl_set_seccomp(unsigned long arg2)
+static inline long prctl_set_seccomp(unsigned long a2);
  {
       return -EINVAL;
  }
 
  #endif /* CONFIG_SECCOMP */
 
+#ifdef CONFIG_SECCOMP_FILTER
+
+#define inherit_tsk_seccomp(_child, _orig) do { \
+     _child->seccomp.mode = _orig->seccomp.mode; \
+     _child->seccomp.filters = get_seccomp_filters(_orig->seccomp.filters); \
+     } while (0)
+#define put_tsk_seccomp(_tsk) put_seccomp_filters(_tsk->seccomp.filters)
+
+extern int seccomp_show_filters(struct seccomp_filters *filters,
+                             struct seq_file *);
+extern long seccomp_set_filter(int, char *);
+extern long seccomp_clear_filter(int);
+extern long seccomp_get_filter(int, char *, unsigned long);
+
+extern long prctl_set_seccomp_filter(unsigned long, char __user *);
+extern long prctl_get_seccomp_filter(unsigned long, char __user *,
+                                  unsigned long);
+extern long prctl_clear_seccomp_filter(unsigned long);
+
+extern struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *);
+extern void put_seccomp_filters(struct seccomp_filters *);
+
+extern int seccomp_test_filters(int);
+extern void seccomp_filter_log_failure(int);
+
+#else  /* CONFIG_SECCOMP_FILTER */
+
+struct seccomp_filters { };
+#define inherit_tsk_seccomp(_child, _orig) do { } while (0)
+#define put_tsk_seccomp(_tsk) do { } while (0)
+
+static inline int seccomp_show_filters(struct seccomp_filters *filters,
+                                    struct seq_file *m)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_set_filter(int syscall_nr, char *filter)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_clear_filter(int syscall_nr)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_get_filter(int syscall_nr,
+                                   char *buf, unsigned long available)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_set_seccomp_filter(unsigned long a2, char __user *a3)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_clear_seccomp_filter(unsigned long a2)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_get_seccomp_filter(unsigned long a2, char __user *a3,
+                                         unsigned long a4)
+{
+     return -ENOSYS;
+}
+#endif  /* CONFIG_SECCOMP_FILTER */
  #endif /* _LINUX_SECCOMP_H */
include/trace/syscall.h +7 -0
index 242ae04..e061ad0 100644
@@ -35,6 +35,8 @@ struct syscall_metadata {
  extern unsigned long arch_syscall_addr(int nr);
  extern int init_syscall_trace(struct ftrace_event_call *call);
 
+extern struct syscall_metadata *syscall_nr_to_meta(int);
+
  extern int reg_event_syscall_enter(struct ftrace_event_call *call);
  extern void unreg_event_syscall_enter(struct ftrace_event_call *call);
  extern int reg_event_syscall_exit(struct ftrace_event_call *call);
@@ -49,6 +51,11 @@ enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
                                     struct trace_event *event);
  enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
                                    struct trace_event *event);
+#else
+static inline struct syscall_metadata *syscall_nr_to_meta(int nr)
+{
+     return NULL;
+}
  #endif
 
  #ifdef CONFIG_PERF_EVENTS
kernel/Makefile +0 -0
index 85cbfb3..84e7dfb 100644
@@ -81,6 +81,9 @@ obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o

 obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
 obj-$(CONFIG_GENERIC_HARDIRQS) += irq/
 obj-$(CONFIG_SECCOMP) += seccomp.o

kernel/Makefile +3 -0
+ifeq ($(CONFIG_SECCOMP_FILTER),y)
+obj-$(CONFIG_SECCOMP) += seccomp_filter.o
+endif

 obj-$(CONFIG_RCU_TORTURE_TEST) += rcutorture.o
 obj-$(CONFIG_TREE_RCU) += rcutree.o
 obj-$(CONFIG_TREE_PREEMPT_RCU) += rcutree.o

kernel/fork.c +3 -0
index e7548de..6f835e0 100644
@@ -34,6 +34,7 @@
  #include <linux/cgroup.h>
  #include <linux/security.h>
  #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
  #include <linux/swap.h>
  #include <linux/syscalls.h>
  #include <linux/jiffies.h>
@@ -169,6 +170,7 @@ void free_task(struct task_struct *tsk)
       free_thread_info(tsk->stack);
       rt_mutex_debug_task_free(tsk);
       ftrace_graph_exit_task(tsk);
+     put_tsk_seccomp(tsk);
       free_task_struct(tsk);
  }
  EXPORT_SYMBOL(free_task);
@@ -280,6 +282,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
       if (err)
               goto out;
 
+     inherit_tsk_seccomp(tsk, orig);
       setup_thread_stack(tsk, orig);
       clear_user_return_notifier(tsk);
       clear_tsk_need_resched(tsk);
kernel/seccomp.c +6 -3
index 57d4b13..0a942be 100644
@@ -2,16 +2,20 @@
   * linux/kernel/seccomp.c
   *
   * Copyright 2004-2005  Andrea Arcangeli <[email protected]>
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
   *
   * This defines a simple but solid secure-computing mode.
   */
 
  #include <linux/seccomp.h>
  #include <linux/sched.h>
+#include <linux/slab.h>
  #include <linux/compat.h>
+#include <linux/unistd.h>
+#include <linux/ftrace_event.h>
 
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
  /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
 
  /*
   * Secure computing mode 1 allows only read/write/exit/sigreturn.
@@ -32,10 +36,9 @@ static int mode1_syscalls_32[] = {
 
  void __secure_computing(int this_syscall)
  {
-     int mode = current->seccomp.mode;
       int * syscall;
 
-     switch (mode) {
+     switch (current->seccomp.mode) {

      case 1:
              syscall = mode1_syscalls;
 #ifdef CONFIG_COMPAT

kernel/seccomp.c +11 -0
@@ -47,6 +50,17 @@ void __secure_computing(int this_syscall)
                               return;
               } while (*++syscall);
               break;
+#ifdef CONFIG_SECCOMP_FILTER
+     case 2:
+             if (this_syscall >= NR_syscalls || this_syscall < 0)
+                     break;
+
+             if (!seccomp_test_filters(this_syscall))
+                     return;
+
+             seccomp_filter_log_failure(this_syscall);
+             break;
+#endif

      default:
              BUG();
      }

kernel/seccomp.c +12 -6
@@ -71,16 +85,22 @@ long prctl_set_seccomp(unsigned long seccomp_mode)
       if (unlikely(current->seccomp.mode))
               goto out;
 
-     ret = -EINVAL;
-     if (seccomp_mode && seccomp_mode <= NR_SECCOMP_MODES) {
-             current->seccomp.mode = seccomp_mode;
-             set_thread_flag(TIF_SECCOMP);
+     ret = 0;
+     switch (seccomp_mode) {
+     case 1:
  #ifdef TIF_NOTSC
               disable_TSC();
  #endif
-             ret = 0;
+#ifdef CONFIG_SECCOMP_FILTER
+     case 2:
+#endif
+             current->seccomp.mode = seccomp_mode;
+             set_thread_flag(TIF_SECCOMP);
+             break;
+     default:
+             ret = -EINVAL;
       }
 
- out:
+out:
       return ret;
  }
kernel/seccomp_filter.c new file +409 -0
new file mode 100644
index 0000000..9782f25
@@ -0,0 +1,784 @@
+/* filter engine-based seccomp system call filtering
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
+ */
+
+#include <linux/compat.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/ftrace_event.h>
+#include <linux/seccomp.h>
+#include <linux/seq_file.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/uaccess.h>
+
+#include <asm/syscall.h>
+#include <trace/syscall.h>
+
+
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
+
+#define SECCOMP_FILTER_ALLOW "1"
+#define SECCOMP_ACTION_DENY 0xffff
+#define SECCOMP_ACTION_ALLOW 0xfffe
+
+/**
+ * struct seccomp_filters - container for seccomp filterset
+ *
+ * @syscalls: array of 16-bit indices into @event_filters by syscall_nr
+ *            May also be SECCOMP_ACTION_DENY or SECCOMP_ACTION_ALLOW
+ * @event_filters: array of pointers to ftrace event objects
+ * @count: size of @event_filters
+ * @flags: anonymous struct to wrap filters-specific flags
+ * @usage: reference count to simplify use.
+ */
+struct seccomp_filters {
+     uint16_t syscalls[NR_syscalls];
+     struct event_filter **event_filters;
+     uint16_t count;
+     struct {
+             uint32_t compat:1,
+                      __reserved:31;
+     } flags;
+     atomic_t usage;
+};
+
+/* Handle ftrace symbol non-existence */
+#ifdef CONFIG_FTRACE_SYSCALLS
+#define create_event_filter(_ef_pptr, _event_type, _str) \
+     ftrace_parse_filter(_ef_pptr, _event_type, _str)
+#define get_filter_string(_ef) ftrace_get_filter_string(_ef)
+#define free_event_filter(_f) ftrace_free_filter(_f)
+
+#else
+
+#define create_event_filter(_ef_pptr, _event_type, _str) (-ENOSYS)
+#define get_filter_string(_ef) (NULL)
+#define free_event_filter(_f) do { } while (0)
+#endif
+
+/**
+ * seccomp_filters_new - allocates a new filters object
+ * @count: count to allocate for the event_filters array
+ *
+ * Returns ERR_PTR on error or an allocated object.
+ */
+static struct seccomp_filters *seccomp_filters_new(uint16_t count)
+{
+     struct seccomp_filters *f;
+
+     if (count >= SECCOMP_ACTION_ALLOW)
+             return ERR_PTR(-EINVAL);
+
+     f = kzalloc(sizeof(struct seccomp_filters), GFP_KERNEL);
+     if (!f)
+             return ERR_PTR(-ENOMEM);
+
+     /* Lazy SECCOMP_ACTION_DENY assignment. */
+     memset(f->syscalls, 0xff, sizeof(f->syscalls));
+     atomic_set(&f->usage, 1);
+
+     f->event_filters = NULL;
+     f->count = count;
+     if (!count)
+             return f;
+
+     f->event_filters = kzalloc(count * sizeof(struct event_filter *),
+                                GFP_KERNEL);
+     if (!f->event_filters) {
+             kfree(f);
+             f = ERR_PTR(-ENOMEM);
+     }
+     return f;
+}
+
+/**
+ * seccomp_filters_free - cleans up the filter list and frees the table
+ * @filters: NULL or live object to be completely destructed.
+ */
+static void seccomp_filters_free(struct seccomp_filters *filters)
+{
+     uint16_t count = 0;
+     if (!filters)
+             return;
+     while (count < filters->count) {
+             struct event_filter *f = filters->event_filters[count];
+             free_event_filter(f);
+             count++;
+     }
+     kfree(filters->event_filters);
+     kfree(filters);
+}
+
+static void __put_seccomp_filters(struct seccomp_filters *orig)
+{
+     WARN_ON(atomic_read(&orig->usage));
+     seccomp_filters_free(orig);
+}
+
+#define seccomp_filter_allow(_id) ((_id) == SECCOMP_ACTION_ALLOW)
+#define seccomp_filter_deny(_id) ((_id) == SECCOMP_ACTION_DENY)
+#define seccomp_filter_dynamic(_id) \
+     (!seccomp_filter_allow(_id) && !seccomp_filter_deny(_id))
+static inline uint16_t seccomp_filter_id(const struct seccomp_filters *f,
+                                      int syscall_nr)
+{
+     if (!f)
+             return SECCOMP_ACTION_DENY;
+     return f->syscalls[syscall_nr];
+}
+
+static inline struct event_filter *seccomp_dynamic_filter(
+             const struct seccomp_filters *filters, uint16_t id)
+{
+     if (!seccomp_filter_dynamic(id))
+             return NULL;
+     return filters->event_filters[id];
+}
+
+static inline void set_seccomp_filter_id(struct seccomp_filters *filters,
+                                      int syscall_nr, uint16_t id)
+{
+     filters->syscalls[syscall_nr] = id;
+}
+
+static inline void set_seccomp_filter(struct seccomp_filters *filters,
+                                   int syscall_nr, uint16_t id,
+                                   struct event_filter *dynamic_filter)
+{
+     filters->syscalls[syscall_nr] = id;
+     if (seccomp_filter_dynamic(id))
+             filters->event_filters[id] = dynamic_filter;
+}
+
+static struct event_filter *alloc_event_filter(int syscall_nr,
+                                            const char *filter_string)
+{
+     struct syscall_metadata *data;
+     struct event_filter *filter = NULL;
+     int err;
+
+     data = syscall_nr_to_meta(syscall_nr);
+     /* Argument-based filtering only works on ftrace-hooked syscalls. */
+     err = -ENOSYS;
+     if (!data)
+             goto fail;
+     err = create_event_filter(&filter,
+                               data->enter_event->event.type,
+                               filter_string);
+     if (err)
+             goto fail;
+
+     return filter;
+fail:
+     kfree(filter);
+     return ERR_PTR(err);
+}
+
+/**
+ * seccomp_filters_copy - copies filters from src to dst.
+ *
+ * @dst: seccomp_filters to populate.
+ * @src: table to read from.
+ * @skip: specifies an entry, by system call, to skip.
+ *
+ * Returns non-zero on failure.
+ * Both the source and the destination should have no simultaneous
+ * writers, and dst should be exclusive to the caller.
+ * If @skip is < 0, it is ignored.
+ */
+static int seccomp_filters_copy(struct seccomp_filters *dst,
+                             const struct seccomp_filters *src,
+                             int skip)
+{
+     int id = 0, ret = 0, nr;
+     memcpy(&dst->flags, &src->flags, sizeof(src->flags));
+     memcpy(dst->syscalls, src->syscalls, sizeof(dst->syscalls));
+     if (!src->count)
+             goto done;
+     for (nr = 0; nr < NR_syscalls; ++nr) {
+             struct event_filter *filter;
+             const char *str;
+             uint16_t src_id = seccomp_filter_id(src, nr);
+             if (nr == skip) {
+                     set_seccomp_filter(dst, nr, SECCOMP_ACTION_DENY,
+                                        NULL);
+                     continue;
+             }
+             if (!seccomp_filter_dynamic(src_id))
+                     continue;
+             if (id >= dst->count) {
+                     ret = -EINVAL;
+                     goto done;
+             }
+             str = get_filter_string(seccomp_dynamic_filter(src, src_id));
+             filter = alloc_event_filter(nr, str);
+             if (IS_ERR(filter)) {
+                     ret = PTR_ERR(filter);
+                     goto done;
+             }
+             set_seccomp_filter(dst, nr, id, filter);
+             id++;
+     }
+
+done:
+     return ret;
+}
+
+/**
+ * seccomp_extend_filter - appends more text to a syscall_nr's filter
+ * @filters: unattached filter object to operate on
+ * @syscall_nr: syscall number to update filters for
+ * @filter_string: string to append to the existing filter
+ *
+ * The new string will be &&'d to the original filter string to ensure that it
+ * always matches the existing predicates or less:
+ *   (old_filter) && @filter_string
+ * A new seccomp_filters instance is returned on success and a ERR_PTR on
+ * failure.
+ */
+static int seccomp_extend_filter(struct seccomp_filters *filters,
+                              int syscall_nr, char *filter_string)
+{
+     struct event_filter *filter;
+     uint16_t id = seccomp_filter_id(filters, syscall_nr);
+     char *merged = NULL;
+     int ret = -EINVAL, expected;
+
+     /* No extending with a "1". */
+     if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string))
+             goto out;
+
+     filter = seccomp_dynamic_filter(filters, id);
+     ret = -ENOENT;
+     if (!filter)
+             goto out;
+
+     merged = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+     ret = -ENOMEM;
+     if (!merged)
+             goto out;
+
+     expected = snprintf(merged, SECCOMP_MAX_FILTER_LENGTH, "(%s) && %s",
+                         get_filter_string(filter), filter_string);
+     ret = -E2BIG;
+     if (expected >= SECCOMP_MAX_FILTER_LENGTH || expected < 0)
+             goto out;
+
+     /* Free the old filter */
+     free_event_filter(filter);
+     set_seccomp_filter(filters, syscall_nr, id, NULL);
+
+     /* Replace it */
+     filter = alloc_event_filter(syscall_nr, merged);
+     if (IS_ERR(filter)) {
+             ret = PTR_ERR(filter);
+             goto out;
+     }
+     set_seccomp_filter(filters, syscall_nr, id, filter);
+     ret = 0;
+
+out:
+     kfree(merged);
+     return ret;
+}
+
+/**
+ * seccomp_add_filter - adds a filter for an unfiltered syscall
+ * @filters: filters object to add a filter/action to
+ * @syscall_nr: system call number to add a filter for
+ * @filter_string: the filter string to apply
+ *
+ * Returns 0 on success and non-zero otherwise.
+ */
+static int seccomp_add_filter(struct seccomp_filters *filters, int syscall_nr,
+                           char *filter_string)
+{
+     struct event_filter *filter;
+     int ret = 0;
+
+     if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string)) {
+             set_seccomp_filter(filters, syscall_nr,
+                                SECCOMP_ACTION_ALLOW, NULL);
+             goto out;
+     }
+
+     filter = alloc_event_filter(syscall_nr, filter_string);
+     if (IS_ERR(filter)) {
+             ret = PTR_ERR(filter);
+             goto out;
+     }
+     /* Always add to the last slot available since additions are
+      * are only done one at a time.
+      */
+     set_seccomp_filter(filters, syscall_nr, filters->count - 1, filter);
+out:
+     return ret;
+}
+
+/* Wrap optional ftrace syscall support. Returns 1 on match or 0 otherwise. */
+static int filter_match_current(struct event_filter *event_filter)
+{
+     int err = 0;
+#ifdef CONFIG_FTRACE_SYSCALLS
+     uint8_t syscall_state[64];
+
+     memset(syscall_state, 0, sizeof(syscall_state));
+
+     /* The generic tracing entry can remain zeroed. */
+     err = ftrace_syscall_enter_state(syscall_state, sizeof(syscall_state),
+                                      NULL);
+     if (err)
+             return 0;
+
+     err = filter_match_preds(event_filter, syscall_state);
+#endif
+     return err;
+}
+
+static const char *syscall_nr_to_name(int syscall)
+{
+     const char *syscall_name = "unknown";
+     struct syscall_metadata *data = syscall_nr_to_meta(syscall);
+     if (data)
+             syscall_name = data->name;
+     return syscall_name;
+}
+
+static void filters_set_compat(struct seccomp_filters *filters)
+{
+#ifdef CONFIG_COMPAT
+     if (is_compat_task())
+             filters->flags.compat = 1;
+#endif
+}
+
+static inline int filters_compat_mismatch(struct seccomp_filters *filters)
+{
+     int ret = 0;
+     if (!filters)
+             return 0;
+#ifdef CONFIG_COMPAT
+     if (!!(is_compat_task()) == filters->flags.compat)
+             ret = 1;
+#endif
+     return ret;
+}
+
+static inline int syscall_is_execve(int syscall)
+{
+     int nr = __NR_execve;
+#ifdef CONFIG_COMPAT
+     if (is_compat_task())
+             nr = __NR_seccomp_execve_32;
+#endif
+     return syscall == nr;
+}
+
+#ifndef KSTK_EIP
+#define KSTK_EIP(x) 0L
+#endif
+
+void seccomp_filter_log_failure(int syscall)
+{
+     pr_info("%s[%d]: system call %d (%s) blocked at 0x%lx\n",
+             current->comm, task_pid_nr(current), syscall,
+             syscall_nr_to_name(syscall), KSTK_EIP(current));
+}
+
+/* put_seccomp_state - decrements the reference count of @orig and may free. */
+void put_seccomp_filters(struct seccomp_filters *orig)
+{
+     if (!orig)
+             return;
+
Quoted 8 lines

kernel/seccomp_filter.c line 415

Quoted 6 lines
kernel/seccomp_filter.c new file +6 -0
+     if (atomic_dec_and_test(&orig->usage))
+             __put_seccomp_filters(orig);
+}
+
+/* get_seccomp_state - increments the reference count of @orig */
+struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *orig)

Nit: the name does not match the comment.

Will fix it here and above. Thanks!

Quoted 9 lines

kernel/seccomp_filter.c line 420

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+{
+     if (!orig)
+             return NULL;
+     atomic_inc(&orig->usage);
+     return orig;

This is called in an RCU read-side critical section.  What exactly is RCU protecting?  I would expect an rcu_dereference() or one of the RCU list-traversal primitives somewhere, either here or at the caller.

Ah, I spaced on rcu_dereference(). The goal was to make the assignment and replacement of the seccomp_filters pointer RCU-protected (in seccomp_state) so there's no concern over it being replaced partial on platforms where pointer assignments are non-atomic
- such as via /proc/<pid>/seccomp_filters access or a call via the exported symbols. Object lifetime is managed by reference counting so that I don't have to worry about extending the RCU read-side critical section by much or deal with pre-allocations.

Quoted 3 lines

I'll add rcu_dereference() to all the get_seccomp_filters() uses where it makes sense, so that it is called safely. Just to make sure, does it make sense to continue to rcu protect the specific pointer?

It might. The usual other options is to use a lock outside of the element containing the reference count to protect reference-count manipulation. If there is some convenient lock, especially if it is already held where needed, then locking is more straightforward. Otherwise, RCU is usually a reasonable option.

Quoted 193 lines
Quoted 184 lines
Quoted 184 lines
kernel/seccomp_filter.c new file +184 -0
+}
+
+/**
+ * seccomp_test_filters - tests 'current' against the given syscall
+ * @state: seccomp_state of current to use.
+ * @syscall: number of the system call to test
+ *
+ * Returns 0 on ok and non-zero on error/failure.
+ */
+int seccomp_test_filters(int syscall)
+{
+     uint16_t id;
+     struct event_filter *filter;
+     struct seccomp_filters *filters;
+     int ret = -EACCES;
+
+     rcu_read_lock();
+     filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!filters)
+             goto out;
+
+     if (filters_compat_mismatch(filters)) {
+             pr_info("%s[%d]: seccomp_filter compat() mismatch.\n",
+                     current->comm, task_pid_nr(current));
+             goto out;
+     }
+
+     /* execve is never allowed. */
+     if (syscall_is_execve(syscall))
+             goto out;
+
+     ret = 0;
+     id = seccomp_filter_id(filters, syscall);
+     if (seccomp_filter_allow(id))
+             goto out;
+
+     ret = -EACCES;
+     if (!seccomp_filter_dynamic(id))
+             goto out;
+
+     filter = seccomp_dynamic_filter(filters, id);
+     if (filter && filter_match_current(filter))
+             ret = 0;
+out:
+     put_seccomp_filters(filters);
+     return ret;
+}
+
+/**
+ * seccomp_show_filters - prints the current filter state to a seq_file
+ * @filters: properly get()'d filters object
+ * @m: the prepared seq_file to receive the data
+ *
+ * Returns 0 on a successful write.
+ */
+int seccomp_show_filters(struct seccomp_filters *filters, struct seq_file *m)
+{
+     int syscall;
+     seq_printf(m, "Mode: %d\n", current->seccomp.mode);
+     if (!filters)
+             goto out;
+
+     for (syscall = 0; syscall < NR_syscalls; ++syscall) {
+             uint16_t id = seccomp_filter_id(filters, syscall);
+             const char *filter_string = SECCOMP_FILTER_ALLOW;
+             if (seccomp_filter_deny(id))
+                     continue;
+             seq_printf(m, "%d (%s): ",
+                           syscall,
+                           syscall_nr_to_name(syscall));
+             if (seccomp_filter_dynamic(id))
+                     filter_string = get_filter_string(
+                                       seccomp_dynamic_filter(filters, id));
+             seq_printf(m, "%s\n", filter_string);
+     }
+out:
+     return 0;
+}
+EXPORT_SYMBOL_GPL(seccomp_show_filters);
+
+/**
+ * seccomp_get_filter - copies the filter_string into "buf"
+ * @syscall_nr: system call number to look up
+ * @buf: destination buffer
+ * @bufsize: available space in the buffer.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Looks up the filter for the given system call number on current.  If found,
+ * the string length of the NUL-terminated buffer is returned and < 0 is
+ * returned on error. The NUL byte is not included in the length.
+ */
+long seccomp_get_filter(int syscall_nr, char *buf, unsigned long bufsize)
+{
+     struct seccomp_filters *filters;
+     struct event_filter *filter;
+     long ret = -EINVAL;
+     uint16_t id;
+
+     if (bufsize > SECCOMP_MAX_FILTER_LENGTH)
+             bufsize = SECCOMP_MAX_FILTER_LENGTH;
+
+     rcu_read_lock();
+     filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!filters)
+             goto out;
+
+     ret = -ENOENT;
+     id = seccomp_filter_id(filters, syscall_nr);
+     if (seccomp_filter_deny(id))
+             goto out;
+
+     if (seccomp_filter_allow(id)) {
+             ret = strlcpy(buf, SECCOMP_FILTER_ALLOW, bufsize);
+             goto copied;
+     }
+
+     filter = seccomp_dynamic_filter(filters, id);
+     if (!filter)
+             goto out;
+     ret = strlcpy(buf, get_filter_string(filter), bufsize);
+
+copied:
+     if (ret >= bufsize) {
+             ret = -ENOSPC;
+             goto out;
+     }
+     /* Zero out any remaining buffer, just in case. */
+     memset(buf + ret, 0, bufsize - ret);
+out:
+     put_seccomp_filters(filters);
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_get_filter);
+
+/**
+ * seccomp_clear_filter: clears the seccomp filter for a syscall.
+ * @syscall_nr: the system call number to clear filters for.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Returns 0 on success.
+ */
+long seccomp_clear_filter(int syscall_nr)
+{
+     struct seccomp_filters *filters = NULL, *orig_filters;
+     uint16_t id;
+     int ret = -EINVAL;
+
+     rcu_read_lock();
+     orig_filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!orig_filters)
+             goto out;
+
+     if (filters_compat_mismatch(orig_filters))
+             goto out;
+
+     id = seccomp_filter_id(orig_filters, syscall_nr);
+     if (seccomp_filter_deny(id))
+             goto out;
+
+     /* Create a new filters object for the task */
+     if (seccomp_filter_dynamic(id))
+             filters = seccomp_filters_new(orig_filters->count - 1);
+     else
+             filters = seccomp_filters_new(orig_filters->count);
+
+     if (IS_ERR(filters)) {
+             ret = PTR_ERR(filters);
+             goto out;
+     }
+
+     /* Copy, but drop the requested entry. */
+     ret = seccomp_filters_copy(filters, orig_filters, syscall_nr);
Quoted 8 lines

kernel/seccomp_filter.c line 609

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+     if (ret)
+             goto out;
+     get_seccomp_filters(filters);  /* simplify the out: path */
+
+     rcu_assign_pointer(current->seccomp.filters, filters);

What prevents two copies of seccomp_clear_filter() from running concurrently?

Quoted 5 lines

Nothing - the last one wins assignment, but the objects themselves should be internally consistent to the parallel calls. If that's a concern, a per-task writer mutex could be used just to ensure simultaneous calls to clear and set are performed serially. Would that make more sense?

Here is the sequence of events that I am concerned about:

o CPU 0 sets orig_filters to point to the current filters.

o CPU 1 sets its local orig_filters to point to the current
set of filters.

o Both CPUs allocate new filters and use rcu_assign_pointer()
to do the update. As you say, the last one wins, but it appears to me that the first one leaks memory.

o Both CPUs free the object referenced by their orig_filters,
which might or might not result in a double free, depending on exactly what happens below. (You might actually be OK, I didn't check -- leaking memory was enough for me to call attention to this.)

So yes, please use some kind of mutual exclusion. Not sure what you mean by "per-task mutex", but whatever it is must prevent two different tasks from acting on the same set of filters at the same time. The thing that I call "per-task mutex" would -not- do that.

Quoted 262 lines
Quoted 75 lines
Quoted 75 lines
kernel/seccomp_filter.c new file +75 -0
+     synchronize_rcu();
+     put_seccomp_filters(orig_filters);  /* for the task */
+out:
+     put_seccomp_filters(orig_filters);  /* for the get */
+     put_seccomp_filters(filters);  /* for the extra get */
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_clear_filter);
+
+/**
+ * seccomp_set_filter: - Adds/extends a seccomp filter for a syscall.
+ * @syscall_nr: system call number to apply the filter to.
+ * @filter: ftrace filter string to apply.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * New filters may be added for system calls when the current task is
+ * not in a secure computing mode (seccomp).  Otherwise, existing filters may
+ * be extended.
+ *
+ * Returns 0 on success or an errno on failure.
+ */
+long seccomp_set_filter(int syscall_nr, char *filter)
+{
+     struct seccomp_filters *filters = NULL, *orig_filters = NULL;
+     uint16_t id;
+     long ret = -EINVAL;
+     uint16_t filters_needed;
+
+     if (!filter)
+             goto out;
+
+     filter = strstrip(filter);
+     /* Disallow empty strings. */
+     if (filter[0] == 0)
+             goto out;
+
+     rcu_read_lock();
+     orig_filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     /* After the first call, compatibility mode is selected permanently. */
+     ret = -EACCES;
+     if (filters_compat_mismatch(orig_filters))
+             goto out;
+
+     filters_needed = orig_filters ? orig_filters->count : 0;
+     id = seccomp_filter_id(orig_filters, syscall_nr);
+     if (seccomp_filter_deny(id)) {
+             /* Don't allow DENYs to be changed when in a seccomp mode */
+             ret = -EACCES;
+             if (current->seccomp.mode)
+                     goto out;
+             filters_needed++;
+     }
+
+     filters = seccomp_filters_new(filters_needed);
+     if (IS_ERR(filters)) {
+             ret = PTR_ERR(filters);
+             goto out;
+     }
+
+     filters_set_compat(filters);
+     if (orig_filters) {
+             ret = seccomp_filters_copy(filters, orig_filters, -1);
+             if (ret)
+                     goto out;
+     }
+
+     if (seccomp_filter_deny(id))
+             ret = seccomp_add_filter(filters, syscall_nr, filter);
+     else
+             ret = seccomp_extend_filter(filters, syscall_nr, filter);
Quoted 8 lines

kernel/seccomp_filter.c line 689

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+     if (ret)
+             goto out;
+     get_seccomp_filters(filters);  /* simplify the error paths */
+
+     rcu_assign_pointer(current->seccomp.filters, filters);

Again, what prevents two copies of seccomp_set_filter() from running concurrently?

Same deal - nothing, but I'd be happy to add a guard if it makes sense.

Thanks!

Quoted 163 lines
Quoted 163 lines
kernel/seccomp_filter.c new file +95 -0
+     synchronize_rcu();
+     put_seccomp_filters(orig_filters);  /* for the task */
+out:
+     put_seccomp_filters(orig_filters);  /* for the get */
+     put_seccomp_filters(filters);  /* for get or task, on err */
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_set_filter);
+
+long prctl_set_seccomp_filter(unsigned long syscall_nr,
+                           char __user *user_filter)
+{
+     int nr;
+     long ret;
+     char *filter = NULL;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+
+     ret = -EFAULT;
+     if (!user_filter)
+             goto out;
+
+     filter = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+     ret = -ENOMEM;
+     if (!filter)
+             goto out;
+
+     ret = -EFAULT;
+     if (strncpy_from_user(filter, user_filter,
+                           SECCOMP_MAX_FILTER_LENGTH - 1) < 0)
+             goto out;
+
+     nr = (int) syscall_nr;
+     ret = seccomp_set_filter(nr, filter);
+
+out:
+     kfree(filter);
+     return ret;
+}
+
+long prctl_clear_seccomp_filter(unsigned long syscall_nr)
+{
+     int nr = -1;
+     long ret;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+
+     nr = (int) syscall_nr;
+     ret = seccomp_clear_filter(nr);
+
+out:
+     return ret;
+}
+
+long prctl_get_seccomp_filter(unsigned long syscall_nr, char __user *dst,
+                           unsigned long available)
+{
+     int ret, nr;
+     unsigned long copied;
+     char *buf = NULL;
+     ret = -EINVAL;
+     if (!available)
+             goto out;
+     /* Ignore extra buffer space. */
+     if (available > SECCOMP_MAX_FILTER_LENGTH)
+             available = SECCOMP_MAX_FILTER_LENGTH;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+     nr = (int) syscall_nr;
+
+     ret = -ENOMEM;
+     buf = kmalloc(available, GFP_KERNEL);
+     if (!buf)
+             goto out;
+
+     ret = seccomp_get_filter(nr, buf, available);
+     if (ret < 0)
+             goto out;
+
+     /* Include the NUL byte in the copy. */
+     copied = copy_to_user(dst, buf, ret + 1);
+     ret = -ENOSPC;
+     if (copied)
+             goto out;
+     ret = 0;
+out:
+     kfree(buf);
+     return ret;
+}
kernel/sys.c +0 -0
index af468ed..ed60d06 100644
@@ -1698,13 +1698,24 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,

              case PR_SET_ENDIAN:
                      error = SET_ENDIAN(me, arg2);
                      break;
-
              case PR_GET_SECCOMP:
                      error = prctl_get_seccomp();
                      break;
              case PR_SET_SECCOMP:
                      error = prctl_set_seccomp(arg2);
                      break;
+             case PR_SET_SECCOMP_FILTER:
+                     error = prctl_set_seccomp_filter(arg2,
+                                                      (char __user *) arg3);
+                     break;
+             case PR_CLEAR_SECCOMP_FILTER:
+                     error = prctl_clear_seccomp_filter(arg2);
+                     break;
+             case PR_GET_SECCOMP_FILTER:
+                     error = prctl_get_seccomp_filter(arg2,
+                                                      (char __user *) arg3,
+                                                      arg4);
+                     break;
              case PR_GET_TSC:
                      error = GET_TSC_CTL(arg2);
                      break;

security/Kconfig +4 -0
index 95accd4..c76adf2 100644
@@ -2,6 +2,10 @@
  # Security configuration
  #
 
+# Make seccomp filter Kconfig switch below available
+config HAVE_SECCOMP_FILTER
+       bool
+

 menu "Security options"

 config KEYS

security/Kconfig +0 -0
@@ -82,6 +86,19 @@ config SECURITY_DMESG_RESTRICT
 

        If you are unsure how to answer this question, answer N.

security/Kconfig +13 -0
+config SECCOMP_FILTER
+     bool "Enable seccomp-based system call filtering"
+     select SECCOMP
+     depends on HAVE_SECCOMP_FILTER && EXPERIMENTAL
+     help
+       This kernel feature expands CONFIG_SECCOMP to allow computing
+       in environments with reduced kernel access dictated by the
+       application itself through prctl calls.  If
+       CONFIG_FTRACE_SYSCALLS is available, then system call
+       argument-based filtering predicates may be used.
+
+       See Documentation/prctl/seccomp_filter.txt for more detail.
+

 config SECURITY
      bool "Enable different security models"
      depends on SYSFS
--
1.7.0.4

Quoted 6 lines
Quoted 5 lines

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/

author reviewer
#104 lore raw

Re: [PATCH v3 03/13] seccomp_filters: new mode with configurable syscall filters

Quoted 874 lines · Paul E. McKenney
Quoted 869 lines · Will Drewry
Quoted 837 lines · Paul E. McKenney
Quoted 6 lines · Will Drewry

This change adds a new seccomp mode which specifies the allowed system calls dynamically.  When in the new mode (2), all system calls are checked against process-defined filters - first by system call number, then by a filter string.  If an entry exists for a given system call and all filter predicates evaluate to true, then the task may proceed. Otherwise, the task is killed.

A few questions below -- I can't say that I understand the RCU usage.

                                                       Thanx, Paul

Quoted 825 lines

Filter string parsing and evaluation is handled by the ftrace filter engine.  Related patches tweak to the perf filter trace and free allowing the calls to be shared. Filters inherit their understanding of types and arguments for each system call from the CONFIG_FTRACE_SYSCALLS subsystem which already populates this information in syscall_metadata associated enter_event (and exit_event) structures. If CONFIG_FTRACE_SYSCALLS is not compiled in, only filter strings of "1" will be allowed.

The net result is a process may have its system calls filtered using the ftrace filter engine's inherent understanding of systems calls.  The set of filters is specified through the PR_SET_SECCOMP_FILTER argument in prctl(). For example, a filterset for a process, like pdftotext, that should only process read-only input could (roughly) look like:
  sprintf(rdonly, "flags == %u", O_RDONLY|O_LARGEFILE); prctl(PR_SET_SECCOMP_FILTER, __NR_open, rdonly); prctl(PR_SET_SECCOMP_FILTER, __NR__llseek, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_brk, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_close, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_exit_group, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_fstat64, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_mmap2, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_munmap, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "1"); prctl(PR_SET_SECCOMP_FILTER, __NR_write, "(fd == 1 | fd == 2)"); prctl(PR_SET_SECCOMP, 2);

Subsequent calls to PR_SET_SECCOMP_FILTER for the same system call will be &&'d together to ensure that attack surface may only be reduced:
  prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd != 2");

With the earlier example, the active filter becomes:
  "(fd == 1 || fd == 2) && fd != 2"

The patch also adds PR_CLEAR_SECCOMP_FILTER and PR_GET_SECCOMP_FILTER. The latter returns the current filter for a system call to userspace:

  prctl(PR_GET_SECCOMP_FILTER, __NR_write, buf, bufsize);

while the former clears any filters for a given system call changing it back to a defaulty deny:

  prctl(PR_CLEAR_SECCOMP_FILTER, __NR_write);

v3: - always block execve calls (as per linus torvalds)
    - add __NR_seccomp_execve(_32) to seccomp-supporting arches
    - ensure compat tasks can't reach ftrace:syscalls
    - dropped new defines for seccomp modes.
    - two level array instead of hlists (sugg. by olof johansson)
    - added generic Kconfig entry that is not connected.
    - dropped internal seccomp.h
    - move prctl helpers to seccomp_filter
    - killed seccomp_t typedef (as per checkpatch)
v2: - changed to use the existing syscall number ABI.
    - prctl changes to minimize parsing in the kernel:
      prctl(PR_SET_SECCOMP, {0 | 1 | 2 }, { 0 | ON_EXEC }); prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 5"); prctl(PR_CLEAR_SECCOMP_FILTER, __NR_read); prctl(PR_GET_SECCOMP_FILTER, __NR_read, buf, bufsize);
    - defined PR_SECCOMP_MODE_STRICT and ..._FILTER
    - added flags
    - provide a default fail syscall_nr_to_meta in ftrace
    - provides fallback for unhooked system calls
    - use -ENOSYS and ERR_PTR(-ENOSYS) for stubbed functionality
    - added kernel/seccomp.h to share seccomp.c/seccomp_filter.c
    - moved to a hlist and 4 bit hash of linked lists
    - added support to operate without CONFIG_FTRACE_SYSCALLS
    - moved Kconfig support next to SECCOMP
    - made Kconfig entries dependent on EXPERIMENTAL
    - added macros to avoid ifdefs from kernel/fork.c
    - added compat task/filter matching
    - drop seccomp.h inclusion in sched.h and drop seccomp_t
    - added Filtering to "show" output
    - added on_exec state dup'ing when enabling after a fast-path accept.

---
 include/linux/prctl.h   |    5 +
 include/linux/sched.h   |    2 +-
 include/linux/seccomp.h |   98 ++++++-
 include/trace/syscall.h |    7 +
 kernel/Makefile         |    3 +
 kernel/fork.c           |    3 +
 kernel/seccomp.c        |   38 ++-
 kernel/seccomp_filter.c |  784 +++++++++++++++++++++++++++++++++++++++++++++++ kernel/sys.c            |   13 +-
 security/Kconfig        |   17 +

 10 files changed, 954 insertions(+), 16 deletions(-)

 create mode 100644 kernel/seccomp_filter.c

include/linux/prctl.h +5 -0
index a3baeb2..44723ce 100644
@@ -64,6 +64,11 @@
  #define PR_GET_SECCOMP       21
  #define PR_SET_SECCOMP       22
 
+/* Get/set process seccomp filters */
+#define PR_GET_SECCOMP_FILTER        35
+#define PR_SET_SECCOMP_FILTER        36
+#define PR_CLEAR_SECCOMP_FILTER      37
+
  /* Get/set the capability bounding set (as per security/commoncap.c) */
  #define PR_CAPBSET_READ 23
  #define PR_CAPBSET_DROP 24
include/linux/sched.h +1 -1
index 18d63ce..3f0bc8d 100644
@@ -1374,7 +1374,7 @@ struct task_struct {
       uid_t loginuid;
       unsigned int sessionid;
  #endif
-     seccomp_t seccomp;
+     struct seccomp_struct seccomp;
 
  /* Thread group tracking */
       u32 parent_exec_id;
include/linux/seccomp.h +93 -5
index 167c333..f4434ca 100644
@@ -1,13 +1,33 @@
  #ifndef _LINUX_SECCOMP_H
  #define _LINUX_SECCOMP_H
 
+struct seq_file;
 
  #ifdef CONFIG_SECCOMP
 
+#include <linux/errno.h>
  #include <linux/thread_info.h>
+#include <linux/types.h>
  #include <asm/seccomp.h>
 
-typedef struct { int mode; } seccomp_t;
+struct seccomp_filters;
+/**
+ * struct seccomp_struct - the state of a seccomp'ed process
+ *
+ * @mode:
+ *     if this is 1, the process is under standard seccomp rules
+ *             is 2, the process is only allowed to make system calls where
+ *                   associated filters evaluate successfully.
+ * @filters: Metadata for filters if using CONFIG_SECCOMP_FILTER.
+ *           filters assignment/use should be RCU-protected and its contents
+ *           should never be modified when attached to a seccomp_struct.
+ */
+struct seccomp_struct {
+     uint16_t mode;
+#ifdef CONFIG_SECCOMP_FILTER
+     struct seccomp_filters *filters;
+#endif
+};
 
  extern void __secure_computing(int);
  static inline void secure_computing(int this_syscall)
@@ -16,15 +36,14 @@ static inline void secure_computing(int this_syscall)
               __secure_computing(this_syscall);
  }
 
-extern long prctl_get_seccomp(void);
  extern long prctl_set_seccomp(unsigned long);
+extern long prctl_get_seccomp(void);
 
  #else /* CONFIG_SECCOMP */
 
  #include <linux/errno.h>
 
-typedef struct { } seccomp_t;
-
+struct seccomp_struct { };
  #define secure_computing(x) do { } while (0)
 
  static inline long prctl_get_seccomp(void)
@@ -32,11 +51,80 @@ static inline long prctl_get_seccomp(void)
       return -EINVAL;
  }
 
-static inline long prctl_set_seccomp(unsigned long arg2)
+static inline long prctl_set_seccomp(unsigned long a2);
  {
       return -EINVAL;
  }
 
  #endif /* CONFIG_SECCOMP */
 
+#ifdef CONFIG_SECCOMP_FILTER
+
+#define inherit_tsk_seccomp(_child, _orig) do { \
+     _child->seccomp.mode = _orig->seccomp.mode; \
+     _child->seccomp.filters = get_seccomp_filters(_orig->seccomp.filters); \
+     } while (0)
+#define put_tsk_seccomp(_tsk) put_seccomp_filters(_tsk->seccomp.filters)
+
+extern int seccomp_show_filters(struct seccomp_filters *filters,
+                             struct seq_file *);
+extern long seccomp_set_filter(int, char *);
+extern long seccomp_clear_filter(int);
+extern long seccomp_get_filter(int, char *, unsigned long);
+
+extern long prctl_set_seccomp_filter(unsigned long, char __user *);
+extern long prctl_get_seccomp_filter(unsigned long, char __user *,
+                                  unsigned long);
+extern long prctl_clear_seccomp_filter(unsigned long);
+
+extern struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *);
+extern void put_seccomp_filters(struct seccomp_filters *);
+
+extern int seccomp_test_filters(int);
+extern void seccomp_filter_log_failure(int);
+
+#else  /* CONFIG_SECCOMP_FILTER */
+
+struct seccomp_filters { };
+#define inherit_tsk_seccomp(_child, _orig) do { } while (0)
+#define put_tsk_seccomp(_tsk) do { } while (0)
+
+static inline int seccomp_show_filters(struct seccomp_filters *filters,
+                                    struct seq_file *m)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_set_filter(int syscall_nr, char *filter)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_clear_filter(int syscall_nr)
+{
+     return -ENOSYS;
+}
+
+static inline long seccomp_get_filter(int syscall_nr,
+                                   char *buf, unsigned long available)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_set_seccomp_filter(unsigned long a2, char __user *a3)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_clear_seccomp_filter(unsigned long a2)
+{
+     return -ENOSYS;
+}
+
+static inline long prctl_get_seccomp_filter(unsigned long a2, char __user *a3,
+                                         unsigned long a4)
+{
+     return -ENOSYS;
+}
+#endif  /* CONFIG_SECCOMP_FILTER */
  #endif /* _LINUX_SECCOMP_H */
include/trace/syscall.h +7 -0
index 242ae04..e061ad0 100644
@@ -35,6 +35,8 @@ struct syscall_metadata {
  extern unsigned long arch_syscall_addr(int nr);
  extern int init_syscall_trace(struct ftrace_event_call *call);
 
+extern struct syscall_metadata *syscall_nr_to_meta(int);
+
  extern int reg_event_syscall_enter(struct ftrace_event_call *call);
  extern void unreg_event_syscall_enter(struct ftrace_event_call *call);
  extern int reg_event_syscall_exit(struct ftrace_event_call *call);
@@ -49,6 +51,11 @@ enum print_line_t print_syscall_enter(struct trace_iterator *iter, int flags,
                                     struct trace_event *event);
  enum print_line_t print_syscall_exit(struct trace_iterator *iter, int flags,
                                    struct trace_event *event);
+#else
+static inline struct syscall_metadata *syscall_nr_to_meta(int nr)
+{
+     return NULL;
+}
  #endif
 
  #ifdef CONFIG_PERF_EVENTS
kernel/Makefile +0 -0
index 85cbfb3..84e7dfb 100644
@@ -81,6 +81,9 @@ obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o

 obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
 obj-$(CONFIG_GENERIC_HARDIRQS) += irq/
 obj-$(CONFIG_SECCOMP) += seccomp.o

kernel/Makefile +3 -0
+ifeq ($(CONFIG_SECCOMP_FILTER),y)
+obj-$(CONFIG_SECCOMP) += seccomp_filter.o
+endif

 obj-$(CONFIG_RCU_TORTURE_TEST) += rcutorture.o
 obj-$(CONFIG_TREE_RCU) += rcutree.o
 obj-$(CONFIG_TREE_PREEMPT_RCU) += rcutree.o

kernel/fork.c +3 -0
index e7548de..6f835e0 100644
@@ -34,6 +34,7 @@
  #include <linux/cgroup.h>
  #include <linux/security.h>
  #include <linux/hugetlb.h>
+#include <linux/seccomp.h>
  #include <linux/swap.h>
  #include <linux/syscalls.h>
  #include <linux/jiffies.h>
@@ -169,6 +170,7 @@ void free_task(struct task_struct *tsk)
       free_thread_info(tsk->stack);
       rt_mutex_debug_task_free(tsk);
       ftrace_graph_exit_task(tsk);
+     put_tsk_seccomp(tsk);
       free_task_struct(tsk);
  }
  EXPORT_SYMBOL(free_task);
@@ -280,6 +282,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig)
       if (err)
               goto out;
 
+     inherit_tsk_seccomp(tsk, orig);
       setup_thread_stack(tsk, orig);
       clear_user_return_notifier(tsk);
       clear_tsk_need_resched(tsk);
kernel/seccomp.c +6 -3
index 57d4b13..0a942be 100644
@@ -2,16 +2,20 @@
   * linux/kernel/seccomp.c
   *
   * Copyright 2004-2005  Andrea Arcangeli <[email protected]>
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
   *
   * This defines a simple but solid secure-computing mode.
   */
 
  #include <linux/seccomp.h>
  #include <linux/sched.h>
+#include <linux/slab.h>
  #include <linux/compat.h>
+#include <linux/unistd.h>
+#include <linux/ftrace_event.h>
 
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
  /* #define SECCOMP_DEBUG 1 */
-#define NR_SECCOMP_MODES 1
 
  /*
   * Secure computing mode 1 allows only read/write/exit/sigreturn.
@@ -32,10 +36,9 @@ static int mode1_syscalls_32[] = {
 
  void __secure_computing(int this_syscall)
  {
-     int mode = current->seccomp.mode;
       int * syscall;
 
-     switch (mode) {
+     switch (current->seccomp.mode) {

      case 1:
              syscall = mode1_syscalls;
 #ifdef CONFIG_COMPAT

kernel/seccomp.c +11 -0
@@ -47,6 +50,17 @@ void __secure_computing(int this_syscall)
                               return;
               } while (*++syscall);
               break;
+#ifdef CONFIG_SECCOMP_FILTER
+     case 2:
+             if (this_syscall >= NR_syscalls || this_syscall < 0)
+                     break;
+
+             if (!seccomp_test_filters(this_syscall))
+                     return;
+
+             seccomp_filter_log_failure(this_syscall);
+             break;
+#endif

      default:
              BUG();
      }

kernel/seccomp.c +12 -6
@@ -71,16 +85,22 @@ long prctl_set_seccomp(unsigned long seccomp_mode)
       if (unlikely(current->seccomp.mode))
               goto out;
 
-     ret = -EINVAL;
-     if (seccomp_mode && seccomp_mode <= NR_SECCOMP_MODES) {
-             current->seccomp.mode = seccomp_mode;
-             set_thread_flag(TIF_SECCOMP);
+     ret = 0;
+     switch (seccomp_mode) {
+     case 1:
  #ifdef TIF_NOTSC
               disable_TSC();
  #endif
-             ret = 0;
+#ifdef CONFIG_SECCOMP_FILTER
+     case 2:
+#endif
+             current->seccomp.mode = seccomp_mode;
+             set_thread_flag(TIF_SECCOMP);
+             break;
+     default:
+             ret = -EINVAL;
       }
 
- out:
+out:
       return ret;
  }
kernel/seccomp_filter.c new file +409 -0
new file mode 100644
index 0000000..9782f25
@@ -0,0 +1,784 @@
+/* filter engine-based seccomp system call filtering
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * Copyright (C) 2011 The Chromium OS Authors <[email protected]>
+ */
+
+#include <linux/compat.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/ftrace_event.h>
+#include <linux/seccomp.h>
+#include <linux/seq_file.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/uaccess.h>
+
+#include <asm/syscall.h>
+#include <trace/syscall.h>
+
+
+#define SECCOMP_MAX_FILTER_LENGTH MAX_FILTER_STR_VAL
+
+#define SECCOMP_FILTER_ALLOW "1"
+#define SECCOMP_ACTION_DENY 0xffff
+#define SECCOMP_ACTION_ALLOW 0xfffe
+
+/**
+ * struct seccomp_filters - container for seccomp filterset
+ *
+ * @syscalls: array of 16-bit indices into @event_filters by syscall_nr
+ *            May also be SECCOMP_ACTION_DENY or SECCOMP_ACTION_ALLOW
+ * @event_filters: array of pointers to ftrace event objects
+ * @count: size of @event_filters
+ * @flags: anonymous struct to wrap filters-specific flags
+ * @usage: reference count to simplify use.
+ */
+struct seccomp_filters {
+     uint16_t syscalls[NR_syscalls];
+     struct event_filter **event_filters;
+     uint16_t count;
+     struct {
+             uint32_t compat:1,
+                      __reserved:31;
+     } flags;
+     atomic_t usage;
+};
+
+/* Handle ftrace symbol non-existence */
+#ifdef CONFIG_FTRACE_SYSCALLS
+#define create_event_filter(_ef_pptr, _event_type, _str) \
+     ftrace_parse_filter(_ef_pptr, _event_type, _str)
+#define get_filter_string(_ef) ftrace_get_filter_string(_ef)
+#define free_event_filter(_f) ftrace_free_filter(_f)
+
+#else
+
+#define create_event_filter(_ef_pptr, _event_type, _str) (-ENOSYS)
+#define get_filter_string(_ef) (NULL)
+#define free_event_filter(_f) do { } while (0)
+#endif
+
+/**
+ * seccomp_filters_new - allocates a new filters object
+ * @count: count to allocate for the event_filters array
+ *
+ * Returns ERR_PTR on error or an allocated object.
+ */
+static struct seccomp_filters *seccomp_filters_new(uint16_t count)
+{
+     struct seccomp_filters *f;
+
+     if (count >= SECCOMP_ACTION_ALLOW)
+             return ERR_PTR(-EINVAL);
+
+     f = kzalloc(sizeof(struct seccomp_filters), GFP_KERNEL);
+     if (!f)
+             return ERR_PTR(-ENOMEM);
+
+     /* Lazy SECCOMP_ACTION_DENY assignment. */
+     memset(f->syscalls, 0xff, sizeof(f->syscalls));
+     atomic_set(&f->usage, 1);
+
+     f->event_filters = NULL;
+     f->count = count;
+     if (!count)
+             return f;
+
+     f->event_filters = kzalloc(count * sizeof(struct event_filter *),
+                                GFP_KERNEL);
+     if (!f->event_filters) {
+             kfree(f);
+             f = ERR_PTR(-ENOMEM);
+     }
+     return f;
+}
+
+/**
+ * seccomp_filters_free - cleans up the filter list and frees the table
+ * @filters: NULL or live object to be completely destructed.
+ */
+static void seccomp_filters_free(struct seccomp_filters *filters)
+{
+     uint16_t count = 0;
+     if (!filters)
+             return;
+     while (count < filters->count) {
+             struct event_filter *f = filters->event_filters[count];
+             free_event_filter(f);
+             count++;
+     }
+     kfree(filters->event_filters);
+     kfree(filters);
+}
+
+static void __put_seccomp_filters(struct seccomp_filters *orig)
+{
+     WARN_ON(atomic_read(&orig->usage));
+     seccomp_filters_free(orig);
+}
+
+#define seccomp_filter_allow(_id) ((_id) == SECCOMP_ACTION_ALLOW)
+#define seccomp_filter_deny(_id) ((_id) == SECCOMP_ACTION_DENY)
+#define seccomp_filter_dynamic(_id) \
+     (!seccomp_filter_allow(_id) && !seccomp_filter_deny(_id))
+static inline uint16_t seccomp_filter_id(const struct seccomp_filters *f,
+                                      int syscall_nr)
+{
+     if (!f)
+             return SECCOMP_ACTION_DENY;
+     return f->syscalls[syscall_nr];
+}
+
+static inline struct event_filter *seccomp_dynamic_filter(
+             const struct seccomp_filters *filters, uint16_t id)
+{
+     if (!seccomp_filter_dynamic(id))
+             return NULL;
+     return filters->event_filters[id];
+}
+
+static inline void set_seccomp_filter_id(struct seccomp_filters *filters,
+                                      int syscall_nr, uint16_t id)
+{
+     filters->syscalls[syscall_nr] = id;
+}
+
+static inline void set_seccomp_filter(struct seccomp_filters *filters,
+                                   int syscall_nr, uint16_t id,
+                                   struct event_filter *dynamic_filter)
+{
+     filters->syscalls[syscall_nr] = id;
+     if (seccomp_filter_dynamic(id))
+             filters->event_filters[id] = dynamic_filter;
+}
+
+static struct event_filter *alloc_event_filter(int syscall_nr,
+                                            const char *filter_string)
+{
+     struct syscall_metadata *data;
+     struct event_filter *filter = NULL;
+     int err;
+
+     data = syscall_nr_to_meta(syscall_nr);
+     /* Argument-based filtering only works on ftrace-hooked syscalls. */
+     err = -ENOSYS;
+     if (!data)
+             goto fail;
+     err = create_event_filter(&filter,
+                               data->enter_event->event.type,
+                               filter_string);
+     if (err)
+             goto fail;
+
+     return filter;
+fail:
+     kfree(filter);
+     return ERR_PTR(err);
+}
+
+/**
+ * seccomp_filters_copy - copies filters from src to dst.
+ *
+ * @dst: seccomp_filters to populate.
+ * @src: table to read from.
+ * @skip: specifies an entry, by system call, to skip.
+ *
+ * Returns non-zero on failure.
+ * Both the source and the destination should have no simultaneous
+ * writers, and dst should be exclusive to the caller.
+ * If @skip is < 0, it is ignored.
+ */
+static int seccomp_filters_copy(struct seccomp_filters *dst,
+                             const struct seccomp_filters *src,
+                             int skip)
+{
+     int id = 0, ret = 0, nr;
+     memcpy(&dst->flags, &src->flags, sizeof(src->flags));
+     memcpy(dst->syscalls, src->syscalls, sizeof(dst->syscalls));
+     if (!src->count)
+             goto done;
+     for (nr = 0; nr < NR_syscalls; ++nr) {
+             struct event_filter *filter;
+             const char *str;
+             uint16_t src_id = seccomp_filter_id(src, nr);
+             if (nr == skip) {
+                     set_seccomp_filter(dst, nr, SECCOMP_ACTION_DENY,
+                                        NULL);
+                     continue;
+             }
+             if (!seccomp_filter_dynamic(src_id))
+                     continue;
+             if (id >= dst->count) {
+                     ret = -EINVAL;
+                     goto done;
+             }
+             str = get_filter_string(seccomp_dynamic_filter(src, src_id));
+             filter = alloc_event_filter(nr, str);
+             if (IS_ERR(filter)) {
+                     ret = PTR_ERR(filter);
+                     goto done;
+             }
+             set_seccomp_filter(dst, nr, id, filter);
+             id++;
+     }
+
+done:
+     return ret;
+}
+
+/**
+ * seccomp_extend_filter - appends more text to a syscall_nr's filter
+ * @filters: unattached filter object to operate on
+ * @syscall_nr: syscall number to update filters for
+ * @filter_string: string to append to the existing filter
+ *
+ * The new string will be &&'d to the original filter string to ensure that it
+ * always matches the existing predicates or less:
+ *   (old_filter) && @filter_string
+ * A new seccomp_filters instance is returned on success and a ERR_PTR on
+ * failure.
+ */
+static int seccomp_extend_filter(struct seccomp_filters *filters,
+                              int syscall_nr, char *filter_string)
+{
+     struct event_filter *filter;
+     uint16_t id = seccomp_filter_id(filters, syscall_nr);
+     char *merged = NULL;
+     int ret = -EINVAL, expected;
+
+     /* No extending with a "1". */
+     if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string))
+             goto out;
+
+     filter = seccomp_dynamic_filter(filters, id);
+     ret = -ENOENT;
+     if (!filter)
+             goto out;
+
+     merged = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+     ret = -ENOMEM;
+     if (!merged)
+             goto out;
+
+     expected = snprintf(merged, SECCOMP_MAX_FILTER_LENGTH, "(%s) && %s",
+                         get_filter_string(filter), filter_string);
+     ret = -E2BIG;
+     if (expected >= SECCOMP_MAX_FILTER_LENGTH || expected < 0)
+             goto out;
+
+     /* Free the old filter */
+     free_event_filter(filter);
+     set_seccomp_filter(filters, syscall_nr, id, NULL);
+
+     /* Replace it */
+     filter = alloc_event_filter(syscall_nr, merged);
+     if (IS_ERR(filter)) {
+             ret = PTR_ERR(filter);
+             goto out;
+     }
+     set_seccomp_filter(filters, syscall_nr, id, filter);
+     ret = 0;
+
+out:
+     kfree(merged);
+     return ret;
+}
+
+/**
+ * seccomp_add_filter - adds a filter for an unfiltered syscall
+ * @filters: filters object to add a filter/action to
+ * @syscall_nr: system call number to add a filter for
+ * @filter_string: the filter string to apply
+ *
+ * Returns 0 on success and non-zero otherwise.
+ */
+static int seccomp_add_filter(struct seccomp_filters *filters, int syscall_nr,
+                           char *filter_string)
+{
+     struct event_filter *filter;
+     int ret = 0;
+
+     if (!strcmp(SECCOMP_FILTER_ALLOW, filter_string)) {
+             set_seccomp_filter(filters, syscall_nr,
+                                SECCOMP_ACTION_ALLOW, NULL);
+             goto out;
+     }
+
+     filter = alloc_event_filter(syscall_nr, filter_string);
+     if (IS_ERR(filter)) {
+             ret = PTR_ERR(filter);
+             goto out;
+     }
+     /* Always add to the last slot available since additions are
+      * are only done one at a time.
+      */
+     set_seccomp_filter(filters, syscall_nr, filters->count - 1, filter);
+out:
+     return ret;
+}
+
+/* Wrap optional ftrace syscall support. Returns 1 on match or 0 otherwise. */
+static int filter_match_current(struct event_filter *event_filter)
+{
+     int err = 0;
+#ifdef CONFIG_FTRACE_SYSCALLS
+     uint8_t syscall_state[64];
+
+     memset(syscall_state, 0, sizeof(syscall_state));
+
+     /* The generic tracing entry can remain zeroed. */
+     err = ftrace_syscall_enter_state(syscall_state, sizeof(syscall_state),
+                                      NULL);
+     if (err)
+             return 0;
+
+     err = filter_match_preds(event_filter, syscall_state);
+#endif
+     return err;
+}
+
+static const char *syscall_nr_to_name(int syscall)
+{
+     const char *syscall_name = "unknown";
+     struct syscall_metadata *data = syscall_nr_to_meta(syscall);
+     if (data)
+             syscall_name = data->name;
+     return syscall_name;
+}
+
+static void filters_set_compat(struct seccomp_filters *filters)
+{
+#ifdef CONFIG_COMPAT
+     if (is_compat_task())
+             filters->flags.compat = 1;
+#endif
+}
+
+static inline int filters_compat_mismatch(struct seccomp_filters *filters)
+{
+     int ret = 0;
+     if (!filters)
+             return 0;
+#ifdef CONFIG_COMPAT
+     if (!!(is_compat_task()) == filters->flags.compat)
+             ret = 1;
+#endif
+     return ret;
+}
+
+static inline int syscall_is_execve(int syscall)
+{
+     int nr = __NR_execve;
+#ifdef CONFIG_COMPAT
+     if (is_compat_task())
+             nr = __NR_seccomp_execve_32;
+#endif
+     return syscall == nr;
+}
+
+#ifndef KSTK_EIP
+#define KSTK_EIP(x) 0L
+#endif
+
+void seccomp_filter_log_failure(int syscall)
+{
+     pr_info("%s[%d]: system call %d (%s) blocked at 0x%lx\n",
+             current->comm, task_pid_nr(current), syscall,
+             syscall_nr_to_name(syscall), KSTK_EIP(current));
+}
+
+/* put_seccomp_state - decrements the reference count of @orig and may free. */
+void put_seccomp_filters(struct seccomp_filters *orig)
+{
+     if (!orig)
+             return;
+
Quoted 8 lines

kernel/seccomp_filter.c line 415

Quoted 6 lines
kernel/seccomp_filter.c new file +6 -0
+     if (atomic_dec_and_test(&orig->usage))
+             __put_seccomp_filters(orig);
+}
+
+/* get_seccomp_state - increments the reference count of @orig */
+struct seccomp_filters *get_seccomp_filters(struct seccomp_filters *orig)

Nit: the name does not match the comment.

Will fix it here and above. Thanks!

Quoted 9 lines

kernel/seccomp_filter.c line 420

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+{
+     if (!orig)
+             return NULL;
+     atomic_inc(&orig->usage);
+     return orig;

This is called in an RCU read-side critical section.  What exactly is RCU protecting?  I would expect an rcu_dereference() or one of the RCU list-traversal primitives somewhere, either here or at the caller.

Ah, I spaced on rcu_dereference().  The goal was to make the assignment and replacement of the seccomp_filters pointer RCU-protected (in seccomp_state) so there's no concern over it being replaced partial on platforms where pointer assignments are non-atomic
- such as via /proc/<pid>/seccomp_filters access or a call via the exported symbols.  Object lifetime is managed by reference counting so that I don't have to worry about extending the RCU read-side critical section by much or deal with pre-allocations.

Quoted 3 lines

I'll add rcu_dereference() to all the get_seccomp_filters() uses where it makes sense, so that it is called safely.  Just to make sure, does it make sense to continue to rcu protect the specific pointer?

Quoted 5 lines

It might.  The usual other options is to use a lock outside of the element containing the reference count to protect reference-count manipulation. If there is some convenient lock, especially if it is already held where needed, then locking is more straightforward.  Otherwise, RCU is usually a reasonable option.

I was concerned about the overhead a lock would have at each system call entry, but I didn't benchmark it to see. I'll add the rcu_dereference right away, then look into seeing whether there's a cleaner approach. I was trying to be overly protective of mutating any data internal to the filters through complete replacement on any change. I'll take a step back and see if

Quoted 216 lines
Quoted 193 lines
Quoted 184 lines
Quoted 184 lines
kernel/seccomp_filter.c new file +184 -0
+}
+
+/**
+ * seccomp_test_filters - tests 'current' against the given syscall
+ * @state: seccomp_state of current to use.
+ * @syscall: number of the system call to test
+ *
+ * Returns 0 on ok and non-zero on error/failure.
+ */
+int seccomp_test_filters(int syscall)
+{
+     uint16_t id;
+     struct event_filter *filter;
+     struct seccomp_filters *filters;
+     int ret = -EACCES;
+
+     rcu_read_lock();
+     filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!filters)
+             goto out;
+
+     if (filters_compat_mismatch(filters)) {
+             pr_info("%s[%d]: seccomp_filter compat() mismatch.\n",
+                     current->comm, task_pid_nr(current));
+             goto out;
+     }
+
+     /* execve is never allowed. */
+     if (syscall_is_execve(syscall))
+             goto out;
+
+     ret = 0;
+     id = seccomp_filter_id(filters, syscall);
+     if (seccomp_filter_allow(id))
+             goto out;
+
+     ret = -EACCES;
+     if (!seccomp_filter_dynamic(id))
+             goto out;
+
+     filter = seccomp_dynamic_filter(filters, id);
+     if (filter && filter_match_current(filter))
+             ret = 0;
+out:
+     put_seccomp_filters(filters);
+     return ret;
+}
+
+/**
+ * seccomp_show_filters - prints the current filter state to a seq_file
+ * @filters: properly get()'d filters object
+ * @m: the prepared seq_file to receive the data
+ *
+ * Returns 0 on a successful write.
+ */
+int seccomp_show_filters(struct seccomp_filters *filters, struct seq_file *m)
+{
+     int syscall;
+     seq_printf(m, "Mode: %d\n", current->seccomp.mode);
+     if (!filters)
+             goto out;
+
+     for (syscall = 0; syscall < NR_syscalls; ++syscall) {
+             uint16_t id = seccomp_filter_id(filters, syscall);
+             const char *filter_string = SECCOMP_FILTER_ALLOW;
+             if (seccomp_filter_deny(id))
+                     continue;
+             seq_printf(m, "%d (%s): ",
+                           syscall,
+                           syscall_nr_to_name(syscall));
+             if (seccomp_filter_dynamic(id))
+                     filter_string = get_filter_string(
+                                       seccomp_dynamic_filter(filters, id));
+             seq_printf(m, "%s\n", filter_string);
+     }
+out:
+     return 0;
+}
+EXPORT_SYMBOL_GPL(seccomp_show_filters);
+
+/**
+ * seccomp_get_filter - copies the filter_string into "buf"
+ * @syscall_nr: system call number to look up
+ * @buf: destination buffer
+ * @bufsize: available space in the buffer.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Looks up the filter for the given system call number on current.  If found,
+ * the string length of the NUL-terminated buffer is returned and < 0 is
+ * returned on error. The NUL byte is not included in the length.
+ */
+long seccomp_get_filter(int syscall_nr, char *buf, unsigned long bufsize)
+{
+     struct seccomp_filters *filters;
+     struct event_filter *filter;
+     long ret = -EINVAL;
+     uint16_t id;
+
+     if (bufsize > SECCOMP_MAX_FILTER_LENGTH)
+             bufsize = SECCOMP_MAX_FILTER_LENGTH;
+
+     rcu_read_lock();
+     filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!filters)
+             goto out;
+
+     ret = -ENOENT;
+     id = seccomp_filter_id(filters, syscall_nr);
+     if (seccomp_filter_deny(id))
+             goto out;
+
+     if (seccomp_filter_allow(id)) {
+             ret = strlcpy(buf, SECCOMP_FILTER_ALLOW, bufsize);
+             goto copied;
+     }
+
+     filter = seccomp_dynamic_filter(filters, id);
+     if (!filter)
+             goto out;
+     ret = strlcpy(buf, get_filter_string(filter), bufsize);
+
+copied:
+     if (ret >= bufsize) {
+             ret = -ENOSPC;
+             goto out;
+     }
+     /* Zero out any remaining buffer, just in case. */
+     memset(buf + ret, 0, bufsize - ret);
+out:
+     put_seccomp_filters(filters);
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_get_filter);
+
+/**
+ * seccomp_clear_filter: clears the seccomp filter for a syscall.
+ * @syscall_nr: the system call number to clear filters for.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * Returns 0 on success.
+ */
+long seccomp_clear_filter(int syscall_nr)
+{
+     struct seccomp_filters *filters = NULL, *orig_filters;
+     uint16_t id;
+     int ret = -EINVAL;
+
+     rcu_read_lock();
+     orig_filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     if (!orig_filters)
+             goto out;
+
+     if (filters_compat_mismatch(orig_filters))
+             goto out;
+
+     id = seccomp_filter_id(orig_filters, syscall_nr);
+     if (seccomp_filter_deny(id))
+             goto out;
+
+     /* Create a new filters object for the task */
+     if (seccomp_filter_dynamic(id))
+             filters = seccomp_filters_new(orig_filters->count - 1);
+     else
+             filters = seccomp_filters_new(orig_filters->count);
+
+     if (IS_ERR(filters)) {
+             ret = PTR_ERR(filters);
+             goto out;
+     }
+
+     /* Copy, but drop the requested entry. */
+     ret = seccomp_filters_copy(filters, orig_filters, syscall_nr);
Quoted 8 lines

kernel/seccomp_filter.c line 609

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+     if (ret)
+             goto out;
+     get_seccomp_filters(filters);  /* simplify the out: path */
+
+     rcu_assign_pointer(current->seccomp.filters, filters);

What prevents two copies of seccomp_clear_filter() from running concurrently?

Quoted 5 lines

Nothing - the last one wins assignment, but the objects themselves should be internally consistent to the parallel calls.  If that's a concern, a per-task writer mutex could be used just to ensure simultaneous calls to clear and set are performed serially.  Would that make more sense?

Here is the sequence of events that I am concerned about:

o       CPU 0 sets orig_filters to point to the current filters.

o       CPU 1 sets its local orig_filters to point to the current set of filters.

o       Both CPUs allocate new filters and use rcu_assign_pointer() to do the update.  As you say, the last one wins, but it appears to me that the first one leaks memory.

o       Both CPUs free the object referenced by their orig_filters, which might or might not result in a double free, depending on exactly what happens below.  (You might actually be OK, I didn't check -- leaking memory was enough for me to call attention to this.)

Quoted 4 lines

So yes, please use some kind of mutual exclusion.  Not sure what you mean by "per-task mutex", but whatever it is must prevent two different tasks from acting on the same set of filters at the same time.  The thing that I call "per-task mutex" would -not- do that.

Ah nice. Yeah that would most definitely leak as there would be a remaining increment for the task that isn't dropped.

Since those interfaces acquire the filter itself from current->seccomp.filters, I was thinking a mutex in current, e.g., current->seccomp.write_mutex, would fit the bill to ensure that pointer isn't accessed for replacement. I'll look at this and the rcu usage to see if I'm taking the most logical approach. I pretty much always get locking wrong in some way and perhaps I can simplify further and get the correct guarantees. I really appreciate the keen observation and explanation!

Quoted 263 lines
Quoted 262 lines
Quoted 75 lines
Quoted 75 lines
kernel/seccomp_filter.c new file +75 -0
+     synchronize_rcu();
+     put_seccomp_filters(orig_filters);  /* for the task */
+out:
+     put_seccomp_filters(orig_filters);  /* for the get */
+     put_seccomp_filters(filters);  /* for the extra get */
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_clear_filter);
+
+/**
+ * seccomp_set_filter: - Adds/extends a seccomp filter for a syscall.
+ * @syscall_nr: system call number to apply the filter to.
+ * @filter: ftrace filter string to apply.
+ *
+ * Context: User context only. This function may sleep on allocation and
+ *          operates on current. current must be attempting a system call
+ *          when this is called.
+ *
+ * New filters may be added for system calls when the current task is
+ * not in a secure computing mode (seccomp).  Otherwise, existing filters may
+ * be extended.
+ *
+ * Returns 0 on success or an errno on failure.
+ */
+long seccomp_set_filter(int syscall_nr, char *filter)
+{
+     struct seccomp_filters *filters = NULL, *orig_filters = NULL;
+     uint16_t id;
+     long ret = -EINVAL;
+     uint16_t filters_needed;
+
+     if (!filter)
+             goto out;
+
+     filter = strstrip(filter);
+     /* Disallow empty strings. */
+     if (filter[0] == 0)
+             goto out;
+
+     rcu_read_lock();
+     orig_filters = get_seccomp_filters(current->seccomp.filters);
+     rcu_read_unlock();
+
+     /* After the first call, compatibility mode is selected permanently. */
+     ret = -EACCES;
+     if (filters_compat_mismatch(orig_filters))
+             goto out;
+
+     filters_needed = orig_filters ? orig_filters->count : 0;
+     id = seccomp_filter_id(orig_filters, syscall_nr);
+     if (seccomp_filter_deny(id)) {
+             /* Don't allow DENYs to be changed when in a seccomp mode */
+             ret = -EACCES;
+             if (current->seccomp.mode)
+                     goto out;
+             filters_needed++;
+     }
+
+     filters = seccomp_filters_new(filters_needed);
+     if (IS_ERR(filters)) {
+             ret = PTR_ERR(filters);
+             goto out;
+     }
+
+     filters_set_compat(filters);
+     if (orig_filters) {
+             ret = seccomp_filters_copy(filters, orig_filters, -1);
+             if (ret)
+                     goto out;
+     }
+
+     if (seccomp_filter_deny(id))
+             ret = seccomp_add_filter(filters, syscall_nr, filter);
+     else
+             ret = seccomp_extend_filter(filters, syscall_nr, filter);
Quoted 8 lines

kernel/seccomp_filter.c line 689

Quoted 5 lines
kernel/seccomp_filter.c new file +5 -0
+     if (ret)
+             goto out;
+     get_seccomp_filters(filters);  /* simplify the error paths */
+
+     rcu_assign_pointer(current->seccomp.filters, filters);

Again, what prevents two copies of seccomp_set_filter() from running concurrently?

Same deal - nothing, but I'd be happy to add a guard if it makes sense.

Thanks!

Quoted 163 lines
Quoted 163 lines
kernel/seccomp_filter.c new file +95 -0
+     synchronize_rcu();
+     put_seccomp_filters(orig_filters);  /* for the task */
+out:
+     put_seccomp_filters(orig_filters);  /* for the get */
+     put_seccomp_filters(filters);  /* for get or task, on err */
+     return ret;
+}
+EXPORT_SYMBOL_GPL(seccomp_set_filter);
+
+long prctl_set_seccomp_filter(unsigned long syscall_nr,
+                           char __user *user_filter)
+{
+     int nr;
+     long ret;
+     char *filter = NULL;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+
+     ret = -EFAULT;
+     if (!user_filter)
+             goto out;
+
+     filter = kzalloc(SECCOMP_MAX_FILTER_LENGTH + 1, GFP_KERNEL);
+     ret = -ENOMEM;
+     if (!filter)
+             goto out;
+
+     ret = -EFAULT;
+     if (strncpy_from_user(filter, user_filter,
+                           SECCOMP_MAX_FILTER_LENGTH - 1) < 0)
+             goto out;
+
+     nr = (int) syscall_nr;
+     ret = seccomp_set_filter(nr, filter);
+
+out:
+     kfree(filter);
+     return ret;
+}
+
+long prctl_clear_seccomp_filter(unsigned long syscall_nr)
+{
+     int nr = -1;
+     long ret;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+
+     nr = (int) syscall_nr;
+     ret = seccomp_clear_filter(nr);
+
+out:
+     return ret;
+}
+
+long prctl_get_seccomp_filter(unsigned long syscall_nr, char __user *dst,
+                           unsigned long available)
+{
+     int ret, nr;
+     unsigned long copied;
+     char *buf = NULL;
+     ret = -EINVAL;
+     if (!available)
+             goto out;
+     /* Ignore extra buffer space. */
+     if (available > SECCOMP_MAX_FILTER_LENGTH)
+             available = SECCOMP_MAX_FILTER_LENGTH;
+
+     ret = -EINVAL;
+     if (syscall_nr >= NR_syscalls)
+             goto out;
+     nr = (int) syscall_nr;
+
+     ret = -ENOMEM;
+     buf = kmalloc(available, GFP_KERNEL);
+     if (!buf)
+             goto out;
+
+     ret = seccomp_get_filter(nr, buf, available);
+     if (ret < 0)
+             goto out;
+
+     /* Include the NUL byte in the copy. */
+     copied = copy_to_user(dst, buf, ret + 1);
+     ret = -ENOSPC;
+     if (copied)
+             goto out;
+     ret = 0;
+out:
+     kfree(buf);
+     return ret;
+}
kernel/sys.c +0 -0
index af468ed..ed60d06 100644
@@ -1698,13 +1698,24 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,

              case PR_SET_ENDIAN:
                      error = SET_ENDIAN(me, arg2);
                      break;
-
              case PR_GET_SECCOMP:
                      error = prctl_get_seccomp();
                      break;
              case PR_SET_SECCOMP:
                      error = prctl_set_seccomp(arg2);
                      break;
+             case PR_SET_SECCOMP_FILTER:
+                     error = prctl_set_seccomp_filter(arg2,
+                                                      (char __user *) arg3);
+                     break;
+             case PR_CLEAR_SECCOMP_FILTER:
+                     error = prctl_clear_seccomp_filter(arg2);
+                     break;
+             case PR_GET_SECCOMP_FILTER:
+                     error = prctl_get_seccomp_filter(arg2,
+                                                      (char __user *) arg3,
+                                                      arg4);
+                     break;
              case PR_GET_TSC:
                      error = GET_TSC_CTL(arg2);
                      break;

security/Kconfig +4 -0
index 95accd4..c76adf2 100644
@@ -2,6 +2,10 @@
  # Security configuration
  #
 
+# Make seccomp filter Kconfig switch below available
+config HAVE_SECCOMP_FILTER
+       bool
+

 menu "Security options"

 config KEYS

security/Kconfig +0 -0
@@ -82,6 +86,19 @@ config SECURITY_DMESG_RESTRICT
 

        If you are unsure how to answer this question, answer N.

security/Kconfig +13 -0
+config SECCOMP_FILTER
+     bool "Enable seccomp-based system call filtering"
+     select SECCOMP
+     depends on HAVE_SECCOMP_FILTER && EXPERIMENTAL
+     help
+       This kernel feature expands CONFIG_SECCOMP to allow computing
+       in environments with reduced kernel access dictated by the
+       application itself through prctl calls.  If
+       CONFIG_FTRACE_SYSCALLS is available, then system call
+       argument-based filtering predicates may be used.
+
+       See Documentation/prctl/seccomp_filter.txt for more detail.
+

 config SECURITY
      bool "Enable different security models"
      depends on SYSFS
--
1.7.0.4

Quoted 6 lines
Quoted 5 lines

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/

maintainer
#105 lore raw

Re: [PATCH v3 03/13] seccomp_filters: new mode with configurable syscall filters

On Thu, 2011-06-02 at 15:28 -0500, Will Drewry wrote:

[ Snipped 860 lines of non relevant text ]

Seriously guys, Please trim your replies. These last few messages were ridicules. I spent more than 30 seconds searching for what the email was about. That's too much wasted time.

-- Steve

Quoted 26 lines
Quoted 13 lines
Quoted 9 lines

Ah, I spaced on rcu_dereference(). The goal was to make the assignment and replacement of the seccomp_filters pointer RCU-protected (in seccomp_state) so there's no concern over it being replaced partial on platforms where pointer assignments are non-atomic
- such as via /proc/<pid>/seccomp_filters access or a call via the exported symbols. Object lifetime is managed by reference counting so that I don't have to worry about extending the RCU read-side critical section by much or deal with pre-allocations.

Quoted 3 lines

I'll add rcu_dereference() to all the get_seccomp_filters() uses where it makes sense, so that it is called safely. Just to make sure, does it make sense to continue to rcu protect the specific pointer?

Quoted 5 lines

It might. The usual other options is to use a lock outside of the element containing the reference count to protect reference-count manipulation. If there is some convenient lock, especially if it is already held where needed, then locking is more straightforward. Otherwise, RCU is usually a reasonable option.

I was concerned about the overhead a lock would have at each system call entry, but I didn't benchmark it to see. I'll add the rcu_dereference right away, then look into seeing whether there's a cleaner approach. I was trying to be overly protective of mutating any data internal to the filters through complete replacement on any change. I'll take a step back and see if

#106 lore raw

Re: [PATCH v3 03/13] seccomp_filters: new mode with configurable syscall filters

Quoted 7 lines · Steven Rostedt

On Thu, 2011-06-02 at 15:28 -0500, Will Drewry wrote:

[ Snipped 860 lines of non relevant text ]

Seriously guys, Please trim your replies. These last few messages were ridicules. I spent more than 30 seconds searching for what the email was about. That's too much wasted time.

Because every time I do trim the messages, I get a response from the reviewee of the form "Oh, I take care of that in function foo()." And of course function foo() will be in the part I trimmed. So I then have to find the earlier message, copy the function back in, and by that time something else has distracted me.

Thanx, Paul

Quoted 36 lines

-- Steve

Quoted 19 lines
Quoted 13 lines
Quoted 9 lines

Ah, I spaced on rcu_dereference(). The goal was to make the assignment and replacement of the seccomp_filters pointer RCU-protected (in seccomp_state) so there's no concern over it being replaced partial on platforms where pointer assignments are non-atomic
- such as via /proc/<pid>/seccomp_filters access or a call via the exported symbols. Object lifetime is managed by reference counting so that I don't have to worry about extending the RCU read-side critical section by much or deal with pre-allocations.

Quoted 3 lines

I'll add rcu_dereference() to all the get_seccomp_filters() uses where it makes sense, so that it is called safely. Just to make sure, does it make sense to continue to rcu protect the specific pointer?

Quoted 5 lines

It might. The usual other options is to use a lock outside of the element containing the reference count to protect reference-count manipulation. If there is some convenient lock, especially if it is already held where needed, then locking is more straightforward. Otherwise, RCU is usually a reasonable option.

Quoted 7 lines

I was concerned about the overhead a lock would have at each system call entry, but I didn't benchmark it to see. I'll add the rcu_dereference right away, then look into seeing whether there's a cleaner approach. I was trying to be overly protective of mutating any data internal to the filters through complete replacement on any change. I'll take a step back and see if

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/

author reviewer
#107 lore raw

PATCH v3 4/13 seccomp_filter: add process state reporting

In reply to Will Drewry

Adds seccomp and seccomp_filter status reporting to proc. /proc/<pid>/seccomp_filter provides the current seccomp mode and the list of allowed or dynamically filtered system calls.

v3: changed to using filters directly.
v2: removed status entry, added seccomp file.
(requested by [email protected])
allowed S_IRUGO reading of entries
(requested by [email protected])
added flags
got rid of the seccomp_t type
dropped seccomp file

---
 fs/proc/base.c |   25 +++++++++++++++++++++++++
 1 files changed, 25 insertions(+), 0 deletions(-)
fs/proc/base.c +25 -0
index dfa5327..01473fe 100644
@@ -73,6 +73,7 @@
 #include <linux/security.h>
 #include <linux/ptrace.h>
 #include <linux/tracehook.h>
+#include <linux/seccomp.h>
 #include <linux/cgroup.h>
 #include <linux/cpuset.h>
 #include <linux/audit.h>
@@ -579,6 +580,24 @@ static int proc_pid_syscall(struct task_struct *task, char *buffer)
 }
 #endif /* CONFIG_HAVE_ARCH_TRACEHOOK */
 
+/*
+ * Print out the current seccomp filter set for the task.
+ */
+#ifdef CONFIG_SECCOMP_FILTER
+int proc_pid_seccomp_filter_show(struct seq_file *m, struct pid_namespace *ns,
+				 struct pid *pid, struct task_struct *task)
+{
+	struct seccomp_filters *filters;
+
+	rcu_read_lock();
+	filters = get_seccomp_filters(task->seccomp.filters);
+	rcu_read_unlock();
+	seccomp_show_filters(filters, m);
+	put_seccomp_filters(filters);
+	return 0;
+}
+#endif /* CONFIG_SECCOMP_FILTER */
+
 /************************************************************************/
 /*                       Here the fs part begins                        */
 /************************************************************************/
@@ -2838,6 +2857,9 @@ static const struct pid_entry tgid_base_stuff[] = {
 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
 	INF("syscall",    S_IRUGO, proc_pid_syscall),
 #endif
+#ifdef CONFIG_SECCOMP_FILTER
+	ONE("seccomp_filter",     S_IRUGO, proc_pid_seccomp_filter_show),
+#endif
 	INF("cmdline",    S_IRUGO, proc_pid_cmdline),
 	ONE("stat",       S_IRUGO, proc_tgid_stat),
 	ONE("statm",      S_IRUGO, proc_pid_statm),
@@ -3180,6 +3202,9 @@ static const struct pid_entry tid_base_stuff[] = {
 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
 	INF("syscall",   S_IRUGO, proc_pid_syscall),
 #endif
+#ifdef CONFIG_SECCOMP_FILTER
+	ONE("seccomp_filter",     S_IRUGO, proc_pid_seccomp_filter_show),
+#endif
 	INF("cmdline",   S_IRUGO, proc_pid_cmdline),
 	ONE("stat",      S_IRUGO, proc_tid_stat),
 	ONE("statm",     S_IRUGO, proc_pid_statm),
Signature · 1 line
1.7.0.4
author reviewer
#108 lore raw

PATCH v3 5/13 seccomp_filter: Document what seccomp_filter is and how it works.

In reply to Will Drewry

Adds a text file covering what CONFIG_SECCOMP_FILTER is, how it is implemented presently, and what it may be used for. In addition, the limitations and caveats of the proposed implementation are included.

v3: a little more cleanup
v2: moved to prctl/
updated for the v2 syntax.
adds a note about compat behavior

---
 Documentation/prctl/seccomp_filter.txt |  145 ++++++++++++++++++++++++++++++++
 1 files changed, 145 insertions(+), 0 deletions(-)
 create mode 100644 Documentation/prctl/seccomp_filter.txt
Documentation/prctl/seccomp_filter.txt new file +145 -0
new file mode 100644
index 0000000..27ac5af
@@ -0,0 +1,145 @@
+		Seccomp filtering
+		=================
+
+Introduction
+------------
+
+A large number of system calls are exposed to every userland process
+with many of them going unused for the entire lifetime of the process.
+As system calls change and mature, bugs are found and eradicated.  A
+certain subset of userland applications benefit by having a reduce set
+of available system calls.  The reduced set reduces the total kernel
+surface exposed to the application.  System call filtering is meant for
+use with those applications.
+
+The implementation currently leverages both the existing seccomp
+infrastructure and the kernel tracing infrastructure.  By centralizing
+hooks for attack surface reduction in seccomp, it is possible to assure
+attention to security that is less relevant in normal ftrace scenarios,
+such as time-of-check, time-of-use attacks.  However, ftrace provides a
+rich, human-friendly environment for interfacing with system call
+specific arguments.  (As such, this requires FTRACE_SYSCALLS for any
+introspective filtering support.)
+
+
+What it isn't
+-------------
+
+System call filtering isn't a sandbox.  It provides a clearly defined
+mechanism for minimizing the exposed kernel surface.  Beyond that,
+policy for logical behavior and information flow should be managed with
+a combinations of other system hardening techniques and, potentially, a
+LSM of your choosing.  Expressive, dynamic filters based on the ftrace
+filter engine provide further options down this path (avoiding
+pathological sizes or selecting which of the multiplexed system calls in
+socketcall() is allowed, for instance) which could be construed,
+incorrectly, as a more complete sandboxing solution.
+
+
+Usage
+-----
+
+An additional seccomp mode is exposed through mode '2'.
+This mode depends on CONFIG_SECCOMP_FILTER.  By default, it provides
+only the most trivial of filter support "1" or cleared.  However, if
+CONFIG_FTRACE_SYSCALLS is enabled, the ftrace filter engine may be used
+for more expressive filters.
+
+A collection of filters may be supplied via prctl, and the current set
+of filters is exposed in /proc/<pid>/seccomp_filter.
+
+Interacting with seccomp filters can be done through three new prctl calls
+and one existing one.
+
+PR_SET_SECCOMP:
+	A pre-existing option for enabling strict seccomp mode (1) or
+	filtering seccomp (2).
+
+	Usage:
+		prctl(PR_SET_SECCOMP, 1);  /* strict */
+		prctl(PR_SET_SECCOMP, 2);  /* filters */
+
+PR_SET_SECCOMP_FILTER:
+	Allows the specification of a new filter for a given system
+	call, by number, and filter string. If CONFIG_FTRACE_SYSCALLS is
+	supported, the filter string may be any valid value for the
+	given system call.  If it is not supported, the filter string
+	may only be "1".
+
+	All calls to PR_SET_SECCOMP_FILTER for a given system
+	call will append the supplied string to any existing filters.
+	Filter construction looks as follows:
+		(Nothing) + "fd == 1 || fd == 2" => fd == 1 || fd == 2
+		... + "fd != 2" => (fd == 1 || fd == 2) && fd != 2
+		... + "size < 100" =>
+			((fd == 1 || fd == 2) && fd != 2) && size < 100
+	If there is no filter and the seccomp mode has already
+	transitioned to filtering, additions cannot be made.  Filters
+	may only be added that reduce the available kernel surface.
+
+	Usage (per the construction example above):
+		prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd == 1 || fd == 2");
+		prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd != 2");
+		prctl(PR_SET_SECCOMP_FILTER, __NR_write, "size < 100");
+
+PR_CLEAR_SECCOMP_FILTER:
+	Removes all filter entries for a given system call number.  When
+	called prior to entering seccomp filtering mode, it allows for
+	new filters to be applied to the same system call.  After
+	transition, however, it completely drops access to the call.
+
+	Usage:
+		prctl(PR_CLEAR_SECCOMP_FILTER, __NR_open);
+
+PR_GET_SECCOMP_FILTER: Returns the aggregated filter string for a system
+	call into a user-supplied buffer of a given length.
+
+	Usage:
+		prctl(PR_GET_SECCOMP_FILTER, __NR_write, buf,
+		      sizeof(buf));
+
+All of the above calls return 0 on success and non-zero on error.
+
+
+Example
+-------
+
+Assume a process would like to cleanly read and write to stdin/out/err
+as well as access its filters after seccomp enforcement begins.  This
+may be done as follows:
+
+  prctl(PR_SET_SECCOMP_FILTER, __NR_read, "fd == 0");
+  prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd == 1 || fd == 2");
+  prctl(PR_SET_SECCOMP_FILTER, __NR_exit, "1");
+  prctl(PR_SET_SECCOMP_FILTER, __NR_prctl, "1");
+
+  prctl(PR_SET_SECCOMP, PR_SECCOMP_MODE_FILTER, 0);
+
+  /* Do stuff with fdset . . .*/
+
+  /* Drop read access and keep only write access to fd 1. */
+  prctl(PR_CLEAR_SECCOMP_FILTER, __NR_read);
+  prctl(PR_SET_SECCOMP_FILTER, __NR_write, "fd != 2");
+
+  /* Perform any final processing . . . */
+  syscall(__NR_exit, 0);
+
+
+Caveats
+-------
+
+- The filter event subsystem comes from CONFIG_TRACE_EVENTS, and the
+system call events come from CONFIG_FTRACE_SYSCALLS.  However, if
+neither are available, a filter string of "1" will be honored, and it may
+be removed using PR_CLEAR_SECCOMP_FILTER.  With ftrace filtering,
+calling PR_SET_SECCOMP_FILTER with a filter of "0" would have similar
+affect but would not be consistent on a kernel without the support.
+
+- Some platforms support a 32-bit userspace with 64-bit kernels.  In
+these cases (CONFIG_COMPAT), system call numbers may not match across
+64-bit and 32-bit system calls. When the first PRCTL_SET_SECCOMP_FILTER
+is called, the in-memory filters state is annotated with whether the
+call has been made via the compat interface.  All subsequent calls will
+be checked for compat call mismatch.  In the long run, it may make sense
+to store compat and non-compat filters separately, but that is not
+supported at present.
Signature · 1 line
1.7.0.4
#109 lore raw

Re: [PATCH v3 05/13] seccomp_filter: Document what seccomp_filter is and how it works.

Hi Will,

Minor typo corrections below...

Documentation/prctl/seccomp_filter.txt line 10

Quoted 10 lines · Will Drewry

Adds a text file covering what CONFIG_SECCOMP_FILTER is, how it is implemented presently, and what it may be used for. In addition, the limitations and caveats of the proposed implementation are included.

Documentation/prctl/seccomp_filter.txt new file +1 -0
@@ -0,0 +1,145 @@
...
+certain subset of userland applications benefit by having a reduce set

reduced

Quoted 1 line

+of available system calls. The reduced set reduces the total kernel

Maybe "The resulting set reduces ... " ?

-Kees

Signature · 2 lines
Kees Cook
Ubuntu Security Team
author reviewer
#110 lore raw

Re: [PATCH v3 05/13] seccomp_filter: Document what seccomp_filter is and how it works.

Quoted 17 lines · Kees Cook

Hi Will,

Minor typo corrections below...

Documentation/prctl/seccomp_filter.txt line 10

Quoted 10 lines · Will Drewry

 Adds a text file covering what CONFIG_SECCOMP_FILTER is, how it is implemented presently, and what it may be used for.  In addition, the limitations and caveats of the proposed implementation are included.

Documentation/prctl/seccomp_filter.txt new file +1 -0
@@ -0,0 +1,145 @@
...
+certain subset of userland applications benefit by having a reduce set

                                                              reduced

Quoted 3 lines
Quoted 1 line

+of available system calls.  The reduced set reduces the total kernel

Maybe "The resulting set reduces ... " ?

Cool - I'll clean it up in the next cut.

Thanks!
will

author reviewer
#111 lore raw

PATCH v3 6/13 x86: add HAVE_SECCOMP_FILTER and seccomp_execve

In reply to Will Drewry

Adds support to the x86 architecture by providing a compatibility mode wrapper for sys_execve's number and selecting HAVE_SECCOMP_FILTER

---
 arch/x86/Kconfig                   |    1 +
 arch/x86/include/asm/ia32_unistd.h |    1 +
 arch/x86/include/asm/seccomp_64.h  |    2 ++
 3 files changed, 4 insertions(+), 0 deletions(-)
arch/x86/Kconfig +1 -0
index cc6c53a..1843d17 100644
@@ -64,6 +64,7 @@ config X86
 	select HAVE_TEXT_POKE_SMP
 	select HAVE_GENERIC_HARDIRQS
 	select HAVE_SPARSE_IRQ
+	select HAVE_SECCOMP_FILTER
 	select GENERIC_FIND_FIRST_BIT
 	select GENERIC_FIND_NEXT_BIT
 	select GENERIC_IRQ_PROBE
arch/x86/include/asm/ia32_unistd.h +1 -0
index 976f6ec..8ed2922 100644
@@ -12,6 +12,7 @@
 #define __NR_ia32_exit		  1
 #define __NR_ia32_read		  3
 #define __NR_ia32_write		  4
+#define __NR_ia32_execve	 11
 #define __NR_ia32_sigreturn	119
 #define __NR_ia32_rt_sigreturn	173
 
arch/x86/include/asm/seccomp_64.h +2 -0
index 84ec1bd..85c4219 100644
@@ -8,10 +8,12 @@
 #define __NR_seccomp_write __NR_write
 #define __NR_seccomp_exit __NR_exit
 #define __NR_seccomp_sigreturn __NR_rt_sigreturn
+#define __NR_seccomp_execve __NR_execve
 
 #define __NR_seccomp_read_32 __NR_ia32_read
 #define __NR_seccomp_write_32 __NR_ia32_write
 #define __NR_seccomp_exit_32 __NR_ia32_exit
 #define __NR_seccomp_sigreturn_32 __NR_ia32_sigreturn
+#define __NR_seccomp_execve_32 __NR_ia32_execve
 
 #endif /* _ASM_X86_SECCOMP_64_H */
Signature · 1 line
1.7.0.4
author reviewer
#112 lore raw

PATCH v3 7/13 arm: select HAVE_SECCOMP_FILTER

In reply to Will Drewry

Enable support for CONFIG_SECCOMP_FILTER by selecting HAVE_SECCOMP_FILTER by default.

---
 arch/arm/Kconfig |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)
arch/arm/Kconfig +1 -0
index 377a7a5..4725fbc 100644
@@ -16,6 +16,7 @@ config ARM
 	select HAVE_FTRACE_MCOUNT_RECORD if (!XIP_KERNEL)
 	select HAVE_DYNAMIC_FTRACE if (!XIP_KERNEL)
 	select HAVE_FUNCTION_GRAPH_TRACER if (!THUMB2_KERNEL)
+	select HAVE_SECCOMP_FILTER
 	select HAVE_GENERIC_DMA_COHERENT
 	select HAVE_KERNEL_GZIP
 	select HAVE_KERNEL_LZO
Signature · 1 line
1.7.0.4
author reviewer
#113 lore raw

PATCH v3 8/13 microblaze: select HAVE_SECCOMP_FILTER and provide seccomp_execve

In reply to Will Drewry

Facilitate the use of CONFIG_SECCOMP_FILTER by wrapping compatibility system call numbering for execve and selecting HAVE_SECCOMP_FILTER.

---
 arch/microblaze/Kconfig               |    1 +
 arch/microblaze/include/asm/seccomp.h |    2 ++
 2 files changed, 3 insertions(+), 0 deletions(-)
arch/microblaze/Kconfig +1 -0
index eccdefe..30ef677 100644
@@ -1,6 +1,7 @@
 config MICROBLAZE
 	def_bool y
 	select HAVE_MEMBLOCK
+	select HAVE_SECCOMP_FILTER
 	select HAVE_FUNCTION_TRACER
 	select HAVE_FUNCTION_TRACE_MCOUNT_TEST
 	select HAVE_FUNCTION_GRAPH_TRACER
arch/microblaze/include/asm/seccomp.h +2 -0
index 0d91275..0e38eed 100644
@@ -7,10 +7,12 @@
 #define __NR_seccomp_write		__NR_write
 #define __NR_seccomp_exit		__NR_exit
 #define __NR_seccomp_sigreturn		__NR_sigreturn
+#define __NR_seccomp_execve		__NR_execve
 
 #define __NR_seccomp_read_32		__NR_read
 #define __NR_seccomp_write_32		__NR_write
 #define __NR_seccomp_exit_32		__NR_exit
 #define __NR_seccomp_sigreturn_32	__NR_sigreturn
+#define __NR_seccomp_execve_32		__NR_execve
 
 #endif	/* _ASM_MICROBLAZE_SECCOMP_H */
Signature · 1 line
1.7.0.4
maintainer Acked-by on v3 8/13
#114 lore raw

Re: [PATCH v3 08/13] microblaze: select HAVE_SECCOMP_FILTER and provide seccomp_execve

Quoted 8 lines · Will Drewry

Facilitate the use of CONFIG_SECCOMP_FILTER by wrapping compatibility system call numbering for execve and selecting HAVE_SECCOMP_FILTER.

---
 arch/microblaze/Kconfig               |    1 +
 arch/microblaze/include/asm/seccomp.h |    2 ++
 2 files changed, 3 insertions(+), 0 deletions(-)
Signature · 4 lines
Michal Simek, Ing. (M.Eng)
w: www.monstr.eu p: +42-0-721842854
Maintainer of Linux kernel 2.6 Microblaze Linux - http://www.monstr.eu/fdt/
Microblaze U-BOOT custodian
author reviewer
#115 lore raw

PATCH v3 9/13 mips: select HAVE_SECCOMP_FILTER and provide seccomp_execve

In reply to Will Drewry

Facilitate the use of CONFIG_SECCOMP_FILTER by wrapping compatibility system call numbering for execve and selecting HAVE_SECCOMP_FILTER.

---
 arch/mips/Kconfig               |    1 +
 arch/mips/include/asm/seccomp.h |    3 +++
 2 files changed, 4 insertions(+), 0 deletions(-)
arch/mips/Kconfig +1 -0
index 8e256cc..d376f68 100644
@@ -10,6 +10,7 @@ config MIPS
 	select HAVE_ARCH_KGDB
 	select HAVE_FUNCTION_TRACER
 	select HAVE_FUNCTION_TRACE_MCOUNT_TEST
+	select HAVE_SECCOMP_FILTER
 	select HAVE_DYNAMIC_FTRACE
 	select HAVE_FTRACE_MCOUNT_RECORD
 	select HAVE_C_RECORDMCOUNT
arch/mips/include/asm/seccomp.h +3 -0
index ae6306e..4014a3a 100644
@@ -6,6 +6,7 @@
 #define __NR_seccomp_write __NR_write
 #define __NR_seccomp_exit __NR_exit
 #define __NR_seccomp_sigreturn __NR_rt_sigreturn
+#define __NR_seccomp_execve __NR_execve
 
 /*
  * Kludge alert:
@@ -19,6 +20,7 @@
 #define __NR_seccomp_write_32		4004
 #define __NR_seccomp_exit_32		4001
 #define __NR_seccomp_sigreturn_32	4193	/* rt_sigreturn */
+#define __NR_seccomp_execve_32		4011
 
 #elif defined(CONFIG_MIPS32_N32)
 
@@ -26,6 +28,7 @@
 #define __NR_seccomp_write_32		6001
 #define __NR_seccomp_exit_32		6058
 #define __NR_seccomp_sigreturn_32	6211	/* rt_sigreturn */
+#define __NR_seccomp_execve_32		6057
 
 #endif /* CONFIG_MIPS32_O32 */
 
Signature · 1 line
1.7.0.4
author reviewer
#116 lore raw

PATCH v3 10/13 s390: select HAVE_SECCOMP_FILTER and provide seccomp_execve

In reply to Will Drewry

Facilitate the use of CONFIG_SECCOMP_FILTER by wrapping compatibility system call numbering for execve and selecting HAVE_SECCOMP_FILTER.

---
 arch/s390/Kconfig               |    1 +
 arch/s390/include/asm/seccomp.h |    3 ++-
 2 files changed, 3 insertions(+), 1 deletions(-)
arch/s390/Kconfig +1 -0
index 2508a6f..9382198 100644
@@ -64,6 +64,7 @@ config ARCH_SUPPORTS_DEBUG_PAGEALLOC
 config S390
 	def_bool y
 	select USE_GENERIC_SMP_HELPERS if SMP
+	select HAVE_SECCOMP_FILTER
 	select HAVE_SYSCALL_WRAPPERS
 	select HAVE_FUNCTION_TRACER
 	select HAVE_FUNCTION_TRACE_MCOUNT_TEST
arch/s390/include/asm/seccomp.h +2 -1
index 781a9cf..e5792f5 100644
@@ -7,10 +7,11 @@
 #define __NR_seccomp_write	__NR_write
 #define __NR_seccomp_exit	__NR_exit
 #define __NR_seccomp_sigreturn	__NR_sigreturn
+#define __NR_seccomp_execve	__NR_execve
 
 #define __NR_seccomp_read_32	__NR_read
 #define __NR_seccomp_write_32	__NR_write
 #define __NR_seccomp_exit_32	__NR_exit
-#define __NR_seccomp_sigreturn_32 __NR_sigreturn
+#define __NR_seccomp_execve_32	__NR_execve
 
 #endif	/* _ASM_S390_SECCOMP_H */
Signature · 1 line
1.7.0.4
author reviewer
#117 lore raw

PATCH v3 11/13 powerpc: select HAVE_SECCOMP_FILTER and provide seccomp_execve

In reply to Will Drewry

Facilitate the use of CONFIG_SECCOMP_FILTER by wrapping compatibility system call numbering for execve and selecting HAVE_SECCOMP_FILTER.

---
 arch/powerpc/Kconfig               |    1 +
 arch/powerpc/include/asm/seccomp.h |    2 ++
 2 files changed, 3 insertions(+), 0 deletions(-)
arch/powerpc/Kconfig +1 -0
index 8f4d50b..0bd4574 100644
@@ -137,6 +137,7 @@ config PPC
 	select HAVE_HW_BREAKPOINT if PERF_EVENTS && PPC_BOOK3S_64
 	select HAVE_GENERIC_HARDIRQS
 	select HAVE_SPARSE_IRQ
+	select HAVE_SECCOMP_FILTER
 	select IRQ_PER_CPU
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
arch/powerpc/include/asm/seccomp.h +2 -0
index 00c1d91..3cb9cc1 100644
@@ -7,10 +7,12 @@
 #define __NR_seccomp_write __NR_write
 #define __NR_seccomp_exit __NR_exit
 #define __NR_seccomp_sigreturn __NR_rt_sigreturn
+#define __NR_seccomp_execve __NR_execve
 
 #define __NR_seccomp_read_32 __NR_read
 #define __NR_seccomp_write_32 __NR_write
 #define __NR_seccomp_exit_32 __NR_exit
 #define __NR_seccomp_sigreturn_32 __NR_sigreturn
+#define __NR_seccomp_execve_32 __NR_execve
 
 #endif	/* _ASM_POWERPC_SECCOMP_H */
Signature · 1 line
1.7.0.4
author reviewer
#118 lore raw

PATCH v3 12/13 sparc: select HAVE_SECCOMP_FILTER and provide seccomp_execve

In reply to Will Drewry

Facilitate the use of CONFIG_SECCOMP_FILTER by wrapping compatibility system call numbering for execve and selecting HAVE_SECCOMP_FILTER.

---
 arch/sparc/Kconfig               |    2 ++
 arch/sparc/include/asm/seccomp.h |    2 ++
 2 files changed, 4 insertions(+), 0 deletions(-)
arch/sparc/Kconfig +2 -0
index e560d10..5249760 100644
@@ -25,6 +25,7 @@ config SPARC
 	select HAVE_DMA_ATTRS
 	select HAVE_DMA_API_DEBUG
 	select HAVE_ARCH_JUMP_LABEL
+	select HAVE_SECCOMP_FILTER
 
 config SPARC32
 	def_bool !64BIT
@@ -39,6 +40,7 @@ config SPARC64
 	select HAVE_KRETPROBES
 	select HAVE_KPROBES
 	select HAVE_MEMBLOCK
+	select HAVE_SECCOMP_FILTER
 	select HAVE_SYSCALL_WRAPPERS
 	select HAVE_DYNAMIC_FTRACE
 	select HAVE_FTRACE_MCOUNT_RECORD
arch/sparc/include/asm/seccomp.h +2 -0
index adca1bc..a1dac08 100644
@@ -6,10 +6,12 @@
 #define __NR_seccomp_write __NR_write
 #define __NR_seccomp_exit __NR_exit
 #define __NR_seccomp_sigreturn __NR_rt_sigreturn
+#define __NR_seccomp_execve __NR_execve
 
 #define __NR_seccomp_read_32 __NR_read
 #define __NR_seccomp_write_32 __NR_write
 #define __NR_seccomp_exit_32 __NR_exit
 #define __NR_seccomp_sigreturn_32 __NR_sigreturn
+#define __NR_seccomp_execve_32 __NR_execve
 
 #endif /* _ASM_SECCOMP_H */
Signature · 1 line
1.7.0.4
author reviewer
#120 lore raw

PATCH v3 13/13 sh: select HAVE_SECCOMP_FILTER

In reply to Will Drewry

Add support for CONFIG_SECCOMP_FILTER by selecting HAVE_SECCOMP_FILTER.

---
 arch/sh/Kconfig |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)
arch/sh/Kconfig +1 -0
index 4b89da2..41ea3a7 100644
@@ -10,6 +10,7 @@ config SUPERH
 	select HAVE_DMA_API_DEBUG
 	select HAVE_DMA_ATTRS
 	select HAVE_IRQ_WORK
+	select HAVE_SECCOMP_FILTER
 	select HAVE_PERF_EVENTS
 	select PERF_USE_VMALLOC
 	select HAVE_KERNEL_GZIP
Signature · 1 line
1.7.0.4
Acked-by on v3 13/13
#121 lore raw

Re: [PATCH v3 13/13] sh: select HAVE_SECCOMP_FILTER

Quoted 5 lines · Will Drewry

Add support for CONFIG_SECCOMP_FILTER by selecting HAVE_SECCOMP_FILTER.

---
 arch/sh/Kconfig |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)
#122 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Will Drewry
Quoted 6 lines · Will Drewry

Absolutely - that was what I meant :/ The patches do not currently check creds at creation or again at use, which would lead to unprivileged filters being used in a privileged context. Right now, though, if setuid() is not allowed by the seccomp-filter, the process will be immediately killed with do_exit(SIGKILL) on call -- thus avoiding a silent failure.

How do you know you have the bounding set correct?

This has been a long-standing issue for SELinux policy writing - it's usually easy to get 95% of the bounding box right (you need these rules for shared libraries, you need these rules to access the user's home directory, you need these other rules to talk TCP to the net, etc). There's a nice tool that converts any remaining rejection messages into rules you can add to the policy.

The problem is twofold: (a) that way you can never be sure you got *all* the rules right and (b) the missing rules are almost always in squirrelly little error-handling code that gets invoked once in a blue moon. So in this case, you end up with trying to debug the SIGKILL that happened when the process was already in trouble for some other reason...

"Wow. Who would have guessed that program only called gettimeofday() in the error handler for when it was formatting its crash message?"

Exactly.

author reviewer
#123 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 23 lines · On Thu, May 26, 2011 at 12:38 PM, <[email protected]> wrote:
Quoted 6 lines · Will Drewry

Absolutely - that was what I meant :/  The patches do not currently check creds at creation or again at use, which would lead to unprivileged filters being used in a privileged context.  Right now, though, if setuid() is not allowed by the seccomp-filter, the process will be immediately killed with do_exit(SIGKILL) on call -- thus avoiding a silent failure.

How do you know you have the bounding set correct?

This has been a long-standing issue for SELinux policy writing - it's usually easy to get 95% of the bounding box right (you need these rules for shared libraries, you need these rules to access the user's home directory, you need these other rules to talk TCP to the net, etc).  There's a nice tool that converts any remaining rejection messages into rules you can add to the policy.

The problem is twofold: (a) that way you can never be sure you got *all* the rules right and (b) the missing rules are almost always in squirrelly little error-handling code that gets invoked once in a blue moon.  So in this case, you end up with trying to debug the SIGKILL that happened when the process was already in trouble for some other reason...

Quoted 4 lines

"Wow. Who would have guessed that program only called gettimeofday() in the error handler for when it was formatting its crash message?"

Exactly.

Depending on the need, there is work involved, and there are many ways to determine your bounding box. It can be very tight -- where you analyze normal workloads (perf,strace,objdump) and accept the fact that pathological workloads may result in process death -- or it can be quite loose and enable most system calls, just not newer ones, let's say. In practice, you might get bit a few times if you're overly zealous (I know I have), but it's the difference between failing open and failing closed. There are some scenarios where you never, ever want to fail-open even at the cost of process death and lack of solid insight into a valid failure path.

Hope that makes sense and isn't too general,
will

#124 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 11 lines · Will Drewry

Depending on the need, there is work involved, and there are many ways to determine your bounding box. It can be very tight -- where you analyze normal workloads (perf,strace,objdump) and accept the fact that pathological workloads may result in process death -- or it can be quite loose and enable most system calls, just not newer ones, let's say. In practice, you might get bit a few times if you're overly zealous (I know I have), but it's the difference between failing open and failing closed. There are some scenarios where you never, ever want to fail-open even at the cost of process death and lack of solid insight into a valid failure path.

Quoted 1 line

Hope that makes sense and isn't too general,

Oh, I already understood all that. :) I'd have to double-check the actual
patch, does it give a (hopefully rate-limited) printk or other hint which syscall caused the issue, to help in making up the list of needed syscalls?

And we probably want a cleaned-up copy of the quoted paragraph in the documentation for this feature when it hits the streets. People tuning in late will need guidance on how to use this in their projects.

maintainer
#125 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Linus Torvalds
Quoted 6 lines · Linus Torvalds

And if you filter system calls, it's entirely possible that you can attack suid executables through such a vector. Your "limit system calls for security" security suddenly turned into "avoid the system call that made things secure"!

See what I'm saying?

So you are not complaining about this implementation, but the use of syscall filtering?

There may be some user that says, "oh I don't want my other apps to be able to call setuid" thinking it will secure their application even more. But because that application did the brain dead thing to not check the return code of setuid, and it just happened to be running privileged, it then execs off another application that can root the box.

Because, originally that setuid would have succeeded if the user did nothing special, but now with this filtering, and the user thinking that they could limit their app from doing harm, they just opened up a hole that caused their app to do the exact opposite and give the exec'd app full root privileges.

Did I get this right?

-- Steve

#126 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 17 lines · Steven Rostedt
Quoted 6 lines · Linus Torvalds

And if you filter system calls, it's entirely possible that you can attack suid executables through such a vector. Your "limit system calls for security" security suddenly turned into "avoid the system call that made things secure"!

See what I'm saying?

So you are not complaining about this implementation, but the use of syscall filtering?

There may be some user that says, "oh I don't want my other apps to be able to call setuid" thinking it will secure their application even more. But because that application did the brain dead thing to not check the return code of setuid, and it just happened to be running privileged, it then execs off another application that can root the box.

Quoted 7 lines

Because, originally that setuid would have succeeded if the user did nothing special, but now with this filtering, and the user thinking that they could limit their app from doing harm, they just opened up a hole that caused their app to do the exact opposite and give the exec'd app full root privileges.

Did I get this right?

Yes. Some system calls are there so that you can turn off privilege. There was a major exploit with sendmail when capabilities were first introduced that brought the potential for this sort of problem into the public eye. Kernel mechanisms intended to provide additional security have to be massively careful about the impact they may have on applications that are currently security aware and that make use of the existing mechanisms. The ACL mechanism is much more complicated than it probably ought to be to accommodate chmod() and capabilities go way over the top to deal with traditional root behavior.

Quoted 10 lines

-- Steve

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/

maintainer
#127 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

Quoted 3 lines · Casey Schaufler
Quoted 1 line

Did I get this right?

Yes.

Thanks for the validation ;)

-- Steve

#128 lore raw

Re: [PATCH 3/5] v2 seccomp_filters: Enable ftrace-based system call filtering

In reply to Linus Torvalds
Quoted 18 lines · Linus Torvalds
Quoted 3 lines · Will Drewry

FWIW, none of the patches deal with privilege escalation via setuid files or file capabilities.

That is NOT AT ALL what I'm talking about.

I'm talking about the "setuid()" system call (and all its cousins:
setgit/setreuid etc). And the whole thread has been about filtering system calls, no?

Do a google code search for setuid.

In good code, it will look something like

uid = getuid();

Quoted 8 lines
 if (setuid(uid)) {
   fprintf(stderr, "Unable to drop provileges\n");
   exit(1);

}

but I guarantee you that there are cases where people just blindly drop privileges. google code search found me at least the "heirloom" source code doing exactly that.

I believe that sendmail had this exact vunerability when capibilities were used to control setuid a couple of years ago.

David Lang