Skip to contentSkip to conversation

x86: introduce system calls addess space isolation

RFC PATCH In review Mike Rapoport 10 participants 41 messages Apr 25, 2019 – May 2, 2019

Subsystems (6)
lore
Share & tools
lore
#0 lore raw

cover x86: introduce system calls addess space isolation

Hi,

Address space isolation has been used to protect the kernel from the userspace and userspace programs from each other since the invention of the virtual memory.

Assuming that kernel bugs and therefore vulnerabilities are inevitable it might be worth isolating parts of the kernel to minimize damage that these vulnerabilities can cause.

The idea here is to allow an untrusted user access to a potentially vulnerable kernel in such a way that any kernel vulnerability they find to exploit is either prevented or the consequences confined to their isolated address space such that the compromise attempt has minimal impact on other tenants or the protected structures of the monolithic kernel. Although we hope to prevent many classes of attack, the first target we're looking at is ROP gadget protection.

These patches implement a "system call isolation (SCI)" mechanism that allows running system calls in an isolated address space with reduced page tables to prevent ROP attacks.

ROP attacks involve corrupting the stack return address to repoint it to a segment of code you know exists in the kernel that can be used to perform the action you need to exploit the system.

The idea behind the prevention is that if we fault in pages in the execution path, we can compare target address against the kernel symbol table. So if we're in a function, we allow local jumps (and simply falling of the end of a page) but if we're jumping to a new function it must be to an external label in the symbol table. Since ROP attacks are all about jumping to gadget code which is effectively in the middle of real functions, the jumps they induce are to code that doesn't have an external symbol, so it should mostly detect when they happen.

This is very early POC, it's able to run the simple dummy system calls and a little bit beyond that, but it's not yet stable and robust enough to boot a system with system call isolation enabled for all system calls. Still, we wanted to get some feedback about the concept in general as early as possible.

At this time we are not suggesting any API that will enable the system calls isolation. Because of the overhead required for this, it should only be activated for processes or containers we know should be untrusted. We still have no actual numbers, but surely forcing page faults during system call execution will not come for free.

One possible way is to create a namespace, and force the system calls isolation on all the processes in that namespace. Another thing that came to mind was to use a seccomp filter to allow fine grained control of this feature.

The current implementation is pretty much x86-centric, but the general idea can be used on other architectures.

A brief TOC of the set:
* patch 1 adds definitions of X86_FEATURE_SCI
* patch 2 is the core implementation of system calls isolation (SCI)
* patches 3-5 add hooks to SCI at entry paths and in the page fault handler
* patch 6 enables the SCI in Kconfig
* patch 7 includes example dummy system calls that are used to demonstrate the SCI in action.

Mike Rapoport (7):
x86/cpufeatures: add X86_FEATURE_SCI
x86/sci: add core implementation for system call isolation x86/entry/64: add infrastructure for switching to isolated syscall
context
x86/sci: hook up isolated system call entry and exit x86/mm/fault: hook up SCI verification
security: enable system call isolation in kernel config
sci: add example system calls to exercse SCI

 arch/x86/entry/calling.h                 |  65 ++++
 arch/x86/entry/common.c                  |  65 ++++
 arch/x86/entry/entry_64.S                |  13 +-
 arch/x86/entry/syscalls/syscall_64.tbl   |   3 +
 arch/x86/include/asm/cpufeatures.h       |   1 +
 arch/x86/include/asm/disabled-features.h |   8 +-
 arch/x86/include/asm/processor-flags.h   |   8 +
 arch/x86/include/asm/sci.h               |  55 +++
 arch/x86/include/asm/tlbflush.h          |   8 +-
 arch/x86/kernel/asm-offsets.c            |   7 +
 arch/x86/kernel/process_64.c             |   5 +
 arch/x86/mm/Makefile                     |   1 +
 arch/x86/mm/fault.c                      |  28 ++
 arch/x86/mm/init.c                       |   2 +
 arch/x86/mm/sci.c                        | 608 +++++++++++++++++++++++++++++++
 include/linux/sched.h                    |   5 +
 include/linux/sci.h                      |  12 +
 kernel/Makefile                          |   2 +-
 kernel/exit.c                            |   3 +
 kernel/sci-examples.c                    |  52 +++
 security/Kconfig                         |  10 +
 21 files changed, 956 insertions(+), 5 deletions(-)
 create mode 100644 arch/x86/include/asm/sci.h
 create mode 100644 arch/x86/mm/sci.c
 create mode 100644 include/linux/sci.h
 create mode 100644 kernel/sci-examples.c
Signature · 1 line
2.7.4
#1 lore raw

RFC PATCH 1/7 x86/cpufeatures: add X86_FEATURE_SCI

The X86_FEATURE_SCI will be set when system call isolation is enabled.

---
 arch/x86/include/asm/cpufeatures.h       | 1 +
 arch/x86/include/asm/disabled-features.h | 8 +++++++-
 2 files changed, 8 insertions(+), 1 deletion(-)
arch/x86/include/asm/cpufeatures.h +1 -0
index 6d61225..a01c6dd 100644
@@ -221,6 +221,7 @@
 #define X86_FEATURE_ZEN			( 7*32+28) /* "" CPU is AMD family 0x17 (Zen) */
 #define X86_FEATURE_L1TF_PTEINV		( 7*32+29) /* "" L1TF workaround PTE inversion */
 #define X86_FEATURE_IBRS_ENHANCED	( 7*32+30) /* Enhanced IBRS */
+#define X86_FEATURE_SCI			( 7*32+31) /* "" System call isolation */
 
 /* Virtualization flags: Linux defined, word 8 */
 #define X86_FEATURE_TPR_SHADOW		( 8*32+ 0) /* Intel TPR Shadow */
arch/x86/include/asm/disabled-features.h +7 -1
index a5ea841..79947f0 100644
@@ -62,6 +62,12 @@
 # define DISABLE_PTI		(1 << (X86_FEATURE_PTI & 31))
 #endif
 
+#ifdef CONFIG_SYSCALL_ISOLATION
+# define DISABLE_SCI		0
+#else
+# define DISABLE_SCI		(1 << (X86_FEATURE_SCI & 31))
+#endif
+
 /*
  * Make sure to add features to the correct mask
  */
@@ -72,7 +78,7 @@
 #define DISABLED_MASK4	(DISABLE_PCID)
 #define DISABLED_MASK5	0
 #define DISABLED_MASK6	0
-#define DISABLED_MASK7	(DISABLE_PTI)
+#define DISABLED_MASK7	(DISABLE_PTI|DISABLE_SCI)
 #define DISABLED_MASK8	0
 #define DISABLED_MASK9	(DISABLE_MPX|DISABLE_SMAP)
 #define DISABLED_MASK10	0
Signature · 1 line
2.7.4
#2 lore raw

RFC PATCH 2/7 x86/sci: add core implementation for system call isolation

In reply to Mike Rapoport

When enabled, the system call isolation (SCI) would allow execution of the system calls with reduced page tables. These page tables are almost identical to the user page tables in PTI. The only addition is the code page containing system call entry function that will continue exectution after the context switch.

Unlike PTI page tables, there is no sharing at higher levels and all the hierarchy for SCI page tables is cloned.

The SCI page tables are created when a system call that requires isolation is executed for the first time.

Whenever a system call should be executed in the isolated environment, the context is switched to the SCI page tables. Any further access to the kernel memory will generate a page fault. The page fault handler can verify that the access is safe and grant it or kill the task otherwise.

The initial SCI implementation allows access to any kernel data, but it limits access to the code in the following way:
* calls and jumps to known code symbols without offset are allowed
* calls and jumps into a known symbol with offset are allowed only if that symbol was already accessed and the offset is in the next page
* all other code access are blocked

After the isolated system call finishes, the mappings created during its execution are cleared.

The entire SCI page table is lazily freed at task exit() time.

---
 arch/x86/include/asm/sci.h |  55 ++++
 arch/x86/mm/Makefile       |   1 +
 arch/x86/mm/init.c         |   2 +
 arch/x86/mm/sci.c          | 608 +++++++++++++++++++++++++++++++++++++++++++++
 include/linux/sched.h      |   5 +
 include/linux/sci.h        |  12 +
 6 files changed, 683 insertions(+)
 create mode 100644 arch/x86/include/asm/sci.h
 create mode 100644 arch/x86/mm/sci.c
 create mode 100644 include/linux/sci.h
arch/x86/include/asm/sci.h new file +55 -0
new file mode 100644
index 0000000..0b56200
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-2.0
+#ifndef _ASM_X86_SCI_H
+#define _ASM_X86_SCI_H
+
+#ifdef CONFIG_SYSCALL_ISOLATION
+
+struct sci_task_data {
+	pgd_t		*pgd;
+	unsigned long	cr3_offset;
+	unsigned long	backtrace_size;
+	unsigned long	*backtrace;
+	unsigned long	ptes_count;
+	pte_t		**ptes;
+};
+
+struct sci_percpu_data {
+	unsigned long		sci_syscall;
+	unsigned long		sci_cr3_offset;
+};
+
+DECLARE_PER_CPU_PAGE_ALIGNED(struct sci_percpu_data, cpu_sci);
+
+void sci_check_boottime_disable(void);
+
+int sci_init(struct task_struct *tsk);
+void sci_exit(struct task_struct *tsk);
+
+bool sci_verify_and_map(struct pt_regs *regs, unsigned long addr,
+			unsigned long hw_error_code);
+void sci_clear_data(void);
+
+static inline void sci_switch_to(struct task_struct *next)
+{
+	this_cpu_write(cpu_sci.sci_syscall, next->in_isolated_syscall);
+	if (next->sci)
+		this_cpu_write(cpu_sci.sci_cr3_offset, next->sci->cr3_offset);
+}
+
+#else /* CONFIG_SYSCALL_ISOLATION */
+
+static inline void sci_check_boottime_disable(void) {}
+
+static inline bool sci_verify_and_map(struct pt_regs *regs,unsigned long addr,
+				      unsigned long hw_error_code)
+{
+	return true;
+}
+
+static inline void sci_clear_data(void) {}
+
+static inline void sci_switch_to(struct task_struct *next) {}
+
+#endif /* CONFIG_SYSCALL_ISOLATION */
+
+#endif /* _ASM_X86_SCI_H */
arch/x86/mm/Makefile +1 -0
index 4b101dd..9a728b7 100644
@@ -49,6 +49,7 @@ obj-$(CONFIG_X86_INTEL_MPX)			+= mpx.o
 obj-$(CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS)	+= pkeys.o
 obj-$(CONFIG_RANDOMIZE_MEMORY)			+= kaslr.o
 obj-$(CONFIG_PAGE_TABLE_ISOLATION)		+= pti.o
+obj-$(CONFIG_SYSCALL_ISOLATION)			+= sci.o
 
 obj-$(CONFIG_AMD_MEM_ENCRYPT)	+= mem_encrypt.o
 obj-$(CONFIG_AMD_MEM_ENCRYPT)	+= mem_encrypt_identity.o
arch/x86/mm/init.c +2 -0
index f905a23..b6e2db4 100644
@@ -22,6 +22,7 @@
 #include <asm/hypervisor.h>
 #include <asm/cpufeature.h>
 #include <asm/pti.h>
+#include <asm/sci.h>
 
 /*
  * We need to define the tracepoints somewhere, and tlb.c
@@ -648,6 +649,7 @@ void __init init_mem_mapping(void)
 	unsigned long end;
 
 	pti_check_boottime_disable();
+	sci_check_boottime_disable();
 	probe_page_size_mask();
 	setup_pcid();
 
arch/x86/mm/sci.c new file +608 -0

608 lines not on this page · raw message

include/linux/sched.h +5 -0
index f9b43c9..cdcdb07 100644
@@ -1202,6 +1202,11 @@ struct task_struct {
 	unsigned long			prev_lowest_stack;
 #endif
 
+#ifdef CONFIG_SYSCALL_ISOLATION
+	unsigned long			in_isolated_syscall;
+	struct sci_task_data		*sci;
+#endif
+
 	/*
 	 * New fields for task_struct should be added above here, so that
 	 * they are included in the randomized portion of task_struct.
include/linux/sci.h new file +12 -0
new file mode 100644
index 0000000..7a6beac
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-2.0
+#ifndef _LINUX_SCI_H
+#define _LINUX_SCI_H
+
+#ifdef CONFIG_SYSCALL_ISOLATION
+#include <asm/sci.h>
+#else
+static inline int sci_init(struct task_struct *tsk) { return 0; }
+static inline void sci_exit(struct task_struct *tsk) {}
+#endif
+
+#endif /* _LINUX_SCI_H */
Signature · 1 line
2.7.4
maintainer
#3 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 6 lines · Mike Rapoport

The initial SCI implementation allows access to any kernel data, but it limits access to the code in the following way:
* calls and jumps to known code symbols without offset are allowed
* calls and jumps into a known symbol with offset are allowed only if that symbol was already accessed and the offset is in the next page
* all other code access are blocked

So if you have a large function and an in-function jump skips a page you're toast.

Why not employ the instruction decoder we have and unconditionally allow all direct JMP/CALL but verify indirect JMP/CALL and RET ?

Anyway, I'm fearing the overhead of this one, this cannot be fast.

#4 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Mike Rapoport

The initial SCI implementation allows access to any kernel data, but it limits access to the code in the following way:
* calls and jumps to known code symbols without offset are allowed
* calls and jumps into a known symbol with offset are allowed only if that symbol was already accessed and the offset is in the next page
* all other code access are blocked

So if you have a large function and an in-function jump skips a page you're toast.

Right :(

Quoted 2 lines

Why not employ the instruction decoder we have and unconditionally allow all direct JMP/CALL but verify indirect JMP/CALL and RET ?

Apparently I didn't dig deep enough to find the instruction decoder :) Surely I can use it.

Quoted 1 line

Anyway, I'm fearing the overhead of this one, this cannot be fast.

Well, I think that the verification itself is not what will slow things down the most. IMHO, the major overhead is coming from cr3 switch.

Signature · 2 lines
Sincerely yours,
Mike.
#5 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

In reply to Mike Rapoport
Quoted 25 lines · Mike Rapoport

When enabled, the system call isolation (SCI) would allow execution of the system calls with reduced page tables. These page tables are almost identical to the user page tables in PTI. The only addition is the code page containing system call entry function that will continue exectution after the context switch.

Unlike PTI page tables, there is no sharing at higher levels and all the hierarchy for SCI page tables is cloned.

The SCI page tables are created when a system call that requires isolation is executed for the first time.

Whenever a system call should be executed in the isolated environment, the context is switched to the SCI page tables. Any further access to the kernel memory will generate a page fault. The page fault handler can verify that the access is safe and grant it or kill the task otherwise.

The initial SCI implementation allows access to any kernel data, but it limits access to the code in the following way:
* calls and jumps to known code symbols without offset are allowed
* calls and jumps into a known symbol with offset are allowed only if that symbol was already accessed and the offset is in the next page
* all other code access are blocked

Quoted 4 lines

After the isolated system call finishes, the mappings created during its execution are cleared.

The entire SCI page table is lazily freed at task exit() time.

So this basically uses a similar mechanism to the horrendous PTI CR3 switching overhead whenever a syscall seeks "protection", which overhead is only somewhat mitigated by PCID.

This might work on PTI-encumbered CPUs.

While AMD CPUs don't need PTI, nor do they have PCID.

So this feature is hurting the CPU maker who didn't mess up, and is hurting future CPUs that don't need PTI ..

I really don't like it where this is going. In a couple of years I really want to be able to think of PTI as a bad dream that is mostly over fortunately.

I have the feeling that compiler level protection that avoids corrupting the stack in the first place is going to be lower overhead, and would work in a much broader range of environments. Do we have analysis of what the compiler would have to do to prevent most ROP attacks, and what the runtime cost of that is?

I mean, C# and Java programs aren't able to corrupt the stack as long as the language runtime is corect. Has to be possible, right?

Thanks,

Ingo

#6 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 4 lines · Ingo Molnar

I really don't like it where this is going. In a couple of years I really want to be able to think of PTI as a bad dream that is mostly over fortunately.

Quoted 8 lines

I have the feeling that compiler level protection that avoids corrupting the stack in the first place is going to be lower overhead, and would work in a much broader range of environments. Do we have analysis of what the compiler would have to do to prevent most ROP attacks, and what the runtime cost of that is?

I mean, C# and Java programs aren't able to corrupt the stack as long as the language runtime is corect. Has to be possible, right?

So if such security feature is offered then I'm afraid distros would be strongly inclined to enable it - saying 'yes' to a kernel feature that can keep your product off CVE advisories is a strong force.

To phrase the argument in a bit more controversial form:

If the price of Linux using an insecure C runtime is to slow down system calls with immense PTI-alike runtime costs, then wouldn't it be the right technical decision to write the kernel in a language runtime that doesn't allow stack overflows and such?

I.e. if having Linux in C ends up being slower than having it in Java, then what's the performance argument in favor of using C to begin with? ;-)

And no, I'm not arguing for Java or C#, but I am arguing for a saner version of C.

Thanks,

Ingo

maintainer
#7 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 29 lines · Ingo Molnar
Quoted 4 lines · Ingo Molnar

I really don't like it where this is going. In a couple of years I really want to be able to think of PTI as a bad dream that is mostly over fortunately.

Quoted 8 lines

I have the feeling that compiler level protection that avoids corrupting the stack in the first place is going to be lower overhead, and would work in a much broader range of environments. Do we have analysis of what the compiler would have to do to prevent most ROP attacks, and what the runtime cost of that is?

I mean, C# and Java programs aren't able to corrupt the stack as long as the language runtime is corect. Has to be possible, right?

So if such security feature is offered then I'm afraid distros would be strongly inclined to enable it - saying 'yes' to a kernel feature that can keep your product off CVE advisories is a strong force.

To phrase the argument in a bit more controversial form:

If the price of Linux using an insecure C runtime is to slow down system calls with immense PTI-alike runtime costs, then wouldn't it be the right technical decision to write the kernel in a language runtime that doesn't allow stack overflows and such?

Quoted 8 lines

I.e. if having Linux in C ends up being slower than having it in Java, then what's the performance argument in favor of using C to begin with? ;-)

And no, I'm not arguing for Java or C#, but I am arguing for a saner version of C.

IMO three are three credible choices:

1. C with fairly strong CFI protection. Grsecurity has his (supposedly — there’s a distinct lack of source code available), and clang is gradually working on it.

2. A safe language for parts of the kernel, e.g. drivers and maybe eventually filesystems. Rust is probably the only credible candidate. Actually creating a decent Rust wrapper around the core kernel facilities would be quite a bit of work. Things like sysfs would be interesting in Rust, since AFAIK few or even no drivers actually get the locking fully correct. This means that naive users of the API cannot port directly to safe Rust, because all the races won't compile :)

3. A sandbox for parts of the kernel, e.g. drivers. The obvious candidates are eBPF and WASM.

#2 will give very good performance. #3 gives potentially stronger protection against a sandboxed component corrupting the kernel overall, but it gives much weaker protection against a sandboxed component corrupting itself.

In an ideal world, we could do #2 *and* #3. Drivers could, for example, be written in a language like Rust, compiled to WASM, and run in the kernel.

#8 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 56 lines · Andy Lutomirski
Quoted 29 lines · Ingo Molnar
Quoted 4 lines · Ingo Molnar

I really don't like it where this is going. In a couple of years I really want to be able to think of PTI as a bad dream that is mostly over fortunately.

Quoted 8 lines

I have the feeling that compiler level protection that avoids corrupting the stack in the first place is going to be lower overhead, and would work in a much broader range of environments. Do we have analysis of what the compiler would have to do to prevent most ROP attacks, and what the runtime cost of that is?

I mean, C# and Java programs aren't able to corrupt the stack as long as the language runtime is corect. Has to be possible, right?

So if such security feature is offered then I'm afraid distros would be strongly inclined to enable it - saying 'yes' to a kernel feature that can keep your product off CVE advisories is a strong force.

To phrase the argument in a bit more controversial form:

If the price of Linux using an insecure C runtime is to slow down system calls with immense PTI-alike runtime costs, then wouldn't it be the right technical decision to write the kernel in a language runtime that doesn't allow stack overflows and such?

Quoted 8 lines

I.e. if having Linux in C ends up being slower than having it in Java, then what's the performance argument in favor of using C to begin with? ;-)

And no, I'm not arguing for Java or C#, but I am arguing for a saner version of C.

IMO three are three credible choices:

1. C with fairly strong CFI protection. Grsecurity has this (supposedly — there’s a distinct lack of source code available), and clang is gradually working on it.

2. A safe language for parts of the kernel, e.g. drivers and maybe eventually filesystems. Rust is probably the only credible candidate. Actually creating a decent Rust wrapper around the core kernel facilities would be quite a bit of work. Things like sysfs would be interesting in Rust, since AFAIK few or even no drivers actually get the locking fully correct. This means that naive users of the API cannot port directly to safe Rust, because all the races won't compile :)

3. A sandbox for parts of the kernel, e.g. drivers. The obvious candidates are eBPF and WASM.

Quoted 8 lines

#2 will give very good performance. #3 gives potentially stronger protection against a sandboxed component corrupting the kernel overall, but it gives much weaker protection against a sandboxed component corrupting itself.

In an ideal world, we could do #2 *and* #3. Drivers could, for example, be written in a language like Rust, compiled to WASM, and run in the kernel.

So why not go for #1, which would still outperform #2/#3, right? Do we know what it would take, roughly, and how the runtime overhead looks like?

Thanks,

Ingo

#9 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 28 lines · Ingo Molnar
Quoted 26 lines · Andy Lutomirski
Quoted 2 lines

And no, I'm not arguing for Java or C#, but I am arguing for a saner version of C.

IMO three are three credible choices:

1. C with fairly strong CFI protection. Grsecurity has this (supposedly — there’s a distinct lack of source code available), and clang is gradually working on it.

2. A safe language for parts of the kernel, e.g. drivers and maybe eventually filesystems. Rust is probably the only credible candidate. Actually creating a decent Rust wrapper around the core kernel facilities would be quite a bit of work. Things like sysfs would be interesting in Rust, since AFAIK few or even no drivers actually get the locking fully correct. This means that naive users of the API cannot port directly to safe Rust, because all the races won't compile :)

3. A sandbox for parts of the kernel, e.g. drivers. The obvious candidates are eBPF and WASM.

#2 will give very good performance. #3 gives potentially stronger protection against a sandboxed component corrupting the kernel overall, but it gives much weaker protection against a sandboxed component corrupting itself.

Quoted 7 lines
Quoted 3 lines

In an ideal world, we could do #2 *and* #3. Drivers could, for example, be written in a language like Rust, compiled to WASM, and run in the kernel.

So why not go for #1, which would still outperform #2/#3, right? Do we know what it would take, roughly, and how the runtime overhead looks like?

BTW., CFI protection is in essence a compiler (or hardware) technique to detect stack frame or function pointer corruption after the fact.

So I'm wondering whether there's a 4th choice as well, which avoids control flow corruption *before* it happens:

- A C language runtime that is a subset of current C syntax and semantics used in the kernel, and which doesn't allow access outside of existing objects and thus creates a strictly enforced separation between memory used for data, and memory used for code and control flow.

- This would involve, at minimum:

- tracking every type and object and its inherent length and valid access patterns, and never losing track of its type.

- being a lot more organized about initialization, i.e. no uninitialized variables/fields.

- being a lot more strict about type conversions and pointers in general.

- ... and a metric ton of other details.

- If such a runtime could co-exist without big complications with regular C kernel code then we could convert particular pieces of C code into this safe-C runtime step by step, and would also allow the compilation of a piece of code as regular C, or into the safe runtime.

- If a particular function can be formally proven to be safe, it can be compiled as C - otherwise it would be compiled as safe-C.

- ... or something like this.

The advantage would be: data corruption could never be triggered by code itself, if the compiler and runtime is correct. Return addresses and stacks wouldn't have to be 'hardened' or 'checked', because they'd never be corrupted in the first place. WX memory wouldn't be an issue as kernel code could never jump into generated shell code or ROP gadgets.

The disadvantage: the overhead of managing this, and any loss of flexibility on the kernel programming side.

Does this make sense, and if yes, does such a project exist already? (And no, I don't mean Java or C#.)

Or would we in essence end up with a Java runtime, with C syntax?

Thanks,

Ingo

maintainer
#10 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 5 lines · Ingo Molnar

- A C language runtime that is a subset of current C syntax and semantics used in the kernel, and which doesn't allow access outside of existing objects and thus creates a strictly enforced separation between memory used for data, and memory used for code and control flow.

Might be better to start with Rust.

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

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 11 lines · James Morris
Quoted 5 lines · Ingo Molnar

- A C language runtime that is a subset of current C syntax and semantics used in the kernel, and which doesn't allow access outside of existing objects and thus creates a strictly enforced separation between memory used for data, and memory used for code and control flow.

Might be better to start with Rust.

I think that Rust would be the clear winner as measured by how fun it sounds :)

maintainer
#12 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

In reply to Ingo Molnar
Quoted 54 lines · Ingo Molnar
Quoted 28 lines · Ingo Molnar
Quoted 26 lines · Andy Lutomirski
Quoted 2 lines

And no, I'm not arguing for Java or C#, but I am arguing for a saner version of C.

IMO three are three credible choices:

1. C with fairly strong CFI protection. Grsecurity has this (supposedly — there’s a distinct lack of source code available), and clang is gradually working on it.

2. A safe language for parts of the kernel, e.g. drivers and maybe eventually filesystems. Rust is probably the only credible candidate. Actually creating a decent Rust wrapper around the core kernel facilities would be quite a bit of work. Things like sysfs would be interesting in Rust, since AFAIK few or even no drivers actually get the locking fully correct. This means that naive users of the API cannot port directly to safe Rust, because all the races won't compile :)

3. A sandbox for parts of the kernel, e.g. drivers. The obvious candidates are eBPF and WASM.

#2 will give very good performance. #3 gives potentially stronger protection against a sandboxed component corrupting the kernel overall, but it gives much weaker protection against a sandboxed component corrupting itself.

Quoted 7 lines
Quoted 3 lines

In an ideal world, we could do #2 *and* #3. Drivers could, for example, be written in a language like Rust, compiled to WASM, and run in the kernel.

So why not go for #1, which would still outperform #2/#3, right? Do we know what it would take, roughly, and how the runtime overhead looks like?

BTW., CFI protection is in essence a compiler (or hardware) technique to detect stack frame or function pointer corruption after the fact.

So I'm wondering whether there's a 4th choice as well, which avoids control flow corruption *before* it happens:

- A C language runtime that is a subset of current C syntax and semantics used in the kernel, and which doesn't allow access outside of existing objects and thus creates a strictly enforced separation between memory used for data, and memory used for code and control flow.

- This would involve, at minimum:

Quoted 8 lines

- tracking every type and object and its inherent length and valid access patterns, and never losing track of its type.

- being a lot more organized about initialization, i.e. no uninitialized variables/fields.

- being a lot more strict about type conversions and pointers in general.

You're not the only one to suggest this. There are at least a few things that make this extremely difficult if not impossible. For example, consider this code:

void maybe_buggy(void)
{
int a, b;
int *p = &a;
int *q = (int *)some_function((unsigned long)p); *q = 1;
}

If some_function(&a) returns &a, then all is well. But if some_function(&a) returns &b or even a valid address of some unrelated kernel object, then the code might be entirely valid and correct C, but I don't see how the runtime checks are supposed to tell whether the resulting address is valid or is a bug. This type of code is, I think, quite common in the kernel -- it happens in every data structure where we have unions of pointers and integers or where we steal some known-zero bits of a pointer to store something else.

--Andy

#13 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 34 lines · Andy Lutomirski
Quoted 11 lines · Ingo Molnar

So I'm wondering whether there's a 4th choice as well, which avoids control flow corruption *before* it happens:

- A C language runtime that is a subset of current C syntax and semantics used in the kernel, and which doesn't allow access outside of existing objects and thus creates a strictly enforced separation between memory used for data, and memory used for code and control flow.

- This would involve, at minimum:

Quoted 8 lines

- tracking every type and object and its inherent length and valid access patterns, and never losing track of its type.

- being a lot more organized about initialization, i.e. no uninitialized variables/fields.

- being a lot more strict about type conversions and pointers in general.

You're not the only one to suggest this. There are at least a few things that make this extremely difficult if not impossible. For example, consider this code:

void maybe_buggy(void)
{
int a, b;
int *p = &a;
int *q = (int *)some_function((unsigned long)p); *q = 1;
}

Quoted 8 lines

If some_function(&a) returns &a, then all is well. But if some_function(&a) returns &b or even a valid address of some unrelated kernel object, then the code might be entirely valid and correct C, but I don't see how the runtime checks are supposed to tell whether the resulting address is valid or is a bug. This type of code is, I think, quite common in the kernel -- it happens in every data structure where we have unions of pointers and integers or where we steal some known-zero bits of a pointer to store something else.

So the thing is, for the infinitely large state space of "valid C code" we already disallow an infinitely many versions in the Linux kernel.

We have complicated rules that disallow certain C syntactical and semantical constructs, both on the tooling (build failure/warning) and on the review (style/taste) level.

So the question IMHO isn't whether it's "valid C", because we already have the Linux kernel's own C syntax variant and are enforcing it with varying degrees of success.

The question is whether the example you gave can be written in a strongly typed fashion, whether it makes sense to do so, and what the costs are.

I think it's evident that it can be written with strongly typed constructs, by separating pointers from embedded error codes - with negative side effects to code generation: for example it increases structure sizes and error return paths.

I think there's four main costs of converting such a pattern to strongly typed constructs:

 - memory/cache footprint:  there's a nonzero cost there.
 - performance:             this will hurt too.
 - code readability:        this will probably improve.
 - code robustness:         this will improve too.

So I think the proper question to ask is not whether there's common C syntax within the kernel that would have to be rewritten, but whether the total sum of memory and runtime overhead of strongly typed C programming (if it's possible/desirable) is larger than the total sum of a typical Linux distro enabling the various current and proposed kernel hardening features that have a runtime overhead:

- the SMAP/SMEP overhead of STAC/CLAC for every single user copy

- other usercopy hardening features

- stackprotector

- KASLR

- compiler plugins against information leaks

- proposed KASLR extension to implement module randomization and -PIE overhead

- proposed function call integrity checks

- proposed per system call kernel stack offset randomization

- ( and I'm sure I forgot about a few more, and it's all still only reactive security, not proactive security. )

That's death by a thousand cuts and CR3 switching during system calls is also throwing a hand grenade into the fight ;-)

So if people are also proposing to do CR3 switches in every system call, I'm pretty sure the answer is "yes, even a managed C runtime is probably faster than *THAT* sum of a performanc mess" - at least with the current CR3 switching x86-uarch cost structure...

Thanks,

Ingo

maintainer
#14 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 3 lines · Ingo Molnar

So the question IMHO isn't whether it's "valid C", because we already have the Linux kernel's own C syntax variant and are enforcing it with varying degrees of success.

I'm not getting into the whole 'safe' fight here; but you're under selling things. We don't have a C syntax, we have a full blown C lanugeage variant.

The 'Kernel C' that we write is very much not 'ANSI/ISO C' anymore in a fair number of places. And if I can get my way, we'll only diverge further from the standard.

And this is quite separate from us using every GCC extention under the sun; which of course also doesn't help. It mostly has to do with us treating C as a portable assembler and the C people not wanting to commit to sensible things because they think C is a high-level language.

#15 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

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

So the question IMHO isn't whether it's "valid C", because we already have the Linux kernel's own C syntax variant and are enforcing it with varying degrees of success.

Quoted 7 lines

I'm not getting into the whole 'safe' fight here; but you're under selling things. We don't have a C syntax, we have a full blown C lanugeage variant.

The 'Kernel C' that we write is very much not 'ANSI/ISO C' anymore in a fair number of places. And if I can get my way, we'll only diverge further from the standard.

Yeah, but I think it would be fair to say that random style variations aside, in the kernel we still allow about 95%+ of 'sensible C'.

Quoted 5 lines

And this is quite separate from us using every GCC extention under the sun; which of course also doesn't help. It mostly has to do with us treating C as a portable assembler and the C people not wanting to commit to sensible things because they think C is a high-level language.

Indeed, and also because there's arguably somewhat of a "if the spec allows it then performance first, common-sense semantics second" mindset. Which is an understandable social dynamic, as compiler developers tend to distinguish themselves via the optimizations they've authored.

Anyway, the main point I tried to make is that I think we'd still be able to allow 95%+ of "sensible C" even if executed in a "safe runtime", and we'd still be able to build and run without such strong runtime type enforcement, i.e. get kernel code close to what we have today, minus a handful of optimizations and data structures. (But the performance costs even in that case are nonzero - I'm not sugarcoating it.)

( Plus even that isn't a fully secure solution with deterministic
outcomes, due to parallelism and data races. )

Thanks,

Ingo

#16 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

In reply to Ingo Molnar
Quoted 11 lines · Ingo Molnar

- A C language runtime that is a subset of current C syntax and semantics used in the kernel, and which doesn't allow access outside of existing objects and thus creates a strictly enforced separation between memory used for data, and memory used for code and control flow.

- This would involve, at minimum:

- tracking every type and object and its inherent length and valid access patterns, and never losing track of its type.

Quoted 7 lines

- being a lot more organized about initialization, i.e. no uninitialized variables/fields.

- being a lot more strict about type conversions and pointers in general.

- ... and a metric ton of other details.

Several research groups have tried to do this, and it is very difficult to do. In particular this was almost exactly the goal of C-Cured [1]. Much more recently, there's Microsoft's CheckedC [2] [3], which is less ambitious. Check the references of the latter for lots of relevant work. If anyone really pursues this they should talk directly to researchers who've worked on this, e.g. George Necula; you need to know what *didn't* work well, which is hard to glean from papers. (Academic publishing is broken that way.)

One problem with adopting "safe C" or Rust in the kernel is that most of your security mitigations (e.g. KASLR, CFI, other randomizations) probably need to remain in place as long as there is a significant amount of C in the kernel, which means the benefits from eliminating them will be realized very far in the future, if ever, which makes the whole exercise harder to justify.

Having said that, I think there's a good case to be made for writing kernel code in Rust, e.g. sketchy drivers. The classes of bugs prevented in Rust are significantly broader than your usual safe-C dialect (e.g. data races).

[1] https://web.eecs.umich.edu/~weimerw/p/p477-necula.pdf
[2] https://www.microsoft.com/en-us/research/uploads/prod/2019/05/checkedc-post2019.pdf
[3] https://github.com/Microsoft/checkedc

Rob

Signature · 5 lines
Su ot deraeppa sah dna Rehtaf eht htiw saw hcihw, efil lanrete eht uoy
ot mialcorp ew dna, ti ot yfitset dna ti nees evah ew; deraeppa efil
eht. Efil fo Drow eht gninrecnoc mialcorp ew siht - dehcuot evah sdnah
ruo dna ta dekool evah ew hcihw, seye ruo htiw nees evah ew hcihw,
draeh evah ew hcihw, gninnigeb eht morf saw hcihw taht.
#17 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 36 lines · Robert O'Callahan
Quoted 11 lines · Ingo Molnar

- A C language runtime that is a subset of current C syntax and semantics used in the kernel, and which doesn't allow access outside of existing objects and thus creates a strictly enforced separation between memory used for data, and memory used for code and control flow.

- This would involve, at minimum:

- tracking every type and object and its inherent length and valid access patterns, and never losing track of its type.

Quoted 7 lines

- being a lot more organized about initialization, i.e. no uninitialized variables/fields.

- being a lot more strict about type conversions and pointers in general.

- ... and a metric ton of other details.

Several research groups have tried to do this, and it is very difficult to do. In particular this was almost exactly the goal of C-Cured [1]. Much more recently, there's Microsoft's CheckedC [2] [3], which is less ambitious. Check the references of the latter for lots of relevant work. If anyone really pursues this they should talk directly to researchers who've worked on this, e.g. George Necula; you need to know what *didn't* work well, which is hard to glean from papers. (Academic publishing is broken that way.)

One problem with adopting "safe C" or Rust in the kernel is that most of your security mitigations (e.g. KASLR, CFI, other randomizations) probably need to remain in place as long as there is a significant amount of C in the kernel, which means the benefits from eliminating them will be realized very far in the future, if ever, which makes the whole exercise harder to justify.

Quoted 8 lines

Having said that, I think there's a good case to be made for writing kernel code in Rust, e.g. sketchy drivers. The classes of bugs prevented in Rust are significantly broader than your usual safe-C dialect (e.g. data races).

[1] https://web.eecs.umich.edu/~weimerw/p/p477-necula.pdf
[2] https://www.microsoft.com/en-us/research/uploads/prod/2019/05/checkedc-post2019.pdf
[3] https://github.com/Microsoft/checkedc

So what might work better is if we defined a Rust dialect that used C syntax. I.e. the end result would be something like the 'c2rust' or 'citrus' projects, where code like this would be directly translatable to Rust:

void gz_compress(FILE * in, gzFile out)

{
	char buf[BUFLEN];
	int len;
	int err;

	for (;;) {
		len = fread(buf, 1, sizeof(buf), in);
		if (ferror(in)) {
			perror("fread");
			exit(1);
		}
		if (len == 0)
			break;
		if (gzwrite(out, buf, (unsigned)len) != len)
			error(gzerror(out, &err));
	}
	fclose(in);

	if (gzclose(out) != Z_OK)
		error("failed gzclose");
}

#[no_mangle]
pub unsafe extern "C" fn gz_compress(mut in_: *mut FILE, mut out: gzFile) {

    let mut buf: [i8; 16384];
    let mut len;
    let mut err;
    loop  {
        len = fread(buf, 1, std::mem::size_of_val(&buf), in_);
        if ferror(in_) != 0 { perror("fread"); exit(1); }
        if len == 0 { break ; }
        if gzwrite(out, buf, len as c_uint) != len {
            error(gzerror(out, &mut err));
        };
    }
    fclose(in_);
    if gzclose(out) != Z_OK { error("failed gzclose"); };
}

Example taken from:

https://gitlab.com/citrus-rs/citrus

Does this make sense?

Thanks,

Ingo

#18 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 46 lines · Ingo Molnar

So what might work better is if we defined a Rust dialect that used C syntax. I.e. the end result would be something like the 'c2rust' or 'citrus' projects, where code like this would be directly translatable to Rust:

void gz_compress(FILE * in, gzFile out)

{
        char buf[BUFLEN];
        int len;
        int err;

        for (;;) {
                len = fread(buf, 1, sizeof(buf), in);
                if (ferror(in)) {
                        perror("fread");
                        exit(1);
                }
                if (len == 0)
                        break;
                if (gzwrite(out, buf, (unsigned)len) != len)
                        error(gzerror(out, &err));
        }
        fclose(in);

        if (gzclose(out) != Z_OK)
                error("failed gzclose");
}

#[no_mangle]
pub unsafe extern "C" fn gz_compress(mut in_: *mut FILE, mut out: gzFile) {

    let mut buf: [i8; 16384];
    let mut len;
    let mut err;
    loop  {
        len = fread(buf, 1, std::mem::size_of_val(&buf), in_);
        if ferror(in_) != 0 { perror("fread"); exit(1); }
        if len == 0 { break ; }
        if gzwrite(out, buf, len as c_uint) != len {
            error(gzerror(out, &mut err));
        };
    }
    fclose(in_);
    if gzclose(out) != Z_OK { error("failed gzclose"); };
}
Quoted 5 lines

Example taken from:

https://gitlab.com/citrus-rs/citrus

Does this make sense?

Are you saying you want a tool like c2rust/citrus that translates some new "looks like C, but really Rust" language into actual Rust at build time? I guess that might work, but I suspect your "looks like C" language isn't going to end up being much like C (e.g. it's going to need Rust-style enums-with-fields, Rust polymorphism, Rust traits, and Rust lifetimes), so it may not be beneficial, because you've just created a new language no-one knows, and that has some real downsides.

If you're inspired by the dream of transitioning to safer languages, then I think the first practical step would be to identify some part of the kernel where the payoff of converting code would be highest. This is probably something small, relatively isolated, that's not well tested, generally suspicious, but still in use. Then do an experiment, converting it to Rust (or something else) using off-the-shelf tools and manual labor, and see where the pain points are and what benefits accrue, if any. (Work like https://github.com/tsgates/rust.ko might be a helpful starting point.) Then you'd have some data to start thinking about how to reduce the costs, increase the benefits, and sell it to the kernel community. If you reached out to the Rust community you might find some volunteers to help with this.

Rob

Signature · 5 lines
Su ot deraeppa sah dna Rehtaf eht htiw saw hcihw, efil lanrete eht uoy
ot mialcorp ew dna, ti ot yfitset dna ti nees evah ew; deraeppa efil
eht. Efil fo Drow eht gninrecnoc mialcorp ew siht - dehcuot evah sdnah
ruo dna ta dekool evah ew hcihw, seye ruo htiw nees evah ew hcihw,
draeh evah ew hcihw, gninnigeb eht morf saw hcihw taht.
#19 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

In reply to Ingo Molnar
Quoted 39 lines · Ingo Molnar
Quoted 26 lines · Mike Rapoport

When enabled, the system call isolation (SCI) would allow execution of the system calls with reduced page tables. These page tables are almost identical to the user page tables in PTI. The only addition is the code page containing system call entry function that will continue exectution after the context switch.

Unlike PTI page tables, there is no sharing at higher levels and all the hierarchy for SCI page tables is cloned.

The SCI page tables are created when a system call that requires isolation is executed for the first time.

Whenever a system call should be executed in the isolated environment, the context is switched to the SCI page tables. Any further access to the kernel memory will generate a page fault. The page fault handler can verify that the access is safe and grant it or kill the task otherwise.

The initial SCI implementation allows access to any kernel data, but it limits access to the code in the following way:
* calls and jumps to known code symbols without offset are allowed
* calls and jumps into a known symbol with offset are allowed only if that symbol was already accessed and the offset is in the next page
* all other code access are blocked

Quoted 4 lines

After the isolated system call finishes, the mappings created during its execution are cleared.

The entire SCI page table is lazily freed at task exit() time.

So this basically uses a similar mechanism to the horrendous PTI CR3 switching overhead whenever a syscall seeks "protection", which overhead is only somewhat mitigated by PCID.

This might work on PTI-encumbered CPUs.

Quoted 8 lines

While AMD CPUs don't need PTI, nor do they have PCID.

So this feature is hurting the CPU maker who didn't mess up, and is hurting future CPUs that don't need PTI ..

I really don't like it where this is going. In a couple of years I really want to be able to think of PTI as a bad dream that is mostly over fortunately.

Perhaps ROP gadgets were a bad first example. The research object of the current patch set is really to investigate eliminating sandboxing for containers. As you know, current sandboxes like gVisor and Nabla try to reduce the exposure to horizontal exploits (ability of an untrusted tenant to exploit the shared kernel to attack another tenant) by running significant chunks of kernel emulation code in userspace to reduce exposure of the tenant to code in the shared kernel. The price paid for this is pretty horrendous in performance terms, but the benefit is multi-tenant safety.

The question we were looking into is if we used per-tenant in-kernel address space isolation to improve the security of kernel system calls such that either the exploit becomes detectable or its consequences bounce back only on the tenant trying the exploit, we could eliminate the emulation for that system call and instead pass it through to the kernel, thus thinning out the sandbox layer without losing the security benefits.

We are looking at other aspects as well, like can we simply run chunks of the kernel in the user's address space as the sanbox emulation currently does, or can we hide a tenant's data objects such that they're not easily accessible from an exploited kernel.

James

#20 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

In reply to Mike Rapoport
Quoted 2 lines · Mike Rapoport

After the isolated system call finishes, the mappings created during its execution are cleared.

Yikes. I guess that stops someone from calling write() a bunch of times on every filesystem using every block device driver and all the DM code to get a lot of code/data faulted in. But, it also means not even long-running processes will ever have a chance of behaving anything close to normally.

Is this something you think can be rectified or is there something fundamental that would keep SCI page tables from being cached across different invocations of the same syscall?

#21 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 10 lines · Dave Hansen
Quoted 2 lines · Mike Rapoport

After the isolated system call finishes, the mappings created during its execution are cleared.

Yikes. I guess that stops someone from calling write() a bunch of times on every filesystem using every block device driver and all the DM code to get a lot of code/data faulted in. But, it also means not even long-running processes will ever have a chance of behaving anything close to normally.

Quoted 3 lines

Is this something you think can be rectified or is there something fundamental that would keep SCI page tables from being cached across different invocations of the same syscall?

There is some work being done to look at pre-populating the isolated address space with the expected execution footprint of the system call, yes. It lessens the ROP gadget protection slightly because you might find a gadget in the pre-populated code, but it solves a lot of the overhead problem.

James

#22 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 19 lines · James Bottomley
Quoted 12 lines · Dave Hansen
Quoted 3 lines · Mike Rapoport

After the isolated system call finishes, the mappings created during its execution are cleared.

Yikes. I guess that stops someone from calling write() a bunch of times on every filesystem using every block device driver and all the DM code to get a lot of code/data faulted in. But, it also means not even long-running processes will ever have a chance of behaving anything close to normally.

Quoted 3 lines

Is this something you think can be rectified or is there something fundamental that would keep SCI page tables from being cached across different invocations of the same syscall?

Quoted 6 lines

There is some work being done to look at pre-populating the isolated address space with the expected execution footprint of the system call, yes. It lessens the ROP gadget protection slightly because you might find a gadget in the pre-populated code, but it solves a lot of the overhead problem.

I’m not even remotely a ROP expert, but: what stops a ROP payload from using all the “fault-in” gadgets that exist — any function that can return on an error without doing to much will fault in the whole page containing the function.

To improve this, we would want some thing that would try to check whether the caller is actually supposed to call the callee, which is more or less the hard part of CFI. So can’t we just do CFI and call it a day?

On top of that, a robust, maintainable implementation of this thing seems very complicated — for example, what happens if vfree() gets called?

#23 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 25 lines · Andy Lutomirski
Quoted 18 lines
Quoted 11 lines · James Bottomley
Quoted 3 lines · Dave Hansen

On 4/25/19 2:45 PM, Mike Rapoport wrote:
After the isolated system call finishes, the mappings created during its execution are cleared.

Yikes. I guess that stops someone from calling write() a bunch of times on every filesystem using every block device driver and all the DM code to get a lot of code/data faulted in. But, it also means not even long-running processes will ever have a chance of behaving anything close to normally.

Quoted 3 lines

Is this something you think can be rectified or is there something fundamental that would keep SCI page tables from being cached across different invocations of the same syscall?

Quoted 6 lines

There is some work being done to look at pre-populating the isolated address space with the expected execution footprint of the system call, yes. It lessens the ROP gadget protection slightly because you might find a gadget in the pre-populated code, but it solves a lot of the overhead problem.

Quoted 4 lines

I’m not even remotely a ROP expert, but: what stops a ROP payload from using all the “fault-in” gadgets that exist — any function that can return on an error without doing to much will fault in the whole page containing the function.

The address space pre-population is still per syscall, so you don't get access to the code footprint of a different syscall. So the isolated address space is created anew for every system call, it's just pre- populated with that system call's expected footprint.

Quoted 4 lines

To improve this, we would want some thing that would try to check whether the caller is actually supposed to call the callee, which is more or less the hard part of CFI. So can’t we just do CFI and call it a day?

By CFI you mean control flow integrity? In theory I believe so, yes, but in practice doesn't it require a lot of semantic object information which is easy to get from higher level languages like java but a bit more difficult for plain C.

Quoted 3 lines

On top of that, a robust, maintainable implementation of this thing seems very complicated — for example, what happens if vfree() gets called?

Address space Local vs global object tracking is another thing on our list. What we'd probably do is verify the global object was allowed to be freed and then hand it off safely to the main kernel address space.

James

#24 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 34 lines · James Bottomley
Quoted 24 lines · Andy Lutomirski
Quoted 18 lines
Quoted 11 lines · James Bottomley
Quoted 4 lines · Dave Hansen

On 4/25/19 2:45 PM, Mike Rapoport wrote:
After the isolated system call finishes, the mappings created during its execution are cleared.

Yikes. I guess that stops someone from calling write() a bunch of times on every filesystem using every block device driver and all the DM code to get a lot of code/data faulted in. But, it also means not even long-running processes will ever have a chance of behaving anything close to normally.

Quoted 3 lines

Is this something you think can be rectified or is there something fundamental that would keep SCI page tables from being cached across different invocations of the same syscall?

Quoted 5 lines

There is some work being done to look at pre-populating the isolated address space with the expected execution footprint of the system call, yes. It lessens the ROP gadget protection slightly because you might find a gadget in the pre-populated code, but it solves a lot of the overhead problem.

Quoted 4 lines

I’m not even remotely a ROP expert, but: what stops a ROP payload from using all the “fault-in” gadgets that exist — any function that can return on an error without doing to much will fault in the whole page containing the function.

Quoted 4 lines

The address space pre-population is still per syscall, so you don't get access to the code footprint of a different syscall. So the isolated address space is created anew for every system call, it's just pre- populated with that system call's expected footprint.

That’s not what I mean. Suppose I want to use a ROP gadget in vmalloc(), but vmalloc isn’t in the page tables. Then first push vmalloc itself into the stack. As long as RDI contains a sufficiently ridiculous value, it should just return without doing anything. And it can return right back into the ROP gadget, which is now available.

Quoted 10 lines
Quoted 5 lines

To improve this, we would want some thing that would try to check whether the caller is actually supposed to call the callee, which is more or less the hard part of CFI. So can’t we just do CFI and call it a day?

By CFI you mean control flow integrity? In theory I believe so, yes, but in practice doesn't it require a lot of semantic object information which is easy to get from higher level languages like java but a bit more difficult for plain C.

Yes. As I understand it, grsecurity instruments gcc to create some kind of hash of all function signatures. Then any indirect call can effectively verify that it’s calling a function of the right type. And every return verified a cookie.

On CET CPUs, RET gets checked directly, and I don’t see the benefit of SCI.

Quoted 10 lines
Quoted 4 lines

On top of that, a robust, maintainable implementation of this thing seems very complicated — for example, what happens if vfree() gets called?

Address space Local vs global object tracking is another thing on our list. What we'd probably do is verify the global object was allowed to be freed and then hand it off safely to the main kernel address space.

This seems exceedingly complicated.

#25 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 39 lines · Andy Lutomirski
Quoted 34 lines

On Apr 26, 2019, at 8:19 AM, James Bottomley <James.Bottomley@hanse npartnership.com> wrote:

Quoted 25 lines · Andy Lutomirski
Quoted 19 lines
Quoted 11 lines · James Bottomley
Quoted 4 lines · Dave Hansen

On 4/25/19 2:45 PM, Mike Rapoport wrote:
After the isolated system call finishes, the mappings created during its execution are cleared.

Yikes. I guess that stops someone from calling write() a bunch of times on every filesystem using every block device driver and all the DM code to get a lot of code/data faulted in. But, it also means not even long-running processes will ever have a chance of behaving anything close to normally.

Quoted 4 lines

Is this something you think can be rectified or is there something fundamental that would keep SCI page tables from being cached across different invocations of the same syscall?

Quoted 5 lines

There is some work being done to look at pre-populating the isolated address space with the expected execution footprint of the system call, yes. It lessens the ROP gadget protection slightly because you might find a gadget in the pre-populated code, but it solves a lot of the overhead problem.

Quoted 4 lines

I’m not even remotely a ROP expert, but: what stops a ROP payload from using all the “fault-in” gadgets that exist — any function that can return on an error without doing to much will fault in the whole page containing the function.

Quoted 4 lines

The address space pre-population is still per syscall, so you don't get access to the code footprint of a different syscall. So the isolated address space is created anew for every system call, it's just pre-populated with that system call's expected footprint.

Quoted 5 lines

That’s not what I mean. Suppose I want to use a ROP gadget in vmalloc(), but vmalloc isn’t in the page tables. Then first push vmalloc itself into the stack. As long as RDI contains a sufficiently ridiculous value, it should just return without doing anything. And it can return right back into the ROP gadget, which is now available.

Yes, it's not perfect, but stack space for a smashing attack is at a premium and now you need two stack frames for every gadget you chain instead of one so we've halved your ability to chain gadgets.

Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

To improve this, we would want some thing that would try to check whether the caller is actually supposed to call the callee, which is more or less the hard part of CFI. So can’t we just do CFI and call it a day?

By CFI you mean control flow integrity? In theory I believe so, yes, but in practice doesn't it require a lot of semantic object information which is easy to get from higher level languages like java but a bit more difficult for plain C.

Quoted 7 lines

Yes. As I understand it, grsecurity instruments gcc to create some kind of hash of all function signatures. Then any indirect call can effectively verify that it’s calling a function of the right type. And every return verified a cookie.

On CET CPUs, RET gets checked directly, and I don’t see the benefit of SCI.

Presumably you know something I don't but I thought CET CPUs had been planned for release for ages, but not actually released yet?

Quoted 10 lines
Quoted 8 lines
Quoted 3 lines

On top of that, a robust, maintainable implementation of this thing seems very complicated — for example, what happens if vfree() gets called?

Address space Local vs global object tracking is another thing on our list. What we'd probably do is verify the global object was allowed to be freed and then hand it off safely to the main kernel address space.

This seems exceedingly complicated.

It's a research project: we're exploring what's possible so we can choose the techniques that give the best security improvement for the additional overhead.

James

#26 lore raw

Re: [RFC PATCH 2/7] x86/sci: add core implementation for system call isolation

Quoted 69 lines · James Bottomley
Quoted 39 lines · Andy Lutomirski
Quoted 34 lines

On Apr 26, 2019, at 8:19 AM, James Bottomley <James.Bottomley@hanse npartnership.com> wrote:

Quoted 25 lines · Andy Lutomirski
Quoted 19 lines
Quoted 11 lines · James Bottomley
Quoted 4 lines · Dave Hansen

On 4/25/19 2:45 PM, Mike Rapoport wrote:
After the isolated system call finishes, the mappings created during its execution are cleared.

Yikes. I guess that stops someone from calling write() a bunch of times on every filesystem using every block device driver and all the DM code to get a lot of code/data faulted in. But, it also means not even long-running processes will ever have a chance of behaving anything close to normally.

Quoted 4 lines

Is this something you think can be rectified or is there something fundamental that would keep SCI page tables from being cached across different invocations of the same syscall?

Quoted 5 lines

There is some work being done to look at pre-populating the isolated address space with the expected execution footprint of the system call, yes. It lessens the ROP gadget protection slightly because you might find a gadget in the pre-populated code, but it solves a lot of the overhead problem.

Quoted 4 lines

I’m not even remotely a ROP expert, but: what stops a ROP payload from using all the “fault-in” gadgets that exist — any function that can return on an error without doing to much will fault in the whole page containing the function.

Quoted 4 lines

The address space pre-population is still per syscall, so you don't get access to the code footprint of a different syscall. So the isolated address space is created anew for every system call, it's just pre-populated with that system call's expected footprint.

Quoted 5 lines

That’s not what I mean. Suppose I want to use a ROP gadget in vmalloc(), but vmalloc isn’t in the page tables. Then first push vmalloc itself into the stack. As long as RDI contains a sufficiently ridiculous value, it should just return without doing anything. And it can return right back into the ROP gadget, which is now available.

Yes, it's not perfect, but stack space for a smashing attack is at a premium and now you need two stack frames for every gadget you chain instead of one so we've halved your ability to chain gadgets.

Quoted 15 lines
Quoted 9 lines
Quoted 4 lines

To improve this, we would want some thing that would try to check whether the caller is actually supposed to call the callee, which is more or less the hard part of CFI. So can’t we just do CFI and call it a day?

By CFI you mean control flow integrity? In theory I believe so, yes, but in practice doesn't it require a lot of semantic object information which is easy to get from higher level languages like java but a bit more difficult for plain C.

Yes. As I understand it, grsecurity instruments gcc to create some kind of hash of all function signatures. Then any indirect call can effectively verify that it’s calling a function of the right type. And every return verified a cookie.

Quoted 5 lines
Quoted 2 lines

On CET CPUs, RET gets checked directly, and I don’t see the benefit of SCI.

Presumably you know something I don't but I thought CET CPUs had been planned for release for ages, but not actually released yet?

I don’t know any secrets about this, but I don’t think it’s released. Last I checked, it didn’t even have a final public spec.

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

On top of that, a robust, maintainable implementation of this thing seems very complicated — for example, what happens if vfree() gets called?

Address space Local vs global object tracking is another thing on our list. What we'd probably do is verify the global object was allowed to be freed and then hand it off safely to the main kernel address space.

Quoted 6 lines
Quoted 1 line

This seems exceedingly complicated.

It's a research project: we're exploring what's possible so we can choose the techniques that give the best security improvement for the additional overhead.

:)

#27 lore raw

RFC PATCH 3/7 x86/entry/64: add infrastructure for switching to isolated syscall context

In reply to Mike Rapoport

The isolated system calls will use a separate page table that does not map the entire kernel. Exception and interrupts entries should switch the context to the full kernel page tables and then restore it back to continue the execution of the isolated system call.

---
 arch/x86/entry/calling.h               | 65 ++++++++++++++++++++++++++++++++++
 arch/x86/entry/entry_64.S              | 13 +++++--
 arch/x86/include/asm/processor-flags.h |  8 +++++
 arch/x86/include/asm/tlbflush.h        |  8 ++++-
 arch/x86/kernel/asm-offsets.c          |  7 ++++
 5 files changed, 98 insertions(+), 3 deletions(-)
arch/x86/entry/calling.h +65 -0
index efb0d1b..766e74e 100644
@@ -187,6 +187,56 @@ For 32-bit we have the following conventions - kernel is built with
 #endif
 .endm
 
+#ifdef CONFIG_SYSCALL_ISOLATION
+
+#define SCI_PCID_BIT		X86_CR3_SCI_PCID_BIT
+
+#define THIS_CPU_sci_syscall   \
+	PER_CPU_VAR(cpu_sci) + SCI_SYSCALL
+
+#define THIS_CPU_sci_cr3_offset   \
+	PER_CPU_VAR(cpu_sci) + SCI_CR3_OFFSET
+
+.macro SAVE_AND_SWITCH_SCI_TO_KERNEL_CR3 scratch_reg:req save_reg:req
+	ALTERNATIVE "jmp .Ldone_\@", "", X86_FEATURE_SCI
+	movq	THIS_CPU_sci_syscall, \scratch_reg
+	cmpq	$0, \scratch_reg
+	je	.Ldone_\@
+	movq	%cr3, \scratch_reg
+	bt	$SCI_PCID_BIT, \scratch_reg
+	jc	.Lsci_context_\@
+	xorq	\save_reg, \save_reg
+	jmp	.Ldone_\@
+.Lsci_context_\@:
+	movq	\scratch_reg, \save_reg
+	addq	THIS_CPU_sci_cr3_offset, \scratch_reg
+	movq	\scratch_reg, %cr3
+.Ldone_\@:
+.endm
+
+.macro RESTORE_SCI_CR3 scratch_reg:req save_reg:req
+	ALTERNATIVE "jmp .Ldone_\@", "", X86_FEATURE_SCI
+	movq	THIS_CPU_sci_syscall, \scratch_reg
+	cmpq	$0, \scratch_reg
+	je	.Ldone_\@
+	movq	\save_reg, \scratch_reg
+	cmpq	$0, \scratch_reg
+	je	.Ldone_\@
+	xorq	\save_reg, \save_reg
+	movq	\scratch_reg, %cr3
+.Ldone_\@:
+.endm
+
+#else /* CONFIG_SYSCALL_ISOLATION */
+
+.macro SAVE_AND_SWITCH_SCI_TO_KERNEL_CR3 scratch_reg:req save_reg:req
+.endm
+
+.macro RESTORE_SCI_CR3 scratch_reg:req save_reg:req
+.endm
+
+#endif /* CONFIG_SYSCALL_ISOLATION */
+
 #ifdef CONFIG_PAGE_TABLE_ISOLATION
 
 /*
@@ -264,6 +314,21 @@ For 32-bit we have the following conventions - kernel is built with
 	ALTERNATIVE "jmp .Ldone_\@", "", X86_FEATURE_PTI
 	movq	%cr3, \scratch_reg
 	movq	\scratch_reg, \save_reg
+
+#ifdef CONFIG_SYSCALL_ISOLATION
+	/*
+	 * Test the SCI PCID bit. If set, then the SCI page tables are
+	 * active. If clear CR3 has either the kernel or user page
+	 * table active.
+	 */
+	ALTERNATIVE "jmp .Lcheck_user_pt_\@", "", X86_FEATURE_SCI
+	bt	$SCI_PCID_BIT, \scratch_reg
+	jnc	.Lcheck_user_pt_\@
+	addq	THIS_CPU_sci_cr3_offset, \scratch_reg
+	movq	\scratch_reg, %cr3
+	jmp	.Ldone_\@
+.Lcheck_user_pt_\@:
+#endif
 	/*
 	 * Test the user pagetable bit. If set, then the user page tables
 	 * are active. If clear CR3 already has the kernel page table
arch/x86/entry/entry_64.S +11 -2
index 1f0efdb..3cef67b 100644
@@ -543,7 +543,7 @@ ENTRY(interrupt_entry)
 	ENCODE_FRAME_POINTER 8
 
 	testb	$3, CS+8(%rsp)
-	jz	1f
+	jz	.Linterrupt_entry_kernel
 
 	/*
 	 * IRQ from user mode.
@@ -559,12 +559,17 @@ ENTRY(interrupt_entry)
 
 	CALL_enter_from_user_mode
 
-1:
+.Linterrupt_entry_done:
 	ENTER_IRQ_STACK old_rsp=%rdi save_ret=1
 	/* We entered an interrupt context - irqs are off: */
 	TRACE_IRQS_OFF
 
 	ret
+
+.Linterrupt_entry_kernel:
+	SAVE_AND_SWITCH_SCI_TO_KERNEL_CR3 scratch_reg=%rax save_reg=%r14
+	jmp	.Linterrupt_entry_done
+
 END(interrupt_entry)
 _ASM_NOKPROBE(interrupt_entry)
 
@@ -656,6 +661,8 @@ retint_kernel:
 	 */
 	TRACE_IRQS_IRETQ
 
+	RESTORE_SCI_CR3 scratch_reg=%rax save_reg=%r14
+
 GLOBAL(restore_regs_and_return_to_kernel)
 #ifdef CONFIG_DEBUG_ENTRY
 	/* Assert that pt_regs indicates kernel mode. */
@@ -1263,6 +1270,8 @@ ENTRY(error_entry)
 	 * for these here too.
 	 */
 .Lerror_kernelspace:
+	SAVE_AND_SWITCH_SCI_TO_KERNEL_CR3 scratch_reg=%rax save_reg=%r14
+
 	leaq	native_irq_return_iret(%rip), %rcx
 	cmpq	%rcx, RIP+8(%rsp)
 	je	.Lerror_bad_iret
arch/x86/include/asm/processor-flags.h +8 -0
index 02c2cbd..eca9e17 100644
@@ -53,4 +53,12 @@
 # define X86_CR3_PTI_PCID_USER_BIT	11
 #endif
 
+#ifdef CONFIG_SYSCALL_ISOLATION
+# if defined(X86_CR3_PTI_PCID_USER_BIT)
+#  define X86_CR3_SCI_PCID_BIT		(X86_CR3_PTI_PCID_USER_BIT - 1)
+# else
+#  define X86_CR3_SCI_PCID_BIT		11
+# endif
+#endif
+
 #endif /* _ASM_X86_PROCESSOR_FLAGS_H */
arch/x86/include/asm/tlbflush.h +7 -1
index f4204bf..dc69cc4 100644
@@ -54,7 +54,13 @@
 # define PTI_CONSUMED_PCID_BITS	0
 #endif
 
-#define CR3_AVAIL_PCID_BITS (X86_CR3_PCID_BITS - PTI_CONSUMED_PCID_BITS)
+#ifdef CONFIG_SYSCALL_ISOLATION
+# define SCI_CONSUMED_PCID_BITS	1
+#else
+# define SCI_CONSUMED_PCID_BITS	0
+#endif
+
+#define CR3_AVAIL_PCID_BITS (X86_CR3_PCID_BITS - PTI_CONSUMED_PCID_BITS - SCI_CONSUMED_PCID_BITS)
 
 /*
  * ASIDs are zero-based: 0->MAX_AVAIL_ASID are valid.  -1 below to account
arch/x86/kernel/asm-offsets.c +7 -0
index 168543d..f2c9cd3f 100644
@@ -18,6 +18,7 @@
 #include <asm/bootparam.h>
 #include <asm/suspend.h>
 #include <asm/tlbflush.h>
+#include <asm/sci.h>
 
 #ifdef CONFIG_XEN
 #include <xen/interface/xen.h>
@@ -105,4 +106,10 @@ static void __used common(void)
 	OFFSET(TSS_sp0, tss_struct, x86_tss.sp0);
 	OFFSET(TSS_sp1, tss_struct, x86_tss.sp1);
 	OFFSET(TSS_sp2, tss_struct, x86_tss.sp2);
+
+#ifdef CONFIG_SYSCALL_ISOLATION
+	/* system calls isolation */
+	OFFSET(SCI_SYSCALL, sci_percpu_data, sci_syscall);
+	OFFSET(SCI_CR3_OFFSET, sci_percpu_data, sci_cr3_offset);
+#endif
 }
Signature · 1 line
2.7.4
#28 lore raw

RFC PATCH 4/7 x86/sci: hook up isolated system call entry and exit

In reply to Mike Rapoport

When a system call is required to run in an isolated context, the CR3 will be switched to the SCI page table a per-cpu variable will contain and offset from the original CR3. This offset is used to switch back to the full kernel context when a trap occurs during isolated system call.

---
 arch/x86/entry/common.c      | 61 ++++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kernel/process_64.c |  5 ++++
 kernel/exit.c                |  3 +++
 3 files changed, 69 insertions(+)
arch/x86/entry/common.c +61 -0
index 7bc105f..8f2a6fd 100644
@@ -25,12 +25,14 @@
 #include <linux/uprobes.h>
 #include <linux/livepatch.h>
 #include <linux/syscalls.h>
+#include <linux/sci.h>
 
 #include <asm/desc.h>
 #include <asm/traps.h>
 #include <asm/vdso.h>
 #include <linux/uaccess.h>
 #include <asm/cpufeature.h>
+#include <asm/tlbflush.h>
 
 #define CREATE_TRACE_POINTS
 #include <trace/events/syscalls.h>
@@ -269,6 +271,50 @@ __visible inline void syscall_return_slowpath(struct pt_regs *regs)
 }
 
 #ifdef CONFIG_X86_64
+
+#ifdef CONFIG_SYSCALL_ISOLATION
+static inline bool sci_required(unsigned long nr)
+{
+	return false;
+}
+
+static inline unsigned long sci_syscall_enter(unsigned long nr)
+{
+	unsigned long sci_cr3, kernel_cr3;
+	unsigned long asid;
+
+	kernel_cr3 = __read_cr3();
+	asid = kernel_cr3 & ~PAGE_MASK;
+
+	sci_cr3 = build_cr3(current->sci->pgd, 0) & PAGE_MASK;
+	sci_cr3 |= (asid | (1 << X86_CR3_SCI_PCID_BIT));
+
+	current->in_isolated_syscall = 1;
+	current->sci->cr3_offset = kernel_cr3 - sci_cr3;
+
+	this_cpu_write(cpu_sci.sci_syscall, 1);
+	this_cpu_write(cpu_sci.sci_cr3_offset, current->sci->cr3_offset);
+
+	write_cr3(sci_cr3);
+
+	return kernel_cr3;
+}
+
+static inline void sci_syscall_exit(unsigned long cr3)
+{
+	if (cr3) {
+		write_cr3(cr3);
+		current->in_isolated_syscall = 0;
+		this_cpu_write(cpu_sci.sci_syscall, 0);
+		sci_clear_data();
+	}
+}
+#else
+static inline bool sci_required(unsigned long nr) { return false; }
+static inline unsigned long sci_syscall_enter(unsigned long nr) { return 0; }
+static inline void sci_syscall_exit(unsigned long cr3) {}
+#endif
+
 __visible void do_syscall_64(unsigned long nr, struct pt_regs *regs)
 {
 	struct thread_info *ti;
@@ -286,10 +332,25 @@ __visible void do_syscall_64(unsigned long nr, struct pt_regs *regs)
 	 */
 	nr &= __SYSCALL_MASK;
 	if (likely(nr < NR_syscalls)) {
+		unsigned long sci_cr3 = 0;
+
 		nr = array_index_nospec(nr, NR_syscalls);
+
+		if (sci_required(nr)) {
+			int err = sci_init(current);
+
+			if (err) {
+				regs->ax = err;
+				goto err_return_from_syscall;
+			}
+			sci_cr3 = sci_syscall_enter(nr);
+		}
+
 		regs->ax = sys_call_table[nr](regs);
+		sci_syscall_exit(sci_cr3);
 	}
 
+err_return_from_syscall:
 	syscall_return_slowpath(regs);
 }
 #endif
arch/x86/kernel/process_64.c +5 -0
index 6a62f4a..b8aa624 100644
@@ -55,6 +55,8 @@
 #include <asm/resctrl_sched.h>
 #include <asm/unistd.h>
 #include <asm/fsgsbase.h>
+#include <asm/sci.h>
+
 #ifdef CONFIG_IA32_EMULATION
 /* Not included via unistd.h */
 #include <asm/unistd_32_ia32.h>
@@ -581,6 +583,9 @@ __switch_to(struct task_struct *prev_p, struct task_struct *next_p)
 
 	switch_to_extra(prev_p, next_p);
 
+	/* update syscall isolation per-cpu data */
+	sci_switch_to(next_p);
+
 #ifdef CONFIG_XEN_PV
 	/*
 	 * On Xen PV, IOPL bits in pt_regs->flags have no effect, and
kernel/exit.c +3 -0
index 2639a30..8e81353 100644
@@ -62,6 +62,7 @@
 #include <linux/random.h>
 #include <linux/rcuwait.h>
 #include <linux/compat.h>
+#include <linux/sci.h>
 
 #include <linux/uaccess.h>
 #include <asm/unistd.h>
@@ -859,6 +860,8 @@ void __noreturn do_exit(long code)
 	tsk->exit_code = code;
 	taskstats_exit(tsk, group_dead);
 
+	sci_exit(tsk);
+
 	exit_mm();
 
 	if (group_dead)
Signature · 1 line
2.7.4
#29 lore raw

RFC PATCH 5/7 x86/mm/fault: hook up SCI verification

In reply to Mike Rapoport

If a system call runs in isolated context, it's accesses to kernel code and data will be verified by SCI susbsytem.

---
 arch/x86/mm/fault.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
arch/x86/mm/fault.c +28 -0
index 9d5c75f..baa2a2f 100644
@@ -18,6 +18,7 @@
 #include <linux/uaccess.h>		/* faulthandler_disabled()	*/
 #include <linux/efi.h>			/* efi_recover_from_page_fault()*/
 #include <linux/mm_types.h>
+#include <linux/sci.h>			/* sci_verify_and_map()		*/
 
 #include <asm/cpufeature.h>		/* boot_cpu_has, ...		*/
 #include <asm/traps.h>			/* dotraplinkage, ...		*/
@@ -1254,6 +1255,30 @@ static int fault_in_kernel_space(unsigned long address)
 	return address >= TASK_SIZE_MAX;
 }
 
+#ifdef CONFIG_SYSCALL_ISOLATION
+static int sci_fault(struct pt_regs *regs, unsigned long hw_error_code,
+		     unsigned long address)
+{
+	struct task_struct *tsk = current;
+
+	if (!tsk->in_isolated_syscall)
+		return 0;
+
+	if (!sci_verify_and_map(regs, address, hw_error_code)) {
+		this_cpu_write(cpu_sci.sci_syscall, 0);
+		no_context(regs, hw_error_code, address, SIGKILL, 0);
+	}
+
+	return 1;
+}
+#else
+static inline int sci_fault(struct pt_regs *regs, unsigned long hw_error_code,
+			    unsigned long address)
+{
+	return 0;
+}
+#endif
+
 /*
  * Called for all faults where 'address' is part of the kernel address
  * space.  Might get called for faults that originate from *code* that
@@ -1301,6 +1326,9 @@ do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code,
 	if (kprobes_fault(regs))
 		return;
 
+	if (sci_fault(regs, hw_error_code, address))
+		return;
+
 	/*
 	 * Note, despite being a "bad area", there are quite a few
 	 * acceptable reasons to get here, such as erratum fixups
Signature · 1 line
2.7.4
maintainer
#30 lore raw

Re: [RFC PATCH 5/7] x86/mm/fault: hook up SCI verification

Quoted 7 lines · Mike Rapoport

If a system call runs in isolated context, it's accesses to kernel code and data will be verified by SCI susbsytem.

---
 arch/x86/mm/fault.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

There's a distinct lack of touching do_double_fault(). It appears to me that you'll instantly trigger #DF when you #PF, because the #PF handler itself will not be able to run.

And then obviously you have to be very careful to make sure #DF can, _at_all_times_ run, otherwise you'll tripple-fault and we all know what that does.

#31 lore raw

Re: [RFC PATCH 5/7] x86/mm/fault: hook up SCI verification

Quoted 4 lines · Peter Zijlstra
Quoted 3 lines · Mike Rapoport

If a system call runs in isolated context, it's accesses to kernel code and data will be verified by SCI susbsytem.

Quoted 8 lines
Quoted 4 lines
---
 arch/x86/mm/fault.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

There's a distinct lack of touching do_double_fault(). It appears to me that you'll instantly trigger #DF when you #PF, because the #PF handler itself will not be able to run.

The #PF handler is able to run. On interrupt/error entry the cr3 is switched to the full kernel page tables, pretty much like PTI does for user <-> kernel transitions. It's in the patch 3.

Quoted 4 lines

And then obviously you have to be very careful to make sure #DF can, _at_all_times_ run, otherwise you'll tripple-fault and we all know what that does.

Signature · 2 lines
Sincerely yours,
Mike.
maintainer
#32 lore raw

Re: [RFC PATCH 5/7] x86/mm/fault: hook up SCI verification

Quoted 11 lines · Mike Rapoport
Quoted 9 lines · Peter Zijlstra
Quoted 7 lines · Mike Rapoport

If a system call runs in isolated context, it's accesses to kernel code and data will be verified by SCI susbsytem.

---
 arch/x86/mm/fault.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
Quoted 9 lines
Quoted 3 lines

There's a distinct lack of touching do_double_fault(). It appears to me that you'll instantly trigger #DF when you #PF, because the #PF handler itself will not be able to run.

The #PF handler is able to run. On interrupt/error entry the cr3 is switched to the full kernel page tables, pretty much like PTI does for user <-> kernel transitions. It's in the patch 3.

PeterZ meant page_fault, not do_page_fault. In your patch, page_fault and some of error_entry run before that magic switchover happens. If they're not in the page tables, you double-fault.

And don't even try to do SCI magic in the double-fault handler. As I understand it, the SDM and APM aren't kidding when they say that #DF is an abort, not a fault. There is a single case in the kernel where we recover from #DF, and it was vetted by microcode people.

#33 lore raw

Re: [RFC PATCH 5/7] x86/mm/fault: hook up SCI verification

Quoted 22 lines · Andy Lutomirski
Quoted 11 lines · Mike Rapoport
Quoted 9 lines · Peter Zijlstra
Quoted 7 lines · Mike Rapoport

If a system call runs in isolated context, it's accesses to kernel code and data will be verified by SCI susbsytem.

---
 arch/x86/mm/fault.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
Quoted 9 lines
Quoted 3 lines

There's a distinct lack of touching do_double_fault(). It appears to me that you'll instantly trigger #DF when you #PF, because the #PF handler itself will not be able to run.

The #PF handler is able to run. On interrupt/error entry the cr3 is switched to the full kernel page tables, pretty much like PTI does for user <-> kernel transitions. It's in the patch 3.

Quoted 3 lines

PeterZ meant page_fault, not do_page_fault. In your patch, page_fault and some of error_entry run before that magic switchover happens. If they're not in the page tables, you double-fault.

The entry code is in sci page tables, just like in user-space page tables with PTI.

Quoted 5 lines

And don't even try to do SCI magic in the double-fault handler. As I understand it, the SDM and APM aren't kidding when they say that #DF is an abort, not a fault. There is a single case in the kernel where we recover from #DF, and it was vetted by microcode people.

Signature · 2 lines
Sincerely yours,
Mike.
#34 lore raw

RFC PATCH 6/7 security: enable system call isolation in kernel config

In reply to Mike Rapoport

Add SYSCALL_ISOLATION Kconfig option to enable build of SCI infrastructure.

---
 security/Kconfig | 10 ++++++++++
 1 file changed, 10 insertions(+)
security/Kconfig +10 -0
index e4fe2f3..0c6929a 100644
@@ -65,6 +65,16 @@ config PAGE_TABLE_ISOLATION
 
 	  See Documentation/x86/pti.txt for more details.
 
+config SYSCALL_ISOLATION
+	bool "System call isolation"
+	default n
+	depends on PAGE_TABLE_ISOLATION && !X86_PAE
+	help
+	  This is an experimental feature to allow executing system
+	  calls in an isolated address space.
+
+	  If you are unsure how to answer this question, answer N.
+
 config SECURITY_INFINIBAND
 	bool "Infiniband Security Hooks"
 	depends on SECURITY && INFINIBAND
Signature · 1 line
2.7.4
#35 lore raw

RFC PATCH 7/7 sci: add example system calls to exercse SCI

In reply to Mike Rapoport
---
 arch/x86/entry/common.c                |  6 +++-
 arch/x86/entry/syscalls/syscall_64.tbl |  3 ++
 kernel/Makefile                        |  2 +-
 kernel/sci-examples.c                  | 52 ++++++++++++++++++++++++++++++++++
 4 files changed, 61 insertions(+), 2 deletions(-)
 create mode 100644 kernel/sci-examples.c
arch/x86/entry/common.c +5 -1
index 8f2a6fd..be0e1a7 100644
@@ -275,7 +275,11 @@ __visible inline void syscall_return_slowpath(struct pt_regs *regs)
 #ifdef CONFIG_SYSCALL_ISOLATION
 static inline bool sci_required(unsigned long nr)
 {
-	return false;
+	if (!static_cpu_has(X86_FEATURE_SCI))
+		return false;
+	if (nr < __NR_get_answer)
+		return false;
+	return true;
 }
 
 static inline unsigned long sci_syscall_enter(unsigned long nr)
arch/x86/entry/syscalls/syscall_64.tbl +3 -0
index f0b1709..a25e838 100644
@@ -343,6 +343,9 @@
 332	common	statx			__x64_sys_statx
 333	common	io_pgetevents		__x64_sys_io_pgetevents
 334	common	rseq			__x64_sys_rseq
+335	64	get_answer		__x64_sys_get_answer
+336	64	sci_write_dmesg		__x64_sys_sci_write_dmesg
+337	64	sci_write_dmesg_bad	__x64_sys_sci_write_dmesg_bad
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
kernel/Makefile +1 -1
index 6aa7543..d6441d0 100644
@@ -10,7 +10,7 @@ obj-y     = fork.o exec_domain.o panic.o \
 	    extable.o params.o \
 	    kthread.o sys_ni.o nsproxy.o \
 	    notifier.o ksysfs.o cred.o reboot.o \
-	    async.o range.o smpboot.o ucount.o
+	    async.o range.o smpboot.o ucount.o sci-examples.o
 
 obj-$(CONFIG_MODULES) += kmod.o
 obj-$(CONFIG_MULTIUSER) += groups.o
kernel/sci-examples.c new file +52 -0

52 lines not on this page · raw message

Signature · 1 line
2.7.4
maintainer
#36 lore raw
In reply to Mike Rapoport
Quoted 27 lines · Mike Rapoport

Hi,

Address space isolation has been used to protect the kernel from the userspace and userspace programs from each other since the invention of the virtual memory.

Assuming that kernel bugs and therefore vulnerabilities are inevitable it might be worth isolating parts of the kernel to minimize damage that these vulnerabilities can cause.

The idea here is to allow an untrusted user access to a potentially vulnerable kernel in such a way that any kernel vulnerability they find to exploit is either prevented or the consequences confined to their isolated address space such that the compromise attempt has minimal impact on other tenants or the protected structures of the monolithic kernel. Although we hope to prevent many classes of attack, the first target we're looking at is ROP gadget protection.

These patches implement a "system call isolation (SCI)" mechanism that allows running system calls in an isolated address space with reduced page tables to prevent ROP attacks.

ROP attacks involve corrupting the stack return address to repoint it to a segment of code you know exists in the kernel that can be used to perform the action you need to exploit the system.

Quoted 5 lines

The idea behind the prevention is that if we fault in pages in the execution path, we can compare target address against the kernel symbol table. So if we're in a function, we allow local jumps (and simply falling of the end of a page) but if we're jumping to a new function it must be to an external label in the symbol table.

That's quite an assumption. The entry code at least uses .L labels. Do you get that right?

As far as I can see, most of what's going on here has very little to do with jumps and calls. The benefit seems to come from making sure that the RET instruction actually goes somewhere that's already been faulted in. Am I understanding right?

--Andy

#37 lore raw
Quoted 2 lines · Andy Lutomirski

The benefit seems to come from making sure that the RET instruction actually goes somewhere that's already been faulted in.

Which doesn't seem to be really compatible with things like retpolines or anyone using FTRACE_WITH_REGS to modify stored instruction pointer.

Signature · 2 lines
Jiri Kosina
SUSE Labs
#38 lore raw
In reply to Andy Lutomirski
Quoted 34 lines · Andy Lutomirski
Quoted 27 lines · Mike Rapoport

Hi,

Address space isolation has been used to protect the kernel from the userspace and userspace programs from each other since the invention of the virtual memory.

Assuming that kernel bugs and therefore vulnerabilities are inevitable it might be worth isolating parts of the kernel to minimize damage that these vulnerabilities can cause.

The idea here is to allow an untrusted user access to a potentially vulnerable kernel in such a way that any kernel vulnerability they find to exploit is either prevented or the consequences confined to their isolated address space such that the compromise attempt has minimal impact on other tenants or the protected structures of the monolithic kernel. Although we hope to prevent many classes of attack, the first target we're looking at is ROP gadget protection.

These patches implement a "system call isolation (SCI)" mechanism that allows running system calls in an isolated address space with reduced page tables to prevent ROP attacks.

ROP attacks involve corrupting the stack return address to repoint it to a segment of code you know exists in the kernel that can be used to perform the action you need to exploit the system.

Quoted 5 lines

The idea behind the prevention is that if we fault in pages in the execution path, we can compare target address against the kernel symbol table. So if we're in a function, we allow local jumps (and simply falling of the end of a page) but if we're jumping to a new function it must be to an external label in the symbol table.

Quoted 7 lines

That's quite an assumption. The entry code at least uses .L labels. Do you get that right?

As far as I can see, most of what's going on here has very little to do with jumps and calls. The benefit seems to come from making sure that the RET instruction actually goes somewhere that's already been faulted in. Am I understanding right?

Well, RET indeed will go somewhere that's already been faulted in. But before that, the first CALL to not-yet-mapped code will fault and bring in the page containing the CALL target.

If the CALL is made into a middle of a function, SCI will refuse to continue the syscall execution.

As for the local jumps, as long as they are inside a page that was already mapped or the next page, they are allowed.

This does not take care (yet) of larger functions where local jumps are further then PAGE_SIZE.

Here's an example trace of #PF's produced by a dummy get_answer system call from patch 7:

[   12.012906] #PF: DATA: do_syscall_64+0x26b/0x4c0 fault at 0xffffffff82000bb8
[   12.012918] #PF: INSN: __x86_indirect_thunk_rax+0x0/0x20 fault at __x86_indirect_thunk_rax+0x0/0x20
[   12.012929] #PF: INSN: __x64_sys_get_answer+0x0/0x10 fault at __x64_sys_get_answer+0x0/0x10
Quoted 2 lines

--Andy

Signature · 2 lines
Sincerely yours,
Mike.
#39 lore raw
In reply to Mike Rapoport
Quoted 8 lines · Mike Rapoport

The idea behind the prevention is that if we fault in pages in the execution path, we can compare target address against the kernel symbol table. So if we're in a function, we allow local jumps (and simply falling of the end of a page) but if we're jumping to a new function it must be to an external label in the symbol table. Since ROP attacks are all about jumping to gadget code which is effectively in the middle of real functions, the jumps they induce are to code that doesn't have an external symbol, so it should mostly detect when they happen.

This turns the problem from: "attackers can leverage any data/code that the kernel has mapped (anything)" to "attackers can leverage any code/data that the current syscall has faulted in".

That seems like a pretty restrictive change.

Quoted 5 lines

At this time we are not suggesting any API that will enable the system calls isolation. Because of the overhead required for this, it should only be activated for processes or containers we know should be untrusted. We still have no actual numbers, but surely forcing page faults during system call execution will not come for free.

What's the minimum number of faults that have to occur to handle the simplest dummy fault?

#40 lore raw
Quoted 16 lines · Dave Hansen
Quoted 8 lines · Mike Rapoport

The idea behind the prevention is that if we fault in pages in the execution path, we can compare target address against the kernel symbol table. So if we're in a function, we allow local jumps (and simply falling of the end of a page) but if we're jumping to a new function it must be to an external label in the symbol table. Since ROP attacks are all about jumping to gadget code which is effectively in the middle of real functions, the jumps they induce are to code that doesn't have an external symbol, so it should mostly detect when they happen.

This turns the problem from: "attackers can leverage any data/code that the kernel has mapped (anything)" to "attackers can leverage any code/data that the current syscall has faulted in".

That seems like a pretty restrictive change.

Quoted 8 lines
Quoted 5 lines

At this time we are not suggesting any API that will enable the system calls isolation. Because of the overhead required for this, it should only be activated for processes or containers we know should be untrusted. We still have no actual numbers, but surely forcing page faults during system call execution will not come for free.

What's the minimum number of faults that have to occur to handle the simplest dummy fault?

For the current implementation it's 3.

Here is the example trace of #PF's produced by a dummy get_answer system call from patch 7:

[   12.012906] #PF: DATA: do_syscall_64+0x26b/0x4c0 fault at 0xffffffff82000bb8
[   12.012918] #PF: INSN: __x86_indirect_thunk_rax+0x0/0x20 fault at __x86_indirect_thunk_rax+0x0/0x20
[   12.012929] #PF: INSN: __x64_sys_get_answer+0x0/0x10 fault at__x64_sys_get_answer+0x0/0x10

For the sci_write_dmesg syscall that does copy_from_user() and printk() its between 35 and 60 depending on console and /proc/sys/kernel/printk values.

This includes both code and data accesses. The data page faults can be avoided if we pre-populate SCI page tables with data.

Signature · 2 lines
Sincerely yours,
Mike.