linux-mm.kvack.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v38 10/24] mm: Add vm_ops->mprotect()
       [not found] <20200915112842.897265-1-jarkko.sakkinen@linux.intel.com>
@ 2020-09-15 11:28 ` Jarkko Sakkinen
  2020-09-18 12:44   ` Borislav Petkov
  2020-09-18 15:09   ` Andy Lutomirski
  2020-09-15 11:28 ` [PATCH v38 11/24] x86/sgx: Add SGX enclave driver Jarkko Sakkinen
  2020-09-15 11:28 ` [PATCH v38 16/24] x86/sgx: Add a page reclaimer Jarkko Sakkinen
  2 siblings, 2 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-15 11:28 UTC (permalink / raw)
  To: x86, linux-sgx
  Cc: linux-kernel, Sean Christopherson, linux-mm, Andrew Morton,
	Matthew Wilcox, Jethro Beekman, Darren Kenny, Jarkko Sakkinen,
	andriy.shevchenko, asapek, bp, cedric.xing, chenalexchen,
	conradparker, cyhanish, dave.hansen, haitao.huang, josh,
	kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman, npmccallum,
	puiterwijk, rientjes, tglx, yaozhangx

From: Sean Christopherson <sean.j.christopherson@intel.com>

Add vm_ops()->mprotect() for additional constraints for a VMA.

Intel Software Guard eXtensions (SGX) will use this callback to add two
constraints:

1. Verify that the address range does not have holes: each page address
   must be filled with an enclave page.
2. Verify that VMA permissions won't surpass the permissions of any enclave
   page within the address range. Enclave cryptographically sealed
   permissions for each page address that set the upper limit for possible
   VMA permissions. Not respecting this can cause #GP's to be emitted.

Cc: linux-mm@kvack.org
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Matthew Wilcox <willy@infradead.org>
Acked-by: Jethro Beekman <jethro@fortanix.com>
Reviewed-by: Darren Kenny <darren.kenny@oracle.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 include/linux/mm.h | 3 +++
 mm/mprotect.c      | 5 ++++-
 2 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/include/linux/mm.h b/include/linux/mm.h
index 97c83773b6f0..717726fcace6 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -547,6 +547,9 @@ struct vm_operations_struct {
 	void (*close)(struct vm_area_struct * area);
 	int (*split)(struct vm_area_struct * area, unsigned long addr);
 	int (*mremap)(struct vm_area_struct * area);
+	int (*mprotect)(struct vm_area_struct *vma,
+			struct vm_area_struct **pprev, unsigned long start,
+			unsigned long end, unsigned long newflags);
 	vm_fault_t (*fault)(struct vm_fault *vmf);
 	vm_fault_t (*huge_fault)(struct vm_fault *vmf,
 			enum page_entry_size pe_size);
diff --git a/mm/mprotect.c b/mm/mprotect.c
index ce8b8a5eacbb..f170f3da8a4f 100644
--- a/mm/mprotect.c
+++ b/mm/mprotect.c
@@ -610,7 +610,10 @@ static int do_mprotect_pkey(unsigned long start, size_t len,
 		tmp = vma->vm_end;
 		if (tmp > end)
 			tmp = end;
-		error = mprotect_fixup(vma, &prev, nstart, tmp, newflags);
+		if (vma->vm_ops && vma->vm_ops->mprotect)
+			error = vma->vm_ops->mprotect(vma, &prev, nstart, tmp, newflags);
+		else
+			error = mprotect_fixup(vma, &prev, nstart, tmp, newflags);
 		if (error)
 			goto out;
 		nstart = tmp;
-- 
2.25.1



^ permalink raw reply related	[flat|nested] 81+ messages in thread

* [PATCH v38 11/24] x86/sgx: Add SGX enclave driver
       [not found] <20200915112842.897265-1-jarkko.sakkinen@linux.intel.com>
  2020-09-15 11:28 ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Jarkko Sakkinen
@ 2020-09-15 11:28 ` Jarkko Sakkinen
  2020-09-21  9:30   ` Borislav Petkov
  2020-10-01 17:36   ` Sean Christopherson
  2020-09-15 11:28 ` [PATCH v38 16/24] x86/sgx: Add a page reclaimer Jarkko Sakkinen
  2 siblings, 2 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-15 11:28 UTC (permalink / raw)
  To: x86, linux-sgx
  Cc: linux-kernel, Jarkko Sakkinen, linux-security-module, linux-mm,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Haitao Huang,
	Chunyang Hui, Jordan Hand, Nathaniel McCallum, Seth Moore,
	Darren Kenny, Sean Christopherson, Suresh Siddha,
	andriy.shevchenko, asapek, bp, cedric.xing, chenalexchen,
	conradparker, cyhanish, dave.hansen, haitao.huang, josh,
	kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman, puiterwijk,
	rientjes, tglx, yaozhangx

Intel Software Guard eXtensions (SGX) is a set of CPU instructions that can
be used by applications to set aside private regions of code and data. The
code outside the SGX hosted software entity is prevented from accessing the
memory inside the enclave by the CPU. We call these entities as enclaves.

Add a driver that provides an ioctl API to construct and run enclaves.
Enclaves are constructed from pages residing in reserved physical memory
areas. The contents of these pages can only be accessed when they are
mapped as part of an enclave, by a hardware thread running inside the
enclave.

The starting state of an enclave consists of a fixed measured set of
pages that are copied to the EPC during the construction process by
using the opcode ENCLS leaf functions and Software Enclave Control
Structure (SECS) that defines the enclave properties.

Enclaves are constructed by using ENCLS leaf functions ECREATE, EADD and
EINIT. ECREATE initializes SECS, EADD copies pages from system memory to
the EPC and EINIT checks a given signed measurement and moves the enclave
into a state ready for execution.

An initialized enclave can only be accessed through special Thread Control
Structure (TCS) pages by using ENCLU (ring-3 only) leaf EENTER.  This leaf
function converts a thread into enclave mode and continues the execution in
the offset defined by the TCS provided to EENTER. An enclave is exited
through syscall, exception, interrupts or by explicitly calling another
ENCLU leaf EEXIT.

The mmap() permissions are capped by the contained enclave page
permissions. The mapped areas must also be populated, i.e. each page
address must contain a page. This logic is implemented in
sgx_encl_may_map().

Cc: linux-security-module@vger.kernel.org
Cc: linux-mm@kvack.org
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Matthew Wilcox <willy@infradead.org>
Acked-by: Jethro Beekman <jethro@fortanix.com>
Tested-by: Jethro Beekman <jethro@fortanix.com>
Tested-by: Haitao Huang <haitao.huang@linux.intel.com>
Tested-by: Chunyang Hui <sanqian.hcy@antfin.com>
Tested-by: Jordan Hand <jorhand@linux.microsoft.com>
Tested-by: Nathaniel McCallum <npmccallum@redhat.com>
Tested-by: Seth Moore <sethmo@google.com>
Tested-by: Darren Kenny <darren.kenny@oracle.com>
Reviewed-by: Darren Kenny <darren.kenny@oracle.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Suresh Siddha <suresh.b.siddha@intel.com>
Signed-off-by: Suresh Siddha <suresh.b.siddha@intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/kernel/cpu/sgx/Makefile |   2 +
 arch/x86/kernel/cpu/sgx/driver.c | 173 ++++++++++++++++
 arch/x86/kernel/cpu/sgx/driver.h |  29 +++
 arch/x86/kernel/cpu/sgx/encl.c   | 331 +++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/encl.h   |  85 ++++++++
 arch/x86/kernel/cpu/sgx/main.c   |  11 +
 6 files changed, 631 insertions(+)
 create mode 100644 arch/x86/kernel/cpu/sgx/driver.c
 create mode 100644 arch/x86/kernel/cpu/sgx/driver.h
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.h

diff --git a/arch/x86/kernel/cpu/sgx/Makefile b/arch/x86/kernel/cpu/sgx/Makefile
index 79510ce01b3b..3fc451120735 100644
--- a/arch/x86/kernel/cpu/sgx/Makefile
+++ b/arch/x86/kernel/cpu/sgx/Makefile
@@ -1,2 +1,4 @@
 obj-y += \
+	driver.o \
+	encl.o \
 	main.o
diff --git a/arch/x86/kernel/cpu/sgx/driver.c b/arch/x86/kernel/cpu/sgx/driver.c
new file mode 100644
index 000000000000..f54da5f19c2b
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/driver.c
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-18 Intel Corporation.
+
+#include <linux/acpi.h>
+#include <linux/miscdevice.h>
+#include <linux/mman.h>
+#include <linux/security.h>
+#include <linux/suspend.h>
+#include <asm/traps.h>
+#include "driver.h"
+#include "encl.h"
+
+u64 sgx_encl_size_max_32;
+u64 sgx_encl_size_max_64;
+u32 sgx_misc_reserved_mask;
+u64 sgx_attributes_reserved_mask;
+u64 sgx_xfrm_reserved_mask = ~0x3;
+u32 sgx_xsave_size_tbl[64];
+
+static int sgx_open(struct inode *inode, struct file *file)
+{
+	struct sgx_encl *encl;
+	int ret;
+
+	encl = kzalloc(sizeof(*encl), GFP_KERNEL);
+	if (!encl)
+		return -ENOMEM;
+
+	atomic_set(&encl->flags, 0);
+	kref_init(&encl->refcount);
+	xa_init(&encl->page_array);
+	mutex_init(&encl->lock);
+	INIT_LIST_HEAD(&encl->mm_list);
+	spin_lock_init(&encl->mm_lock);
+
+	ret = init_srcu_struct(&encl->srcu);
+	if (ret) {
+		kfree(encl);
+		return ret;
+	}
+
+	file->private_data = encl;
+
+	return 0;
+}
+
+static int sgx_release(struct inode *inode, struct file *file)
+{
+	struct sgx_encl *encl = file->private_data;
+	struct sgx_encl_mm *encl_mm;
+
+	for ( ; ; )  {
+		spin_lock(&encl->mm_lock);
+
+		if (list_empty(&encl->mm_list)) {
+			encl_mm = NULL;
+		} else {
+			encl_mm = list_first_entry(&encl->mm_list,
+						   struct sgx_encl_mm, list);
+			list_del_rcu(&encl_mm->list);
+		}
+
+		spin_unlock(&encl->mm_lock);
+
+		/* The list is empty, ready to go. */
+		if (!encl_mm)
+			break;
+
+		synchronize_srcu(&encl->srcu);
+		mmu_notifier_unregister(&encl_mm->mmu_notifier, encl_mm->mm);
+		kfree(encl_mm);
+	}
+
+	mutex_lock(&encl->lock);
+	atomic_or(SGX_ENCL_DEAD, &encl->flags);
+	mutex_unlock(&encl->lock);
+
+	kref_put(&encl->refcount, sgx_encl_release);
+	return 0;
+}
+
+static int sgx_mmap(struct file *file, struct vm_area_struct *vma)
+{
+	struct sgx_encl *encl = file->private_data;
+	int ret;
+
+	ret = sgx_encl_may_map(encl, vma->vm_start, vma->vm_end, vma->vm_flags);
+	if (ret)
+		return ret;
+
+	ret = sgx_encl_mm_add(encl, vma->vm_mm);
+	if (ret)
+		return ret;
+
+	vma->vm_ops = &sgx_vm_ops;
+	vma->vm_flags |= VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP | VM_IO;
+	vma->vm_private_data = encl;
+
+	return 0;
+}
+
+static unsigned long sgx_get_unmapped_area(struct file *file,
+					   unsigned long addr,
+					   unsigned long len,
+					   unsigned long pgoff,
+					   unsigned long flags)
+{
+	if ((flags & MAP_TYPE) == MAP_PRIVATE)
+		return -EINVAL;
+
+	if (flags & MAP_FIXED)
+		return addr;
+
+	return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
+}
+
+static const struct file_operations sgx_encl_fops = {
+	.owner			= THIS_MODULE,
+	.open			= sgx_open,
+	.release		= sgx_release,
+	.mmap			= sgx_mmap,
+	.get_unmapped_area	= sgx_get_unmapped_area,
+};
+
+static struct miscdevice sgx_dev_enclave = {
+	.minor = MISC_DYNAMIC_MINOR,
+	.name = "enclave",
+	.nodename = "sgx/enclave",
+	.fops = &sgx_encl_fops,
+};
+
+int __init sgx_drv_init(void)
+{
+	unsigned int eax, ebx, ecx, edx;
+	u64 attr_mask, xfrm_mask;
+	int ret;
+	int i;
+
+	if (!boot_cpu_has(X86_FEATURE_SGX_LC)) {
+		pr_info("The public key MSRs are not writable.\n");
+		return -ENODEV;
+	}
+
+	cpuid_count(SGX_CPUID, 0, &eax, &ebx, &ecx, &edx);
+	sgx_misc_reserved_mask = ~ebx | SGX_MISC_RESERVED_MASK;
+	sgx_encl_size_max_64 = 1ULL << ((edx >> 8) & 0xFF);
+	sgx_encl_size_max_32 = 1ULL << (edx & 0xFF);
+
+	cpuid_count(SGX_CPUID, 1, &eax, &ebx, &ecx, &edx);
+
+	attr_mask = (((u64)ebx) << 32) + (u64)eax;
+	sgx_attributes_reserved_mask = ~attr_mask | SGX_ATTR_RESERVED_MASK;
+
+	if (boot_cpu_has(X86_FEATURE_OSXSAVE)) {
+		xfrm_mask = (((u64)edx) << 32) + (u64)ecx;
+
+		for (i = 2; i < 64; i++) {
+			cpuid_count(0x0D, i, &eax, &ebx, &ecx, &edx);
+			if ((1UL << i) & xfrm_mask)
+				sgx_xsave_size_tbl[i] = eax + ebx;
+		}
+
+		sgx_xfrm_reserved_mask = ~xfrm_mask;
+	}
+
+	ret = misc_register(&sgx_dev_enclave);
+	if (ret) {
+		pr_err("Creating /dev/sgx/enclave failed with %d.\n", ret);
+		return ret;
+	}
+
+	return 0;
+}
diff --git a/arch/x86/kernel/cpu/sgx/driver.h b/arch/x86/kernel/cpu/sgx/driver.h
new file mode 100644
index 000000000000..f7ce40dedc91
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/driver.h
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+#ifndef __ARCH_SGX_DRIVER_H__
+#define __ARCH_SGX_DRIVER_H__
+
+#include <crypto/hash.h>
+#include <linux/kref.h>
+#include <linux/mmu_notifier.h>
+#include <linux/radix-tree.h>
+#include <linux/rwsem.h>
+#include <linux/sched.h>
+#include <linux/workqueue.h>
+#include "sgx.h"
+
+#define SGX_EINIT_SPIN_COUNT	20
+#define SGX_EINIT_SLEEP_COUNT	50
+#define SGX_EINIT_SLEEP_TIME	20
+
+extern u64 sgx_encl_size_max_32;
+extern u64 sgx_encl_size_max_64;
+extern u32 sgx_misc_reserved_mask;
+extern u64 sgx_attributes_reserved_mask;
+extern u64 sgx_xfrm_reserved_mask;
+extern u32 sgx_xsave_size_tbl[64];
+
+long sgx_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
+
+int sgx_drv_init(void);
+
+#endif /* __ARCH_X86_SGX_DRIVER_H__ */
diff --git a/arch/x86/kernel/cpu/sgx/encl.c b/arch/x86/kernel/cpu/sgx/encl.c
new file mode 100644
index 000000000000..c2c4a77af36b
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/encl.c
@@ -0,0 +1,331 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-18 Intel Corporation.
+
+#include <linux/lockdep.h>
+#include <linux/mm.h>
+#include <linux/mman.h>
+#include <linux/shmem_fs.h>
+#include <linux/suspend.h>
+#include <linux/sched/mm.h>
+#include "arch.h"
+#include "encl.h"
+#include "encls.h"
+#include "sgx.h"
+
+static struct sgx_encl_page *sgx_encl_load_page(struct sgx_encl *encl,
+						unsigned long addr)
+{
+	struct sgx_encl_page *entry;
+	unsigned int flags;
+
+	/* If process was forked, VMA is still there but vm_private_data is set
+	 * to NULL.
+	 */
+	if (!encl)
+		return ERR_PTR(-EFAULT);
+
+	flags = atomic_read(&encl->flags);
+	if ((flags & SGX_ENCL_DEAD) || !(flags & SGX_ENCL_INITIALIZED))
+		return ERR_PTR(-EFAULT);
+
+	entry = xa_load(&encl->page_array, PFN_DOWN(addr));
+	if (!entry)
+		return ERR_PTR(-EFAULT);
+
+	/* Page is already resident in the EPC. */
+	if (entry->epc_page)
+		return entry;
+
+	return ERR_PTR(-EFAULT);
+}
+
+static void sgx_mmu_notifier_release(struct mmu_notifier *mn,
+				     struct mm_struct *mm)
+{
+	struct sgx_encl_mm *encl_mm = container_of(mn, struct sgx_encl_mm, mmu_notifier);
+	struct sgx_encl_mm *tmp = NULL;
+
+	/*
+	 * The enclave itself can remove encl_mm.  Note, objects can't be moved
+	 * off an RCU protected list, but deletion is ok.
+	 */
+	spin_lock(&encl_mm->encl->mm_lock);
+	list_for_each_entry(tmp, &encl_mm->encl->mm_list, list) {
+		if (tmp == encl_mm) {
+			list_del_rcu(&encl_mm->list);
+			break;
+		}
+	}
+	spin_unlock(&encl_mm->encl->mm_lock);
+
+	if (tmp == encl_mm) {
+		synchronize_srcu(&encl_mm->encl->srcu);
+		mmu_notifier_put(mn);
+	}
+}
+
+static void sgx_mmu_notifier_free(struct mmu_notifier *mn)
+{
+	struct sgx_encl_mm *encl_mm = container_of(mn, struct sgx_encl_mm, mmu_notifier);
+
+	kfree(encl_mm);
+}
+
+static const struct mmu_notifier_ops sgx_mmu_notifier_ops = {
+	.release		= sgx_mmu_notifier_release,
+	.free_notifier		= sgx_mmu_notifier_free,
+};
+
+static struct sgx_encl_mm *sgx_encl_find_mm(struct sgx_encl *encl,
+					    struct mm_struct *mm)
+{
+	struct sgx_encl_mm *encl_mm = NULL;
+	struct sgx_encl_mm *tmp;
+	int idx;
+
+	idx = srcu_read_lock(&encl->srcu);
+
+	list_for_each_entry_rcu(tmp, &encl->mm_list, list) {
+		if (tmp->mm == mm) {
+			encl_mm = tmp;
+			break;
+		}
+	}
+
+	srcu_read_unlock(&encl->srcu, idx);
+
+	return encl_mm;
+}
+
+int sgx_encl_mm_add(struct sgx_encl *encl, struct mm_struct *mm)
+{
+	struct sgx_encl_mm *encl_mm;
+	int ret;
+
+	/* mm_list can be accessed only by a single thread at a time. */
+	mmap_assert_write_locked(mm);
+
+	if (atomic_read(&encl->flags) & SGX_ENCL_DEAD)
+		return -EINVAL;
+
+	/*
+	 * mm_structs are kept on mm_list until the mm or the enclave dies,
+	 * i.e. once an mm is off the list, it's gone for good, therefore it's
+	 * impossible to get a false positive on @mm due to a stale mm_list.
+	 */
+	if (sgx_encl_find_mm(encl, mm))
+		return 0;
+
+	encl_mm = kzalloc(sizeof(*encl_mm), GFP_KERNEL);
+	if (!encl_mm)
+		return -ENOMEM;
+
+	encl_mm->encl = encl;
+	encl_mm->mm = mm;
+	encl_mm->mmu_notifier.ops = &sgx_mmu_notifier_ops;
+
+	ret = __mmu_notifier_register(&encl_mm->mmu_notifier, mm);
+	if (ret) {
+		kfree(encl_mm);
+		return ret;
+	}
+
+	spin_lock(&encl->mm_lock);
+	list_add_rcu(&encl_mm->list, &encl->mm_list);
+	spin_unlock(&encl->mm_lock);
+
+	return 0;
+}
+
+static void sgx_vma_open(struct vm_area_struct *vma)
+{
+	struct sgx_encl *encl = vma->vm_private_data;
+
+	if (!encl)
+		return;
+
+	if (sgx_encl_mm_add(encl, vma->vm_mm))
+		vma->vm_private_data = NULL;
+}
+
+static unsigned int sgx_vma_fault(struct vm_fault *vmf)
+{
+	unsigned long addr = (unsigned long)vmf->address;
+	struct vm_area_struct *vma = vmf->vma;
+	struct sgx_encl *encl = vma->vm_private_data;
+	struct sgx_encl_page *entry;
+	int ret = VM_FAULT_NOPAGE;
+	unsigned long pfn;
+
+	if (!encl)
+		return VM_FAULT_SIGBUS;
+
+	mutex_lock(&encl->lock);
+
+	entry = sgx_encl_load_page(encl, addr);
+	if (IS_ERR(entry)) {
+		if (unlikely(PTR_ERR(entry) != -EBUSY))
+			ret = VM_FAULT_SIGBUS;
+
+		goto out;
+	}
+
+	if (!follow_pfn(vma, addr, &pfn))
+		goto out;
+
+	ret = vmf_insert_pfn(vma, addr, PFN_DOWN(entry->epc_page->desc));
+	if (ret != VM_FAULT_NOPAGE) {
+		ret = VM_FAULT_SIGBUS;
+		goto out;
+	}
+
+out:
+	mutex_unlock(&encl->lock);
+	return ret;
+}
+
+/**
+ * sgx_encl_may_map() - Check if a requested VMA mapping is allowed
+ * @encl:		an enclave pointer
+ * @start:		lower bound of the address range, inclusive
+ * @end:		upper bound of the address range, exclusive
+ * @vm_prot_bits:	requested protections of the address range
+ *
+ * Iterate through the enclave pages contained within [@start, @end) to verify
+ * the permissions requested by @vm_prot_bits do not exceed that of any enclave
+ * page to be mapped.
+ *
+ * Return:
+ *   0 on success,
+ *   -EACCES if VMA permissions exceed enclave page permissions
+ */
+int sgx_encl_may_map(struct sgx_encl *encl, unsigned long start,
+		     unsigned long end, unsigned long vm_flags)
+{
+	unsigned long vm_prot_bits = vm_flags & (VM_READ | VM_WRITE | VM_EXEC);
+	unsigned long idx_start = PFN_DOWN(start);
+	unsigned long idx_end = PFN_DOWN(end - 1);
+	struct sgx_encl_page *page;
+
+	XA_STATE(xas, &encl->page_array, idx_start);
+
+	/*
+	 * Disallow READ_IMPLIES_EXEC tasks as their VMA permissions might
+	 * conflict with the enclave page permissions.
+	 */
+	if (current->personality & READ_IMPLIES_EXEC)
+		return -EACCES;
+
+	xas_for_each(&xas, page, idx_end)
+		if (!page || (~page->vm_max_prot_bits & vm_prot_bits))
+			return -EACCES;
+
+	return 0;
+}
+
+static int sgx_vma_mprotect(struct vm_area_struct *vma,
+			    struct vm_area_struct **pprev, unsigned long start,
+			    unsigned long end, unsigned long newflags)
+{
+	int ret;
+
+	ret = sgx_encl_may_map(vma->vm_private_data, start, end, newflags);
+	if (ret)
+		return ret;
+
+	return mprotect_fixup(vma, pprev, start, end, newflags);
+}
+
+const struct vm_operations_struct sgx_vm_ops = {
+	.open = sgx_vma_open,
+	.fault = sgx_vma_fault,
+	.mprotect = sgx_vma_mprotect,
+};
+
+/**
+ * sgx_encl_find - find an enclave
+ * @mm:		mm struct of the current process
+ * @addr:	address in the ELRANGE
+ * @vma:	the resulting VMA
+ *
+ * Find an enclave identified by the given address. Give back a VMA that is
+ * part of the enclave and located in that address. The VMA is given back if it
+ * is a proper enclave VMA even if an &sgx_encl instance does not exist yet
+ * (enclave creation has not been performed).
+ *
+ * Return:
+ *   0 on success,
+ *   -EINVAL if an enclave was not found,
+ *   -ENOENT if the enclave has not been created yet
+ */
+int sgx_encl_find(struct mm_struct *mm, unsigned long addr,
+		  struct vm_area_struct **vma)
+{
+	struct vm_area_struct *result;
+	struct sgx_encl *encl;
+
+	result = find_vma(mm, addr);
+	if (!result || result->vm_ops != &sgx_vm_ops || addr < result->vm_start)
+		return -EINVAL;
+
+	encl = result->vm_private_data;
+	*vma = result;
+
+	return encl ? 0 : -ENOENT;
+}
+
+/**
+ * sgx_encl_destroy() - destroy enclave resources
+ * @encl:	an enclave pointer
+ */
+void sgx_encl_destroy(struct sgx_encl *encl)
+{
+	struct sgx_encl_page *entry;
+	unsigned long index;
+
+	atomic_or(SGX_ENCL_DEAD, &encl->flags);
+
+	xa_for_each(&encl->page_array, index, entry) {
+		if (entry->epc_page) {
+			sgx_free_epc_page(entry->epc_page);
+			encl->secs_child_cnt--;
+			entry->epc_page = NULL;
+		}
+
+		kfree(entry);
+	}
+
+	xa_destroy(&encl->page_array);
+
+	if (!encl->secs_child_cnt && encl->secs.epc_page) {
+		sgx_free_epc_page(encl->secs.epc_page);
+		encl->secs.epc_page = NULL;
+	}
+}
+
+/**
+ * sgx_encl_release - Destroy an enclave instance
+ * @kref:	address of a kref inside &sgx_encl
+ *
+ * Used together with kref_put(). Frees all the resources associated with the
+ * enclave and the instance itself.
+ */
+void sgx_encl_release(struct kref *ref)
+{
+	struct sgx_encl *encl = container_of(ref, struct sgx_encl, refcount);
+
+	sgx_encl_destroy(encl);
+
+	if (encl->backing)
+		fput(encl->backing);
+
+	cleanup_srcu_struct(&encl->srcu);
+
+	WARN_ON_ONCE(!list_empty(&encl->mm_list));
+
+	/* Detect EPC page leak's. */
+	WARN_ON_ONCE(encl->secs_child_cnt);
+	WARN_ON_ONCE(encl->secs.epc_page);
+
+	kfree(encl);
+}
diff --git a/arch/x86/kernel/cpu/sgx/encl.h b/arch/x86/kernel/cpu/sgx/encl.h
new file mode 100644
index 000000000000..8ff445476657
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/encl.h
@@ -0,0 +1,85 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/**
+ * Copyright(c) 2016-19 Intel Corporation.
+ */
+#ifndef _X86_ENCL_H
+#define _X86_ENCL_H
+
+#include <linux/cpumask.h>
+#include <linux/kref.h>
+#include <linux/list.h>
+#include <linux/mm_types.h>
+#include <linux/mmu_notifier.h>
+#include <linux/mutex.h>
+#include <linux/notifier.h>
+#include <linux/srcu.h>
+#include <linux/workqueue.h>
+#include <linux/xarray.h>
+#include "sgx.h"
+
+/**
+ * enum sgx_encl_page_desc - defines bits for an enclave page's descriptor
+ * %SGX_ENCL_PAGE_ADDR_MASK:		Holds the virtual address of the page.
+ *
+ * The page address for SECS is zero and is used by the subsystem to recognize
+ * the SECS page.
+ */
+enum sgx_encl_page_desc {
+	/* Bits 11:3 are available when the page is not swapped. */
+	SGX_ENCL_PAGE_ADDR_MASK		= PAGE_MASK,
+};
+
+#define SGX_ENCL_PAGE_ADDR(page) \
+	((page)->desc & SGX_ENCL_PAGE_ADDR_MASK)
+
+struct sgx_encl_page {
+	unsigned long desc;
+	unsigned long vm_max_prot_bits;
+	struct sgx_epc_page *epc_page;
+	struct sgx_encl *encl;
+};
+
+enum sgx_encl_flags {
+	SGX_ENCL_CREATED	= BIT(0),
+	SGX_ENCL_INITIALIZED	= BIT(1),
+	SGX_ENCL_DEBUG		= BIT(2),
+	SGX_ENCL_DEAD		= BIT(3),
+	SGX_ENCL_IOCTL		= BIT(4),
+};
+
+struct sgx_encl_mm {
+	struct sgx_encl *encl;
+	struct mm_struct *mm;
+	struct list_head list;
+	struct mmu_notifier mmu_notifier;
+};
+
+struct sgx_encl {
+	atomic_t flags;
+	unsigned int page_cnt;
+	unsigned int secs_child_cnt;
+	struct mutex lock;
+	struct list_head mm_list;
+	spinlock_t mm_lock;
+	struct file *backing;
+	struct kref refcount;
+	struct srcu_struct srcu;
+	unsigned long base;
+	unsigned long size;
+	unsigned long ssaframesize;
+	struct xarray page_array;
+	struct sgx_encl_page secs;
+	cpumask_t cpumask;
+};
+
+extern const struct vm_operations_struct sgx_vm_ops;
+
+int sgx_encl_find(struct mm_struct *mm, unsigned long addr,
+		  struct vm_area_struct **vma);
+void sgx_encl_destroy(struct sgx_encl *encl);
+void sgx_encl_release(struct kref *ref);
+int sgx_encl_mm_add(struct sgx_encl *encl, struct mm_struct *mm);
+int sgx_encl_may_map(struct sgx_encl *encl, unsigned long start,
+		     unsigned long end, unsigned long vm_flags);
+
+#endif /* _X86_ENCL_H */
diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
index 97c6895fb6c9..4137254fb29e 100644
--- a/arch/x86/kernel/cpu/sgx/main.c
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -9,6 +9,8 @@
 #include <linux/sched/mm.h>
 #include <linux/sched/signal.h>
 #include <linux/slab.h>
+#include "driver.h"
+#include "encl.h"
 #include "encls.h"
 
 struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
@@ -260,6 +262,8 @@ static bool __init sgx_page_cache_init(void)
 
 static void __init sgx_init(void)
 {
+	int ret;
+
 	if (!boot_cpu_has(X86_FEATURE_SGX))
 		return;
 
@@ -269,8 +273,15 @@ static void __init sgx_init(void)
 	if (!sgx_page_reclaimer_init())
 		goto err_page_cache;
 
+	ret = sgx_drv_init();
+	if (ret)
+		goto err_kthread;
+
 	return;
 
+err_kthread:
+	kthread_stop(ksgxswapd_tsk);
+
 err_page_cache:
 	sgx_page_cache_teardown();
 }
-- 
2.25.1



^ permalink raw reply related	[flat|nested] 81+ messages in thread

* [PATCH v38 16/24] x86/sgx: Add a page reclaimer
       [not found] <20200915112842.897265-1-jarkko.sakkinen@linux.intel.com>
  2020-09-15 11:28 ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Jarkko Sakkinen
  2020-09-15 11:28 ` [PATCH v38 11/24] x86/sgx: Add SGX enclave driver Jarkko Sakkinen
@ 2020-09-15 11:28 ` Jarkko Sakkinen
  2020-09-22 10:45   ` Borislav Petkov
  2 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-15 11:28 UTC (permalink / raw)
  To: x86, linux-sgx
  Cc: linux-kernel, Jarkko Sakkinen, linux-mm, Jethro Beekman,
	Jordan Hand, Nathaniel McCallum, Chunyang Hui, Seth Moore,
	Sean Christopherson, akpm, andriy.shevchenko, asapek, bp,
	cedric.xing, chenalexchen, conradparker, cyhanish, dave.hansen,
	haitao.huang, josh, kai.huang, kai.svahn, kmoy, ludloff, luto,
	nhorman, puiterwijk, rientjes, tglx, yaozhangx

There is a limited amount of EPC available. Therefore, some of it must be
copied to the regular memory, and only subset kept in the SGX reserved
memory. While kernel cannot directly access enclave memory, SGX provides a
set of ENCLS leaf functions to perform reclaiming.

This commits implements a page reclaimer by using these leaf functions. It
picks the victim pages in LRU fashion from all the enclaves running in the
system. The thread ksgxswapd reclaims pages on the event when the number of
free EPC pages goes below SGX_NR_LOW_PAGES up until it reaches
SGX_NR_HIGH_PAGES.

sgx_alloc_epc_page() can optionally directly reclaim pages with @reclaim
set true. A caller must also supply owner for each page so that the
reclaimer can access the associated enclaves. This is needed for locking,
as most of the ENCLS leafs cannot be executed concurrently for an enclave.
The owner is also needed for accessing SECS, which is required to be
resident when its child pages are being reclaimed.

Cc: linux-mm@kvack.org
Acked-by: Jethro Beekman <jethro@fortanix.com>
Tested-by: Jethro Beekman <jethro@fortanix.com>
Tested-by: Jordan Hand <jorhand@linux.microsoft.com>
Tested-by: Nathaniel McCallum <npmccallum@redhat.com>
Tested-by: Chunyang Hui <sanqian.hcy@antfin.com>
Tested-by: Seth Moore <sethmo@google.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/kernel/cpu/sgx/driver.c |   1 +
 arch/x86/kernel/cpu/sgx/encl.c   | 340 +++++++++++++++++++++-
 arch/x86/kernel/cpu/sgx/encl.h   |  41 +++
 arch/x86/kernel/cpu/sgx/ioctl.c  |  77 ++++-
 arch/x86/kernel/cpu/sgx/main.c   | 464 +++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h    |   9 +
 6 files changed, 925 insertions(+), 7 deletions(-)

diff --git a/arch/x86/kernel/cpu/sgx/driver.c b/arch/x86/kernel/cpu/sgx/driver.c
index d01b28f7ce4a..0446781cc7a2 100644
--- a/arch/x86/kernel/cpu/sgx/driver.c
+++ b/arch/x86/kernel/cpu/sgx/driver.c
@@ -29,6 +29,7 @@ static int sgx_open(struct inode *inode, struct file *file)
 	atomic_set(&encl->flags, 0);
 	kref_init(&encl->refcount);
 	xa_init(&encl->page_array);
+	INIT_LIST_HEAD(&encl->va_pages);
 	mutex_init(&encl->lock);
 	INIT_LIST_HEAD(&encl->mm_list);
 	spin_lock_init(&encl->mm_lock);
diff --git a/arch/x86/kernel/cpu/sgx/encl.c b/arch/x86/kernel/cpu/sgx/encl.c
index c2c4a77af36b..11ec2df59b54 100644
--- a/arch/x86/kernel/cpu/sgx/encl.c
+++ b/arch/x86/kernel/cpu/sgx/encl.c
@@ -12,9 +12,84 @@
 #include "encls.h"
 #include "sgx.h"
 
+static int __sgx_encl_eldu(struct sgx_encl_page *encl_page,
+			   struct sgx_epc_page *epc_page,
+			   struct sgx_epc_page *secs_page)
+{
+	unsigned long va_offset = SGX_ENCL_PAGE_VA_OFFSET(encl_page);
+	struct sgx_encl *encl = encl_page->encl;
+	struct sgx_pageinfo pginfo;
+	struct sgx_backing b;
+	pgoff_t page_index;
+	int ret;
+
+	if (secs_page)
+		page_index = SGX_ENCL_PAGE_INDEX(encl_page);
+	else
+		page_index = PFN_DOWN(encl->size);
+
+	ret = sgx_encl_get_backing(encl, page_index, &b);
+	if (ret)
+		return ret;
+
+	pginfo.addr = SGX_ENCL_PAGE_ADDR(encl_page);
+	pginfo.contents = (unsigned long)kmap_atomic(b.contents);
+	pginfo.metadata = (unsigned long)kmap_atomic(b.pcmd) +
+			  b.pcmd_offset;
+
+	if (secs_page)
+		pginfo.secs = (u64)sgx_get_epc_addr(secs_page);
+	else
+		pginfo.secs = 0;
+
+	ret = __eldu(&pginfo, sgx_get_epc_addr(epc_page),
+		     sgx_get_epc_addr(encl_page->va_page->epc_page) +
+				      va_offset);
+	if (ret) {
+		if (encls_failed(ret))
+			ENCLS_WARN(ret, "ELDU");
+
+		ret = -EFAULT;
+	}
+
+	kunmap_atomic((void *)(unsigned long)(pginfo.metadata - b.pcmd_offset));
+	kunmap_atomic((void *)(unsigned long)pginfo.contents);
+
+	sgx_encl_put_backing(&b, false);
+
+	return ret;
+}
+
+static struct sgx_epc_page *sgx_encl_eldu(struct sgx_encl_page *encl_page,
+					  struct sgx_epc_page *secs_page)
+{
+	unsigned long va_offset = SGX_ENCL_PAGE_VA_OFFSET(encl_page);
+	struct sgx_encl *encl = encl_page->encl;
+	struct sgx_epc_page *epc_page;
+	int ret;
+
+	epc_page = sgx_alloc_epc_page(encl_page, false);
+	if (IS_ERR(epc_page))
+		return epc_page;
+
+	ret = __sgx_encl_eldu(encl_page, epc_page, secs_page);
+	if (ret) {
+		sgx_free_epc_page(epc_page);
+		return ERR_PTR(ret);
+	}
+
+	sgx_free_va_slot(encl_page->va_page, va_offset);
+	list_move(&encl_page->va_page->list, &encl->va_pages);
+	encl_page->desc &= ~SGX_ENCL_PAGE_VA_OFFSET_MASK;
+	encl_page->epc_page = epc_page;
+
+	return epc_page;
+}
+
 static struct sgx_encl_page *sgx_encl_load_page(struct sgx_encl *encl,
 						unsigned long addr)
 {
+	struct sgx_epc_page *epc_page;
 	struct sgx_encl_page *entry;
 	unsigned int flags;
 
@@ -33,10 +108,27 @@ static struct sgx_encl_page *sgx_encl_load_page(struct sgx_encl *encl,
 		return ERR_PTR(-EFAULT);
 
 	/* Page is already resident in the EPC. */
-	if (entry->epc_page)
+	if (entry->epc_page) {
+		if (entry->desc & SGX_ENCL_PAGE_RECLAIMED)
+			return ERR_PTR(-EBUSY);
+
 		return entry;
+	}
+
+	if (!(encl->secs.epc_page)) {
+		epc_page = sgx_encl_eldu(&encl->secs, NULL);
+		if (IS_ERR(epc_page))
+			return ERR_CAST(epc_page);
+	}
+
+	epc_page = sgx_encl_eldu(entry, encl->secs.epc_page);
+	if (IS_ERR(epc_page))
+		return ERR_CAST(epc_page);
 
-	return ERR_PTR(-EFAULT);
+	encl->secs_child_cnt++;
+	sgx_mark_page_reclaimable(entry->epc_page);
+
+	return entry;
 }
 
 static void sgx_mmu_notifier_release(struct mmu_notifier *mn,
@@ -132,6 +224,9 @@ int sgx_encl_mm_add(struct sgx_encl *encl, struct mm_struct *mm)
 
 	spin_lock(&encl->mm_lock);
 	list_add_rcu(&encl_mm->list, &encl->mm_list);
+	/* Pairs with smp_rmb() in sgx_reclaimer_block(). */
+	smp_wmb();
+	encl->mm_list_version++;
 	spin_unlock(&encl->mm_lock);
 
 	return 0;
@@ -179,6 +274,8 @@ static unsigned int sgx_vma_fault(struct vm_fault *vmf)
 		goto out;
 	}
 
+	sgx_encl_test_and_clear_young(vma->vm_mm, entry);
+
 out:
 	mutex_unlock(&encl->lock);
 	return ret;
@@ -280,6 +377,7 @@ int sgx_encl_find(struct mm_struct *mm, unsigned long addr,
  */
 void sgx_encl_destroy(struct sgx_encl *encl)
 {
+	struct sgx_va_page *va_page;
 	struct sgx_encl_page *entry;
 	unsigned long index;
 
@@ -287,6 +385,13 @@ void sgx_encl_destroy(struct sgx_encl *encl)
 
 	xa_for_each(&encl->page_array, index, entry) {
 		if (entry->epc_page) {
+			/*
+			 * The page and its radix tree entry cannot be freed
+			 * if the page is being held by the reclaimer.
+			 */
+			if (sgx_unmark_page_reclaimable(entry->epc_page))
+				continue;
+
 			sgx_free_epc_page(entry->epc_page);
 			encl->secs_child_cnt--;
 			entry->epc_page = NULL;
@@ -301,6 +406,19 @@ void sgx_encl_destroy(struct sgx_encl *encl)
 		sgx_free_epc_page(encl->secs.epc_page);
 		encl->secs.epc_page = NULL;
 	}
+
+	/*
+	 * The reclaimer is responsible for checking SGX_ENCL_DEAD before doing
+	 * EWB, thus it's safe to free VA pages even if the reclaimer holds a
+	 * reference to the enclave.
+	 */
+	while (!list_empty(&encl->va_pages)) {
+		va_page = list_first_entry(&encl->va_pages, struct sgx_va_page,
+					   list);
+		list_del(&va_page->list);
+		sgx_free_epc_page(va_page->epc_page);
+		kfree(va_page);
+	}
 }
 
 /**
@@ -329,3 +447,221 @@ void sgx_encl_release(struct kref *ref)
 
 	kfree(encl);
 }
+
+static struct page *sgx_encl_get_backing_page(struct sgx_encl *encl,
+					      pgoff_t index)
+{
+	struct inode *inode = encl->backing->f_path.dentry->d_inode;
+	struct address_space *mapping = inode->i_mapping;
+	gfp_t gfpmask = mapping_gfp_mask(mapping);
+
+	return shmem_read_mapping_page_gfp(mapping, index, gfpmask);
+}
+
+/**
+ * sgx_encl_get_backing() - Pin the backing storage
+ * @encl:	an enclave pointer
+ * @page_index:	enclave page index
+ * @backing:	data for accessing backing storage for the page
+ *
+ * Pin the backing storage pages for storing the encrypted contents and Paging
+ * Crypto MetaData (PCMD) of an enclave page.
+ *
+ * Return:
+ *   0 on success,
+ *   -errno otherwise.
+ */
+int sgx_encl_get_backing(struct sgx_encl *encl, unsigned long page_index,
+			 struct sgx_backing *backing)
+{
+	pgoff_t pcmd_index = PFN_DOWN(encl->size) + 1 + (page_index >> 5);
+	struct page *contents;
+	struct page *pcmd;
+
+	contents = sgx_encl_get_backing_page(encl, page_index);
+	if (IS_ERR(contents))
+		return PTR_ERR(contents);
+
+	pcmd = sgx_encl_get_backing_page(encl, pcmd_index);
+	if (IS_ERR(pcmd)) {
+		put_page(contents);
+		return PTR_ERR(pcmd);
+	}
+
+	backing->page_index = page_index;
+	backing->contents = contents;
+	backing->pcmd = pcmd;
+	backing->pcmd_offset =
+		(page_index & (PAGE_SIZE / sizeof(struct sgx_pcmd) - 1)) *
+		sizeof(struct sgx_pcmd);
+
+	return 0;
+}
+
+/**
+ * sgx_encl_put_backing() - Unpin the backing storage
+ * @backing:	data for accessing backing storage for the page
+ * @do_write:	mark pages dirty
+ */
+void sgx_encl_put_backing(struct sgx_backing *backing, bool do_write)
+{
+	if (do_write) {
+		set_page_dirty(backing->pcmd);
+		set_page_dirty(backing->contents);
+	}
+
+	put_page(backing->pcmd);
+	put_page(backing->contents);
+}
+
+static int sgx_encl_test_and_clear_young_cb(pte_t *ptep, unsigned long addr,
+					    void *data)
+{
+	pte_t pte;
+	int ret;
+
+	ret = pte_young(*ptep);
+	if (ret) {
+		pte = pte_mkold(*ptep);
+		set_pte_at((struct mm_struct *)data, addr, ptep, pte);
+	}
+
+	return ret;
+}
+
+/**
+ * sgx_encl_test_and_clear_young() - Test and reset the accessed bit
+ * @mm:		mm_struct that is checked
+ * @page:	enclave page to be tested for recent access
+ *
+ * Checks the Access (A) bit from the PTE corresponding to the enclave page and
+ * clears it.
+ *
+ * Return: 1 if the page has been recently accessed and 0 if not.
+ */
+int sgx_encl_test_and_clear_young(struct mm_struct *mm,
+				  struct sgx_encl_page *page)
+{
+	unsigned long addr = SGX_ENCL_PAGE_ADDR(page);
+	struct sgx_encl *encl = page->encl;
+	struct vm_area_struct *vma;
+	int ret;
+
+	ret = sgx_encl_find(mm, addr, &vma);
+	if (ret)
+		return 0;
+
+	if (encl != vma->vm_private_data)
+		return 0;
+
+	ret = apply_to_page_range(vma->vm_mm, addr, PAGE_SIZE,
+				  sgx_encl_test_and_clear_young_cb, vma->vm_mm);
+	if (ret < 0)
+		return 0;
+
+	return ret;
+}
+
+/**
+ * sgx_encl_reserve_page() - Reserve an enclave page
+ * @encl:	an enclave pointer
+ * @addr:	a page address
+ *
+ * Load an enclave page and lock the enclave so that the page can be used by
+ * EDBG* and EMOD*.
+ *
+ * Return:
+ *   an enclave page on success
+ *   -EFAULT	if the load fails
+ */
+struct sgx_encl_page *sgx_encl_reserve_page(struct sgx_encl *encl,
+					    unsigned long addr)
+{
+	struct sgx_encl_page *entry;
+
+	for ( ; ; ) {
+		mutex_lock(&encl->lock);
+
+		entry = sgx_encl_load_page(encl, addr);
+		if (PTR_ERR(entry) != -EBUSY)
+			break;
+
+		mutex_unlock(&encl->lock);
+	}
+
+	if (IS_ERR(entry))
+		mutex_unlock(&encl->lock);
+
+	return entry;
+}
+
+/**
+ * sgx_alloc_va_page() - Allocate a Version Array (VA) page
+ *
+ * Allocate a free EPC page and convert it to a Version Array (VA) page.
+ *
+ * Return:
+ *   a VA page,
+ *   -errno otherwise
+ */
+struct sgx_epc_page *sgx_alloc_va_page(void)
+{
+	struct sgx_epc_page *epc_page;
+	int ret;
+
+	epc_page = sgx_alloc_epc_page(NULL, true);
+	if (IS_ERR(epc_page))
+		return ERR_CAST(epc_page);
+
+	ret = __epa(sgx_get_epc_addr(epc_page));
+	if (ret) {
+		WARN_ONCE(1, "EPA returned %d (0x%x)", ret, ret);
+		sgx_free_epc_page(epc_page);
+		return ERR_PTR(-EFAULT);
+	}
+
+	return epc_page;
+}
+
+/**
+ * sgx_alloc_va_slot - allocate a VA slot
+ * @va_page:	a &struct sgx_va_page instance
+ *
+ * Allocates a slot from a &struct sgx_va_page instance.
+ *
+ * Return: offset of the slot inside the VA page
+ */
+unsigned int sgx_alloc_va_slot(struct sgx_va_page *va_page)
+{
+	int slot = find_first_zero_bit(va_page->slots, SGX_VA_SLOT_COUNT);
+
+	if (slot < SGX_VA_SLOT_COUNT)
+		set_bit(slot, va_page->slots);
+
+	return slot << 3;
+}
+
+/**
+ * sgx_free_va_slot - free a VA slot
+ * @va_page:	a &struct sgx_va_page instance
+ * @offset:	offset of the slot inside the VA page
+ *
+ * Frees a slot from a &struct sgx_va_page instance.
+ */
+void sgx_free_va_slot(struct sgx_va_page *va_page, unsigned int offset)
+{
+	clear_bit(offset >> 3, va_page->slots);
+}
+
+/**
+ * sgx_va_page_full - is the VA page full?
+ * @va_page:	a &struct sgx_va_page instance
+ *
+ * Return: true if all slots have been taken
+ */
+bool sgx_va_page_full(struct sgx_va_page *va_page)
+{
+	int slot = find_first_zero_bit(va_page->slots, SGX_VA_SLOT_COUNT);
+
+	return slot == SGX_VA_SLOT_COUNT;
+}
diff --git a/arch/x86/kernel/cpu/sgx/encl.h b/arch/x86/kernel/cpu/sgx/encl.h
index 0448d22d3010..11dcf4e7fb3e 100644
--- a/arch/x86/kernel/cpu/sgx/encl.h
+++ b/arch/x86/kernel/cpu/sgx/encl.h
@@ -19,6 +19,10 @@
 
 /**
  * enum sgx_encl_page_desc - defines bits for an enclave page's descriptor
+ * %SGX_ENCL_PAGE_RECLAIMED:		The page is in the process of being
+ *					reclaimed.
+ * %SGX_ENCL_PAGE_VA_OFFSET_MASK:	Holds the offset in the Version Array
+ *					(VA) page for a swapped page.
  * %SGX_ENCL_PAGE_ADDR_MASK:		Holds the virtual address of the page.
  *
  * The page address for SECS is zero and is used by the subsystem to recognize
@@ -26,16 +30,23 @@
  */
 enum sgx_encl_page_desc {
 	/* Bits 11:3 are available when the page is not swapped. */
+	SGX_ENCL_PAGE_RECLAIMED		= BIT(3),
+	SGX_ENCL_PAGE_VA_OFFSET_MASK	= GENMASK_ULL(11, 3),
 	SGX_ENCL_PAGE_ADDR_MASK		= PAGE_MASK,
 };
 
 #define SGX_ENCL_PAGE_ADDR(page) \
 	((page)->desc & SGX_ENCL_PAGE_ADDR_MASK)
+#define SGX_ENCL_PAGE_VA_OFFSET(page) \
+	((page)->desc & SGX_ENCL_PAGE_VA_OFFSET_MASK)
+#define SGX_ENCL_PAGE_INDEX(page) \
+	PFN_DOWN((page)->desc - (page)->encl->base)
 
 struct sgx_encl_page {
 	unsigned long desc;
 	unsigned long vm_max_prot_bits;
 	struct sgx_epc_page *epc_page;
+	struct sgx_va_page *va_page;
 	struct sgx_encl *encl;
 };
 
@@ -61,6 +72,7 @@ struct sgx_encl {
 	struct mutex lock;
 	struct list_head mm_list;
 	spinlock_t mm_lock;
+	unsigned long mm_list_version;
 	struct file *backing;
 	struct kref refcount;
 	struct srcu_struct srcu;
@@ -68,12 +80,21 @@ struct sgx_encl {
 	unsigned long size;
 	unsigned long ssaframesize;
 	struct xarray page_array;
+	struct list_head va_pages;
 	struct sgx_encl_page secs;
 	cpumask_t cpumask;
 	unsigned long attributes;
 	unsigned long attributes_mask;
 };
 
+#define SGX_VA_SLOT_COUNT 512
+
+struct sgx_va_page {
+	struct sgx_epc_page *epc_page;
+	DECLARE_BITMAP(slots, SGX_VA_SLOT_COUNT);
+	struct list_head list;
+};
+
 extern const struct vm_operations_struct sgx_vm_ops;
 
 int sgx_encl_find(struct mm_struct *mm, unsigned long addr,
@@ -84,4 +105,24 @@ int sgx_encl_mm_add(struct sgx_encl *encl, struct mm_struct *mm);
 int sgx_encl_may_map(struct sgx_encl *encl, unsigned long start,
 		     unsigned long end, unsigned long vm_flags);
 
+struct sgx_backing {
+	pgoff_t page_index;
+	struct page *contents;
+	struct page *pcmd;
+	unsigned long pcmd_offset;
+};
+
+int sgx_encl_get_backing(struct sgx_encl *encl, unsigned long page_index,
+			 struct sgx_backing *backing);
+void sgx_encl_put_backing(struct sgx_backing *backing, bool do_write);
+int sgx_encl_test_and_clear_young(struct mm_struct *mm,
+				  struct sgx_encl_page *page);
+struct sgx_encl_page *sgx_encl_reserve_page(struct sgx_encl *encl,
+					    unsigned long addr);
+
+struct sgx_epc_page *sgx_alloc_va_page(void);
+unsigned int sgx_alloc_va_slot(struct sgx_va_page *va_page);
+void sgx_free_va_slot(struct sgx_va_page *va_page, unsigned int offset);
+bool sgx_va_page_full(struct sgx_va_page *va_page);
+
 #endif /* _X86_ENCL_H */
diff --git a/arch/x86/kernel/cpu/sgx/ioctl.c b/arch/x86/kernel/cpu/sgx/ioctl.c
index 4227bca7b477..4264dc8c2a4f 100644
--- a/arch/x86/kernel/cpu/sgx/ioctl.c
+++ b/arch/x86/kernel/cpu/sgx/ioctl.c
@@ -19,6 +19,43 @@
 /* A per-cpu cache for the last known values of IA32_SGXLEPUBKEYHASHx MSRs. */
 static DEFINE_PER_CPU(u64 [4], sgx_lepubkeyhash_cache);
 
+static struct sgx_va_page *sgx_encl_grow(struct sgx_encl *encl)
+{
+	struct sgx_va_page *va_page = NULL;
+	void *err;
+
+	BUILD_BUG_ON(SGX_VA_SLOT_COUNT !=
+		(SGX_ENCL_PAGE_VA_OFFSET_MASK >> 3) + 1);
+
+	if (!(encl->page_cnt % SGX_VA_SLOT_COUNT)) {
+		va_page = kzalloc(sizeof(*va_page), GFP_KERNEL);
+		if (!va_page)
+			return ERR_PTR(-ENOMEM);
+
+		va_page->epc_page = sgx_alloc_va_page();
+		if (IS_ERR(va_page->epc_page)) {
+			err = ERR_CAST(va_page->epc_page);
+			kfree(va_page);
+			return err;
+		}
+
+		WARN_ON_ONCE(encl->page_cnt % SGX_VA_SLOT_COUNT);
+	}
+	encl->page_cnt++;
+	return va_page;
+}
+
+static void sgx_encl_shrink(struct sgx_encl *encl, struct sgx_va_page *va_page)
+{
+	encl->page_cnt--;
+
+	if (va_page) {
+		sgx_free_epc_page(va_page->epc_page);
+		list_del(&va_page->list);
+		kfree(va_page);
+	}
+}
+
 static u32 sgx_calc_ssa_frame_size(u32 miscselect, u64 xfrm)
 {
 	u32 size_max = PAGE_SIZE;
@@ -86,24 +123,34 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
 {
 	unsigned long encl_size = secs->size + PAGE_SIZE;
 	struct sgx_epc_page *secs_epc;
+	struct sgx_va_page *va_page;
 	struct sgx_pageinfo pginfo;
 	struct sgx_secinfo secinfo;
 	struct file *backing;
 	long ret;
 
+	va_page = sgx_encl_grow(encl);
+	if (IS_ERR(va_page))
+		return PTR_ERR(va_page);
+	else if (va_page)
+		list_add(&va_page->list, &encl->va_pages);
+
 	if (sgx_validate_secs(secs)) {
 		pr_debug("invalid SECS\n");
-		return -EINVAL;
+		ret = -EINVAL;
+		goto err_out_shrink;
 	}
 
 	backing = shmem_file_setup("SGX backing", encl_size + (encl_size >> 5),
 				   VM_NORESERVE);
-	if (IS_ERR(backing))
-		return PTR_ERR(backing);
+	if (IS_ERR(backing)) {
+		ret = PTR_ERR(backing);
+		goto err_out_shrink;
+	}
 
 	encl->backing = backing;
 
-	secs_epc = __sgx_alloc_epc_page();
+	secs_epc = sgx_alloc_epc_page(&encl->secs, true);
 	if (IS_ERR(secs_epc)) {
 		ret = PTR_ERR(secs_epc);
 		goto err_out_backing;
@@ -151,6 +198,9 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
 	fput(encl->backing);
 	encl->backing = NULL;
 
+err_out_shrink:
+	sgx_encl_shrink(encl, va_page);
+
 	return ret;
 }
 
@@ -323,21 +373,35 @@ static int sgx_encl_add_page(struct sgx_encl *encl, unsigned long src,
 {
 	struct sgx_encl_page *encl_page;
 	struct sgx_epc_page *epc_page;
+	struct sgx_va_page *va_page;
 	int ret;
 
 	encl_page = sgx_encl_page_alloc(encl, offset, secinfo->flags);
 	if (IS_ERR(encl_page))
 		return PTR_ERR(encl_page);
 
-	epc_page = __sgx_alloc_epc_page();
+	epc_page = sgx_alloc_epc_page(encl_page, true);
 	if (IS_ERR(epc_page)) {
 		kfree(encl_page);
 		return PTR_ERR(epc_page);
 	}
 
+	va_page = sgx_encl_grow(encl);
+	if (IS_ERR(va_page)) {
+		ret = PTR_ERR(va_page);
+		goto err_out_free;
+	}
+
 	mmap_read_lock(current->mm);
 	mutex_lock(&encl->lock);
 
+	/*
+	 * Adding to encl->va_pages must be done under encl->lock.  Ditto for
+	 * deleting (via sgx_encl_shrink()) in the error path.
+	 */
+	if (va_page)
+		list_add(&va_page->list, &encl->va_pages);
+
 	/*
 	 * Insert prior to EADD in case of OOM.  EADD modifies MRENCLAVE, i.e.
 	 * can't be gracefully unwound, while failure on EADD/EXTEND is limited
@@ -368,6 +432,7 @@ static int sgx_encl_add_page(struct sgx_encl *encl, unsigned long src,
 			goto err_out;
 	}
 
+	sgx_mark_page_reclaimable(encl_page->epc_page);
 	mutex_unlock(&encl->lock);
 	mmap_read_unlock(current->mm);
 	return ret;
@@ -376,9 +441,11 @@ static int sgx_encl_add_page(struct sgx_encl *encl, unsigned long src,
 	xa_erase(&encl->page_array, PFN_DOWN(encl_page->desc));
 
 err_out_unlock:
+	sgx_encl_shrink(encl, va_page);
 	mutex_unlock(&encl->lock);
 	mmap_read_unlock(current->mm);
 
+err_out_free:
 	sgx_free_epc_page(epc_page);
 	kfree(encl_page);
 
diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
index 4137254fb29e..3594d37d545f 100644
--- a/arch/x86/kernel/cpu/sgx/main.c
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -16,6 +16,378 @@
 struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
 static int sgx_nr_epc_sections;
 static struct task_struct *ksgxswapd_tsk;
+static DECLARE_WAIT_QUEUE_HEAD(ksgxswapd_waitq);
+static LIST_HEAD(sgx_active_page_list);
+static DEFINE_SPINLOCK(sgx_active_page_list_lock);
+
+/**
+ * sgx_mark_page_reclaimable() - Mark a page as reclaimable
+ * @page:	EPC page
+ *
+ * Mark a page as reclaimable and add it to the active page list. Pages
+ * are automatically removed from the active list when freed.
+ */
+void sgx_mark_page_reclaimable(struct sgx_epc_page *page)
+{
+	spin_lock(&sgx_active_page_list_lock);
+	page->desc |= SGX_EPC_PAGE_RECLAIMABLE;
+	list_add_tail(&page->list, &sgx_active_page_list);
+	spin_unlock(&sgx_active_page_list_lock);
+}
+
+/**
+ * sgx_unmark_page_reclaimable() - Remove a page from the reclaim list
+ * @page:	EPC page
+ *
+ * Clear the reclaimable flag and remove the page from the active page list.
+ *
+ * Return:
+ *   0 on success,
+ *   -EBUSY if the page is in the process of being reclaimed
+ */
+int sgx_unmark_page_reclaimable(struct sgx_epc_page *page)
+{
+	/*
+	 * Remove the page from the active list if necessary.  If the page
+	 * is actively being reclaimed, i.e. RECLAIMABLE is set but the
+	 * page isn't on the active list, return -EBUSY as we can't free
+	 * the page at this time since it is "owned" by the reclaimer.
+	 */
+	spin_lock(&sgx_active_page_list_lock);
+	if (page->desc & SGX_EPC_PAGE_RECLAIMABLE) {
+		if (list_empty(&page->list)) {
+			spin_unlock(&sgx_active_page_list_lock);
+			return -EBUSY;
+		}
+		list_del(&page->list);
+		page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
+	}
+	spin_unlock(&sgx_active_page_list_lock);
+
+	return 0;
+}
+
+static bool sgx_reclaimer_age(struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *page = epc_page->owner;
+	struct sgx_encl *encl = page->encl;
+	struct sgx_encl_mm *encl_mm;
+	bool ret = true;
+	int idx;
+
+	idx = srcu_read_lock(&encl->srcu);
+
+	list_for_each_entry_rcu(encl_mm, &encl->mm_list, list) {
+		if (!mmget_not_zero(encl_mm->mm))
+			continue;
+
+		mmap_read_lock(encl_mm->mm);
+		ret = !sgx_encl_test_and_clear_young(encl_mm->mm, page);
+		mmap_read_unlock(encl_mm->mm);
+
+		mmput_async(encl_mm->mm);
+
+		if (!ret || (atomic_read(&encl->flags) & SGX_ENCL_DEAD))
+			break;
+	}
+
+	srcu_read_unlock(&encl->srcu, idx);
+
+	if (!ret && !(atomic_read(&encl->flags) & SGX_ENCL_DEAD))
+		return false;
+
+	return true;
+}
+
+static void sgx_reclaimer_block(struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *page = epc_page->owner;
+	unsigned long addr = SGX_ENCL_PAGE_ADDR(page);
+	struct sgx_encl *encl = page->encl;
+	unsigned long mm_list_version;
+	struct sgx_encl_mm *encl_mm;
+	struct vm_area_struct *vma;
+	int idx, ret;
+
+	do {
+		mm_list_version = encl->mm_list_version;
+
+		/* Pairs with smp_rmb() in sgx_encl_mm_add(). */
+		smp_rmb();
+
+		idx = srcu_read_lock(&encl->srcu);
+
+		list_for_each_entry_rcu(encl_mm, &encl->mm_list, list) {
+			if (!mmget_not_zero(encl_mm->mm))
+				continue;
+
+			mmap_read_lock(encl_mm->mm);
+
+			ret = sgx_encl_find(encl_mm->mm, addr, &vma);
+			if (!ret && encl == vma->vm_private_data)
+				zap_vma_ptes(vma, addr, PAGE_SIZE);
+
+			mmap_read_unlock(encl_mm->mm);
+
+			mmput_async(encl_mm->mm);
+		}
+
+		srcu_read_unlock(&encl->srcu, idx);
+	} while (unlikely(encl->mm_list_version != mm_list_version));
+
+	mutex_lock(&encl->lock);
+
+	if (!(atomic_read(&encl->flags) & SGX_ENCL_DEAD)) {
+		ret = __eblock(sgx_get_epc_addr(epc_page));
+		if (encls_failed(ret))
+			ENCLS_WARN(ret, "EBLOCK");
+	}
+
+	mutex_unlock(&encl->lock);
+}
+
+static int __sgx_encl_ewb(struct sgx_epc_page *epc_page, void *va_slot,
+			  struct sgx_backing *backing)
+{
+	struct sgx_pageinfo pginfo;
+	int ret;
+
+	pginfo.addr = 0;
+	pginfo.secs = 0;
+
+	pginfo.contents = (unsigned long)kmap_atomic(backing->contents);
+	pginfo.metadata = (unsigned long)kmap_atomic(backing->pcmd) +
+			  backing->pcmd_offset;
+
+	ret = __ewb(&pginfo, sgx_get_epc_addr(epc_page), va_slot);
+
+	kunmap_atomic((void *)(unsigned long)(pginfo.metadata -
+					      backing->pcmd_offset));
+	kunmap_atomic((void *)(unsigned long)pginfo.contents);
+
+	return ret;
+}
+
+static void sgx_ipi_cb(void *info)
+{
+}
+
+static const cpumask_t *sgx_encl_ewb_cpumask(struct sgx_encl *encl)
+{
+	cpumask_t *cpumask = &encl->cpumask;
+	struct sgx_encl_mm *encl_mm;
+	int idx;
+
+	/*
+	 * Can race with sgx_encl_mm_add(), but ETRACK has already been
+	 * executed, which means that the CPUs running in the new mm will enter
+	 * into the enclave with a fresh epoch.
+	 */
+	cpumask_clear(cpumask);
+
+	idx = srcu_read_lock(&encl->srcu);
+
+	list_for_each_entry_rcu(encl_mm, &encl->mm_list, list) {
+		if (!mmget_not_zero(encl_mm->mm))
+			continue;
+
+		cpumask_or(cpumask, cpumask, mm_cpumask(encl_mm->mm));
+
+		mmput_async(encl_mm->mm);
+	}
+
+	srcu_read_unlock(&encl->srcu, idx);
+
+	return cpumask;
+}
+
+static void sgx_encl_ewb(struct sgx_epc_page *epc_page,
+			 struct sgx_backing *backing)
+{
+	struct sgx_encl_page *encl_page = epc_page->owner;
+	struct sgx_encl *encl = encl_page->encl;
+	struct sgx_va_page *va_page;
+	unsigned int va_offset;
+	void *va_slot;
+	int ret;
+
+	encl_page->desc &= ~SGX_ENCL_PAGE_RECLAIMED;
+
+	va_page = list_first_entry(&encl->va_pages, struct sgx_va_page,
+				   list);
+	va_offset = sgx_alloc_va_slot(va_page);
+	va_slot = sgx_get_epc_addr(va_page->epc_page) + va_offset;
+	if (sgx_va_page_full(va_page))
+		list_move_tail(&va_page->list, &encl->va_pages);
+
+	ret = __sgx_encl_ewb(epc_page, va_slot, backing);
+	if (ret == SGX_NOT_TRACKED) {
+		ret = __etrack(sgx_get_epc_addr(encl->secs.epc_page));
+		if (ret) {
+			if (encls_failed(ret))
+				ENCLS_WARN(ret, "ETRACK");
+		}
+
+		ret = __sgx_encl_ewb(epc_page, va_slot, backing);
+		if (ret == SGX_NOT_TRACKED) {
+			/*
+			 * Slow path, send IPIs to kick cpus out of the
+			 * enclave.  Note, it's imperative that the cpu
+			 * mask is generated *after* ETRACK, else we'll
+			 * miss cpus that entered the enclave between
+			 * generating the mask and incrementing epoch.
+			 */
+			on_each_cpu_mask(sgx_encl_ewb_cpumask(encl),
+					 sgx_ipi_cb, NULL, 1);
+			ret = __sgx_encl_ewb(epc_page, va_slot, backing);
+		}
+	}
+
+	if (ret) {
+		if (encls_failed(ret))
+			ENCLS_WARN(ret, "EWB");
+
+		sgx_free_va_slot(va_page, va_offset);
+	} else {
+		encl_page->desc |= va_offset;
+		encl_page->va_page = va_page;
+	}
+}
+
+static void sgx_reclaimer_write(struct sgx_epc_page *epc_page,
+				struct sgx_backing *backing)
+{
+	struct sgx_encl_page *encl_page = epc_page->owner;
+	struct sgx_encl *encl = encl_page->encl;
+	struct sgx_backing secs_backing;
+	int ret;
+
+	mutex_lock(&encl->lock);
+
+	if (atomic_read(&encl->flags) & SGX_ENCL_DEAD) {
+		ret = __eremove(sgx_get_epc_addr(epc_page));
+		ENCLS_WARN(ret, "EREMOVE");
+	} else {
+		sgx_encl_ewb(epc_page, backing);
+	}
+
+	encl_page->epc_page = NULL;
+	encl->secs_child_cnt--;
+
+	if (!encl->secs_child_cnt) {
+		if (atomic_read(&encl->flags) & SGX_ENCL_DEAD) {
+			sgx_free_epc_page(encl->secs.epc_page);
+			encl->secs.epc_page = NULL;
+		} else if (atomic_read(&encl->flags) & SGX_ENCL_INITIALIZED) {
+			ret = sgx_encl_get_backing(encl, PFN_DOWN(encl->size),
+						   &secs_backing);
+			if (ret)
+				goto out;
+
+			sgx_encl_ewb(encl->secs.epc_page, &secs_backing);
+
+			sgx_free_epc_page(encl->secs.epc_page);
+			encl->secs.epc_page = NULL;
+
+			sgx_encl_put_backing(&secs_backing, true);
+		}
+	}
+
+out:
+	mutex_unlock(&encl->lock);
+}
+
+/*
+ * Take a fixed number of pages from the head of the active page pool and
+ * reclaim them to the enclave's private shmem files. Skip the pages, which have
+ * been accessed since the last scan. Move those pages to the tail of active
+ * page pool so that the pages get scanned in LRU like fashion.
+ */
+static void sgx_reclaim_pages(void)
+{
+	struct sgx_epc_page *chunk[SGX_NR_TO_SCAN];
+	struct sgx_backing backing[SGX_NR_TO_SCAN];
+	struct sgx_epc_section *section;
+	struct sgx_encl_page *encl_page;
+	struct sgx_epc_page *epc_page;
+	int cnt = 0;
+	int ret;
+	int i;
+
+	spin_lock(&sgx_active_page_list_lock);
+	for (i = 0; i < SGX_NR_TO_SCAN; i++) {
+		if (list_empty(&sgx_active_page_list))
+			break;
+
+		epc_page = list_first_entry(&sgx_active_page_list,
+					    struct sgx_epc_page, list);
+		list_del_init(&epc_page->list);
+		encl_page = epc_page->owner;
+
+		if (kref_get_unless_zero(&encl_page->encl->refcount) != 0)
+			chunk[cnt++] = epc_page;
+		else
+			/* The owner is freeing the page. No need to add the
+			 * page back to the list of reclaimable pages.
+			 */
+			epc_page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
+	}
+	spin_unlock(&sgx_active_page_list_lock);
+
+	for (i = 0; i < cnt; i++) {
+		epc_page = chunk[i];
+		encl_page = epc_page->owner;
+
+		if (!sgx_reclaimer_age(epc_page))
+			goto skip;
+
+		ret = sgx_encl_get_backing(encl_page->encl,
+					   SGX_ENCL_PAGE_INDEX(encl_page),
+					   &backing[i]);
+		if (ret)
+			goto skip;
+
+		mutex_lock(&encl_page->encl->lock);
+		encl_page->desc |= SGX_ENCL_PAGE_RECLAIMED;
+		mutex_unlock(&encl_page->encl->lock);
+		continue;
+
+skip:
+		spin_lock(&sgx_active_page_list_lock);
+		list_add_tail(&epc_page->list, &sgx_active_page_list);
+		spin_unlock(&sgx_active_page_list_lock);
+
+		kref_put(&encl_page->encl->refcount, sgx_encl_release);
+
+		chunk[i] = NULL;
+	}
+
+	for (i = 0; i < cnt; i++) {
+		epc_page = chunk[i];
+		if (epc_page)
+			sgx_reclaimer_block(epc_page);
+	}
+
+	for (i = 0; i < cnt; i++) {
+		epc_page = chunk[i];
+		if (!epc_page)
+			continue;
+
+		encl_page = epc_page->owner;
+		sgx_reclaimer_write(epc_page, &backing[i]);
+		sgx_encl_put_backing(&backing[i], true);
+
+		kref_put(&encl_page->encl->refcount, sgx_encl_release);
+		epc_page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
+
+		section = sgx_get_epc_section(epc_page);
+		spin_lock(&section->lock);
+		list_add_tail(&epc_page->list, &section->page_list);
+		section->free_cnt++;
+		spin_unlock(&section->lock);
+	}
+}
+
 
 static void sgx_sanitize_section(struct sgx_epc_section *section)
 {
@@ -44,6 +416,23 @@ static void sgx_sanitize_section(struct sgx_epc_section *section)
 	}
 }
 
+static unsigned long sgx_nr_free_pages(void)
+{
+	unsigned long cnt = 0;
+	int i;
+
+	for (i = 0; i < sgx_nr_epc_sections; i++)
+		cnt += sgx_epc_sections[i].free_cnt;
+
+	return cnt;
+}
+
+static bool sgx_should_reclaim(unsigned long watermark)
+{
+	return sgx_nr_free_pages() < watermark &&
+	       !list_empty(&sgx_active_page_list);
+}
+
 static int ksgxswapd(void *p)
 {
 	int i;
@@ -69,6 +458,20 @@ static int ksgxswapd(void *p)
 			WARN(1, "EPC section %d has unsanitized pages.\n", i);
 	}
 
+	while (!kthread_should_stop()) {
+		if (try_to_freeze())
+			continue;
+
+		wait_event_freezable(ksgxswapd_waitq,
+				     kthread_should_stop() ||
+				     sgx_should_reclaim(SGX_NR_HIGH_PAGES));
+
+		if (sgx_should_reclaim(SGX_NR_HIGH_PAGES))
+			sgx_reclaim_pages();
+
+		cond_resched();
+	}
+
 	return 0;
 }
 
@@ -94,6 +497,7 @@ static struct sgx_epc_page *__sgx_alloc_epc_page_from_section(struct sgx_epc_sec
 
 	page = list_first_entry(&section->page_list, struct sgx_epc_page, list);
 	list_del_init(&page->list);
+	section->free_cnt--;
 
 	return page;
 }
@@ -127,6 +531,57 @@ struct sgx_epc_page *__sgx_alloc_epc_page(void)
 	return ERR_PTR(-ENOMEM);
 }
 
+/**
+ * sgx_alloc_epc_page() - Allocate an EPC page
+ * @owner:	the owner of the EPC page
+ * @reclaim:	reclaim pages if necessary
+ *
+ * Iterate through EPC sections and borrow a free EPC page to the caller. When a
+ * page is no longer needed it must be released with sgx_free_epc_page(). If
+ * @reclaim is set to true, directly reclaim pages when we are out of pages. No
+ * mm's can be locked when @reclaim is set to true.
+ *
+ * Finally, wake up ksgxswapd when the number of pages goes below the watermark
+ * before returning back to the caller.
+ *
+ * Return:
+ *   an EPC page,
+ *   -errno on error
+ */
+struct sgx_epc_page *sgx_alloc_epc_page(void *owner, bool reclaim)
+{
+	struct sgx_epc_page *entry;
+
+	for ( ; ; ) {
+		entry = __sgx_alloc_epc_page();
+		if (!IS_ERR(entry)) {
+			entry->owner = owner;
+			break;
+		}
+
+		if (list_empty(&sgx_active_page_list))
+			return ERR_PTR(-ENOMEM);
+
+		if (!reclaim) {
+			entry = ERR_PTR(-EBUSY);
+			break;
+		}
+
+		if (signal_pending(current)) {
+			entry = ERR_PTR(-ERESTARTSYS);
+			break;
+		}
+
+		sgx_reclaim_pages();
+		schedule();
+	}
+
+	if (sgx_should_reclaim(SGX_NR_LOW_PAGES))
+		wake_up(&ksgxswapd_waitq);
+
+	return entry;
+}
+
 /**
  * sgx_free_epc_page() - Free an EPC page
  * @page:	an EPC page
@@ -138,12 +593,20 @@ void sgx_free_epc_page(struct sgx_epc_page *page)
 	struct sgx_epc_section *section = sgx_get_epc_section(page);
 	int ret;
 
+	/*
+	 * Don't take sgx_active_page_list_lock when asserting the page isn't
+	 * reclaimable, missing a WARN in the very rare case is preferable to
+	 * unnecessarily taking a global lock in the common case.
+	 */
+	WARN_ON_ONCE(page->desc & SGX_EPC_PAGE_RECLAIMABLE);
+
 	ret = __eremove(sgx_get_epc_addr(page));
 	if (WARN_ONCE(ret, "EREMOVE returned %d (0x%x)", ret, ret))
 		return;
 
 	spin_lock(&section->lock);
 	list_add_tail(&page->list, &section->page_list);
+	section->free_cnt++;
 	spin_unlock(&section->lock);
 }
 
@@ -194,6 +657,7 @@ static bool __init sgx_setup_epc_section(u64 addr, u64 size,
 		list_add_tail(&page->list, &section->unsanitized_page_list);
 	}
 
+	section->free_cnt = nr_pages;
 	return true;
 
 err_out:
diff --git a/arch/x86/kernel/cpu/sgx/sgx.h b/arch/x86/kernel/cpu/sgx/sgx.h
index 8d126070db1e..ec4f7b338dbe 100644
--- a/arch/x86/kernel/cpu/sgx/sgx.h
+++ b/arch/x86/kernel/cpu/sgx/sgx.h
@@ -15,6 +15,7 @@
 
 struct sgx_epc_page {
 	unsigned long desc;
+	struct sgx_encl_page *owner;
 	struct list_head list;
 };
 
@@ -27,6 +28,7 @@ struct sgx_epc_page {
 struct sgx_epc_section {
 	unsigned long pa;
 	void *va;
+	unsigned long free_cnt;
 	struct list_head page_list;
 	struct list_head unsanitized_page_list;
 	spinlock_t lock;
@@ -35,6 +37,10 @@ struct sgx_epc_section {
 #define SGX_EPC_SECTION_MASK		GENMASK(7, 0)
 #define SGX_MAX_EPC_SECTIONS		(SGX_EPC_SECTION_MASK + 1)
 #define SGX_MAX_ADD_PAGES_LENGTH	0x100000
+#define SGX_EPC_PAGE_RECLAIMABLE	BIT(8)
+#define SGX_NR_TO_SCAN			16
+#define SGX_NR_LOW_PAGES		32
+#define SGX_NR_HIGH_PAGES		64
 
 extern struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
 
@@ -50,7 +56,10 @@ static inline void *sgx_get_epc_addr(struct sgx_epc_page *page)
 	return section->va + (page->desc & PAGE_MASK) - section->pa;
 }
 
+void sgx_mark_page_reclaimable(struct sgx_epc_page *page);
+int sgx_unmark_page_reclaimable(struct sgx_epc_page *page);
 struct sgx_epc_page *__sgx_alloc_epc_page(void);
+struct sgx_epc_page *sgx_alloc_epc_page(void *owner, bool reclaim);
 void sgx_free_epc_page(struct sgx_epc_page *page);
 
 #endif /* _X86_SGX_H */
-- 
2.25.1



^ permalink raw reply related	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-15 11:28 ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Jarkko Sakkinen
@ 2020-09-18 12:44   ` Borislav Petkov
  2020-09-18 15:09   ` Andy Lutomirski
  1 sibling, 0 replies; 81+ messages in thread
From: Borislav Petkov @ 2020-09-18 12:44 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: x86, linux-sgx, linux-kernel, Sean Christopherson, linux-mm,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	andriy.shevchenko, asapek, cedric.xing, chenalexchen,
	conradparker, cyhanish, dave.hansen, haitao.huang, josh,
	kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman, npmccallum,
	puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 15, 2020 at 02:28:28PM +0300, Jarkko Sakkinen wrote:
> From: Sean Christopherson <sean.j.christopherson@intel.com>
> 
> Add vm_ops()->mprotect() for additional constraints for a VMA.
> 
> Intel Software Guard eXtensions (SGX) will use this callback to add two
> constraints:
> 
> 1. Verify that the address range does not have holes: each page address
>    must be filled with an enclave page.
> 2. Verify that VMA permissions won't surpass the permissions of any enclave
>    page within the address range. Enclave cryptographically sealed
>    permissions for each page address that set the upper limit for possible
>    VMA permissions. Not respecting this can cause #GP's to be emitted.
> 
> Cc: linux-mm@kvack.org
> Cc: Andrew Morton <akpm@linux-foundation.org>
> Cc: Matthew Wilcox <willy@infradead.org>
> Acked-by: Jethro Beekman <jethro@fortanix.com>
> Reviewed-by: Darren Kenny <darren.kenny@oracle.com>
> Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
> Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
> Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
> ---
>  include/linux/mm.h | 3 +++
>  mm/mprotect.c      | 5 ++++-
>  2 files changed, 7 insertions(+), 1 deletion(-)

Needs an ACK from an mm person.

-- 
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-15 11:28 ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Jarkko Sakkinen
  2020-09-18 12:44   ` Borislav Petkov
@ 2020-09-18 15:09   ` Andy Lutomirski
  2020-09-18 23:24     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect()' Jarkko Sakkinen
  2020-09-18 23:53     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Sean Christopherson
  1 sibling, 2 replies; 81+ messages in thread
From: Andy Lutomirski @ 2020-09-18 15:09 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: X86 ML, linux-sgx, LKML, Sean Christopherson, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Andrew Lutomirski, Neil Horman,
	Nathaniel McCallum, Patrick Uiterwijk, David Rientjes,
	Thomas Gleixner, yaozhangx

On Tue, Sep 15, 2020 at 4:28 AM Jarkko Sakkinen
<jarkko.sakkinen@linux.intel.com> wrote:
>
> From: Sean Christopherson <sean.j.christopherson@intel.com>
>
> Add vm_ops()->mprotect() for additional constraints for a VMA.
>
> Intel Software Guard eXtensions (SGX) will use this callback to add two
> constraints:
>
> 1. Verify that the address range does not have holes: each page address
>    must be filled with an enclave page.
> 2. Verify that VMA permissions won't surpass the permissions of any enclave
>    page within the address range. Enclave cryptographically sealed
>    permissions for each page address that set the upper limit for possible
>    VMA permissions. Not respecting this can cause #GP's to be emitted.

It's been awhile since I looked at this.  Can you remind us: is this
just preventing userspace from shooting itself in the foot or is this
something more important?

--Andy


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()'
  2020-09-18 15:09   ` Andy Lutomirski
@ 2020-09-18 23:24     ` Jarkko Sakkinen
  2020-09-18 23:53     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Sean Christopherson
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-18 23:24 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: X86 ML, linux-sgx, LKML, Sean Christopherson, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Fri, Sep 18, 2020 at 08:09:04AM -0700, Andy Lutomirski wrote:
> On Tue, Sep 15, 2020 at 4:28 AM Jarkko Sakkinen
> <jarkko.sakkinen@linux.intel.com> wrote:
> >
> > From: Sean Christopherson <sean.j.christopherson@intel.com>
> >
> > Add vm_ops()->mprotect() for additional constraints for a VMA.
> >
> > Intel Software Guard eXtensions (SGX) will use this callback to add two
> > constraints:
> >
> > 1. Verify that the address range does not have holes: each page address
> >    must be filled with an enclave page.
> > 2. Verify that VMA permissions won't surpass the permissions of any enclave
> >    page within the address range. Enclave cryptographically sealed
> >    permissions for each page address that set the upper limit for possible
> >    VMA permissions. Not respecting this can cause #GP's to be emitted.
> 
> It's been awhile since I looked at this.  Can you remind us: is this
> just preventing userspace from shooting itself in the foot or is this
> something more important?
> 
> --Andy

Haitao found this:

https://patchwork.kernel.org/patch/10978327/

The way I understand it, for an LSM hook it makes sense that the
mprotect() can deduce a single permission for an enclave address range.
With those constraints it is possible.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-18 15:09   ` Andy Lutomirski
  2020-09-18 23:24     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect()' Jarkko Sakkinen
@ 2020-09-18 23:53     ` Sean Christopherson
  2020-09-19  0:15       ` Andy Lutomirski
  2020-09-21 12:49       ` Jarkko Sakkinen
  1 sibling, 2 replies; 81+ messages in thread
From: Sean Christopherson @ 2020-09-18 23:53 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jarkko Sakkinen, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Fri, Sep 18, 2020 at 08:09:04AM -0700, Andy Lutomirski wrote:
> On Tue, Sep 15, 2020 at 4:28 AM Jarkko Sakkinen
> <jarkko.sakkinen@linux.intel.com> wrote:
> >
> > From: Sean Christopherson <sean.j.christopherson@intel.com>
> >
> > Add vm_ops()->mprotect() for additional constraints for a VMA.
> >
> > Intel Software Guard eXtensions (SGX) will use this callback to add two
> > constraints:
> >
> > 1. Verify that the address range does not have holes: each page address
> >    must be filled with an enclave page.
> > 2. Verify that VMA permissions won't surpass the permissions of any enclave
> >    page within the address range. Enclave cryptographically sealed
> >    permissions for each page address that set the upper limit for possible
> >    VMA permissions. Not respecting this can cause #GP's to be emitted.

Side note, #GP is wrong.  EPCM violations are #PFs.  Skylake CPUs #GP, but
that's technically an errata.  But this isn't the real motivation, e.g.
userspace can already trigger #GP/#PF by reading/writing a bad address, SGX
simply adds another flavor.

> It's been awhile since I looked at this.  Can you remind us: is this
> just preventing userspace from shooting itself in the foot or is this
> something more important?

Something more important, it's used to prevent userspace from circumventing
a noexec filesystem by loading code into an enclave, and to give the kernel the
option of adding enclave specific LSM policies in the future.

The source file (if one exists) for the enclave is long gone when the enclave
is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
permissions for a given page are snapshotted when the page is added to the
enclave, i.e. when the enclave is built.  Enclave pages that will be executable
must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
noexec file system.

The ->mprotect() hook allows SGX to reject mprotect() if userspace is declaring
permissions beyond what are allowed, e.g. trying to map an enclave page with
EXEC permissions when the page was added to the enclave without EXEC.

Future LSM policies have a similar need due to vm_file always pointing at
/dev/sgx/enclave, e.g. policies couldn't be attached to a specific enclave.
->mprotect() again allows enforcing permissions at map time that were checked
at enclave build time, e.g. via an LSM hook.

Deferring ->mprotect() until LSM support is added (if it ever is) would be
problematic due to SGX2.  With SGX2, userspace can extend permissions of an
enclave page (for the CPU's EPC Map entry, not the kernel's page tables)
without bouncing through the kernel.  Without ->mprotect () enforcement.
userspace could do EADD(RW) -> mprotect(RWX) -> EMODPE(X) to gain W+X.  We
want to disallow such a flow now, i.e. force userspace to do EADD(RW,X), so
that the hypothetical LSM hook would have all information at EADD(), i.e.
would be aware of the EXEC permission, without creating divergent behavior
based on whether or not an LSM is active.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-18 23:53     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Sean Christopherson
@ 2020-09-19  0:15       ` Andy Lutomirski
  2020-09-22 12:58         ` Jarkko Sakkinen
  2020-09-21 12:49       ` Jarkko Sakkinen
  1 sibling, 1 reply; 81+ messages in thread
From: Andy Lutomirski @ 2020-09-19  0:15 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Jarkko Sakkinen, X86 ML, linux-sgx, LKML,
	Linux-MM, Andrew Morton, Matthew Wilcox, Jethro Beekman,
	Darren Kenny, Andy Shevchenko, asapek, Borislav Petkov, Xing,
	Cedric, chenalexchen, Conrad Parker, cyhanish, Dave Hansen,
	Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx


> On Sep 18, 2020, at 4:53 PM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> 
> On Fri, Sep 18, 2020 at 08:09:04AM -0700, Andy Lutomirski wrote:
>>> On Tue, Sep 15, 2020 at 4:28 AM Jarkko Sakkinen
>>> <jarkko.sakkinen@linux.intel.com> wrote:
>>> 
>>> From: Sean Christopherson <sean.j.christopherson@intel.com>
>>> 
>>> Add vm_ops()->mprotect() for additional constraints for a VMA.
>>> 
>>> Intel Software Guard eXtensions (SGX) will use this callback to add two
>>> constraints:
>>> 
>>> 1. Verify that the address range does not have holes: each page address
>>>   must be filled with an enclave page.
>>> 2. Verify that VMA permissions won't surpass the permissions of any enclave
>>>   page within the address range. Enclave cryptographically sealed
>>>   permissions for each page address that set the upper limit for possible
>>>   VMA permissions. Not respecting this can cause #GP's to be emitted.
> 
> Side note, #GP is wrong.  EPCM violations are #PFs.  Skylake CPUs #GP, but
> that's technically an errata.  But this isn't the real motivation, e.g.
> userspace can already trigger #GP/#PF by reading/writing a bad address, SGX
> simply adds another flavor.
> 
>> It's been awhile since I looked at this.  Can you remind us: is this
>> just preventing userspace from shooting itself in the foot or is this
>> something more important?
> 
> Something more important, it's used to prevent userspace from circumventing
> a noexec filesystem by loading code into an enclave, and to give the kernel the
> option of adding enclave specific LSM policies in the future.
> 
> The source file (if one exists) for the enclave is long gone when the enclave
> is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> permissions for a given page are snapshotted when the page is added to the
> enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> noexec file system.
> 
> The ->mprotect() hook allows SGX to reject mprotect() if userspace is declaring
> permissions beyond what are allowed, e.g. trying to map an enclave page with
> EXEC permissions when the page was added to the enclave without EXEC.
> 
> Future LSM policies have a similar need due to vm_file always pointing at
> /dev/sgx/enclave, e.g. policies couldn't be attached to a specific enclave.
> ->mprotect() again allows enforcing permissions at map time that were checked
> at enclave build time, e.g. via an LSM hook.
> 
> Deferring ->mprotect() until LSM support is added (if it ever is) would be
> problematic due to SGX2.  With SGX2, userspace can extend permissions of an
> enclave page (for the CPU's EPC Map entry, not the kernel's page tables)
> without bouncing through the kernel.  Without ->mprotect () enforcement.
> userspace could do EADD(RW) -> mprotect(RWX) -> EMODPE(X) to gain W+X.  We
> want to disallow such a flow now, i.e. force userspace to do EADD(RW,X), so
> that the hypothetical LSM hook would have all information at EADD(), i.e.
> would be aware of the EXEC permission, without creating divergent behavior
> based on whether or not an LSM is active.

That’s what I thought. Can we get this in the changelog?

^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 11/24] x86/sgx: Add SGX enclave driver
  2020-09-15 11:28 ` [PATCH v38 11/24] x86/sgx: Add SGX enclave driver Jarkko Sakkinen
@ 2020-09-21  9:30   ` Borislav Petkov
  2020-09-21 12:09     ` Jarkko Sakkinen
  2020-10-01 17:36   ` Sean Christopherson
  1 sibling, 1 reply; 81+ messages in thread
From: Borislav Petkov @ 2020-09-21  9:30 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: x86, linux-sgx, linux-kernel, linux-security-module, linux-mm,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Haitao Huang,
	Chunyang Hui, Jordan Hand, Nathaniel McCallum, Seth Moore,
	Darren Kenny, Sean Christopherson, Suresh Siddha,
	andriy.shevchenko, asapek, cedric.xing, chenalexchen,
	conradparker, cyhanish, dave.hansen, haitao.huang, josh,
	kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman, puiterwijk,
	rientjes, tglx, yaozhangx

On Tue, Sep 15, 2020 at 02:28:29PM +0300, Jarkko Sakkinen wrote:
> Intel Software Guard eXtensions (SGX) is a set of CPU instructions that can
> be used by applications to set aside private regions of code and data. The
> code outside the SGX hosted software entity is prevented from accessing the
> memory inside the enclave by the CPU. We call these entities as enclaves.

It was correct before:

-memory inside the enclave by the CPU. We call these entities enclaves.
+memory inside the enclave by the CPU. We call these entities as enclaves.

"as " is not needed.

-- 
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 11/24] x86/sgx: Add SGX enclave driver
  2020-09-21  9:30   ` Borislav Petkov
@ 2020-09-21 12:09     ` Jarkko Sakkinen
  0 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-21 12:09 UTC (permalink / raw)
  To: Borislav Petkov
  Cc: x86, linux-sgx, linux-kernel, linux-security-module, linux-mm,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Haitao Huang,
	Chunyang Hui, Jordan Hand, Nathaniel McCallum, Seth Moore,
	Darren Kenny, Sean Christopherson, Suresh Siddha,
	andriy.shevchenko, asapek, cedric.xing, chenalexchen,
	conradparker, cyhanish, dave.hansen, haitao.huang, josh,
	kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman, puiterwijk,
	rientjes, tglx, yaozhangx

On Mon, Sep 21, 2020 at 11:30:06AM +0200, Borislav Petkov wrote:
> On Tue, Sep 15, 2020 at 02:28:29PM +0300, Jarkko Sakkinen wrote:
> > Intel Software Guard eXtensions (SGX) is a set of CPU instructions that can
> > be used by applications to set aside private regions of code and data. The
> > code outside the SGX hosted software entity is prevented from accessing the
> > memory inside the enclave by the CPU. We call these entities as enclaves.
> 
> It was correct before:
> 
> -memory inside the enclave by the CPU. We call these entities enclaves.
> +memory inside the enclave by the CPU. We call these entities as enclaves.
> 
> "as " is not needed.

I reworded it. Thank you.

> 
> -- 
> Regards/Gruss,
>     Boris.
> 
> https://people.kernel.org/tglx/notes-about-netiquette

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-18 23:53     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Sean Christopherson
  2020-09-19  0:15       ` Andy Lutomirski
@ 2020-09-21 12:49       ` Jarkko Sakkinen
  2020-09-21 12:51         ` Jarkko Sakkinen
                           ` (2 more replies)
  1 sibling, 3 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-21 12:49 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Fri, Sep 18, 2020 at 04:53:37PM -0700, Sean Christopherson wrote:
> On Fri, Sep 18, 2020 at 08:09:04AM -0700, Andy Lutomirski wrote:
> > On Tue, Sep 15, 2020 at 4:28 AM Jarkko Sakkinen
> > <jarkko.sakkinen@linux.intel.com> wrote:
> > >
> > > From: Sean Christopherson <sean.j.christopherson@intel.com>
> > >
> > > Add vm_ops()->mprotect() for additional constraints for a VMA.
> > >
> > > Intel Software Guard eXtensions (SGX) will use this callback to add two
> > > constraints:
> > >
> > > 1. Verify that the address range does not have holes: each page address
> > >    must be filled with an enclave page.
> > > 2. Verify that VMA permissions won't surpass the permissions of any enclave
> > >    page within the address range. Enclave cryptographically sealed
> > >    permissions for each page address that set the upper limit for possible
> > >    VMA permissions. Not respecting this can cause #GP's to be emitted.
> 
> Side note, #GP is wrong.  EPCM violations are #PFs.  Skylake CPUs #GP, but
> that's technically an errata.  But this isn't the real motivation, e.g.
> userspace can already trigger #GP/#PF by reading/writing a bad address, SGX
> simply adds another flavor.
> 
> > It's been awhile since I looked at this.  Can you remind us: is this
> > just preventing userspace from shooting itself in the foot or is this
> > something more important?
> 
> Something more important, it's used to prevent userspace from circumventing
> a noexec filesystem by loading code into an enclave, and to give the kernel the
> option of adding enclave specific LSM policies in the future.
> 
> The source file (if one exists) for the enclave is long gone when the enclave
> is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> permissions for a given page are snapshotted when the page is added to the
> enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> noexec file system.

noexec check is done in __sgx_encl_add_page(), not in this callback.
sgx_vma_mprotect() calls sgx_encl_may_map(), which iterates the
addresses, checks that permissions are not surpassed and there are
no holes.

> The ->mprotect() hook allows SGX to reject mprotect() if userspace is declaring
> permissions beyond what are allowed, e.g. trying to map an enclave page with
> EXEC permissions when the page was added to the enclave without EXEC.

For my ear this is tautological because if user space would use
differing permissions, it would exactly soot itself in the foot.

What really should be documented is to answer why we consider an enclave
mappable, if and only if the conditions are that I described about
sgx_encl_may_map() functioning.

This is obviously part of the answer [*], i.e. with pharsing LSM hook
requires an enclave to have a state, which is compatible with the mmap
permissions and is fully populated.

The 2nd part of the answer is the answer to the question: why we want to
feed LSM hooks enclaves exactly in this state.

What would you answer to that?

[*] https://lore.kernel.org/linux-sgx/20200918232458.GA6175@linux.intel.com/T/#u

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-21 12:49       ` Jarkko Sakkinen
@ 2020-09-21 12:51         ` Jarkko Sakkinen
  2020-09-21 13:14         ` Jarkko Sakkinen
  2020-09-21 16:57         ` Sean Christopherson
  2 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-21 12:51 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 21, 2020 at 03:49:56PM +0300, Jarkko Sakkinen wrote:
> What really should be documented is to answer why we consider an enclave
                                      ~~
				      the (editing mistake)

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-21 12:49       ` Jarkko Sakkinen
  2020-09-21 12:51         ` Jarkko Sakkinen
@ 2020-09-21 13:14         ` Jarkko Sakkinen
  2020-09-21 16:57         ` Sean Christopherson
  2 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-21 13:14 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 21, 2020 at 03:49:56PM +0300, Jarkko Sakkinen wrote:
> The 2nd part of the answer is the answer to the question: why we want to
> feed LSM hooks enclaves exactly in this state.

The question can be further refined as why: why this is the best
possible set of substates to filter in?

"no holes" part is obvious as the consequence of not surpassing
permissions of any of the pages in range, as you could otherwise
break the state with ioctl(SGX_ENCLAVE_ADD_PAGES) with permssions
that are below the mmap permissions.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-21 12:49       ` Jarkko Sakkinen
  2020-09-21 12:51         ` Jarkko Sakkinen
  2020-09-21 13:14         ` Jarkko Sakkinen
@ 2020-09-21 16:57         ` Sean Christopherson
  2020-09-21 21:07           ` Jarkko Sakkinen
  2 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-21 16:57 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 21, 2020 at 03:49:46PM +0300, Jarkko Sakkinen wrote:
> On Fri, Sep 18, 2020 at 04:53:37PM -0700, Sean Christopherson wrote:
> > On Fri, Sep 18, 2020 at 08:09:04AM -0700, Andy Lutomirski wrote:
> > > On Tue, Sep 15, 2020 at 4:28 AM Jarkko Sakkinen
> > > <jarkko.sakkinen@linux.intel.com> wrote:
> > > >
> > > > From: Sean Christopherson <sean.j.christopherson@intel.com>
> > > >
> > > > Add vm_ops()->mprotect() for additional constraints for a VMA.
> > > >
> > > > Intel Software Guard eXtensions (SGX) will use this callback to add two
> > > > constraints:
> > > >
> > > > 1. Verify that the address range does not have holes: each page address
> > > >    must be filled with an enclave page.
> > > > 2. Verify that VMA permissions won't surpass the permissions of any enclave
> > > >    page within the address range. Enclave cryptographically sealed
> > > >    permissions for each page address that set the upper limit for possible
> > > >    VMA permissions. Not respecting this can cause #GP's to be emitted.
> > 
> > Side note, #GP is wrong.  EPCM violations are #PFs.  Skylake CPUs #GP, but
> > that's technically an errata.  But this isn't the real motivation, e.g.
> > userspace can already trigger #GP/#PF by reading/writing a bad address, SGX
> > simply adds another flavor.
> > 
> > > It's been awhile since I looked at this.  Can you remind us: is this
> > > just preventing userspace from shooting itself in the foot or is this
> > > something more important?
> > 
> > Something more important, it's used to prevent userspace from circumventing
> > a noexec filesystem by loading code into an enclave, and to give the kernel the
> > option of adding enclave specific LSM policies in the future.
> > 
> > The source file (if one exists) for the enclave is long gone when the enclave
> > is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> > permissions for a given page are snapshotted when the page is added to the
> > enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> > must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> > noexec file system.
> 
> noexec check is done in __sgx_encl_add_page(), not in this callback.
> sgx_vma_mprotect() calls sgx_encl_may_map(), which iterates the
> addresses, checks that permissions are not surpassed and there are
> no holes.

Yes, that's what I said.

> > The ->mprotect() hook allows SGX to reject mprotect() if userspace is declaring
> > permissions beyond what are allowed, e.g. trying to map an enclave page with
> > EXEC permissions when the page was added to the enclave without EXEC.
> 
> For my ear this is tautological because if user space would use
> differing permissions, it would exactly soot itself in the foot.

Not on SGX2 hardware.  The kernel can't disable ENCLU[MODPE].

> What really should be documented is to answer why we consider an enclave
> mappable, if and only if the conditions are that I described about
> sgx_encl_may_map() functioning.
> 
> This is obviously part of the answer [*], i.e. with pharsing LSM hook
> requires an enclave to have a state, which is compatible with the mmap
> permissions and is fully populated.
> 
> The 2nd part of the answer is the answer to the question: why we want to
> feed LSM hooks enclaves exactly in this state.
> 
> What would you answer to that?

I would copy-paste the part of the response that was snipped...
 
> [*] https://lore.kernel.org/linux-sgx/20200918232458.GA6175@linux.intel.com/T/#u
> 
> /Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-21 16:57         ` Sean Christopherson
@ 2020-09-21 21:07           ` Jarkko Sakkinen
  2020-09-21 21:18             ` Sean Christopherson
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-21 21:07 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 21, 2020 at 09:57:58AM -0700, Sean Christopherson wrote:
> On Mon, Sep 21, 2020 at 03:49:46PM +0300, Jarkko Sakkinen wrote:
> > On Fri, Sep 18, 2020 at 04:53:37PM -0700, Sean Christopherson wrote:
> > > a noexec filesystem by loading code into an enclave, and to give the kernel the
> > > option of adding enclave specific LSM policies in the future.
> > > 
> > > The source file (if one exists) for the enclave is long gone when the enclave
> > > is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> > > permissions for a given page are snapshotted when the page is added to the
> > > enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> > > must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> > > noexec file system.
> > 
> > noexec check is done in __sgx_encl_add_page(), not in this callback.
> > sgx_vma_mprotect() calls sgx_encl_may_map(), which iterates the
> > addresses, checks that permissions are not surpassed and there are
> > no holes.
> 
> Yes, that's what I said.

sgx_encl_add_page() will remove such page. The callback does not
interact with this process as such pages never get to the enclave.

> I would copy-paste the part of the response that was snipped...

I do agree with the main conclusions but it contains also things that I
do not see relating that much, like noexec partitions. It goes too far
in detail what will LSM's end up doing. I absolutely do not want to
forecast too far how LSM hooks would work.

Since we do not have ioctl's for EMODPE and such, I see EMODPE as the
only reason for doing this right now. Otherwise, we are in trouble with
any possible LSM callbacks. For any sort of access control decision,
things decided must stick.

I would add something like this to the commit message largely based on
your text:

"SGX stores the permissions for each page when they are first added, and
will implement this callback to check that mmap() or mprotect() does not
surpass these permissions in the requested address range.

This is done to prevent using EMODPE upgrading permissions of a page
after mmap() or mprotect() has been done, which would prevent any sort
of LSM callbacks to be implemented later on because the access control
decision could deprecate."

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-21 21:07           ` Jarkko Sakkinen
@ 2020-09-21 21:18             ` Sean Christopherson
  2020-09-22  5:29               ` Jarkko Sakkinen
  0 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-21 21:18 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 22, 2020 at 12:07:36AM +0300, Jarkko Sakkinen wrote:
> On Mon, Sep 21, 2020 at 09:57:58AM -0700, Sean Christopherson wrote:
> > On Mon, Sep 21, 2020 at 03:49:46PM +0300, Jarkko Sakkinen wrote:
> > > On Fri, Sep 18, 2020 at 04:53:37PM -0700, Sean Christopherson wrote:
> > > > a noexec filesystem by loading code into an enclave, and to give the kernel the
> > > > option of adding enclave specific LSM policies in the future.
> > > > 
> > > > The source file (if one exists) for the enclave is long gone when the enclave
> > > > is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> > > > permissions for a given page are snapshotted when the page is added to the
> > > > enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> > > > must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> > > > noexec file system.
> > > 
> > > noexec check is done in __sgx_encl_add_page(), not in this callback.
> > > sgx_vma_mprotect() calls sgx_encl_may_map(), which iterates the
> > > addresses, checks that permissions are not surpassed and there are
> > > no holes.
> > 
> > Yes, that's what I said.
> 
> sgx_encl_add_page() will remove such page. The callback does not
> interact with this process as such pages never get to the enclave.

I think we're in violent agreement, mostly.

Userspace can add the page without EXEC permissions in the EPCM, and thus
avoid the noexec/VM_MAYEXEC check.  The enclave can then do EMODPE to gain
EXEC permissions in the EPMC.  Without the ->mprotect() hook, we wouldn't
be able to detect/prevent such shenanigans.

> > I would copy-paste the part of the response that was snipped...
> 
> I do agree with the main conclusions but it contains also things that I
> do not see relating that much, like noexec partitions.

As above, this does directly related to noexec/VM_MAYEXEC.

> It goes too far in detail what will LSM's end up doing. I absolutely do not
> want to forecast too far how LSM hooks would work.

That's fine, I was responding to Andy's question, not intending to write a
changelog.
 
> Since we do not have ioctl's for EMODPE and such, I see EMODPE as the
> only reason for doing this right now. Otherwise, we are in trouble with
> any possible LSM callbacks. For any sort of access control decision,
> things decided must stick.

Yes, again, violent agreement :-).

> I would add something like this to the commit message largely based on
> your text:
> 
> "SGX stores the permissions for each page when they are first added, and
> will implement this callback to check that mmap() or mprotect() does not
> surpass these permissions in the requested address range.
> 
> This is done to prevent using EMODPE upgrading permissions of a page
> after mmap() or mprotect() has been done, which would prevent any sort
> of LSM callbacks to be implemented later on because the access control
> decision could deprecate."


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-21 21:18             ` Sean Christopherson
@ 2020-09-22  5:29               ` Jarkko Sakkinen
  2020-09-22  5:35                 ` Jarkko Sakkinen
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-22  5:29 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 21, 2020 at 02:18:49PM -0700, Sean Christopherson wrote:
> On Tue, Sep 22, 2020 at 12:07:36AM +0300, Jarkko Sakkinen wrote:
> > On Mon, Sep 21, 2020 at 09:57:58AM -0700, Sean Christopherson wrote:
> > > On Mon, Sep 21, 2020 at 03:49:46PM +0300, Jarkko Sakkinen wrote:
> > > > On Fri, Sep 18, 2020 at 04:53:37PM -0700, Sean Christopherson wrote:
> > > > > a noexec filesystem by loading code into an enclave, and to give the kernel the
> > > > > option of adding enclave specific LSM policies in the future.
> > > > > 
> > > > > The source file (if one exists) for the enclave is long gone when the enclave
> > > > > is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> > > > > permissions for a given page are snapshotted when the page is added to the
> > > > > enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> > > > > must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> > > > > noexec file system.
> > > > 
> > > > noexec check is done in __sgx_encl_add_page(), not in this callback.
> > > > sgx_vma_mprotect() calls sgx_encl_may_map(), which iterates the
> > > > addresses, checks that permissions are not surpassed and there are
> > > > no holes.
> > > 
> > > Yes, that's what I said.
> > 
> > sgx_encl_add_page() will remove such page. The callback does not
> > interact with this process as such pages never get to the enclave.
> 
> I think we're in violent agreement, mostly.
> 
> Userspace can add the page without EXEC permissions in the EPCM, and thus
> avoid the noexec/VM_MAYEXEC check.  The enclave can then do EMODPE to gain
> EXEC permissions in the EPMC.  Without the ->mprotect() hook, we wouldn't
> be able to detect/prevent such shenanigans.

Right, the VM_MAYEXEC in the code is nested under VM_EXEC check.

I'm only wondering why not block noexec completely with any permissions,
i.e. why not just have unconditional VM_MAYEXEC check?

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-22  5:29               ` Jarkko Sakkinen
@ 2020-09-22  5:35                 ` Jarkko Sakkinen
  2020-09-22 16:43                   ` Sean Christopherson
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-22  5:35 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 22, 2020 at 08:30:06AM +0300, Jarkko Sakkinen wrote:
> On Mon, Sep 21, 2020 at 02:18:49PM -0700, Sean Christopherson wrote:
> > On Tue, Sep 22, 2020 at 12:07:36AM +0300, Jarkko Sakkinen wrote:
> > > On Mon, Sep 21, 2020 at 09:57:58AM -0700, Sean Christopherson wrote:
> > > > On Mon, Sep 21, 2020 at 03:49:46PM +0300, Jarkko Sakkinen wrote:
> > > > > On Fri, Sep 18, 2020 at 04:53:37PM -0700, Sean Christopherson wrote:
> > > > > > a noexec filesystem by loading code into an enclave, and to give the kernel the
> > > > > > option of adding enclave specific LSM policies in the future.
> > > > > > 
> > > > > > The source file (if one exists) for the enclave is long gone when the enclave
> > > > > > is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> > > > > > permissions for a given page are snapshotted when the page is added to the
> > > > > > enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> > > > > > must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> > > > > > noexec file system.
> > > > > 
> > > > > noexec check is done in __sgx_encl_add_page(), not in this callback.
> > > > > sgx_vma_mprotect() calls sgx_encl_may_map(), which iterates the
> > > > > addresses, checks that permissions are not surpassed and there are
> > > > > no holes.
> > > > 
> > > > Yes, that's what I said.
> > > 
> > > sgx_encl_add_page() will remove such page. The callback does not
> > > interact with this process as such pages never get to the enclave.
> > 
> > I think we're in violent agreement, mostly.
> > 
> > Userspace can add the page without EXEC permissions in the EPCM, and thus
> > avoid the noexec/VM_MAYEXEC check.  The enclave can then do EMODPE to gain
> > EXEC permissions in the EPMC.  Without the ->mprotect() hook, we wouldn't
> > be able to detect/prevent such shenanigans.
> 
> Right, the VM_MAYEXEC in the code is nested under VM_EXEC check.
> 
> I'm only wondering why not block noexec completely with any permissions,
> i.e. why not just have unconditional VM_MAYEXEC check?

I.e. why not this:

static int __sgx_encl_add_page(struct sgx_encl *encl,
			       struct sgx_encl_page *encl_page,
			       struct sgx_epc_page *epc_page,
			       struct sgx_secinfo *secinfo, unsigned long src)
{
	struct sgx_pageinfo pginfo;
	struct vm_area_struct *vma;
	struct page *src_page;
	int ret;

	vma = find_vma(current->mm, src);
	if (!vma)
		return -EFAULT;

	if (!(vma->vm_flags & VM_MAYEXEC))
		return -EACCES;

I'm not seeing the reason for "partial support" for noexec partitions.

If there is a good reason, fine, let's just then document it.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-15 11:28 ` [PATCH v38 16/24] x86/sgx: Add a page reclaimer Jarkko Sakkinen
@ 2020-09-22 10:45   ` Borislav Petkov
  2020-09-22 14:03     ` Jarkko Sakkinen
  2020-09-22 16:24     ` Sean Christopherson
  0 siblings, 2 replies; 81+ messages in thread
From: Borislav Petkov @ 2020-09-22 10:45 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: x86, linux-sgx, linux-kernel, linux-mm, Jethro Beekman,
	Jordan Hand, Nathaniel McCallum, Chunyang Hui, Seth Moore,
	Sean Christopherson, akpm, andriy.shevchenko, asapek,
	cedric.xing, chenalexchen, conradparker, cyhanish, dave.hansen,
	haitao.huang, josh, kai.huang, kai.svahn, kmoy, ludloff, luto,
	nhorman, puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 15, 2020 at 02:28:34PM +0300, Jarkko Sakkinen wrote:
> There is a limited amount of EPC available. Therefore, some of it must be
> copied to the regular memory, and only subset kept in the SGX reserved
> memory. While kernel cannot directly access enclave memory, SGX provides a
> set of ENCLS leaf functions to perform reclaiming.
> 
> This commits implements a page reclaimer by using these leaf functions. It

s/This commits implements/Implement/

> picks the victim pages in LRU fashion from all the enclaves running in the
> system. The thread ksgxswapd reclaims pages on the event when the number of
> free EPC pages goes below SGX_NR_LOW_PAGES up until it reaches
> SGX_NR_HIGH_PAGES.

...

Had to grep the SDM for that "eldu" magic. It could use a comment:

/*
 * ELDU: Load an EPC page as unblocked. For more info, see "OS
 * Management of EPC Pages" in the SDM.
 */

or so, to denote what's going on here.

> +static struct sgx_epc_page *sgx_encl_eldu(struct sgx_encl_page *encl_page,
> +					  struct sgx_epc_page *secs_page)
> +{
> +	unsigned long va_offset = SGX_ENCL_PAGE_VA_OFFSET(encl_page);
> +	struct sgx_encl *encl = encl_page->encl;
> +	struct sgx_epc_page *epc_page;
> +	int ret;
> +
> +	epc_page = sgx_alloc_epc_page(encl_page, false);
> +	if (IS_ERR(epc_page))
> +		return epc_page;
> +
> +	ret = __sgx_encl_eldu(encl_page, epc_page, secs_page);
> +	if (ret) {
> +		sgx_free_epc_page(epc_page);
> +		return ERR_PTR(ret);
> +	}
> +
> +	sgx_free_va_slot(encl_page->va_page, va_offset);
> +	list_move(&encl_page->va_page->list, &encl->va_pages);
> +	encl_page->desc &= ~SGX_ENCL_PAGE_VA_OFFSET_MASK;
> +	encl_page->epc_page = epc_page;
> +
> +	return epc_page;
> +}

...

> diff --git a/arch/x86/kernel/cpu/sgx/encl.h b/arch/x86/kernel/cpu/sgx/encl.h
> index 0448d22d3010..11dcf4e7fb3e 100644
> --- a/arch/x86/kernel/cpu/sgx/encl.h
> +++ b/arch/x86/kernel/cpu/sgx/encl.h
> @@ -19,6 +19,10 @@
>  
>  /**
>   * enum sgx_encl_page_desc - defines bits for an enclave page's descriptor
> + * %SGX_ENCL_PAGE_RECLAIMED:		The page is in the process of being
> + *					reclaimed.

SGX_ENCL_PAGE_RECLAIMED means, tho, that the page has been reclaimed
already.

I guess that reads better:

+		if (entry->desc & SGX_ENCL_PAGE_BEING_RECLAIMED)
+			return ERR_PTR(-EBUSY);


> + * %SGX_ENCL_PAGE_VA_OFFSET_MASK:	Holds the offset in the Version Array
> + *					(VA) page for a swapped page.
>   * %SGX_ENCL_PAGE_ADDR_MASK:		Holds the virtual address of the page.
>   *
>   * The page address for SECS is zero and is used by the subsystem to recognize

...

> @@ -86,24 +123,34 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
>  {
>  	unsigned long encl_size = secs->size + PAGE_SIZE;
>  	struct sgx_epc_page *secs_epc;
> +	struct sgx_va_page *va_page;
>  	struct sgx_pageinfo pginfo;
>  	struct sgx_secinfo secinfo;
>  	struct file *backing;
>  	long ret;
>  
> +	va_page = sgx_encl_grow(encl);
> +	if (IS_ERR(va_page))
> +		return PTR_ERR(va_page);
> +	else if (va_page)

Not "else" simply?

AFAICT, sgx_encl_grow() would either return an ERR_PTR or the actual
page...

Also, should the growing happen *after* the SECS validation?

> +		list_add(&va_page->list, &encl->va_pages);
> +
>  	if (sgx_validate_secs(secs)) {
>  		pr_debug("invalid SECS\n");
> -		return -EINVAL;
> +		ret = -EINVAL;
> +		goto err_out_shrink;
>  	}
>  
>  	backing = shmem_file_setup("SGX backing", encl_size + (encl_size >> 5),
>  				   VM_NORESERVE);
> -	if (IS_ERR(backing))
> -		return PTR_ERR(backing);
> +	if (IS_ERR(backing)) {
> +		ret = PTR_ERR(backing);
> +		goto err_out_shrink;
> +	}
>  
>  	encl->backing = backing;
>  
> -	secs_epc = __sgx_alloc_epc_page();
> +	secs_epc = sgx_alloc_epc_page(&encl->secs, true);
>  	if (IS_ERR(secs_epc)) {
>  		ret = PTR_ERR(secs_epc);
>  		goto err_out_backing;
> @@ -151,6 +198,9 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
>  	fput(encl->backing);
>  	encl->backing = NULL;
>  
> +err_out_shrink:
> +	sgx_encl_shrink(encl, va_page);
> +
>  	return ret;
>  }

...


Let's add some comment blurb about "Write back/invalidate an EPC page"
to at least start to explain what that "ewb" is.

> +static void sgx_encl_ewb(struct sgx_epc_page *epc_page,
> +			 struct sgx_backing *backing)
> +{
> +	struct sgx_encl_page *encl_page = epc_page->owner;
> +	struct sgx_encl *encl = encl_page->encl;
> +	struct sgx_va_page *va_page;
> +	unsigned int va_offset;
> +	void *va_slot;
> +	int ret;
> +
> +	encl_page->desc &= ~SGX_ENCL_PAGE_RECLAIMED;
> +
> +	va_page = list_first_entry(&encl->va_pages, struct sgx_va_page,
> +				   list);
> +	va_offset = sgx_alloc_va_slot(va_page);
> +	va_slot = sgx_get_epc_addr(va_page->epc_page) + va_offset;
> +	if (sgx_va_page_full(va_page))
> +		list_move_tail(&va_page->list, &encl->va_pages);
> +
> +	ret = __sgx_encl_ewb(epc_page, va_slot, backing);
> +	if (ret == SGX_NOT_TRACKED) {
> +		ret = __etrack(sgx_get_epc_addr(encl->secs.epc_page));
> +		if (ret) {
> +			if (encls_failed(ret))
> +				ENCLS_WARN(ret, "ETRACK");
> +		}
> +
> +		ret = __sgx_encl_ewb(epc_page, va_slot, backing);
> +		if (ret == SGX_NOT_TRACKED) {
> +			/*
> +			 * Slow path, send IPIs to kick cpus out of the
> +			 * enclave.  Note, it's imperative that the cpu
> +			 * mask is generated *after* ETRACK, else we'll
> +			 * miss cpus that entered the enclave between
> +			 * generating the mask and incrementing epoch.
> +			 */
> +			on_each_cpu_mask(sgx_encl_ewb_cpumask(encl),
> +					 sgx_ipi_cb, NULL, 1);
> +			ret = __sgx_encl_ewb(epc_page, va_slot, backing);
> +		}
> +	}
> +
> +	if (ret) {
> +		if (encls_failed(ret))
> +			ENCLS_WARN(ret, "EWB");
> +
> +		sgx_free_va_slot(va_page, va_offset);
> +	} else {
> +		encl_page->desc |= va_offset;
> +		encl_page->va_page = va_page;
> +	}

...

> +static void sgx_reclaim_pages(void)
> +{
> +	struct sgx_epc_page *chunk[SGX_NR_TO_SCAN];
> +	struct sgx_backing backing[SGX_NR_TO_SCAN];
> +	struct sgx_epc_section *section;
> +	struct sgx_encl_page *encl_page;
> +	struct sgx_epc_page *epc_page;
> +	int cnt = 0;
> +	int ret;
> +	int i;
> +
> +	spin_lock(&sgx_active_page_list_lock);
> +	for (i = 0; i < SGX_NR_TO_SCAN; i++) {
> +		if (list_empty(&sgx_active_page_list))

Isn't it enough to do this once, i.e., not in the loop? You're holding
sgx_active_page_list_lock...

> +			break;
> +
> +		epc_page = list_first_entry(&sgx_active_page_list,
> +					    struct sgx_epc_page, list);
> +		list_del_init(&epc_page->list);
> +		encl_page = epc_page->owner;
> +
> +		if (kref_get_unless_zero(&encl_page->encl->refcount) != 0)
> +			chunk[cnt++] = epc_page;
> +		else
> +			/* The owner is freeing the page. No need to add the
> +			 * page back to the list of reclaimable pages.
> +			 */
> +			epc_page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
> +	}
> +	spin_unlock(&sgx_active_page_list_lock);
> +
> +	for (i = 0; i < cnt; i++) {
> +		epc_page = chunk[i];
> +		encl_page = epc_page->owner;
> +
> +		if (!sgx_reclaimer_age(epc_page))
> +			goto skip;
> +
> +		ret = sgx_encl_get_backing(encl_page->encl,
> +					   SGX_ENCL_PAGE_INDEX(encl_page),
> +					   &backing[i]);
> +		if (ret)
> +			goto skip;
> +
> +		mutex_lock(&encl_page->encl->lock);
> +		encl_page->desc |= SGX_ENCL_PAGE_RECLAIMED;
> +		mutex_unlock(&encl_page->encl->lock);
> +		continue;
> +
> +skip:
> +		spin_lock(&sgx_active_page_list_lock);
> +		list_add_tail(&epc_page->list, &sgx_active_page_list);
> +		spin_unlock(&sgx_active_page_list_lock);
> +
> +		kref_put(&encl_page->encl->refcount, sgx_encl_release);
> +
> +		chunk[i] = NULL;
> +	}
> +
> +	for (i = 0; i < cnt; i++) {
> +		epc_page = chunk[i];
> +		if (epc_page)
> +			sgx_reclaimer_block(epc_page);
> +	}
> +
> +	for (i = 0; i < cnt; i++) {
> +		epc_page = chunk[i];
> +		if (!epc_page)
> +			continue;
> +
> +		encl_page = epc_page->owner;
> +		sgx_reclaimer_write(epc_page, &backing[i]);
> +		sgx_encl_put_backing(&backing[i], true);
> +
> +		kref_put(&encl_page->encl->refcount, sgx_encl_release);
> +		epc_page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
> +
> +		section = sgx_get_epc_section(epc_page);
> +		spin_lock(&section->lock);
> +		list_add_tail(&epc_page->list, &section->page_list);
> +		section->free_cnt++;
> +		spin_unlock(&section->lock);
> +	}
> +}
> +
>  
>  static void sgx_sanitize_section(struct sgx_epc_section *section)

...

-- 
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-19  0:15       ` Andy Lutomirski
@ 2020-09-22 12:58         ` Jarkko Sakkinen
  2020-09-22 15:11           ` Dave Hansen
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-22 12:58 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Andy Lutomirski, X86 ML, linux-sgx, LKML,
	Linux-MM, Andrew Morton, Matthew Wilcox, Jethro Beekman,
	Darren Kenny, Andy Shevchenko, asapek, Borislav Petkov, Xing,
	Cedric, chenalexchen, Conrad Parker, cyhanish, Dave Hansen,
	Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Fri, Sep 18, 2020 at 05:15:32PM -0700, Andy Lutomirski wrote:
> 
> > On Sep 18, 2020, at 4:53 PM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> > 
> > On Fri, Sep 18, 2020 at 08:09:04AM -0700, Andy Lutomirski wrote:
> >>> On Tue, Sep 15, 2020 at 4:28 AM Jarkko Sakkinen
> >>> <jarkko.sakkinen@linux.intel.com> wrote:
> >>> 
> >>> From: Sean Christopherson <sean.j.christopherson@intel.com>
> >>> 
> >>> Add vm_ops()->mprotect() for additional constraints for a VMA.
> >>> 
> >>> Intel Software Guard eXtensions (SGX) will use this callback to add two
> >>> constraints:
> >>> 
> >>> 1. Verify that the address range does not have holes: each page address
> >>>   must be filled with an enclave page.
> >>> 2. Verify that VMA permissions won't surpass the permissions of any enclave
> >>>   page within the address range. Enclave cryptographically sealed
> >>>   permissions for each page address that set the upper limit for possible
> >>>   VMA permissions. Not respecting this can cause #GP's to be emitted.
> > 
> > Side note, #GP is wrong.  EPCM violations are #PFs.  Skylake CPUs #GP, but
> > that's technically an errata.  But this isn't the real motivation, e.g.
> > userspace can already trigger #GP/#PF by reading/writing a bad address, SGX
> > simply adds another flavor.
> > 
> >> It's been awhile since I looked at this.  Can you remind us: is this
> >> just preventing userspace from shooting itself in the foot or is this
> >> something more important?
> > 
> > Something more important, it's used to prevent userspace from circumventing
> > a noexec filesystem by loading code into an enclave, and to give the kernel the
> > option of adding enclave specific LSM policies in the future.
> > 
> > The source file (if one exists) for the enclave is long gone when the enclave
> > is actually mmap()'d and mprotect()'d.  To enforce noexec, the requested
> > permissions for a given page are snapshotted when the page is added to the
> > enclave, i.e. when the enclave is built.  Enclave pages that will be executable
> > must originate from an a MAYEXEC VMA, e.g. the source page can't come from a
> > noexec file system.
> > 
> > The ->mprotect() hook allows SGX to reject mprotect() if userspace is declaring
> > permissions beyond what are allowed, e.g. trying to map an enclave page with
> > EXEC permissions when the page was added to the enclave without EXEC.
> > 
> > Future LSM policies have a similar need due to vm_file always pointing at
> > /dev/sgx/enclave, e.g. policies couldn't be attached to a specific enclave.
> > ->mprotect() again allows enforcing permissions at map time that were checked
> > at enclave build time, e.g. via an LSM hook.
> > 
> > Deferring ->mprotect() until LSM support is added (if it ever is) would be
> > problematic due to SGX2.  With SGX2, userspace can extend permissions of an
> > enclave page (for the CPU's EPC Map entry, not the kernel's page tables)
> > without bouncing through the kernel.  Without ->mprotect () enforcement.
> > userspace could do EADD(RW) -> mprotect(RWX) -> EMODPE(X) to gain W+X.  We
> > want to disallow such a flow now, i.e. force userspace to do EADD(RW,X), so
> > that the hypothetical LSM hook would have all information at EADD(), i.e.
> > would be aware of the EXEC permission, without creating divergent behavior
> > based on whether or not an LSM is active.
> 
> That’s what I thought. Can we get this in the changelog?

I rewrote the commit message. 

"
mm: Add 'mprotect' callback to vm_ops

Intel Sofware Guard eXtensions (SGX) allows creation of executable blobs
called enclaves, of which page permissions are defined when the enclave
is first loaded. Once an enclave is loaded and initialized, it can be
mapped to the process address space.

Enclave permissions can be dynamically modified by using ENCLS[EMODPE]
instruction. We want to limit its use to not allow higher permissions than
the ones defined when the enclave was first created.

Add 'mprotect' hook to vm_ops, so that we can implement a callback for SGX
that will check that {mmap, mprotect}() permissions do not surpass any of
the page permissions in the address range defined.

This is required in order to be able to make any access control decisions
when enclave pages are loaded.
"

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-22 10:45   ` Borislav Petkov
@ 2020-09-22 14:03     ` Jarkko Sakkinen
  2020-09-22 14:24       ` Borislav Petkov
  2020-09-29  1:14       ` Sean Christopherson
  2020-09-22 16:24     ` Sean Christopherson
  1 sibling, 2 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-22 14:03 UTC (permalink / raw)
  To: Borislav Petkov
  Cc: x86, linux-sgx, linux-kernel, linux-mm, Jethro Beekman,
	Jordan Hand, Nathaniel McCallum, Chunyang Hui, Seth Moore,
	Sean Christopherson, akpm, andriy.shevchenko, asapek,
	cedric.xing, chenalexchen, conradparker, cyhanish, dave.hansen,
	haitao.huang, josh, kai.huang, kai.svahn, kmoy, ludloff, luto,
	nhorman, puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 22, 2020 at 12:45:38PM +0200, Borislav Petkov wrote:
> > + * %SGX_ENCL_PAGE_VA_OFFSET_MASK:	Holds the offset in the Version Array
> > + *					(VA) page for a swapped page.
> >   * %SGX_ENCL_PAGE_ADDR_MASK:		Holds the virtual address of the page.
> >   *
> >   * The page address for SECS is zero and is used by the subsystem to recognize
> 
> ...

So what's wrong over here?

> > @@ -86,24 +123,34 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
> >  {
> >  	unsigned long encl_size = secs->size + PAGE_SIZE;
> >  	struct sgx_epc_page *secs_epc;
> > +	struct sgx_va_page *va_page;
> >  	struct sgx_pageinfo pginfo;
> >  	struct sgx_secinfo secinfo;
> >  	struct file *backing;
> >  	long ret;
> >  
> > +	va_page = sgx_encl_grow(encl);
> > +	if (IS_ERR(va_page))
> > +		return PTR_ERR(va_page);
> > +	else if (va_page)
> 
> Not "else" simply?
> 
> AFAICT, sgx_encl_grow() would either return an ERR_PTR or the actual
> page...
> 
> Also, should the growing happen *after* the SECS validation?

Yes, it would make sense. I'll move it.

> Let's add some comment blurb about "Write back/invalidate an EPC page"
> to at least start to explain what that "ewb" is.

OK, I'll try to write something understandable.

> > +	spin_lock(&sgx_active_page_list_lock);
> > +	for (i = 0; i < SGX_NR_TO_SCAN; i++) {
> > +		if (list_empty(&sgx_active_page_list))
> 
> Isn't it enough to do this once, i.e., not in the loop? You're holding
> sgx_active_page_list_lock...

I think that would make sense. Distantly analogous to the EINIT
discussion. Too complex code for yet to be known problem workloads I'd
say.


> >  static void sgx_sanitize_section(struct sgx_epc_section *section)
> 
> ...

Is this about documenting this function?

> -- 
> Regards/Gruss,
>     Boris.
> 
> https://people.kernel.org/tglx/notes-about-netiquette

Thanks, this was valuable feedback.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-22 14:03     ` Jarkko Sakkinen
@ 2020-09-22 14:24       ` Borislav Petkov
  2020-09-23 14:52         ` Jarkko Sakkinen
  2020-09-29  1:14       ` Sean Christopherson
  1 sibling, 1 reply; 81+ messages in thread
From: Borislav Petkov @ 2020-09-22 14:24 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: x86, linux-sgx, linux-kernel, linux-mm, Jethro Beekman,
	Jordan Hand, Nathaniel McCallum, Chunyang Hui, Seth Moore,
	Sean Christopherson, akpm, andriy.shevchenko, asapek,
	cedric.xing, chenalexchen, conradparker, cyhanish, dave.hansen,
	haitao.huang, josh, kai.huang, kai.svahn, kmoy, ludloff, luto,
	nhorman, puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 22, 2020 at 05:03:23PM +0300, Jarkko Sakkinen wrote:
> On Tue, Sep 22, 2020 at 12:45:38PM +0200, Borislav Petkov wrote:
> > > + * %SGX_ENCL_PAGE_VA_OFFSET_MASK:	Holds the offset in the Version Array
> > > + *					(VA) page for a swapped page.
> > >   * %SGX_ENCL_PAGE_ADDR_MASK:		Holds the virtual address of the page.
> > >   *
> > >   * The page address for SECS is zero and is used by the subsystem to recognize
> > 
> > ...
> 
> So what's wrong over here?

Nothing - that's just an ellipsis: https://en.wikipedia.org/wiki/Ellipsis

I do that because otherwise you'd have to scroll through pages of quoted
mail for no good reason and that ain't friendly at all. And I notice
people not trimming their replies and not quoting only the text they
reply to. They should not wonder if their emails remain unread.

Thx for the rest.

-- 
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-22 12:58         ` Jarkko Sakkinen
@ 2020-09-22 15:11           ` Dave Hansen
  2020-09-23 13:30             ` Jarkko Sakkinen
                               ` (2 more replies)
  0 siblings, 3 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-22 15:11 UTC (permalink / raw)
  To: Jarkko Sakkinen, Andy Lutomirski
  Cc: Sean Christopherson, Andy Lutomirski, X86 ML, linux-sgx, LKML,
	Linux-MM, Andrew Morton, Matthew Wilcox, Jethro Beekman,
	Darren Kenny, Andy Shevchenko, asapek, Borislav Petkov, Xing,
	Cedric, chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/22/20 5:58 AM, Jarkko Sakkinen wrote:
> Intel Sofware Guard eXtensions (SGX) allows creation of executable blobs
> called enclaves, of which page permissions are defined when the enclave

"of which" => "for which"

> is first loaded. Once an enclave is loaded and initialized, it can be
> mapped to the process address space.

Could you compare and contrast this a *bit* with existing executables?
What's special about SGX?  ELF executables have page permissions inside
the binary too.  Why don't we use this mechanism for them?

> Enclave permissions can be dynamically modified by using ENCLS[EMODPE]

I'm not sure this sentence matters.  I'm not sure why I care what the
instruction is named that does this.  But, it _sounds_ here like an
enclave can adjust its own permissions directly with ENCLS[EMODPE].

> instruction. We want to limit its use to not allow higher permissions than
> the ones defined when the enclave was first created.

Rather than higher and lower, please use stronger and weaker.

Also, please get rid of the "we".

> Add 'mprotect' hook to vm_ops, so that we can implement a callback for SGX
> that will check that {mmap, mprotect}() permissions do not surpass any of
> the page permissions in the address range defined.

"check" => "ensure"

> This is required in order to be able to make any access control decisions
> when enclave pages are loaded.
Now I'm confused.  I actually don't think I have a strong understanding
of how an enclave actually gets loaded, how mmap() and mprotect() are
normally used and what this hook is intended to thwart.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-22 10:45   ` Borislav Petkov
  2020-09-22 14:03     ` Jarkko Sakkinen
@ 2020-09-22 16:24     ` Sean Christopherson
  2020-09-22 18:02       ` Borislav Petkov
  2020-09-23 15:25       ` Jarkko Sakkinen
  1 sibling, 2 replies; 81+ messages in thread
From: Sean Christopherson @ 2020-09-22 16:24 UTC (permalink / raw)
  To: Borislav Petkov
  Cc: Jarkko Sakkinen, x86, linux-sgx, linux-kernel, linux-mm,
	Jethro Beekman, Jordan Hand, Nathaniel McCallum, Chunyang Hui,
	Seth Moore, akpm, andriy.shevchenko, asapek, cedric.xing,
	chenalexchen, conradparker, cyhanish, dave.hansen, haitao.huang,
	josh, kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman,
	puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 22, 2020 at 12:45:38PM +0200, Borislav Petkov wrote:
> On Tue, Sep 15, 2020 at 02:28:34PM +0300, Jarkko Sakkinen wrote:
> > + * %SGX_ENCL_PAGE_VA_OFFSET_MASK:	Holds the offset in the Version Array
> > + *					(VA) page for a swapped page.
> >   * %SGX_ENCL_PAGE_ADDR_MASK:		Holds the virtual address of the page.
> >   *
> >   * The page address for SECS is zero and is used by the subsystem to recognize
> 
> ...
> 
> > @@ -86,24 +123,34 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
> >  {
> >  	unsigned long encl_size = secs->size + PAGE_SIZE;
> >  	struct sgx_epc_page *secs_epc;
> > +	struct sgx_va_page *va_page;
> >  	struct sgx_pageinfo pginfo;
> >  	struct sgx_secinfo secinfo;
> >  	struct file *backing;
> >  	long ret;
> >  
> > +	va_page = sgx_encl_grow(encl);
> > +	if (IS_ERR(va_page))
> > +		return PTR_ERR(va_page);
> > +	else if (va_page)
> 
> Not "else" simply?
> 
> AFAICT, sgx_encl_grow() would either return an ERR_PTR or the actual
> page...
> 

The "else if" is correct.  Version Array (VA) pages have 512 slots that hold
metadata for evicted EPC pages, i.e. swapping a page out of the EPC requires
a VA slot.  For simplicity (LOL), the approach we are taking for initial
support is to reserve a VA slot when adding a page to the enclave[*].  In most
cases, reserving a slot does not require allocating a new VA page, e.g. to
reserve slots 1-511 of the "current" VA page.   The if-elif is handling the
case where the current VA page is fully reserved and a new one needs to be
allocated. The if handles the error, the elif handles success, i.e.

	if (IS_ERR(va_page)) <- needed a new VA page, allocation failed
		return PTR_ERR(va_page);
	else if (va_page)    <- needed a new VA page, allocation succeeded
		list_add(&va_page->list, &encl->va_pages);
	else
		             <- reused the current VA page

When reusing a VA page, we obviously don't want to readd the page to the list
of va_pages, and the error handling path also shouldn't free the VA page.

> Also, should the growing happen *after* the SECS validation?
> 
> > +		list_add(&va_page->list, &encl->va_pages);
> > +
> >  	if (sgx_validate_secs(secs)) {
> >  		pr_debug("invalid SECS\n");
> > -		return -EINVAL;
> > +		ret = -EINVAL;
> > +		goto err_out_shrink;
> >  	}


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-22  5:35                 ` Jarkko Sakkinen
@ 2020-09-22 16:43                   ` Sean Christopherson
  2020-09-23 13:50                     ` Jarkko Sakkinen
  0 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-22 16:43 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 22, 2020 at 08:35:15AM +0300, Jarkko Sakkinen wrote:
> On Tue, Sep 22, 2020 at 08:30:06AM +0300, Jarkko Sakkinen wrote:
> > On Mon, Sep 21, 2020 at 02:18:49PM -0700, Sean Christopherson wrote:
> > > Userspace can add the page without EXEC permissions in the EPCM, and thus
> > > avoid the noexec/VM_MAYEXEC check.  The enclave can then do EMODPE to gain
> > > EXEC permissions in the EPMC.  Without the ->mprotect() hook, we wouldn't
> > > be able to detect/prevent such shenanigans.
> > 
> > Right, the VM_MAYEXEC in the code is nested under VM_EXEC check.
> > 
> > I'm only wondering why not block noexec completely with any permissions,
> > i.e. why not just have unconditional VM_MAYEXEC check?
> 
> I.e. why not this:
> 
> static int __sgx_encl_add_page(struct sgx_encl *encl,
> 			       struct sgx_encl_page *encl_page,
> 			       struct sgx_epc_page *epc_page,
> 			       struct sgx_secinfo *secinfo, unsigned long src)
> {
> 	struct sgx_pageinfo pginfo;
> 	struct vm_area_struct *vma;
> 	struct page *src_page;
> 	int ret;
> 
> 	vma = find_vma(current->mm, src);
> 	if (!vma)
> 		return -EFAULT;
> 
> 	if (!(vma->vm_flags & VM_MAYEXEC))
> 		return -EACCES;
> 
> I'm not seeing the reason for "partial support" for noexec partitions.
> 
> If there is a good reason, fine, let's just then document it.

There are scenarios I can contrive, e.g. loading an enclave from a noexec
filesystem without having to copy the entire enclave to anon memory, or
loading a data payload from a noexec FS.

They're definitely contrived scenarios, but given that we also want the
->mprotect() hook/behavior for potential LSM interaction, supporting said
contrived scenarios costs is "free".


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-22 16:24     ` Sean Christopherson
@ 2020-09-22 18:02       ` Borislav Petkov
  2020-09-23 15:25       ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Borislav Petkov @ 2020-09-22 18:02 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Jarkko Sakkinen, x86, linux-sgx, linux-kernel, linux-mm,
	Jethro Beekman, Jordan Hand, Nathaniel McCallum, Chunyang Hui,
	Seth Moore, akpm, andriy.shevchenko, asapek, cedric.xing,
	chenalexchen, conradparker, cyhanish, dave.hansen, haitao.huang,
	josh, kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman,
	puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 22, 2020 at 09:24:38AM -0700, Sean Christopherson wrote:
> The "else if" is correct.  Version Array (VA) pages have 512 slots that hold
> metadata for evicted EPC pages, i.e. swapping a page out of the EPC requires
> a VA slot.  For simplicity (LOL),

I'll say.

> the approach we are taking for initial support is to reserve a VA slot
> when adding a page to the enclave[*]. In most cases, reserving a slot
> does not require allocating a new VA page, e.g. to reserve slots 1-511
> of the "current" VA page. The if-elif is handling the case where the
> current VA page is fully reserved and a new one needs to be allocated.
> The if handles the error, the elif handles success, i.e.
> 
> 	if (IS_ERR(va_page)) <- needed a new VA page, allocation failed
> 		return PTR_ERR(va_page);
> 	else if (va_page)    <- needed a new VA page, allocation succeeded
> 		list_add(&va_page->list, &encl->va_pages);
> 	else
> 		             <- reused the current VA page

Aha, in that case va_page will be NULL but you're not using it in that
function later and that current VA page is on encl->va_pages which
others can get from there. Ok, gotcha.

Thx.

-- 
Regards/Gruss,
    Boris.

https://people.kernel.org/tglx/notes-about-netiquette


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-22 15:11           ` Dave Hansen
@ 2020-09-23 13:30             ` Jarkko Sakkinen
  2020-09-23 13:43             ` Jarkko Sakkinen
  2020-09-23 14:33             ` Jarkko Sakkinen
  2 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-23 13:30 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Andy Lutomirski, Sean Christopherson, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 22, 2020 at 08:11:14AM -0700, Dave Hansen wrote:
> > Enclave permissions can be dynamically modified by using ENCLS[EMODPE]
> 
> I'm not sure this sentence matters.  I'm not sure why I care what the
> instruction is named that does this.  But, it _sounds_ here like an
> enclave can adjust its own permissions directly with ENCLS[EMODPE].

If there was no EMODPE, I would drop this patch from the patch set. It
is the only reason I keep it. There are no other hard reasons to have
this.

> Now I'm confused.  I actually don't think I have a strong understanding
> of how an enclave actually gets loaded, how mmap() and mprotect() are
> normally used and what this hook is intended to thwart.

Enclave gets loaded with the ioctl API so ATM we rely only on
DAC permissions.

In future you might want to have LSM hooks to improve granularity
in two points:

1. When pages are added using SGX_IOC_ENCLAVE ADD_PAGES.
2. When enclave is initialized using SGX_IOC_ENCLAVE_INIT

In both you might want to make a policy decision based on origin
and page permissions.

If we do not limit mmap(), enclave could later on upgrade its
permissions with EMODPE and do mmap().

No matter what kind of LSM hooks or whatever possible improvements
are done later on to access control, they won't work unless we have
this because the permissions could be different than the original.

With this change you can still do EMODPE inside an enclave, but you
don't gain anything with it because your max permissions are capped
during the build time.

I'm not sure what exactly from this is missing from the commit message
but if you get this explanation maybe you can help me out with that.

Thank you for the feedback.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-22 15:11           ` Dave Hansen
  2020-09-23 13:30             ` Jarkko Sakkinen
@ 2020-09-23 13:43             ` Jarkko Sakkinen
  2020-09-23 14:33             ` Jarkko Sakkinen
  2 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-23 13:43 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Andy Lutomirski, Sean Christopherson, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 22, 2020 at 08:11:14AM -0700, Dave Hansen wrote:
> On 9/22/20 5:58 AM, Jarkko Sakkinen wrote:
> > Intel Sofware Guard eXtensions (SGX) allows creation of executable blobs
> > called enclaves, of which page permissions are defined when the enclave
> 
> "of which" => "for which"
> 
> > is first loaded. Once an enclave is loaded and initialized, it can be
> > mapped to the process address space.
> 
> Could you compare and contrast this a *bit* with existing executables?
> What's special about SGX?  ELF executables have page permissions inside
> the binary too.  Why don't we use this mechanism for them?

There is no standard file format for enclaves. They are dynamically
built. And the way enclaves are used as part of an app and throwing
container inside enclave differ. A single format would no work too
well for all possible use cases.

I cannot formally prove this of course but it is highly unlikely that
we could ever define such a format. Thus, the security focus is allow
to verify from origin.

And the existing ecosystem around SGX is already too large to suddenly
move to a single format. User base, I guess, is also an argument. This
is not yet mainline code so technically we have zero ABI debt but I
still think this is a valid point because SGX is already widely used.

I'm not really sure what would be the best way to nail this information
to the commit message but I'll try to figure out something before I send
the next version of the patch set.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-22 16:43                   ` Sean Christopherson
@ 2020-09-23 13:50                     ` Jarkko Sakkinen
  2020-09-24 19:11                       ` Haitao Huang
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-23 13:50 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 22, 2020 at 09:43:02AM -0700, Sean Christopherson wrote:
> On Tue, Sep 22, 2020 at 08:35:15AM +0300, Jarkko Sakkinen wrote:
> > On Tue, Sep 22, 2020 at 08:30:06AM +0300, Jarkko Sakkinen wrote:
> > > On Mon, Sep 21, 2020 at 02:18:49PM -0700, Sean Christopherson wrote:
> > > > Userspace can add the page without EXEC permissions in the EPCM, and thus
> > > > avoid the noexec/VM_MAYEXEC check.  The enclave can then do EMODPE to gain
> > > > EXEC permissions in the EPMC.  Without the ->mprotect() hook, we wouldn't
> > > > be able to detect/prevent such shenanigans.
> > > 
> > > Right, the VM_MAYEXEC in the code is nested under VM_EXEC check.
> > > 
> > > I'm only wondering why not block noexec completely with any permissions,
> > > i.e. why not just have unconditional VM_MAYEXEC check?
> > 
> > I.e. why not this:
> > 
> > static int __sgx_encl_add_page(struct sgx_encl *encl,
> > 			       struct sgx_encl_page *encl_page,
> > 			       struct sgx_epc_page *epc_page,
> > 			       struct sgx_secinfo *secinfo, unsigned long src)
> > {
> > 	struct sgx_pageinfo pginfo;
> > 	struct vm_area_struct *vma;
> > 	struct page *src_page;
> > 	int ret;
> > 
> > 	vma = find_vma(current->mm, src);
> > 	if (!vma)
> > 		return -EFAULT;
> > 
> > 	if (!(vma->vm_flags & VM_MAYEXEC))
> > 		return -EACCES;
> > 
> > I'm not seeing the reason for "partial support" for noexec partitions.
> > 
> > If there is a good reason, fine, let's just then document it.
> 
> There are scenarios I can contrive, e.g. loading an enclave from a noexec
> filesystem without having to copy the entire enclave to anon memory, or
> loading a data payload from a noexec FS.
> 
> They're definitely contrived scenarios, but given that we also want the
> ->mprotect() hook/behavior for potential LSM interaction, supporting said
> contrived scenarios costs is "free".

For me this has caused months of confusion and misunderstanding of this
feature. I only recently realized that "oh, right, we invented this".

They are contrived scenarios enough that they should be considered when
the workloads hit.

Either we fully support noexec or not at all. Any "partial" thing is a
two edged sword: it can bring some robustness with the price of
complexity and possible unknown uknown scenarios where they might become
API issue.

I rather think later on how to extend API in some way to enable such
contrivid scenarios rather than worrying about how this could be abused.

The whole SGX is complex beast already so lets not add any extra when
there is no a hard requirement to do so.

I'll categorically deny noexec in the next patch set version.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-22 15:11           ` Dave Hansen
  2020-09-23 13:30             ` Jarkko Sakkinen
  2020-09-23 13:43             ` Jarkko Sakkinen
@ 2020-09-23 14:33             ` Jarkko Sakkinen
  2020-09-24 14:50               ` Dave Hansen
  2 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-23 14:33 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Andy Lutomirski, Sean Christopherson, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 22, 2020 at 08:11:14AM -0700, Dave Hansen wrote:
> Now I'm confused.  I actually don't think I have a strong understanding
> of how an enclave actually gets loaded, how mmap() and mprotect() are
> normally used and what this hook is intended to thwart.

You saw my other comments. I scraped this together based on your
feedback and my responses:

"
mm: Add 'mprotect' callback to vm_ops

Intel Sofware Guard eXtensions (SGX) allows creation of blobs called
enclaves, for which page permissions are defined when the enclave is first
loaded. Once an enclave is loaded and initialized, it can be mapped to the
process address space.

There is no standard file format for enclaves. They are dynamically built
and the ways how enclaves are deployed differ greatly. For an app you might
want to have a simple static binary, but on the other hand for a container
you might want to dynamically create the whole thing at run-time. Also, the
existing ecosystem for SGX is already large, which would make the task very
hard.

Finally, even if there was a standard format, one would still want a
dynamic way to add pages to the enclave. One big reason for this is that
enclaves have load time defined pages that represent entry points to the
enclave. Each entry point can service one hardware thread at a time and
you might want to run-time parametrize this depending on your environment.

The consequence is that enclaves are best created with an ioctl API and the
access control can be based only to the origin of the source file for the
enclave data, i.e. on VMA file pointer and page permissions. For example,
this could be done with LSM hooks that are triggered in the appropriate
ioctl's and they could make the access control decision based on this
information.

Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
could upgrade its permissions by using EMODPE followed by an appropriate
mprotect() call. This would be completely hidden from the kernel.

Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
that will ensure that {mmap, mprotect}() permissions do not surpass any of
the original page permissions. This feature allows to maintain and refine
sane access control for enclaves.
"

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-22 14:24       ` Borislav Petkov
@ 2020-09-23 14:52         ` Jarkko Sakkinen
  0 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-23 14:52 UTC (permalink / raw)
  To: Borislav Petkov
  Cc: x86, linux-sgx, linux-kernel, linux-mm, Jethro Beekman,
	Jordan Hand, Nathaniel McCallum, Chunyang Hui, Seth Moore,
	Sean Christopherson, akpm, andriy.shevchenko, asapek,
	cedric.xing, chenalexchen, conradparker, cyhanish, dave.hansen,
	haitao.huang, josh, kai.huang, kai.svahn, kmoy, ludloff, luto,
	nhorman, puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 22, 2020 at 04:24:13PM +0200, Borislav Petkov wrote:
> On Tue, Sep 22, 2020 at 05:03:23PM +0300, Jarkko Sakkinen wrote:
> > On Tue, Sep 22, 2020 at 12:45:38PM +0200, Borislav Petkov wrote:
> > > > + * %SGX_ENCL_PAGE_VA_OFFSET_MASK:	Holds the offset in the Version Array
> > > > + *					(VA) page for a swapped page.
> > > >   * %SGX_ENCL_PAGE_ADDR_MASK:		Holds the virtual address of the page.
> > > >   *
> > > >   * The page address for SECS is zero and is used by the subsystem to recognize
> > > 
> > > ...
> > 
> > So what's wrong over here?
> 
> Nothing - that's just an ellipsis: https://en.wikipedia.org/wiki/Ellipsis
> 
> I do that because otherwise you'd have to scroll through pages of quoted
> mail for no good reason and that ain't friendly at all. And I notice
> people not trimming their replies and not quoting only the text they
> reply to. They should not wonder if their emails remain unread.
> 
> Thx for the rest.

OK, I'm just almost paranoic in not addressing all feedback, thanks
for the explanation :-)

Like in this version, I'll try to xref all changes so it will be at
least easier spot if something is missing.

> 
> -- 
> Regards/Gruss,
>     Boris.
> 
> https://people.kernel.org/tglx/notes-about-netiquette

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-22 16:24     ` Sean Christopherson
  2020-09-22 18:02       ` Borislav Petkov
@ 2020-09-23 15:25       ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-23 15:25 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Borislav Petkov, x86, linux-sgx, linux-kernel, linux-mm,
	Jethro Beekman, Jordan Hand, Nathaniel McCallum, Chunyang Hui,
	Seth Moore, akpm, andriy.shevchenko, asapek, cedric.xing,
	chenalexchen, conradparker, cyhanish, dave.hansen, haitao.huang,
	josh, kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman,
	puiterwijk, rientjes, tglx, yaozhangx

> 	if (IS_ERR(va_page)) <- needed a new VA page, allocation failed
> 		return PTR_ERR(va_page);
> 	else if (va_page)    <- needed a new VA page, allocation succeeded
> 		list_add(&va_page->list, &encl->va_pages);
> 	else
> 		             <- reused the current VA page

/* else the tail page of the VA page list had free slots. */

I added this comment as "the missing branch".

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-23 14:33             ` Jarkko Sakkinen
@ 2020-09-24 14:50               ` Dave Hansen
  2020-09-24 16:27                 ` Sean Christopherson
  2020-09-24 19:35                 ` Jarkko Sakkinen
  0 siblings, 2 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-24 14:50 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Sean Christopherson, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/23/20 7:33 AM, Jarkko Sakkinen wrote:
> The consequence is that enclaves are best created with an ioctl API and the
> access control can be based only to the origin of the source file for the
> enclave data, i.e. on VMA file pointer and page permissions. For example,
> this could be done with LSM hooks that are triggered in the appropriate
> ioctl's and they could make the access control decision based on this
> information.
> 
> Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
> upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
> could upgrade its permissions by using EMODPE followed by an appropriate
> mprotect() call. This would be completely hidden from the kernel.
> 
> Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
> that will ensure that {mmap, mprotect}() permissions do not surpass any of
> the original page permissions. This feature allows to maintain and refine
> sane access control for enclaves.

Maybe I'm just being dense, but I still don't have a clear idea what
function this hook serves.

I understand that SGX has an orthogonal set of page permissions to the
normal x86 page tables.  It needs these so that the OS can't play nasty
tricks on the enclave, like removing read-only protections that provide
hardening.

But, I still don't get the connection to mprotect() and the x86 paging
permissions.  If the enclave's permissions are orthogonal, then why
bother with this hook?  Why does the OS view of the enclave's memory matter?


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 14:50               ` Dave Hansen
@ 2020-09-24 16:27                 ` Sean Christopherson
  2020-09-24 19:35                 ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Sean Christopherson @ 2020-09-24 16:27 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Jarkko Sakkinen, Andy Lutomirski, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 07:50:15AM -0700, Dave Hansen wrote:
> On 9/23/20 7:33 AM, Jarkko Sakkinen wrote:
> > The consequence is that enclaves are best created with an ioctl API and the
> > access control can be based only to the origin of the source file for the
> > enclave data, i.e. on VMA file pointer and page permissions. For example,
> > this could be done with LSM hooks that are triggered in the appropriate
> > ioctl's and they could make the access control decision based on this
> > information.
> > 
> > Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
> > upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
> > could upgrade its permissions by using EMODPE followed by an appropriate
> > mprotect() call. This would be completely hidden from the kernel.
> > 
> > Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
> > that will ensure that {mmap, mprotect}() permissions do not surpass any of
> > the original page permissions. This feature allows to maintain and refine
> > sane access control for enclaves.
> 
> Maybe I'm just being dense, but I still don't have a clear idea what
> function this hook serves.
> 
> I understand that SGX has an orthogonal set of page permissions to the
> normal x86 page tables.  It needs these so that the OS can't play nasty
> tricks on the enclave, like removing read-only protections that provide
> hardening.
> 
> But, I still don't get the connection to mprotect() and the x86 paging
> permissions.  If the enclave's permissions are orthogonal, then why
> bother with this hook?  Why does the OS view of the enclave's memory matter?

For the purpose of this discussion, ignore the enclave permissions.  The only
reason they're mentioned is to explain the background (well, try to) of how we
ended up at an ->mprotect() hook.  There was a great deal of discussion in the
past about whether or not we could use enclave permissions to enforce OS
permissions.  The TL:DR version is that because of ENCLU[EMODPE], the answer
is "no".

What we're preventing via ->mprotect() is using SGX to bypass existing
restrictions on code execution, e.g. noexec and LSM policies.

Because code must first be loaded into an enclave before it can be executed,
all enclaves are kind of a variant on (in SELinux terminology) either EXECMOD
or EXECMEM.  I.e. it's simply not possible to execute an enclave by mapping
the source file as executable.  This effectively allows userspace to bypass a
noexec FS by loading code into an enclave without EXEC perms on the source
file, only on /dev/sgx/enclave, and denying EXEC on /dev/sgx/enclave would
prevent running _any_ enclave.

The ->mprotect() hook is used by SGX to require userspace to declare what
permissions are allowed on any given enclave page, e.g. SGX's mmap()/mprotect()
requires all underlying enclave pages to be declared as executable if the
mmap()/mprotect() is specifying VM_EXEC.  By requiring userspace to declare
their intent up front, SGX can then enforce noexec by requiring pages that are
declared as executable to have VM_MAYEXEC set in the source VMA when loading
code into the enclave.

As Jarkko pointed out, an alternative to adding ->mprotect() would be to
simply require VM_MAYEXEC on _all_ source VMAs when loading code into the
enclave.  That would work, albeit with the potentially undesirable side effect
of preventing loading any part of an enclave from e.g. a noexec, readonly FS.

But, unconditionally requiring VM_MAYEXEC doesn't address the Linux Security
Module hooks for mmap() and mprotect(), which could also be bypassed by abusing
SGX.  E.g. a process could gain arbitrary code execution by loading code from
anonymous memory into an enclave, as the LSM checks hooks at mmap()/mprotect()
will see always vm_file=/dev/sgx/enclave.  An LSM could deny a process access
to /dev/sgx/enclave, but again that is very coarse granularity.

By requiring userspace to declare permissions up front (when loading code/data
into an enclave), SGX can make explicit upcalls to LSMs hooks at load time so
that an LSM can enforce a meaningful policy, e.g. require all enclave code to
originate from an executable file system.  This series doesn't actually
implement the LSM integration, but it does ensure that _if_ we want to add LSM
support in the future, we can do so without breaking userspace.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-23 13:50                     ` Jarkko Sakkinen
@ 2020-09-24 19:11                       ` Haitao Huang
  2020-09-24 19:28                         ` Sean Christopherson
  2020-09-24 21:55                         ` Jarkko Sakkinen
  0 siblings, 2 replies; 81+ messages in thread
From: Haitao Huang @ 2020-09-24 19:11 UTC (permalink / raw)
  To: Sean Christopherson, Jarkko Sakkinen
  Cc: Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Wed, 23 Sep 2020 08:50:56 -0500, Jarkko Sakkinen  
<jarkko.sakkinen@linux.intel.com> wrote:

> On Tue, Sep 22, 2020 at 09:43:02AM -0700, Sean Christopherson wrote:
>> On Tue, Sep 22, 2020 at 08:35:15AM +0300, Jarkko Sakkinen wrote:
>> > On Tue, Sep 22, 2020 at 08:30:06AM +0300, Jarkko Sakkinen wrote:
>> > > On Mon, Sep 21, 2020 at 02:18:49PM -0700, Sean Christopherson wrote:
>> > > > Userspace can add the page without EXEC permissions in the EPCM,  
>> and thus
>> > > > avoid the noexec/VM_MAYEXEC check.  The enclave can then do  
>> EMODPE to gain
>> > > > EXEC permissions in the EPMC.  Without the ->mprotect() hook, we  
>> wouldn't
>> > > > be able to detect/prevent such shenanigans.
>> > >
>> > > Right, the VM_MAYEXEC in the code is nested under VM_EXEC check.
>> > >
>> > > I'm only wondering why not block noexec completely with any  
>> permissions,
>> > > i.e. why not just have unconditional VM_MAYEXEC check?
>> >
>> > I.e. why not this:
>> >
>> > static int __sgx_encl_add_page(struct sgx_encl *encl,
>> > 			       struct sgx_encl_page *encl_page,
>> > 			       struct sgx_epc_page *epc_page,
>> > 			       struct sgx_secinfo *secinfo, unsigned long src)
>> > {
>> > 	struct sgx_pageinfo pginfo;
>> > 	struct vm_area_struct *vma;
>> > 	struct page *src_page;
>> > 	int ret;
>> >
>> > 	vma = find_vma(current->mm, src);
>> > 	if (!vma)
>> > 		return -EFAULT;
>> >
>> > 	if (!(vma->vm_flags & VM_MAYEXEC))
>> > 		return -EACCES;
>> >
>> > I'm not seeing the reason for "partial support" for noexec partitions.
>> >
>> > If there is a good reason, fine, let's just then document it.
>>
>> There are scenarios I can contrive, e.g. loading an enclave from a  
>> noexec
>> filesystem without having to copy the entire enclave to anon memory, or
>> loading a data payload from a noexec FS.
>>
>> They're definitely contrived scenarios, but given that we also want the
>> ->mprotect() hook/behavior for potential LSM interaction, supporting  
>> said
>> contrived scenarios costs is "free".
>
> For me this has caused months of confusion and misunderstanding of this
> feature. I only recently realized that "oh, right, we invented this".
>
> They are contrived scenarios enough that they should be considered when
> the workloads hit.
>
> Either we fully support noexec or not at all. Any "partial" thing is a
> two edged sword: it can bring some robustness with the price of
> complexity and possible unknown uknown scenarios where they might become
> API issue.
>
> I rather think later on how to extend API in some way to enable such
> contrivid scenarios rather than worrying about how this could be abused.
>
> The whole SGX is complex beast already so lets not add any extra when
> there is no a hard requirement to do so.
>
> I'll categorically deny noexec in the next patch set version.
>
> /Jarkko

There are use cases supported currently in which enclave binary is  
received via IPC/RPC and held in buffers before EADD. Denying noexec  
altogether would break those, right?
 


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 19:11                       ` Haitao Huang
@ 2020-09-24 19:28                         ` Sean Christopherson
  2020-09-24 19:39                           ` Dave Hansen
  2020-09-24 21:58                           ` Jarkko Sakkinen
  2020-09-24 21:55                         ` Jarkko Sakkinen
  1 sibling, 2 replies; 81+ messages in thread
From: Sean Christopherson @ 2020-09-24 19:28 UTC (permalink / raw)
  To: Haitao Huang
  Cc: Jarkko Sakkinen, Andy Lutomirski, X86 ML, linux-sgx, LKML,
	Linux-MM, Andrew Morton, Matthew Wilcox, Jethro Beekman,
	Darren Kenny, Andy Shevchenko, asapek, Borislav Petkov, Xing,
	Cedric, chenalexchen, Conrad Parker, cyhanish, Dave Hansen,
	Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 02:11:37PM -0500, Haitao Huang wrote:
> On Wed, 23 Sep 2020 08:50:56 -0500, Jarkko Sakkinen
> <jarkko.sakkinen@linux.intel.com> wrote:
> >I'll categorically deny noexec in the next patch set version.
> >
> >/Jarkko
> 
> There are use cases supported currently in which enclave binary is received
> via IPC/RPC and held in buffers before EADD. Denying noexec altogether would
> break those, right?

No.  noexec only applies to file-backed VMAs, what you're describing is loading
an enclave from an anon VMA, which will still have VM_MAYEXEC.

I believe you're thinking of SELinux's EXECMEM, which is required to execute
from anonymous memory, and which we talked about (more than once) applying to
SGX enclaves.

That being said, I still dislike the idea of requiring VM_MAYEXEC, it's a hack
that doesn't really buy us much, if anything.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 14:50               ` Dave Hansen
  2020-09-24 16:27                 ` Sean Christopherson
@ 2020-09-24 19:35                 ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-24 19:35 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Andy Lutomirski, Sean Christopherson, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 07:50:15AM -0700, Dave Hansen wrote:
> On 9/23/20 7:33 AM, Jarkko Sakkinen wrote:
> > The consequence is that enclaves are best created with an ioctl API and the
> > access control can be based only to the origin of the source file for the
> > enclave data, i.e. on VMA file pointer and page permissions. For example,
> > this could be done with LSM hooks that are triggered in the appropriate
> > ioctl's and they could make the access control decision based on this
> > information.
> > 
> > Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
> > upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
> > could upgrade its permissions by using EMODPE followed by an appropriate
> > mprotect() call. This would be completely hidden from the kernel.
> > 
> > Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
> > that will ensure that {mmap, mprotect}() permissions do not surpass any of
> > the original page permissions. This feature allows to maintain and refine
> > sane access control for enclaves.
> 
> Maybe I'm just being dense, but I still don't have a clear idea what
> function this hook serves.
> 
> I understand that SGX has an orthogonal set of page permissions to the
> normal x86 page tables.  It needs these so that the OS can't play nasty
> tricks on the enclave, like removing read-only protections that provide
> hardening.
> 
> But, I still don't get the connection to mprotect() and the x86 paging
> permissions.  If the enclave's permissions are orthogonal, then why
> bother with this hook?  Why does the OS view of the enclave's memory matter?

Consider SGX_IOC_ENCLAVE_ADD_PAGES. It essentially takes from MAC
perpective two items:

1. Source represented as a VMA, and in the end as vm_file, i.e. the
   origin. This good place to anchor a security policy.
2. Permissions.

Since enclaves are dynamically constructed and do not go through
execve() path but are dynamically loaded this is a good place hook make
an LSM hook. Lets imagine that we have an LSM hook in place.

Now when enclave the enclave is loaded the LSM makes decisions based
on its policy, permissions and the origin of the enclave file. After
this decisions has been made it is sane to assume that the enclave
could not be run with higher permissions, right?

Now what an adversary could do after the enclave has been loaded and
initialized is to call EMODPE inside the enclave to upgrade permissions
to some pages. After that mprotect() can be applied to use the new
permissions.

The mprotect() callback keeps any higher permissions than originally
accepted by the MAC policy unusable.

Also without any LSM hooks this allows to have a more privileged launcher
process to build enclaves (e.g. have someone to own /dev/sgx/enclave)
and send fd's to other processes to run them. And with that callback in
place the launcher process can cap the permissions at build time.

That's where the indirect connection originates from. Should I write
this user story to the commit message as an addition. Would that help?

For v39 I did make a change that noexec partitions are categorically
discluded as an origin for enclaves. Before that it was that NX
pages from such partitions are allowed but I thought that it is better
simplify things since they are anyway complex. I'm 100% we can make
that kind of support for noexec partitions later on, if anyone ever
wants that anyway.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 19:28                         ` Sean Christopherson
@ 2020-09-24 19:39                           ` Dave Hansen
  2020-09-24 20:01                             ` Sean Christopherson
  2020-09-24 21:58                           ` Jarkko Sakkinen
  1 sibling, 1 reply; 81+ messages in thread
From: Dave Hansen @ 2020-09-24 19:39 UTC (permalink / raw)
  To: Sean Christopherson, Haitao Huang
  Cc: Jarkko Sakkinen, Andy Lutomirski, X86 ML, linux-sgx, LKML,
	Linux-MM, Andrew Morton, Matthew Wilcox, Jethro Beekman,
	Darren Kenny, Andy Shevchenko, asapek, Borislav Petkov, Xing,
	Cedric, chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/24/20 12:28 PM, Sean Christopherson wrote:
> On Thu, Sep 24, 2020 at 02:11:37PM -0500, Haitao Huang wrote:
>> On Wed, 23 Sep 2020 08:50:56 -0500, Jarkko Sakkinen
>> <jarkko.sakkinen@linux.intel.com> wrote:
>>> I'll categorically deny noexec in the next patch set version.
>>>
>>> /Jarkko
>> There are use cases supported currently in which enclave binary is received
>> via IPC/RPC and held in buffers before EADD. Denying noexec altogether would
>> break those, right?
> No.  noexec only applies to file-backed VMAs, what you're describing is loading
> an enclave from an anon VMA, which will still have VM_MAYEXEC.

Maybe I'm just stupid, but I still don't get the scenario that's being
thwarted or why it is valuable.  The SDM is worthless on what EMODPE
does or what its restrictions are.

In pseudo-C, it's something logically like this for the "nice" case:

	ptr = mmap("/some/executable", PROT_EXEC);
	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
	mmap(sgx_fd);
	EENTER;

And we're trying to thwart:

	ptr = mmap("/mnt/noexec/file", PROT_READ);
	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
	mmap(sgx_fd);
	EENTER;

because that loads data into the enclave which is executable but which
was not executable normally.  But, we're allowing this from anonymous
memory, so this would seem to work:

	ptr = mmap("/mnt/noexec/file", PROT_READ);
	buffer = malloc(PAGE_SIZE);
	memcpy(buffer, ptr, PAGE_SIZE);
	// need mprotect(buf, PROT_EXEC)???
	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, buffer, size);
	mmap(sgx_fd);
	EENTER;

and give the same result.  What am I missing?


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 19:39                           ` Dave Hansen
@ 2020-09-24 20:01                             ` Sean Christopherson
  2020-09-24 20:10                               ` Dave Hansen
  0 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-24 20:01 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 12:39:24PM -0700, Dave Hansen wrote:
> On 9/24/20 12:28 PM, Sean Christopherson wrote:
> > On Thu, Sep 24, 2020 at 02:11:37PM -0500, Haitao Huang wrote:
> >> On Wed, 23 Sep 2020 08:50:56 -0500, Jarkko Sakkinen
> >> <jarkko.sakkinen@linux.intel.com> wrote:
> >>> I'll categorically deny noexec in the next patch set version.
> >>>
> >>> /Jarkko
> >> There are use cases supported currently in which enclave binary is received
> >> via IPC/RPC and held in buffers before EADD. Denying noexec altogether would
> >> break those, right?
> > No.  noexec only applies to file-backed VMAs, what you're describing is loading
> > an enclave from an anon VMA, which will still have VM_MAYEXEC.
> 
> Maybe I'm just stupid, but I still don't get the scenario that's being
> thwarted or why it is valuable.  The SDM is worthless on what EMODPE
> does or what its restrictions are.
> 
> In pseudo-C, it's something logically like this for the "nice" case:
> 
> 	ptr = mmap("/some/executable", PROT_EXEC);
> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
> 	mmap(sgx_fd);
> 	EENTER;
> 
> And we're trying to thwart:
> 
> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
> 	mmap(sgx_fd);
> 	EENTER;
> 
> because that loads data into the enclave which is executable but which
> was not executable normally.  But, we're allowing this from anonymous
> memory, so this would seem to work:
> 
> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
> 	buffer = malloc(PAGE_SIZE);
> 	memcpy(buffer, ptr, PAGE_SIZE);
> 	// need mprotect(buf, PROT_EXEC)???
> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, buffer, size);
> 	mmap(sgx_fd);
> 	EENTER;
> 
> and give the same result.  What am I missing?

The last example, where the enclave is copied to a buffer, is out of scope
for noexec.  But, it is in scope for LSMs, e.g. for this last example, we
could add an LSM upcall so that SELinux could require PROCESS_EXECMEM (or an
SGX specific equivalent).

The ->mprotect() hook gives us direct line of sight to such LSM upcalls,
e.g. I have fully working code that implements the LSM integration.  LSM
support isn't in this series because the only thing everyone could agree on
in terms of an LSM implementation is that it wasn't needed for initial
upstreaming :-)


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 20:01                             ` Sean Christopherson
@ 2020-09-24 20:10                               ` Dave Hansen
  2020-09-24 20:25                                 ` Sean Christopherson
  2020-09-24 22:07                                 ` Jarkko Sakkinen
  0 siblings, 2 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-24 20:10 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/24/20 1:01 PM, Sean Christopherson wrote:
>> In pseudo-C, it's something logically like this for the "nice" case:
>>
>> 	ptr = mmap("/some/executable", PROT_EXEC);
>> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
>> 	mmap(sgx_fd);
>> 	EENTER;
>>
>> And we're trying to thwart:
>>
>> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
>> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
>> 	mmap(sgx_fd);
>> 	EENTER;
>>
>> because that loads data into the enclave which is executable but which
>> was not executable normally.  But, we're allowing this from anonymous
>> memory, so this would seem to work:
>>
>> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
>> 	buffer = malloc(PAGE_SIZE);
>> 	memcpy(buffer, ptr, PAGE_SIZE);
>> 	// need mprotect(buf, PROT_EXEC)???
>> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, buffer, size);
>> 	mmap(sgx_fd);
>> 	EENTER;
>>
>> and give the same result.  What am I missing?
> The last example, where the enclave is copied to a buffer, is out of scope
> for noexec.  But, it is in scope for LSMs, e.g. for this last example, we
> could add an LSM upcall so that SELinux could require PROCESS_EXECMEM (or an
> SGX specific equivalent).

Why don't we just declare enclave memory as "out of scope for noexec" in
the same way that anonymous memory is, and just discard this patch?
That doesn't seem too much of a stretch.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 20:10                               ` Dave Hansen
@ 2020-09-24 20:25                                 ` Sean Christopherson
  2020-09-24 20:54                                   ` Dave Hansen
  2020-09-24 22:07                                 ` Jarkko Sakkinen
  1 sibling, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-24 20:25 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 01:10:31PM -0700, Dave Hansen wrote:
> On 9/24/20 1:01 PM, Sean Christopherson wrote:
> >> In pseudo-C, it's something logically like this for the "nice" case:
> >>
> >> 	ptr = mmap("/some/executable", PROT_EXEC);
> >> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
> >> 	mmap(sgx_fd);
> >> 	EENTER;
> >>
> >> And we're trying to thwart:
> >>
> >> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
> >> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
> >> 	mmap(sgx_fd);
> >> 	EENTER;
> >>
> >> because that loads data into the enclave which is executable but which
> >> was not executable normally.  But, we're allowing this from anonymous
> >> memory, so this would seem to work:
> >>
> >> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
> >> 	buffer = malloc(PAGE_SIZE);
> >> 	memcpy(buffer, ptr, PAGE_SIZE);
> >> 	// need mprotect(buf, PROT_EXEC)???
> >> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, buffer, size);
> >> 	mmap(sgx_fd);
> >> 	EENTER;
> >>
> >> and give the same result.  What am I missing?
> > The last example, where the enclave is copied to a buffer, is out of scope
> > for noexec.  But, it is in scope for LSMs, e.g. for this last example, we
> > could add an LSM upcall so that SELinux could require PROCESS_EXECMEM (or an
> > SGX specific equivalent).
> 
> Why don't we just declare enclave memory as "out of scope for noexec" in
> the same way that anonymous memory is, and just discard this patch?
> That doesn't seem too much of a stretch.

Because we lose line of sight to LSM support.  Without enforcing "declare perms
at load time" in the initial series, we would create an ABI where userspace
could load an enclave page with only READ permissions and then map the enclave
with whatever permissions it wants, without any convenient way for SGX to call
into the LSM.

Retroactively enforcing permissions at load time would break the ABI, or at
least yield different behavior based on the mere existence of LSMs, e.g. if
LSMs are supported, suddenly the ADD_PAGES w/ READ -> mmap(RWX) flow breaks,
even if there is no LSM policy denying that behavior.

Enforcing LSM policies using the existing mmap()/mprotect() hooks doesn't work
well because the only information available is a fd pointing at
/dev/sgx/enclave, which is largely useless because /dev/sgx/enclave must be
map SHARED w/ RWX to run an enclave.  We explored things like grabbing a
reference to the source file for later verification, but that means pinning
files for the entire lifetime of an enclave.

Enforcing noexec was an easy/obvious addition since we need 99% of the code for
potential LSM support anyways.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 20:25                                 ` Sean Christopherson
@ 2020-09-24 20:54                                   ` Dave Hansen
  2020-09-24 22:10                                     ` Jarkko Sakkinen
  2020-09-24 23:05                                     ` Sean Christopherson
  0 siblings, 2 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-24 20:54 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/24/20 1:25 PM, Sean Christopherson wrote:
...
>> Why don't we just declare enclave memory as "out of scope for noexec" in
>> the same way that anonymous memory is, and just discard this patch?
>> That doesn't seem too much of a stretch.
> 
> Because we lose line of sight to LSM support.  Without enforcing "declare perms
> at load time" in the initial series, we would create an ABI where userspace
> could load an enclave page with only READ permissions and then map the enclave
> with whatever permissions it wants, without any convenient way for SGX to call
> into the LSM.

This argument holds no water for me.  LSMs are all about taking what
would otherwise be perfectly acceptable behavior and breaking them in
the name of security.  They fundamentally break applications that used
to work just fine and also did totally sane things.

> Retroactively enforcing permissions at load time would break the ABI, or at
> least yield different behavior based on the mere existence of LSMs, e.g. if
> LSMs are supported, suddenly the ADD_PAGES w/ READ -> mmap(RWX) flow breaks,
> even if there is no LSM policy denying that behavior.

I'm a security dummy.  All I know is that when I see something like this:

	if (security_vm_enough_memory_mm(mm, grow))
		...

I know to ignore it because I like my systems to boot and I'm not using
those hooks.  :)

How could the mere presence of an LSM change the behavior of one of
these hooks?  Don't they have to actually hook into the specific place
and actively go trying to change the behavior at that site?


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 19:11                       ` Haitao Huang
  2020-09-24 19:28                         ` Sean Christopherson
@ 2020-09-24 21:55                         ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-24 21:55 UTC (permalink / raw)
  To: Haitao Huang
  Cc: Sean Christopherson, Andy Lutomirski, X86 ML, linux-sgx, LKML,
	Linux-MM, Andrew Morton, Matthew Wilcox, Jethro Beekman,
	Darren Kenny, Andy Shevchenko, asapek, Borislav Petkov, Xing,
	Cedric, chenalexchen, Conrad Parker, cyhanish, Dave Hansen,
	Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 02:11:37PM -0500, Haitao Huang wrote:
> > For me this has caused months of confusion and misunderstanding of this
> > feature. I only recently realized that "oh, right, we invented this".
> > 
> > They are contrived scenarios enough that they should be considered when
> > the workloads hit.
> > 
> > Either we fully support noexec or not at all. Any "partial" thing is a
> > two edged sword: it can bring some robustness with the price of
> > complexity and possible unknown uknown scenarios where they might become
> > API issue.
> > 
> > I rather think later on how to extend API in some way to enable such
> > contrivid scenarios rather than worrying about how this could be abused.
> > 
> > The whole SGX is complex beast already so lets not add any extra when
> > there is no a hard requirement to do so.
> > 
> > I'll categorically deny noexec in the next patch set version.
> > 
> > /Jarkko
> 
> There are use cases supported currently in which enclave binary is received
> via IPC/RPC and held in buffers before EADD. Denying noexec altogether would
> break those, right?

I do not see why data cannot be provided at run-time. AFAIK, it is not
different from executables how this works when it comes to noexec.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 19:28                         ` Sean Christopherson
  2020-09-24 19:39                           ` Dave Hansen
@ 2020-09-24 21:58                           ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-24 21:58 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Haitao Huang, Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Dave Hansen, Huang,
	Haitao, Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 12:28:54PM -0700, Sean Christopherson wrote:
> On Thu, Sep 24, 2020 at 02:11:37PM -0500, Haitao Huang wrote:
> > On Wed, 23 Sep 2020 08:50:56 -0500, Jarkko Sakkinen
> > <jarkko.sakkinen@linux.intel.com> wrote:
> > >I'll categorically deny noexec in the next patch set version.
> > >
> > >/Jarkko
> > 
> > There are use cases supported currently in which enclave binary is received
> > via IPC/RPC and held in buffers before EADD. Denying noexec altogether would
> > break those, right?
> 
> No.  noexec only applies to file-backed VMAs, what you're describing is loading
> an enclave from an anon VMA, which will still have VM_MAYEXEC.
> 
> I believe you're thinking of SELinux's EXECMEM, which is required to execute
> from anonymous memory, and which we talked about (more than once) applying to
> SGX enclaves.
> 
> That being said, I still dislike the idea of requiring VM_MAYEXEC, it's a hack
> that doesn't really buy us much, if anything.

I think it makes sense as long as it is not half-way there solution.

Either require it for the full binary or not at all. I'm fine with
either.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 20:10                               ` Dave Hansen
  2020-09-24 20:25                                 ` Sean Christopherson
@ 2020-09-24 22:07                                 ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-24 22:07 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 01:10:31PM -0700, Dave Hansen wrote:
> On 9/24/20 1:01 PM, Sean Christopherson wrote:
> >> In pseudo-C, it's something logically like this for the "nice" case:
> >>
> >> 	ptr = mmap("/some/executable", PROT_EXEC);
> >> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
> >> 	mmap(sgx_fd);
> >> 	EENTER;
> >>
> >> And we're trying to thwart:
> >>
> >> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
> >> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, ptr, size);
> >> 	mmap(sgx_fd);
> >> 	EENTER;
> >>
> >> because that loads data into the enclave which is executable but which
> >> was not executable normally.  But, we're allowing this from anonymous
> >> memory, so this would seem to work:
> >>
> >> 	ptr = mmap("/mnt/noexec/file", PROT_READ);
> >> 	buffer = malloc(PAGE_SIZE);
> >> 	memcpy(buffer, ptr, PAGE_SIZE);
> >> 	// need mprotect(buf, PROT_EXEC)???
> >> 	ioctl(sgx_fd, ADD_ENCLAVE_PAGE, SGX_PROT_EXEC, buffer, size);
> >> 	mmap(sgx_fd);
> >> 	EENTER;
> >>
> >> and give the same result.  What am I missing?
> > The last example, where the enclave is copied to a buffer, is out of scope
> > for noexec.  But, it is in scope for LSMs, e.g. for this last example, we
> > could add an LSM upcall so that SELinux could require PROCESS_EXECMEM (or an
> > SGX specific equivalent).
> 
> Why don't we just declare enclave memory as "out of scope for noexec" in
> the same way that anonymous memory is, and just discard this patch?
> That doesn't seem too much of a stretch.

I did that already for v39. It unconditionally discards noexec
partitions.

I see EMODPE as the key driver for this patch, not noexec partitions.

I.e. post you've done SGX_IOC_ENCLAVE_INIT you are capped when it
comes to permissions.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 20:54                                   ` Dave Hansen
@ 2020-09-24 22:10                                     ` Jarkko Sakkinen
  2020-09-24 23:05                                     ` Sean Christopherson
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-24 22:10 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 01:54:09PM -0700, Dave Hansen wrote:
> On 9/24/20 1:25 PM, Sean Christopherson wrote:
> ...
> >> Why don't we just declare enclave memory as "out of scope for noexec" in
> >> the same way that anonymous memory is, and just discard this patch?
> >> That doesn't seem too much of a stretch.
> > 
> > Because we lose line of sight to LSM support.  Without enforcing "declare perms
> > at load time" in the initial series, we would create an ABI where userspace
> > could load an enclave page with only READ permissions and then map the enclave
> > with whatever permissions it wants, without any convenient way for SGX to call
> > into the LSM.
> 
> This argument holds no water for me.  LSMs are all about taking what
> would otherwise be perfectly acceptable behavior and breaking them in
> the name of security.  They fundamentally break applications that used
> to work just fine and also did totally sane things.

Well, I see that having this gives a better assets for a separate
loader. It can load and initialize the enclave and a consumer can
then use it but cannot override its permissions.

I don't even remember exactly how SELinux permissions played together.
I don't think it is required as an argument for this patch.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 20:54                                   ` Dave Hansen
  2020-09-24 22:10                                     ` Jarkko Sakkinen
@ 2020-09-24 23:05                                     ` Sean Christopherson
  2020-09-24 23:09                                       ` Dave Hansen
  1 sibling, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-24 23:05 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 01:54:09PM -0700, Dave Hansen wrote:
> On 9/24/20 1:25 PM, Sean Christopherson wrote:
> ...
> >> Why don't we just declare enclave memory as "out of scope for noexec" in
> >> the same way that anonymous memory is, and just discard this patch?
> >> That doesn't seem too much of a stretch.
> > 
> > Because we lose line of sight to LSM support.  Without enforcing "declare perms
> > at load time" in the initial series, we would create an ABI where userspace
> > could load an enclave page with only READ permissions and then map the enclave
> > with whatever permissions it wants, without any convenient way for SGX to call
> > into the LSM.
> 
> This argument holds no water for me.  LSMs are all about taking what
> would otherwise be perfectly acceptable behavior and breaking them in
> the name of security.  They fundamentally break applications that used
> to work just fine and also did totally sane things.

It's not about LSMs breaking things, they can obviously do that without any
help.  The concern is that, unless we lay the groundwork now, adding support
for LSMs in the future will break existing applications or create an unholy
mess of an ABI.

If we want to support LSM policy for enclave page permissions, checking LSM
policies at load time and hooking mprotect() to enforce the policy at run
time is by far the cleanest solution of the many ideas we discussed.

The problem is that enforcing permissions via mprotect() needs to be done
unconditionally, otherwise we end up with weird behavior where the existence
of an LSM will change what is/isn't allowed, even if the LSM(s) has no SGX
policy whatsover.

And on the flip side, enforcing permissions unconditionally will break
backwards compatibility.

I'm a-ok if we want to kill off the ->mprotect() hook, so long as we
acknowledge that in doing so we are likely throwing in the towel on supporting
LSM policies for enclave page permissions.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 23:05                                     ` Sean Christopherson
@ 2020-09-24 23:09                                       ` Dave Hansen
  2020-09-25  0:00                                         ` Sean Christopherson
  0 siblings, 1 reply; 81+ messages in thread
From: Dave Hansen @ 2020-09-24 23:09 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/24/20 4:05 PM, Sean Christopherson wrote:
> The problem is that enforcing permissions via mprotect() needs to be done
> unconditionally, otherwise we end up with weird behavior where the existence
> of an LSM will change what is/isn't allowed, even if the LSM(s) has no SGX
> policy whatsover.

Could we make this a bit less abstract, please?

Could someone point to code or another examples that demonstrates how
the mere existence of an LSM will change what is/isn't allowed?

I can't seem to wrap my head around it as-is.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-24 23:09                                       ` Dave Hansen
@ 2020-09-25  0:00                                         ` Sean Christopherson
  2020-09-25 17:18                                           ` Dave Hansen
  0 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-25  0:00 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Thu, Sep 24, 2020 at 04:09:25PM -0700, Dave Hansen wrote:
> On 9/24/20 4:05 PM, Sean Christopherson wrote:
> > The problem is that enforcing permissions via mprotect() needs to be done
> > unconditionally, otherwise we end up with weird behavior where the existence
> > of an LSM will change what is/isn't allowed, even if the LSM(s) has no SGX
> > policy whatsover.
> 
> Could we make this a bit less abstract, please?
> 
> Could someone point to code or another examples that demonstrates how
> the mere existence of an LSM will change what is/isn't allowed?
> 
> I can't seem to wrap my head around it as-is.

Without pre-declared permissions, loading and running an enclave would be:

	ptr = malloc(size);
        memcpy(ptr, evil_shenanigans, size);
	ioctl(sgx_fd, ENCLAVE_ADD_PAGE, ptr, size);
        ...
	ioctl(sgx_fd, ENCLAVE_INIT);

        enclave = mmap(sgx_fd, ... PROT_READ);
        mprotect(enclave, ..., PROT_READ | PROT_EXEC);

	EENTER;

With the existing security_file_mprotect(), an LSM will see:

        vma->vm_file ~= /dev/sgx/enclave
        prot = PROT_READ | PROT_EXEC

From a policy perspective, the LSM can't do much because every enclave is
backed by /dev/sgx/enclave, and all enclaves need READ and EXEC perms, i.e.
a policy can only deny all enclaves or allow enclaves.

The solution we came up with is to require userspace to declare the intended
permissions at build time so that an LSM hook can be invoked when the source
VMA is availble, e.g. in this example, the LSM would see that the process is
loading executable code into an enclave from an anonymous VMA:

        ptr = malloc(size);
        memcpy(ptr, evil_shenanigans, size);
	ioctl(sgx_fd, ENCLAVE_ADD_PAGE, SGX_PROT_READ | SGX_PROT_EXEC, ptr, size);
        {
                ret = security_enclave_load(ptr, prot);
                if (ret)
                        return ret;

                enclave_page->declared_prot = prot;
        }
        ...
	ioctl(sgx_fd, ENCLAVE_INIT);

and then enforce the declared perms via ->mprotect()

        enclave = mmap(sgx_fd, ... PROT_READ);
        mprotect(enclave, ..., PROT_READ | PROT_EXEC);
        |
        -> sgx_mprotect(...)
           {
                   if (~enclave_page->declared_prot & prot)
                        return -EACCES;
           }

	EENTER;

So the above would be allowed, but this would fail (irrespective of LSM behavior):

        ptr = malloc(size);
        memcpy(ptr, evil_shenanigans, size);
	ioctl(sgx_fd, ENCLAVE_ADD_PAGE, SGX_PROT_READ, ptr, size);
        ...
	ioctl(sgx_fd, ENCLAVE_INIT);

        enclave = mmap(sgx_fd, ... PROT_READ);
        mprotect(enclave, ..., PROT_READ | PROT_EXEC);


My concern is that if we merge this

        ioctl(sgx_fd, ENCLAVE_ADD_PAGE, SGX_PROT_READ | SGX_PROT_EXEC, ptr, size);

without ->mprotect(), we can't actually enforce the declared protections.  And
if we drop the field altogether:

        ioctl(sgx_fd, ENCLAVE_ADD_PAGE, ptr, size);

then we can't implement security_enclave_load().


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-25  0:00                                         ` Sean Christopherson
@ 2020-09-25 17:18                                           ` Dave Hansen
  2020-09-25 19:43                                             ` Sean Christopherson
  0 siblings, 1 reply; 81+ messages in thread
From: Dave Hansen @ 2020-09-25 17:18 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

Thanks for the walkthrough.  The thing that clicked for me seeing those
examples was how the earlier ioctl(ADD_PAGE) is "bound" to later
enforcement actions at enclave PTE creation time.

On 9/24/20 5:00 PM, Sean Christopherson wrote:
> My concern is that if we merge this
> 
>         ioctl(sgx_fd, ENCLAVE_ADD_PAGE, SGX_PROT_READ | SGX_PROT_EXEC, ptr, size);
> 
> without ->mprotect(), we can't actually enforce the declared protections.  And
> if we drop the field altogether:
> 
>         ioctl(sgx_fd, ENCLAVE_ADD_PAGE, ptr, size);
> 
> then we can't implement security_enclave_load().

To me, it's perfectly OK to have parts of the ABI which are unused.  It
sure makes them harder to test if there are no actual users in the code,
but if it solves a real problem with the ABI, I'm fine with it.

Let's see if I can put all the pieces together.

Background:

1. SGX enclave pages are populated with data by copying data to them
   from normal memory via: ioctl(sgx_fd, ENCLAVE_ADD_PAGE, src_ptr...);
2. We want to be able to restrict those normal memory data sources.  For
   instance, before copying data to an executable enclave page, we might
   ensure that the source is executable.
3. Enclave page permissions are dynamic just like normal permissions and
   can be adjusted at runtime with mprotect() (along with a
   corresponding special instruction inside the enclave)
4. The original data source may have have long since vanished at the
   time when enclave page permission are established (mmap() or
   mprotect())

Solution:

The solution is to force enclaves creators to declare their intent up
front to ioctl(ENCLAVE_ADD_PAGE).  This intent can me immediately
compared to the source data mapping (and rejected if necessary).  It is
also stashed off and then later compared with enclave PTEs to ensure
that any future mmap()/mprotect() operations performed by the enclave
creator or the enclave itself are consistent with the earlier declared
permissions.

Essentially, this means that whenever the kernel is asked to change an
enclave PTE, it needs to ensure the change is consistent with that
stashed intent.  There is an existing vm_ops->mmap() hook which allows
SGX to do that for mmap().  However, there is no ->mprotect() hook.  Add
a vm_ops->mprotect() hook so that mprotect() operations which are
inconsistent with any page's stashed intent can be rejected by the driver.

Implications:

However, there is currently no implementation of the intent checks at
the time of ioctl(ENCLAVE_ADD_PAGE).  That means that the intent
argument (SGX_PROT_*) is currently unused.

--

Is that all correct?  Did I miss anything?


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-25 17:18                                           ` Dave Hansen
@ 2020-09-25 19:43                                             ` Sean Christopherson
  2020-09-25 19:53                                               ` Dave Hansen
  0 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-25 19:43 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Fri, Sep 25, 2020 at 10:18:28AM -0700, Dave Hansen wrote:
> Thanks for the walkthrough.  The thing that clicked for me seeing those
> examples was how the earlier ioctl(ADD_PAGE) is "bound" to later
> enforcement actions at enclave PTE creation time.
> 
> On 9/24/20 5:00 PM, Sean Christopherson wrote:
> > My concern is that if we merge this
> > 
> >         ioctl(sgx_fd, ENCLAVE_ADD_PAGE, SGX_PROT_READ | SGX_PROT_EXEC, ptr, size);
> > 
> > without ->mprotect(), we can't actually enforce the declared protections.  And
> > if we drop the field altogether:
> > 
> >         ioctl(sgx_fd, ENCLAVE_ADD_PAGE, ptr, size);
> > 
> > then we can't implement security_enclave_load().
> 
> To me, it's perfectly OK to have parts of the ABI which are unused.  It
> sure makes them harder to test if there are no actual users in the code,
> but if it solves a real problem with the ABI, I'm fine with it.
> 
> Let's see if I can put all the pieces together.
> 
> Background:
> 
> 1. SGX enclave pages are populated with data by copying data to them
>    from normal memory via: ioctl(sgx_fd, ENCLAVE_ADD_PAGE, src_ptr...);
> 2. We want to be able to restrict those normal memory data sources.  For
>    instance, before copying data to an executable enclave page, we might
>    ensure that the source is executable.
> 3. Enclave page permissions are dynamic just like normal permissions and
>    can be adjusted at runtime with mprotect() (along with a
>    corresponding special instruction inside the enclave)
> 4. The original data source may have have long since vanished at the
>    time when enclave page permission are established (mmap() or
>    mprotect())
> 
> Solution:
> 
> The solution is to force enclaves creators to declare their intent up
> front to ioctl(ENCLAVE_ADD_PAGE).  This intent can me immediately
> compared to the source data mapping (and rejected if necessary).  It is
> also stashed off and then later compared with enclave PTEs to ensure
> that any future mmap()/mprotect() operations performed by the enclave
> creator or the enclave itself are consistent with the earlier declared
> permissions.
> 
> Essentially, this means that whenever the kernel is asked to change an
> enclave PTE, it needs to ensure the change is consistent with that
> stashed intent.  There is an existing vm_ops->mmap() hook which allows
> SGX to do that for mmap().  However, there is no ->mprotect() hook.  Add
> a vm_ops->mprotect() hook so that mprotect() operations which are
> inconsistent with any page's stashed intent can be rejected by the driver.

Yes to all of the above.

> Implications:
> 
> However, there is currently no implementation of the intent checks at
> the time of ioctl(ENCLAVE_ADD_PAGE).

Correct.

> That means that the intent argument (SGX_PROT_*) is currently unused.

No, the intent argument is used (eventually) by SGX's ->mprotect()
implementation, i.e. sgx_mprotect() enforces that the actual protections are a
subset of the declared/intended protections.

If ->mprotect() is not merged, then it yes, it will be unused.  And therein
lies the problem as the kernel can't start using/enforcing the intent without
breaking userspace.  E.g. an enclave loaded with SGX_PROT_READ but mprotect()'d
with PROT_READ | PROT_EXEC would break if sgx_mprotect() came along.

One way to avoid introducing ->mprotect() would be to require all enclaves to
declare all pages with READ|WRITE|EXEC.  Then we could drop sgx_mprotect()
since the mprotect() permissions are guaranteed to be a subset of the declared
permissions.  That would have the added bonus of eliminating the per-page
checks in sgx_mmap()/sgx_mprotect(), though I've no idea if that is a
meaningful optmization or it's lost in the noise.

The big downside of requiring READ|WRITE|EXEC is that it will make life hell
for a LSM policy owner if they ever want to apply EXECMEM or EXECMOD style
restritions on enclaves, i.e. if SELinux folks want to add
security_enclave_load().

I find that I'm more or less ok with that approach, in no small part because
introducing security_enclave_load() might be a pretty big "if", e.g. security
folks may decide that they'd rather allow/deny enclaves based on the
measurement or signer of the enclave and eschew per-page checks entirely.

> --
> 
> Is that all correct?  Did I miss anything?


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-25 19:43                                             ` Sean Christopherson
@ 2020-09-25 19:53                                               ` Dave Hansen
  2020-09-26  4:15                                                 ` Andy Lutomirski
  2020-09-28  0:53                                                 ` Jarkko Sakkinen
  0 siblings, 2 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-25 19:53 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Haitao Huang, Jarkko Sakkinen, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/25/20 12:43 PM, Sean Christopherson wrote:
>> That means that the intent argument (SGX_PROT_*) is currently unused.
> No, the intent argument is used (eventually) by SGX's ->mprotect()
> implementation, i.e. sgx_mprotect() enforces that the actual protections are a
> subset of the declared/intended protections.
> 
> If ->mprotect() is not merged, then it yes, it will be unused.

OK, I think I've got it.

I think I'm OK with adding ->mprotect().  As long as folks buy into the
argument that intent needs to be checked at mmap() time, they obviously
need to be checked at mprotect() too.

Jarkko, if you want to try and rewrite the changelog, capturing the
discussion here and reply, I think I can ack the resulting patch.  I
don't know if that will satisfy the request from Boris from an ack from
a "mm person", but we can at least start there. :)

Please be judicious in what you include in the changelog.  There's been
a lot of detritus in them.  Let's keep it as short, sweet, simple and on
topic as we can.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-25 19:53                                               ` Dave Hansen
@ 2020-09-26  4:15                                                 ` Andy Lutomirski
  2020-09-28  0:53                                                 ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Andy Lutomirski @ 2020-09-26  4:15 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Jarkko Sakkinen,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx


> On Sep 25, 2020, at 12:53 PM, Dave Hansen <dave.hansen@intel.com> wrote:
> 
> On 9/25/20 12:43 PM, Sean Christopherson wrote:
>>> That means that the intent argument (SGX_PROT_*) is currently unused.
>> No, the intent argument is used (eventually) by SGX's ->mprotect()
>> implementation, i.e. sgx_mprotect() enforces that the actual protections are a
>> subset of the declared/intended protections.
>> 
>> If ->mprotect() is not merged, then it yes, it will be unused.
> 
> OK, I think I've got it.
> 
> I think I'm OK with adding ->mprotect().  As long as folks buy into the
> argument that intent needs to be checked at mmap() time, they obviously
> need to be checked at mprotect() too.
> 
> Jarkko, if you want to try and rewrite the changelog, capturing the
> discussion here and reply, I think I can ack the resulting patch.  I
> don't know if that will satisfy the request from Boris from an ack from
> a "mm person", but we can at least start there. :)

I think I agree. ->mprotect seems reasonable to me.

FWIW, I don’t think I should ack this particular thing — it was, to a decent extent, my suggestion in the first place, so I’m biased. I think it turned into something reasonable, and the ->mprotect mechanism seems easily supportable and plausibly useful for other purposes down the road.

> 
> Please be judicious in what you include in the changelog.  There's been
> a lot of detritus in them.  Let's keep it as short, sweet, simple and on
> topic as we can.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-25 19:53                                               ` Dave Hansen
  2020-09-26  4:15                                                 ` Andy Lutomirski
@ 2020-09-28  0:53                                                 ` Jarkko Sakkinen
  2020-09-28 14:04                                                   ` Dave Hansen
  1 sibling, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-28  0:53 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Fri, Sep 25, 2020 at 12:53:35PM -0700, Dave Hansen wrote:
> On 9/25/20 12:43 PM, Sean Christopherson wrote:
> >> That means that the intent argument (SGX_PROT_*) is currently unused.
> > No, the intent argument is used (eventually) by SGX's ->mprotect()
> > implementation, i.e. sgx_mprotect() enforces that the actual protections are a
> > subset of the declared/intended protections.
> > 
> > If ->mprotect() is not merged, then it yes, it will be unused.
> 
> OK, I think I've got it.
> 
> I think I'm OK with adding ->mprotect().  As long as folks buy into the
> argument that intent needs to be checked at mmap() time, they obviously
> need to be checked at mprotect() too.
> 
> Jarkko, if you want to try and rewrite the changelog, capturing the
> discussion here and reply, I think I can ack the resulting patch.  I
> don't know if that will satisfy the request from Boris from an ack from
> a "mm person", but we can at least start there. :)

I think what it needs, based on what I've read, is the step by step
description of the EMODPE scenarion without this callback and with it.

I think other important thing to underline is that an LSM or any other
security measure can only do a sane decision when the enclave is loaded.
At that point we know the source (vm_file).

I.e. when you are doing mmap() or mprotect() you don't have that
information. The permissions kind of describe the contact made at that
point of time.

> Please be judicious in what you include in the changelog.  There's been
> a lot of detritus in them.  Let's keep it as short, sweet, simple and on
> topic as we can.

Of course.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28  0:53                                                 ` Jarkko Sakkinen
@ 2020-09-28 14:04                                                   ` Dave Hansen
  2020-09-28 16:19                                                     ` Jarkko Sakkinen
  2020-10-18  8:49                                                     ` Dr. Greg
  0 siblings, 2 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-28 14:04 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/27/20 5:53 PM, Jarkko Sakkinen wrote:
> On Fri, Sep 25, 2020 at 12:53:35PM -0700, Dave Hansen wrote:
>> On 9/25/20 12:43 PM, Sean Christopherson wrote:
>>>> That means that the intent argument (SGX_PROT_*) is currently unused.
>>> No, the intent argument is used (eventually) by SGX's ->mprotect()
>>> implementation, i.e. sgx_mprotect() enforces that the actual protections are a
>>> subset of the declared/intended protections.
>>>
>>> If ->mprotect() is not merged, then it yes, it will be unused.
>>
>> OK, I think I've got it.
>>
>> I think I'm OK with adding ->mprotect().  As long as folks buy into the
>> argument that intent needs to be checked at mmap() time, they obviously
>> need to be checked at mprotect() too.
>>
>> Jarkko, if you want to try and rewrite the changelog, capturing the
>> discussion here and reply, I think I can ack the resulting patch.  I
>> don't know if that will satisfy the request from Boris from an ack from
>> a "mm person", but we can at least start there. :)
> 
> I think what it needs, based on what I've read, is the step by step
> description of the EMODPE scenarion without this callback and with it.

EMODPE is virtually irrelevant for this whole thing.  The x86 PTE
permissions still specify the most restrictive permissions, which is
what matters the most.

We care about the _worst_ the enclave can do, not what it imposes on
itself on top of that.

> I think other important thing to underline is that an LSM or any other
> security measure can only do a sane decision when the enclave is loaded.
> At that point we know the source (vm_file).

Right, you know the source, but it can be anonymous or a file.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 14:04                                                   ` Dave Hansen
@ 2020-09-28 16:19                                                     ` Jarkko Sakkinen
  2020-09-28 16:48                                                       ` Dave Hansen
  2020-10-18  8:49                                                     ` Dr. Greg
  1 sibling, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-28 16:19 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 28, 2020 at 07:04:38AM -0700, Dave Hansen wrote:
> On 9/27/20 5:53 PM, Jarkko Sakkinen wrote:
> > On Fri, Sep 25, 2020 at 12:53:35PM -0700, Dave Hansen wrote:
> >> On 9/25/20 12:43 PM, Sean Christopherson wrote:
> >>>> That means that the intent argument (SGX_PROT_*) is currently unused.
> >>> No, the intent argument is used (eventually) by SGX's ->mprotect()
> >>> implementation, i.e. sgx_mprotect() enforces that the actual protections are a
> >>> subset of the declared/intended protections.
> >>>
> >>> If ->mprotect() is not merged, then it yes, it will be unused.
> >>
> >> OK, I think I've got it.
> >>
> >> I think I'm OK with adding ->mprotect().  As long as folks buy into the
> >> argument that intent needs to be checked at mmap() time, they obviously
> >> need to be checked at mprotect() too.
> >>
> >> Jarkko, if you want to try and rewrite the changelog, capturing the
> >> discussion here and reply, I think I can ack the resulting patch.  I
> >> don't know if that will satisfy the request from Boris from an ack from
> >> a "mm person", but we can at least start there. :)
> > 
> > I think what it needs, based on what I've read, is the step by step
> > description of the EMODPE scenarion without this callback and with it.
> 
> EMODPE is virtually irrelevant for this whole thing.  The x86 PTE
> permissions still specify the most restrictive permissions, which is
> what matters the most.
> 
> We care about the _worst_ the enclave can do, not what it imposes on
> itself on top of that.

AFAIK it is not, or what we are protecting against with this anyway
then?

Let say an LSM makes decision for the permissions based on origin. If we
do not have this you can:

1. EMODPE
2. mprotect

I.e. whatever LSM decides, won't matter.

The other case, noexec, is now unconditionally denied.

> > I think other important thing to underline is that an LSM or any other
> > security measure can only do a sane decision when the enclave is loaded.
> > At that point we know the source (vm_file).
> 
> Right, you know the source, but it can be anonymous or a file.

They are both origin, the point being that you know what you're dealing
with when you build the enclave, not when you map it.

This is my current rewrite of the commit message in my master branch:

"
    mm: Add 'mprotect' callback to vm_ops
    
    Intel Sofware Guard eXtensions (SGX) allows creation of blobs called
    enclaves, for which page permissions are defined when the enclave is first
    loaded. Once an enclave is loaded and initialized, it can be mapped to the
    process address space.
    
    There is no standard file format for enclaves. They are dynamically built
    and the ways how enclaves are deployed differ greatly. For an app you might
    want to have a simple static binary, but on the other hand for a container
    you might want to dynamically create the whole thing at run-time. Also, the
    existing ecosystem for SGX is already large, which would make the task very
    hard.
    
    Finally, even if there was a standard format, one would still want a
    dynamic way to add pages to the enclave. One big reason for this is that
    enclaves have load time defined pages that represent entry points to the
    enclave. Each entry point can service one hardware thread at a time and
    you might want to run-time parametrize this depending on your environment.
    
    The consequence is that enclaves are best created with an ioctl API and the
    access control can be based only to the origin of the source file for the
    enclave data, i.e. on VMA file pointer and page permissions. For example,
    this could be done with LSM hooks that are triggered in the appropriate
    ioctl's and they could make the access control decision based on this
    information.
    
    Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
    upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
    could upgrade its permissions by using EMODPE followed by an appropriate
    mprotect() call. This would be completely hidden from the kernel.
    
    Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
    that will ensure that {mmap, mprotect}() permissions do not surpass any of
    the original page permissions. This feature allows to maintain and refine
    sane access control for enclaves.
"

I'm mostly happy with this but am open for change suggestions.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 16:19                                                     ` Jarkko Sakkinen
@ 2020-09-28 16:48                                                       ` Dave Hansen
  2020-09-28 19:32                                                         ` Jarkko Sakkinen
  2020-09-28 20:18                                                         ` Jarkko Sakkinen
  0 siblings, 2 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-28 16:48 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/28/20 9:19 AM, Jarkko Sakkinen wrote:
> On Mon, Sep 28, 2020 at 07:04:38AM -0700, Dave Hansen wrote:
>> EMODPE is virtually irrelevant for this whole thing.  The x86 PTE
>> permissions still specify the most restrictive permissions, which is
>> what matters the most.
>>
>> We care about the _worst_ the enclave can do, not what it imposes on
>> itself on top of that.
> 
> AFAIK it is not, or what we are protecting against with this anyway
> then?
> 
> Let say an LSM makes decision for the permissions based on origin. If we
> do not have this you can:
> 
> 1. EMODPE
> 2. mprotect

The thing that matters is that the enclave needs relaxed permissions
from the kernel.  What it *ALSO* needs to do to *ITSELF* to get those
permissions is entirely irrelevant to the kernel.

> I.e. whatever LSM decides, won't matter.
> 
> The other case, noexec, is now unconditionally denied.



>>> I think other important thing to underline is that an LSM or any other
>>> security measure can only do a sane decision when the enclave is loaded.
>>> At that point we know the source (vm_file).
>>
>> Right, you know the source, but it can be anonymous or a file.
> 
> They are both origin, the point being that you know what you're dealing
> with when you build the enclave, not when you map it.
> 
> This is my current rewrite of the commit message in my master branch:
> 
> "
>     mm: Add 'mprotect' callback to vm_ops
>     
>     Intel Sofware Guard eXtensions (SGX) allows creation of blobs called
>     enclaves, for which page permissions are defined when the enclave is first
>     loaded. Once an enclave is loaded and initialized, it can be mapped to the
>     process address space.
>     
>     There is no standard file format for enclaves. They are dynamically built
>     and the ways how enclaves are deployed differ greatly. For an app you might
>     want to have a simple static binary, but on the other hand for a container
>     you might want to dynamically create the whole thing at run-time. Also, the
>     existing ecosystem for SGX is already large, which would make the task very
>     hard.

I'm sorry I ever mentioned the file format.  Please remove any mention
of it.  It's irrelevant.  This entire paragraph is irrelevant.

>     Finally, even if there was a standard format, one would still want a
>     dynamic way to add pages to the enclave. One big reason for this is that
>     enclaves have load time defined pages that represent entry points to the
>     enclave. Each entry point can service one hardware thread at a time and
>     you might want to run-time parametrize this depending on your environment.

I also don't know what this paragraph has to do with the mprotect()
hook.  Please remove it.

>     The consequence is that enclaves are best created with an ioctl API and the
>     access control can be based only to the origin of the source file for the
>     enclave data, i.e. on VMA file pointer and page permissions. For example,

It's not strictly page permissions, though.  It's actually VMA
permissions.  The thing you copy from might be the zero page, and even
though it has Write=0 page permissions, apps are completely OK to write
to the address.  This is the WRITE vs. MAY_WRITE semantic in the VMA flags.

It's also not just about *files*.  Anonymous memory might or might not
be a valid source for enclave data based on LSM hooks.

>     this could be done with LSM hooks that are triggered in the appropriate
>     ioctl's and they could make the access control decision based on this
>     information.

This "appropriate ioctl's" is not good changelog material.  Please use
those bytes to convey actual information.

	... this could be done with LSM hooks which restrict the source
	of enclave page data

I don't care that it's an ioctl(), really.  What matters is what the
ioctl() does: copy data into enclave pages.

>     Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
>     upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
>     could upgrade its permissions by using EMODPE followed by an appropriate
>     mprotect() call. This would be completely hidden from the kernel.

There's too much irrelevant info.

I'll say it again: all that matters is that enclaves can legitimately,
safely, and securely have a need for the kernel to change page
permissions.  That's *IT*.  EMODPE just happens to be part of the
mechanism that makes these permission changes safe for enclaves.  It's a
side show.

>     Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
>     that will ensure that {mmap, mprotect}() permissions do not surpass any of
>     the original page permissions. This feature allows to maintain and refine
>     sane access control for enclaves.

Instead of "original", I'd stick to the "source" page nomenclature.
There are also "original" permissions with mprotect().

Also, it's literally OK for the enclave page permissions to surpass the
original (source) page permissions.  That sentence is incorrect, or at
least misleadingly imprecise.

> I'm mostly happy with this but am open for change suggestions.

I wrote a pretty nice description of this.  It was about 90% correct,
shorter, and conveyed more information.  I'd suggest starting with that.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 16:48                                                       ` Dave Hansen
@ 2020-09-28 19:32                                                         ` Jarkko Sakkinen
  2020-09-28 19:45                                                           ` Dave Hansen
  2020-09-28 20:18                                                         ` Jarkko Sakkinen
  1 sibling, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-28 19:32 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 28, 2020 at 09:48:10AM -0700, Dave Hansen wrote:
> On 9/28/20 9:19 AM, Jarkko Sakkinen wrote:
> > On Mon, Sep 28, 2020 at 07:04:38AM -0700, Dave Hansen wrote:
> >> EMODPE is virtually irrelevant for this whole thing.  The x86 PTE
> >> permissions still specify the most restrictive permissions, which is
> >> what matters the most.
> >>
> >> We care about the _worst_ the enclave can do, not what it imposes on
> >> itself on top of that.
> > 
> > AFAIK it is not, or what we are protecting against with this anyway
> > then?
> > 
> > Let say an LSM makes decision for the permissions based on origin. If we
> > do not have this you can:
> > 
> > 1. EMODPE
> > 2. mprotect
> 
> The thing that matters is that the enclave needs relaxed permissions
> from the kernel.  What it *ALSO* needs to do to *ITSELF* to get those
> permissions is entirely irrelevant to the kernel.

Lets try to find the root of misunderstanding, shall we?

I'm assuming that your statement is encapsulated to:

https://lore.kernel.org/linux-sgx/32fc9df4-d4aa-6768-aa06-0035427b7535@intel.com/

I do agree with this.

And here is a direct quote:

"It is also stashed off and then later compared with enclave PTEs to
ensure that any future mmap()/mprotect() operations performed by the
enclave creator or the enclave itself are consistent with the earlier
declared permissions."

Without the mprotect callback in place, by using EMODPE and mprotect,
one could surpass the permisssions that we declared earlier.

With the callback in place this is not possible. EMODPE can be freely
used but mprotect() always caps the permissions. It enables us to *not
care* about EMODPE.

My problem is that I fully agree what you say in your description but
disagree on that EMODPE should not be mentioned.

> >     There is no standard file format for enclaves. They are dynamically built
> >     and the ways how enclaves are deployed differ greatly. For an app you might
> >     want to have a simple static binary, but on the other hand for a container
> >     you might want to dynamically create the whole thing at run-time. Also, the
> >     existing ecosystem for SGX is already large, which would make the task very
> >     hard.
> 
> I'm sorry I ever mentioned the file format.  Please remove any mention
> of it.  It's irrelevant.  This entire paragraph is irrelevant.

Not sure if it is or not. It is merely to state that execve() path is
possible. Perhaps should be toned down in some way. Should be like the
a small remark at most.

> >     Finally, even if there was a standard format, one would still want a
> >     dynamic way to add pages to the enclave. One big reason for this is that
> >     enclaves have load time defined pages that represent entry points to the
> >     enclave. Each entry point can service one hardware thread at a time and
> >     you might want to run-time parametrize this depending on your environment.
> 
> I also don't know what this paragraph has to do with the mprotect()
> hook.  Please remove it.

Agreed.

> >     The consequence is that enclaves are best created with an ioctl API and the
> >     access control can be based only to the origin of the source file for the
> >     enclave data, i.e. on VMA file pointer and page permissions. For example,
> 
> It's not strictly page permissions, though.  It's actually VMA
> permissions.  The thing you copy from might be the zero page, and even
> though it has Write=0 page permissions, apps are completely OK to write
> to the address.  This is the WRITE vs. MAY_WRITE semantic in the VMA flags.
> 
> It's also not just about *files*.  Anonymous memory might or might not
> be a valid source for enclave data based on LSM hooks.

Yes, this should be refined, agreed. Source can be either anonymous page
or a file, I do of course understand that.

> >     this could be done with LSM hooks that are triggered in the appropriate
> >     ioctl's and they could make the access control decision based on this
> >     information.
> 
> This "appropriate ioctl's" is not good changelog material.  Please use
> those bytes to convey actual information.
> 
> 	... this could be done with LSM hooks which restrict the source
> 	of enclave page data
> 
> I don't care that it's an ioctl(), really.  What matters is what the
> ioctl() does: copy data into enclave pages.

Agreed.

> >     Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
> >     upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
> >     could upgrade its permissions by using EMODPE followed by an appropriate
> >     mprotect() call. This would be completely hidden from the kernel.
> 
> There's too much irrelevant info.
> 
> I'll say it again: all that matters is that enclaves can legitimately,
> safely, and securely have a need for the kernel to change page
> permissions.  That's *IT*.  EMODPE just happens to be part of the
> mechanism that makes these permission changes safe for enclaves.  It's a
> side show.

Disagree on this. I wrote my statement about. Maybe it should not be
driving argument but should be definitely part of the description.

> >     Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
> >     that will ensure that {mmap, mprotect}() permissions do not surpass any of
> >     the original page permissions. This feature allows to maintain and refine
> >     sane access control for enclaves.
> 
> Instead of "original", I'd stick to the "source" page nomenclature.
> There are also "original" permissions with mprotect().
> 
> Also, it's literally OK for the enclave page permissions to surpass the
> original (source) page permissions.  That sentence is incorrect, or at
> least misleadingly imprecise.

Yes it is. It's fine to use EMODPE to upgrade the perms, and by having
this hook, doing anything nasty with it is impossible.

> > I'm mostly happy with this but am open for change suggestions.
> 
> I wrote a pretty nice description of this.  It was about 90% correct,
> shorter, and conveyed more information.  I'd suggest starting with that.

I should have added a disclaimer that my description is not up to date.
Just do not want to make anything final before this EMODPE discussion
has some conclusion.

I'm fine using your description as basis for the commit message if as long
as these few details are settled.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 19:32                                                         ` Jarkko Sakkinen
@ 2020-09-28 19:45                                                           ` Dave Hansen
  2020-09-28 20:19                                                             ` Jarkko Sakkinen
  0 siblings, 1 reply; 81+ messages in thread
From: Dave Hansen @ 2020-09-28 19:45 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/28/20 12:32 PM, Jarkko Sakkinen wrote:
> My problem is that I fully agree what you say in your description but
> disagree on that EMODPE should not be mentioned.

I'll just be very clear: I'm not willing to ack any patch with a
changelog that has more than a passing mention of EMODPE.

Do what you think is best, but if sticking to your guns may deplete the
pool of folks willing to ack your patch.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 16:48                                                       ` Dave Hansen
  2020-09-28 19:32                                                         ` Jarkko Sakkinen
@ 2020-09-28 20:18                                                         ` Jarkko Sakkinen
  1 sibling, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-28 20:18 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 28, 2020 at 09:48:10AM -0700, Dave Hansen wrote:
> On 9/28/20 9:19 AM, Jarkko Sakkinen wrote:
> > On Mon, Sep 28, 2020 at 07:04:38AM -0700, Dave Hansen wrote:
> >> EMODPE is virtually irrelevant for this whole thing.  The x86 PTE
> >> permissions still specify the most restrictive permissions, which is
> >> what matters the most.
> >>
> >> We care about the _worst_ the enclave can do, not what it imposes on
> >> itself on top of that.
> > 
> > AFAIK it is not, or what we are protecting against with this anyway
> > then?
> > 
> > Let say an LSM makes decision for the permissions based on origin. If we
> > do not have this you can:
> > 
> > 1. EMODPE
> > 2. mprotect
> 
> The thing that matters is that the enclave needs relaxed permissions
> from the kernel.  What it *ALSO* needs to do to *ITSELF* to get those
> permissions is entirely irrelevant to the kernel.

Lets try to find the root of misunderstanding, shall we?

I'm assuming that your statement is encapsulated to:

https://lore.kernel.org/linux-sgx/32fc9df4-d4aa-6768-aa06-0035427b7535@intel.com/

I do agree with this.

And here is a direct quote:

"It is also stashed off and then later compared with enclave PTEs to
ensure that any future mmap()/mprotect() operations performed by the
enclave creator or the enclave itself are consistent with the earlier
declared permissions."

Without the mprotect callback in place, by using EMODPE and mprotect,
one could surpass the permisssions that we declared earlier.

With the callback in place this is not possible. EMODPE can be freely
used but mprotect() always caps the permissions. It enables us to *not
care* about EMODPE.

My problem is that I fully agree what you say in your description but
disagree on that EMODPE should not be mentioned.

> >     There is no standard file format for enclaves. They are dynamically built
> >     and the ways how enclaves are deployed differ greatly. For an app you might
> >     want to have a simple static binary, but on the other hand for a container
> >     you might want to dynamically create the whole thing at run-time. Also, the
> >     existing ecosystem for SGX is already large, which would make the task very
> >     hard.
> 
> I'm sorry I ever mentioned the file format.  Please remove any mention
> of it.  It's irrelevant.  This entire paragraph is irrelevant.

Not sure if it is or not. It is merely to state that execve() path is
possible. Perhaps should be toned down in some way. Should be like the
a small remark at most.

> >     Finally, even if there was a standard format, one would still want a
> >     dynamic way to add pages to the enclave. One big reason for this is that
> >     enclaves have load time defined pages that represent entry points to the
> >     enclave. Each entry point can service one hardware thread at a time and
> >     you might want to run-time parametrize this depending on your environment.
> 
> I also don't know what this paragraph has to do with the mprotect()
> hook.  Please remove it.

Agreed.

> >     The consequence is that enclaves are best created with an ioctl API and the
> >     access control can be based only to the origin of the source file for the
> >     enclave data, i.e. on VMA file pointer and page permissions. For example,
> 
> It's not strictly page permissions, though.  It's actually VMA
> permissions.  The thing you copy from might be the zero page, and even
> though it has Write=0 page permissions, apps are completely OK to write
> to the address.  This is the WRITE vs. MAY_WRITE semantic in the VMA flags.
> 
> It's also not just about *files*.  Anonymous memory might or might not
> be a valid source for enclave data based on LSM hooks.

Yes, this should be refined, agreed. Source can be either anonymous page
or a file, I do of course understand that.

> >     this could be done with LSM hooks that are triggered in the appropriate
> >     ioctl's and they could make the access control decision based on this
> >     information.
> 
> This "appropriate ioctl's" is not good changelog material.  Please use
> those bytes to convey actual information.
> 
> 	... this could be done with LSM hooks which restrict the source
> 	of enclave page data
> 
> I don't care that it's an ioctl(), really.  What matters is what the
> ioctl() does: copy data into enclave pages.

Agreed.

> >     Unfortunately, there is ENCLS[EMODPE] that a running enclave can use to
> >     upgrade its permissions. If we do not limit mmap() and mprotect(), enclave
> >     could upgrade its permissions by using EMODPE followed by an appropriate
> >     mprotect() call. This would be completely hidden from the kernel.
> 
> There's too much irrelevant info.
> 
> I'll say it again: all that matters is that enclaves can legitimately,
> safely, and securely have a need for the kernel to change page
> permissions.  That's *IT*.  EMODPE just happens to be part of the
> mechanism that makes these permission changes safe for enclaves.  It's a
> side show.

Disagree on this. I wrote my statement about. Maybe it should not be
driving argument but should be definitely part of the description.

> >     Add 'mprotect' hook to vm_ops, so that a callback can be implemeted for SGX
> >     that will ensure that {mmap, mprotect}() permissions do not surpass any of
> >     the original page permissions. This feature allows to maintain and refine
> >     sane access control for enclaves.
> 
> Instead of "original", I'd stick to the "source" page nomenclature.
> There are also "original" permissions with mprotect().
> 
> Also, it's literally OK for the enclave page permissions to surpass the
> original (source) page permissions.  That sentence is incorrect, or at
> least misleadingly imprecise.

Yes it is. It's fine to use EMODPE to upgrade the perms, and by having
this hook, doing anything nasty with it is impossible.

> > I'm mostly happy with this but am open for change suggestions.
> 
> I wrote a pretty nice description of this.  It was about 90% correct,
> shorter, and conveyed more information.  I'd suggest starting with that.

I should have added a disclaimer that my description is not up to date.
Just do not want to make anything final before this EMODPE discussion
has some conclusion.

I'm fine using your description as basis for the commit message if as long
as these few details are settled.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 19:45                                                           ` Dave Hansen
@ 2020-09-28 20:19                                                             ` Jarkko Sakkinen
  2020-09-29  1:37                                                               ` Andy Lutomirski
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-28 20:19 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 28, 2020 at 12:45:27PM -0700, Dave Hansen wrote:
> On 9/28/20 12:32 PM, Jarkko Sakkinen wrote:
> > My problem is that I fully agree what you say in your description but
> > disagree on that EMODPE should not be mentioned.
> 
> I'll just be very clear: I'm not willing to ack any patch with a
> changelog that has more than a passing mention of EMODPE.
> 
> Do what you think is best, but if sticking to your guns may deplete the
> pool of folks willing to ack your patch.

I do see it mentioned in other responses too in this thread, and not
just mine.

And here is even a request to get it to the changelog:

https://lore.kernel.org/linux-sgx/1B23E216-0229-4BDD-8B09-807256A54AF5@amacapital.net/

I'm absolutely fine not to mention EMODPE but after re-reading the
thread, it is not like there is one voice on it. I don't really
care all that much whether it is mentioned or not but there should
be some reasonable logic behind the decision.

PS. I just noticed that my previous response did not reach lore so
I bounced it again.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-22 14:03     ` Jarkko Sakkinen
  2020-09-22 14:24       ` Borislav Petkov
@ 2020-09-29  1:14       ` Sean Christopherson
  2020-09-29  3:50         ` Jarkko Sakkinen
  1 sibling, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-09-29  1:14 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Borislav Petkov, x86, linux-sgx, linux-kernel, linux-mm,
	Jethro Beekman, Jordan Hand, Nathaniel McCallum, Chunyang Hui,
	Seth Moore, akpm, andriy.shevchenko, asapek, cedric.xing,
	chenalexchen, conradparker, cyhanish, dave.hansen, haitao.huang,
	josh, kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman,
	puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 22, 2020 at 05:03:23PM +0300, Jarkko Sakkinen wrote:
> On Tue, Sep 22, 2020 at 12:45:38PM +0200, Borislav Petkov wrote:
> > > +	spin_lock(&sgx_active_page_list_lock);
> > > +	for (i = 0; i < SGX_NR_TO_SCAN; i++) {
> > > +		if (list_empty(&sgx_active_page_list))
> > 
> > Isn't it enough to do this once, i.e., not in the loop? You're holding
> > sgx_active_page_list_lock...

Argh, I missed this until I looked at Jarkko's updated tree.

The reason for checking list_empty() on every iteration is that the loop is
greedy, i.e. it tries to grab and reclaim up to 16 (SGX_NR_TO_SCAN) EPC pages
at a time.

> I think that would make sense. Distantly analogous to the EINIT
> discussion. Too complex code for yet to be known problem workloads I'd
> say.

Nooooo.  Please no.

This will most definitely impact workloads running a single large enclave, or a
process running multiple enclaves, as we'll lose the batching of ETRACK and IPIs.
ETRACK isn't a big deal, but the IPIs are painful and could thrash the system.
E.g. in the current code, reclaiming 10 pages from an enclave with actively
running threads will generate one round of IPIs to CPUs associated with the
enclave (based on the mm struct).  Going to per-page reclaim will likely result
in 10 rounds of IPIs as threads will reenter the enclave immediately after each
IPI wave.

Having to grab the section spinlock for every page is also (very) problematic.
Reclaiming one page at a time makes it nigh impossible for the reclaimer to
keep up as every allocation attempt acquires the spinlock.  I.e. the reclaimer
has to contend with every CPU that is faulting in an EPC page or is adding a
page to the enclave.  In my experiments with the EPC cgroup, even batching 16
pages may be insufficient to make "forward progress".  That's not an apples to
apples comparison, but it's a rough equivalent of what will happen with the
reclaim thread versus EPC page faults.  We can (and should) play with scaling
the number of reclaim threads, but at this stage, that's an exercise best left
to post-upstreaming.

I can't do A/B testing to provide numbers, because the changes in Jarkko's tree
break basic reclaim.  Which is a nice segue into my last point: this is by far
the most subtle code in the SGX code base; I really, really don't want to be
making last minute changes in this area unless they are absolutely necessary or
obviously benign.  Even if/when we get the basic reclaim functional again, and
assuming it doesn't have performance issues, I wouldn't be comfortable merging
the code without hammering it with the EPC cgroup tests for multiple days (on
top of the 1+ days to rebased the EPC cgroup).  Past testing with the cgroup
found multiple bugs with races between CPUs that required hitting a window that
was open for less than 10 instructions.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 20:19                                                             ` Jarkko Sakkinen
@ 2020-09-29  1:37                                                               ` Andy Lutomirski
  2020-09-29  4:05                                                                 ` Jarkko Sakkinen
  0 siblings, 1 reply; 81+ messages in thread
From: Andy Lutomirski @ 2020-09-29  1:37 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Dave Hansen, Sean Christopherson, Haitao Huang, Andy Lutomirski,
	X86 ML, linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx


> On Sep 28, 2020, at 1:20 PM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
> 
> On Mon, Sep 28, 2020 at 12:45:27PM -0700, Dave Hansen wrote:
>>> On 9/28/20 12:32 PM, Jarkko Sakkinen wrote:
>>> My problem is that I fully agree what you say in your description but
>>> disagree on that EMODPE should not be mentioned.
>> 
>> I'll just be very clear: I'm not willing to ack any patch with a
>> changelog that has more than a passing mention of EMODPE.
>> 
>> Do what you think is best, but if sticking to your guns may deplete the
>> pool of folks willing to ack your patch.
> 
> I do see it mentioned in other responses too in this thread, and not
> just mine.
> 
> And here is even a request to get it to the changelog:
> 
> https://lore.kernel.org/linux-sgx/1B23E216-0229-4BDD-8B09-807256A54AF5@amacapital.net/
> 
> I'm absolutely fine not to mention EMODPE but after re-reading the
> thread, it is not like there is one voice on it. I don't really
> care all that much whether it is mentioned or not but there should
> be some reasonable logic behind the decision.

I don’t personally care that much about EMODPE but, you could probably get the point across with something like:

SGX’s EPCM permission bits do not obviate the need to enforce these rules in the PTEs because enclaves can freely modify the EPCM permissions using EMODPE.

IOW, EMODPE is not really special here; rather, EMODPE’s existence demonstrates that EADD / EEXTEND are not special.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-29  1:14       ` Sean Christopherson
@ 2020-09-29  3:50         ` Jarkko Sakkinen
  2020-09-29  8:35           ` Sean Christopherson
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-29  3:50 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Borislav Petkov, x86, linux-sgx, linux-kernel, linux-mm,
	Jethro Beekman, Jordan Hand, Nathaniel McCallum, Chunyang Hui,
	Seth Moore, akpm, andriy.shevchenko, asapek, cedric.xing,
	chenalexchen, conradparker, cyhanish, dave.hansen, haitao.huang,
	josh, kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman,
	puiterwijk, rientjes, tglx, yaozhangx

On Mon, Sep 28, 2020 at 06:14:39PM -0700, Sean Christopherson wrote:
> On Tue, Sep 22, 2020 at 05:03:23PM +0300, Jarkko Sakkinen wrote:
> > On Tue, Sep 22, 2020 at 12:45:38PM +0200, Borislav Petkov wrote:
> > > > +	spin_lock(&sgx_active_page_list_lock);
> > > > +	for (i = 0; i < SGX_NR_TO_SCAN; i++) {
> > > > +		if (list_empty(&sgx_active_page_list))
> > > 
> > > Isn't it enough to do this once, i.e., not in the loop? You're holding
> > > sgx_active_page_list_lock...
> 
> Argh, I missed this until I looked at Jarkko's updated tree.
> 
> The reason for checking list_empty() on every iteration is that the loop is
> greedy, i.e. it tries to grab and reclaim up to 16 (SGX_NR_TO_SCAN) EPC pages
> at a time.
> 
> > I think that would make sense. Distantly analogous to the EINIT
> > discussion. Too complex code for yet to be known problem workloads I'd
> > say.
> 
> Nooooo.  Please no.

I added this comment in the beginning of the sgx_reclaim_pages() based
on your response:

/*
 * Take a fixed number of pages from the head of the active page pool and
 * reclaim them to the enclave's private shmem files. Skip the pages, which have
 * been accessed since the last scan. Move those pages to the tail of active
 * page pool so that the pages get scanned in LRU like fashion.
 *
 * Batch process a chunk of pages (at the moment 16) in order to degrade amount
 * of IPI's and ETRACK's potentially required. sgx_encl_ewb() does degrade a bit
 * among the HW threads with three stage EWB pipeline (EWB, ETRACK + EWB and IPI
 * + EWB) but not sufficiently. Reclaiming one page at a time would also be
 * problematic as it would increase the lock contention too much, which would
 * halt forward progress.
 */

And reverted reclaimer patch as it was. Do you have anything in mind
that I should add or modify in it?

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-29  1:37                                                               ` Andy Lutomirski
@ 2020-09-29  4:05                                                                 ` Jarkko Sakkinen
  2020-09-29 14:24                                                                   ` Dave Hansen
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-29  4:05 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Dave Hansen, Sean Christopherson, Haitao Huang, Andy Lutomirski,
	X86 ML, linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 28, 2020 at 06:37:54PM -0700, Andy Lutomirski wrote:
> I don’t personally care that much about EMODPE but, you could probably
> get the point across with something like:
> 
> SGX’s EPCM permission bits do not obviate the need to enforce these
> rules in the PTEs because enclaves can freely modify the EPCM
> permissions using EMODPE.
> 
> IOW, EMODPE is not really special here; rather, EMODPE’s existence
> demonstrates that EADD / EEXTEND are not special.

So I did "disagree and commit" with this one. I'm not actually
diagreeing on anything what Dave wrote, on the contrary it is an
understandable high level description. I just thought that it would not
hurt to remark that the ISA contains such peculiarities as EMODPE.

I did only very rudimentary clean up for the text (e.g. fix the ioctl
name, add shortt summary and not much else).

Does not make sense to waste more time to this. I'll move on to
implement the missing boot time patching for the vDSO so that we
get the next version out.

"
mm: Add 'mprotect' hook to struct vm_operations_struct

Background
==========

1. SGX enclave pages are populated with data by copying data to them
   from normal memory via ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).
2. We want to be able to restrict those normal memory data sources.  For
   instance, before copying data to an executable enclave page, we might
   ensure that the source is executable.
3. Enclave page permissions are dynamic just like normal permissions and
   can be adjusted at runtime with mprotect() (along with a
   corresponding special instruction inside the enclave).
4. The original data source may have have long since vanished at the
   time when enclave page permission are established (mmap() or
   mprotect()).

Solution
========

The solution is to force enclaves creators to declare their intent up front
to ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).  This intent can me immediately
compared to the source data mapping (and rejected if necessary).  It is
also stashed off and then later compared with enclave PTEs to ensure that
any future mmap()/mprotect() operations performed by the enclave creator or
the enclave itself are consistent with the earlier declared permissions.

Essentially, this means that whenever the kernel is asked to change an
enclave PTE, it needs to ensure the change is consistent with that stashed
intent.  There is an existing vm_ops->mmap() hook which allows SGX to do
that for mmap().  However, there is no ->mprotect() hook.  Add a
vm_ops->mprotect() hook so that mprotect() operations which are
inconsistent with any page's stashed intent can be rejected by the driver.

Implications
============

However, there is currently no implementation of the intent checks at the
time of ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).  That means that the intent
argument (SGX_PROT_*) is currently unused.
"

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 16/24] x86/sgx: Add a page reclaimer
  2020-09-29  3:50         ` Jarkko Sakkinen
@ 2020-09-29  8:35           ` Sean Christopherson
  0 siblings, 0 replies; 81+ messages in thread
From: Sean Christopherson @ 2020-09-29  8:35 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Borislav Petkov, x86, linux-sgx, linux-kernel, linux-mm,
	Jethro Beekman, Jordan Hand, Nathaniel McCallum, Chunyang Hui,
	Seth Moore, akpm, andriy.shevchenko, asapek, cedric.xing,
	chenalexchen, conradparker, cyhanish, dave.hansen, haitao.huang,
	josh, kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman,
	puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 29, 2020 at 06:50:10AM +0300, Jarkko Sakkinen wrote:
> On Mon, Sep 28, 2020 at 06:14:39PM -0700, Sean Christopherson wrote:
> > On Tue, Sep 22, 2020 at 05:03:23PM +0300, Jarkko Sakkinen wrote:
> > > On Tue, Sep 22, 2020 at 12:45:38PM +0200, Borislav Petkov wrote:
> > > > > +	spin_lock(&sgx_active_page_list_lock);
> > > > > +	for (i = 0; i < SGX_NR_TO_SCAN; i++) {
> > > > > +		if (list_empty(&sgx_active_page_list))
> > > > 
> > > > Isn't it enough to do this once, i.e., not in the loop? You're holding
> > > > sgx_active_page_list_lock...
> > 
> > Argh, I missed this until I looked at Jarkko's updated tree.
> > 
> > The reason for checking list_empty() on every iteration is that the loop is
> > greedy, i.e. it tries to grab and reclaim up to 16 (SGX_NR_TO_SCAN) EPC pages
> > at a time.
> > 
> > > I think that would make sense. Distantly analogous to the EINIT
> > > discussion. Too complex code for yet to be known problem workloads I'd
> > > say.
> > 
> > Nooooo.  Please no.
> 
> I added this comment in the beginning of the sgx_reclaim_pages() based
> on your response:
> 
> /*
>  * Take a fixed number of pages from the head of the active page pool and
>  * reclaim them to the enclave's private shmem files. Skip the pages, which have
>  * been accessed since the last scan. Move those pages to the tail of active
>  * page pool so that the pages get scanned in LRU like fashion.
>  *
>  * Batch process a chunk of pages (at the moment 16) in order to degrade amount
>  * of IPI's and ETRACK's potentially required. sgx_encl_ewb() does degrade a bit
>  * among the HW threads with three stage EWB pipeline (EWB, ETRACK + EWB and IPI
>  * + EWB) but not sufficiently. Reclaiming one page at a time would also be
>  * problematic as it would increase the lock contention too much, which would
>  * halt forward progress.
>  */
> 
> And reverted reclaimer patch as it was. Do you have anything in mind
> that I should add or modify in it?

Nope, can't think of anything.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-29  4:05                                                                 ` Jarkko Sakkinen
@ 2020-09-29 14:24                                                                   ` Dave Hansen
  2020-09-30  0:20                                                                     ` Jarkko Sakkinen
  0 siblings, 1 reply; 81+ messages in thread
From: Dave Hansen @ 2020-09-29 14:24 UTC (permalink / raw)
  To: Jarkko Sakkinen, Andy Lutomirski
  Cc: Sean Christopherson, Haitao Huang, Andy Lutomirski, X86 ML,
	linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/28/20 9:05 PM, Jarkko Sakkinen wrote:
> On Mon, Sep 28, 2020 at 06:37:54PM -0700, Andy Lutomirski wrote:
>> I don’t personally care that much about EMODPE but, you could probably
>> get the point across with something like:
>>
>> SGX’s EPCM permission bits do not obviate the need to enforce these
>> rules in the PTEs because enclaves can freely modify the EPCM
>> permissions using EMODPE.
>>
>> IOW, EMODPE is not really special here; rather, EMODPE’s existence
>> demonstrates that EADD / EEXTEND are not special.
> 
> So I did "disagree and commit" with this one. I'm not actually
> diagreeing on anything what Dave wrote, on the contrary it is an
> understandable high level description. I just thought that it would not
> hurt to remark that the ISA contains such peculiarities as EMODPE.
> 
> I did only very rudimentary clean up for the text (e.g. fix the ioctl
> name, add shortt summary and not much else).
> 
> Does not make sense to waste more time to this. I'll move on to
> implement the missing boot time patching for the vDSO so that we
> get the next version out.
> 
> "
> mm: Add 'mprotect' hook to struct vm_operations_struct
> 
> Background
> ==========
> 
> 1. SGX enclave pages are populated with data by copying data to them
>    from normal memory via ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).
> 2. We want to be able to restrict those normal memory data sources.  For
>    instance, before copying data to an executable enclave page, we might
>    ensure that the source is executable.

I know I wrote that.  I suck, and I wrote it in a changelog-unacceptable
way.  Folks dislike the use of "we" in these things.  Here's a better
version:

  2. It is desirable to be able to restrict those normal memory data
     sources.  For instance, the kernel can ensure that the source is
     executable, before copying data to an executable enclave page.

> 3. Enclave page permissions are dynamic just like normal permissions and
>    can be adjusted at runtime with mprotect() (along with a
>    corresponding special instruction inside the enclave).
> 4. The original data source may have have long since vanished at the
>    time when enclave page permission are established (mmap() or
>    mprotect()).
> 
> Solution
> ========
> 
> The solution is to force enclaves creators to declare their intent up front
> to ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).  This intent can me immediately
> compared to the source data mapping (and rejected if necessary).  It is
> also stashed off and then later compared with enclave PTEs to ensure that
> any future mmap()/mprotect() operations performed by the enclave creator or
> the enclave itself are consistent with the earlier declared permissions.

Let's also say "... or *requested* by the enclave itself ...", since the
enclave itself can't directly make syscalls.

> Essentially, this means that whenever the kernel is asked to change an
> enclave PTE, it needs to ensure the change is consistent with that stashed
> intent.  There is an existing vm_ops->mmap() hook which allows SGX to do
> that for mmap().  However, there is no ->mprotect() hook.  Add a
> vm_ops->mprotect() hook so that mprotect() operations which are
> inconsistent with any page's stashed intent can be rejected by the driver.
> 
> Implications
> ============
> 
> However, there is currently no implementation of the intent checks at the
> time of ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).  That means that the intent
> argument (SGX_PROT_*) is currently unused.

This was incorrect to say.  Sean corrected me on this point.  Could you
look through the thread and incorporate that?


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-29 14:24                                                                   ` Dave Hansen
@ 2020-09-30  0:20                                                                     ` Jarkko Sakkinen
  2020-09-30 14:35                                                                       ` Dave Hansen
  0 siblings, 1 reply; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-30  0:20 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Andy Lutomirski, Sean Christopherson, Haitao Huang,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Sep 29, 2020 at 07:24:24AM -0700, Dave Hansen wrote:
> On 9/28/20 9:05 PM, Jarkko Sakkinen wrote:
> > On Mon, Sep 28, 2020 at 06:37:54PM -0700, Andy Lutomirski wrote:
> >> I don’t personally care that much about EMODPE but, you could probably
> >> get the point across with something like:
> >>
> >> SGX’s EPCM permission bits do not obviate the need to enforce these
> >> rules in the PTEs because enclaves can freely modify the EPCM
> >> permissions using EMODPE.
> >>
> >> IOW, EMODPE is not really special here; rather, EMODPE’s existence
> >> demonstrates that EADD / EEXTEND are not special.
> > 
> > So I did "disagree and commit" with this one. I'm not actually
> > diagreeing on anything what Dave wrote, on the contrary it is an
> > understandable high level description. I just thought that it would not
> > hurt to remark that the ISA contains such peculiarities as EMODPE.
> > 
> > I did only very rudimentary clean up for the text (e.g. fix the ioctl
> > name, add shortt summary and not much else).
> > 
> > Does not make sense to waste more time to this. I'll move on to
> > implement the missing boot time patching for the vDSO so that we
> > get the next version out.
> > 
> > "
> > mm: Add 'mprotect' hook to struct vm_operations_struct
> > 
> > Background
> > ==========
> > 
> > 1. SGX enclave pages are populated with data by copying data to them
> >    from normal memory via ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).
> > 2. We want to be able to restrict those normal memory data sources.  For
> >    instance, before copying data to an executable enclave page, we might
> >    ensure that the source is executable.
> 
> I know I wrote that.  I suck, and I wrote it in a changelog-unacceptable
> way.  Folks dislike the use of "we" in these things.  Here's a better
> version:
> 
>   2. It is desirable to be able to restrict those normal memory data
>      sources.  For instance, the kernel can ensure that the source is
>      executable, before copying data to an executable enclave page.
> 
> > 3. Enclave page permissions are dynamic just like normal permissions and
> >    can be adjusted at runtime with mprotect() (along with a
> >    corresponding special instruction inside the enclave).
> > 4. The original data source may have have long since vanished at the
> >    time when enclave page permission are established (mmap() or
> >    mprotect()).
> > 
> > Solution
> > ========
> > 
> > The solution is to force enclaves creators to declare their intent up front
> > to ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).  This intent can me immediately
> > compared to the source data mapping (and rejected if necessary).  It is
> > also stashed off and then later compared with enclave PTEs to ensure that
> > any future mmap()/mprotect() operations performed by the enclave creator or
> > the enclave itself are consistent with the earlier declared permissions.
> 
> Let's also say "... or *requested* by the enclave itself ...", since the
> enclave itself can't directly make syscalls.

Yes, it is definitely more understandable way to say it. Do you mind
if I rephrase it as:

"It is also stashed off and then later compared with enclave PTEs to
ensure that any future mmap()/mprotect() operations performed by the
enclave creator or requested the enclave by itself (e.g. by issuing
ECLU[EMODPE]) are consistent with the earlier declared permissions."

I'd just mention EMODPE as an example, but I'm also perfectly fine
leaving that out :-) Not a big deal for me.

Also, should there be commas, i.e. ", or requested the enclave by
itself,"? I suck with English comma rules.

> > Essentially, this means that whenever the kernel is asked to change an
> > enclave PTE, it needs to ensure the change is consistent with that stashed
> > intent.  There is an existing vm_ops->mmap() hook which allows SGX to do
> > that for mmap().  However, there is no ->mprotect() hook.  Add a
> > vm_ops->mprotect() hook so that mprotect() operations which are
> > inconsistent with any page's stashed intent can be rejected by the driver.
> > 
> > Implications
> > ============
> > 
> > However, there is currently no implementation of the intent checks at the
> > time of ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).  That means that the intent
> > argument (SGX_PROT_*) is currently unused.
> 
> This was incorrect to say.  Sean corrected me on this point.  Could you
> look through the thread and incorporate that?

OK, so we are probably talking about [1] here, right?

There are at least two checks done with and without the callback:

A. TCS pages are required to be passed with zero EPCM permissions,
   the reason being that CPU will silently overwrite its permissions
   zero. This check resides in sgx_validate_secinfo() [2].
B. noexec partitions are unconditionally disallowed. This check
   resides in __sgx_encl_add_page() [2].

TCS pages are funky in the way that they are also required to be
mapped as RW. OK, then you might argue that why not just require
RW as ioctl supplied permissions. That would cause a mismatch with
CPU calculated MRENCLAVE and one calculated to SIGSTRUCT. I've
written in past quite length explanation of this to the kdoc
of sgx_ioc_enclave_add_pages() [2].

This was something that I did not find from Sean's response.

To encompensate all this information in a paragraph, I'd write along
the lines of

"ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES, ...) checks for every page that
Thread Control Structure (TCS) pages are always added with zero
permissions and no pages are sourced from noexec partitions. TCS pages
are pages that work as entry points to the enclave. This is the basic
acceptance criteria for any enclave page before it gets mapped.

After finishing this, the ioctl will project the enclave permissions to
the corresponding VMA permissions and stores the result for later
lookup.  For regular pages this is an identity mapping but as an
exception TCS pages are unconditionally mapped as RW VMA permssion even
though their enclave permissions are zero. This required by the ISA.

This information will be used by sgx_mmap() and sgx_vma_protect() to
enforce that higher permissions than the projected permissions will
not be used by checking this for each every page in the address
range.

By doing this, we give assets for LSM's to make decisions during the
build time based on projected VMA permissions and the source VMA
(either a file or anonymous mapping) that hold when the enclave is
finally mapped to the visible memory."

Is this sufficient?

[1] https://lore.kernel.org/linux-sgx/20200915112842.897265-1-jarkko.sakkinen@linux.intel.com/T/#m7e84af96d63dd8ec528422cfc942f42e3bdf4356
[2] https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-sgx.git/tree/arch/x86/kernel/cpu/sgx/ioctl.c

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-30  0:20                                                                     ` Jarkko Sakkinen
@ 2020-09-30 14:35                                                                       ` Dave Hansen
  0 siblings, 0 replies; 81+ messages in thread
From: Dave Hansen @ 2020-09-30 14:35 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Sean Christopherson, Haitao Huang,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On 9/29/20 5:20 PM, Jarkko Sakkinen wrote:
> On Tue, Sep 29, 2020 at 07:24:24AM -0700, Dave Hansen wrote:
>> On 9/28/20 9:05 PM, Jarkko Sakkinen wrote:
>>> On Mon, Sep 28, 2020 at 06:37:54PM -0700, Andy Lutomirski wrote:
>>>> I don’t personally care that much about EMODPE but, you could probably
>>>> get the point across with something like:
>>>>
>>>> SGX’s EPCM permission bits do not obviate the need to enforce these
>>>> rules in the PTEs because enclaves can freely modify the EPCM
>>>> permissions using EMODPE.
>>>>
>>>> IOW, EMODPE is not really special here; rather, EMODPE’s existence
>>>> demonstrates that EADD / EEXTEND are not special.
>>>
>>> So I did "disagree and commit" with this one. I'm not actually
>>> diagreeing on anything what Dave wrote, on the contrary it is an
>>> understandable high level description. I just thought that it would not
>>> hurt to remark that the ISA contains such peculiarities as EMODPE.
>>>
>>> I did only very rudimentary clean up for the text (e.g. fix the ioctl
>>> name, add shortt summary and not much else).
>>>
>>> Does not make sense to waste more time to this. I'll move on to
>>> implement the missing boot time patching for the vDSO so that we
>>> get the next version out.
>>>
>>> "
>>> mm: Add 'mprotect' hook to struct vm_operations_struct
>>>
>>> Background
>>> ==========
>>>
>>> 1. SGX enclave pages are populated with data by copying data to them
>>>    from normal memory via ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).
>>> 2. We want to be able to restrict those normal memory data sources.  For
>>>    instance, before copying data to an executable enclave page, we might
>>>    ensure that the source is executable.
>>
>> I know I wrote that.  I suck, and I wrote it in a changelog-unacceptable
>> way.  Folks dislike the use of "we" in these things.  Here's a better
>> version:
>>
>>   2. It is desirable to be able to restrict those normal memory data
>>      sources.  For instance, the kernel can ensure that the source is
>>      executable, before copying data to an executable enclave page.
>>
>>> 3. Enclave page permissions are dynamic just like normal permissions and
>>>    can be adjusted at runtime with mprotect() (along with a
>>>    corresponding special instruction inside the enclave).
>>> 4. The original data source may have have long since vanished at the
>>>    time when enclave page permission are established (mmap() or
>>>    mprotect()).
>>>
>>> Solution
>>> ========
>>>
>>> The solution is to force enclaves creators to declare their intent up front
>>> to ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES).  This intent can me immediately
>>> compared to the source data mapping (and rejected if necessary).  It is
>>> also stashed off and then later compared with enclave PTEs to ensure that
>>> any future mmap()/mprotect() operations performed by the enclave creator or
>>> the enclave itself are consistent with the earlier declared permissions.
>>
>> Let's also say "... or *requested* by the enclave itself ...", since the
>> enclave itself can't directly make syscalls.
> 
> Yes, it is definitely more understandable way to say it. Do you mind
> if I rephrase it as:
> 
> "It is also stashed off and then later compared with enclave PTEs to
> ensure that any future mmap()/mprotect() operations performed by the
> enclave creator or requested the enclave by itself (e.g. by issuing
> ECLU[EMODPE]) are consistent with the earlier declared permissions."
> 
> I'd just mention EMODPE as an example, but I'm also perfectly fine
> leaving that out :-) Not a big deal for me.

If I say it's a big deal for me, will you remove the bloody thing?

Mentioning EMODPE is a distraction for this patch.  It's a big
distraction because it makes it sound like it is some kind of *peer* of
mmap()/mprotect().  It's not.  It's subservient to x86 paging
protections and thus *IRRELEVANT* for this unless you care about the
intricacies of writing enclaves.

It's a big deal to me.

Also, I've tried to give this feedback previously, but the paging
permissions are also essentially irrelevant.

> Also, should there be commas, i.e. ", or requested the enclave by
> itself,"? I suck with English comma rules.

I'd just say this:

	It is also stashed off and then later compared with enclave PTEs
	to ensure that any future mmap()/mprotect() operations are
	consistent with the earlier declared permissions.

Yours was starting to look pretty run on.

> "ioctl(fd, SGX_IOC_ENCLAVE_ADD_PAGES, ...) checks for every page that
> Thread Control Structure (TCS) pages are always added with zero
> permissions and no pages are sourced from noexec partitions. TCS pages
> are pages that work as entry points to the enclave. This is the basic
> acceptance criteria for any enclave page before it gets mapped.

This is going off into the SGX weeds again.

We don't need to justify the ABI for an ioctl() introduced in a
different patch in *THIS* patch.  Just remove this, please.

> After finishing this, the ioctl will project the enclave permissions to
> the corresponding VMA permissions and stores the result for later
> lookup.

That sounds vaguely relevant, although I'm not sure what permission
projection is.  You use that terminology over and over, so you probably
need to define it.

>  For regular pages this is an identity mapping but as an
> exception TCS pages are unconditionally mapped as RW VMA permssion even
> though their enclave permissions are zero. This required by the ISA.

I don't think this is relevant.

> This information will be used by sgx_mmap() and sgx_vma_protect() to
> enforce that higher permissions than the projected permissions will
> not be used by checking this for each every page in the address
> range.

I've given this feedback before.  Please don't use "higher" and "lower"
permissions.  "Stronger/weaker" is my preferred terminology.

You also don't have to *NAME* the functions.  If I want to know where a
structure field is, grep is a better way to find that.

Does this lose any meaning if we just say:

	This information will be to ensure that enclave PTEs will not be
	created with permissions weaker than the source data

?

> By doing this, we give assets for LSM's to make decisions during the
> build time based on projected VMA permissions and the source VMA
> (either a file or anonymous mapping) that hold when the enclave is
> finally mapped to the visible memory."


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 11/24] x86/sgx: Add SGX enclave driver
  2020-09-15 11:28 ` [PATCH v38 11/24] x86/sgx: Add SGX enclave driver Jarkko Sakkinen
  2020-09-21  9:30   ` Borislav Petkov
@ 2020-10-01 17:36   ` Sean Christopherson
  2020-10-01 18:49     ` Jarkko Sakkinen
  1 sibling, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-10-01 17:36 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: x86, linux-sgx, linux-kernel, linux-security-module, linux-mm,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Haitao Huang,
	Chunyang Hui, Jordan Hand, Nathaniel McCallum, Seth Moore,
	Darren Kenny, Suresh Siddha, andriy.shevchenko, asapek, bp,
	cedric.xing, chenalexchen, conradparker, cyhanish, dave.hansen,
	haitao.huang, josh, kai.huang, kai.svahn, kmoy, ludloff, luto,
	nhorman, puiterwijk, rientjes, tglx, yaozhangx

On Tue, Sep 15, 2020 at 02:28:29PM +0300, Jarkko Sakkinen wrote:
> +int __init sgx_drv_init(void)
> +{
> +	unsigned int eax, ebx, ecx, edx;
> +	u64 attr_mask, xfrm_mask;
> +	int ret;
> +	int i;
> +
> +	if (!boot_cpu_has(X86_FEATURE_SGX_LC)) {
> +		pr_info("The public key MSRs are not writable.\n");
> +		return -ENODEV;
> +	}
> +
> +	cpuid_count(SGX_CPUID, 0, &eax, &ebx, &ecx, &edx);
> +	sgx_misc_reserved_mask = ~ebx | SGX_MISC_RESERVED_MASK;
> +	sgx_encl_size_max_64 = 1ULL << ((edx >> 8) & 0xFF);
> +	sgx_encl_size_max_32 = 1ULL << (edx & 0xFF);
> +
> +	cpuid_count(SGX_CPUID, 1, &eax, &ebx, &ecx, &edx);
> +
> +	attr_mask = (((u64)ebx) << 32) + (u64)eax;
> +	sgx_attributes_reserved_mask = ~attr_mask | SGX_ATTR_RESERVED_MASK;
> +
> +	if (boot_cpu_has(X86_FEATURE_OSXSAVE)) {
> +		xfrm_mask = (((u64)edx) << 32) + (u64)ecx;
> +
> +		for (i = 2; i < 64; i++) {
> +			cpuid_count(0x0D, i, &eax, &ebx, &ecx, &edx);
> +			if ((1UL << i) & xfrm_mask)

Any reason not to use BIT()?  The max size computations are arguably not
bit operation, but XFRM is a set of bits.

> +				sgx_xsave_size_tbl[i] = eax + ebx;
> +		}
> +
> +		sgx_xfrm_reserved_mask = ~xfrm_mask;
> +	}
> +
> +	ret = misc_register(&sgx_dev_enclave);
> +	if (ret) {
> +		pr_err("Creating /dev/sgx/enclave failed with %d.\n", ret);
> +		return ret;
> +	}
> +
> +	return 0;
> +}


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 11/24] x86/sgx: Add SGX enclave driver
  2020-10-01 17:36   ` Sean Christopherson
@ 2020-10-01 18:49     ` Jarkko Sakkinen
  0 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-10-01 18:49 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: x86, linux-sgx, linux-kernel, linux-security-module, linux-mm,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Haitao Huang,
	Chunyang Hui, Jordan Hand, Nathaniel McCallum, Seth Moore,
	Darren Kenny, Suresh Siddha, andriy.shevchenko, asapek, bp,
	cedric.xing, chenalexchen, conradparker, cyhanish, dave.hansen,
	haitao.huang, josh, kai.huang, kai.svahn, kmoy, ludloff, luto,
	nhorman, puiterwijk, rientjes, tglx, yaozhangx

On Thu, Oct 01, 2020 at 10:36:53AM -0700, Sean Christopherson wrote:
> On Tue, Sep 15, 2020 at 02:28:29PM +0300, Jarkko Sakkinen wrote:
> > +int __init sgx_drv_init(void)
> > +{
> > +	unsigned int eax, ebx, ecx, edx;
> > +	u64 attr_mask, xfrm_mask;
> > +	int ret;
> > +	int i;
> > +
> > +	if (!boot_cpu_has(X86_FEATURE_SGX_LC)) {
> > +		pr_info("The public key MSRs are not writable.\n");
> > +		return -ENODEV;
> > +	}
> > +
> > +	cpuid_count(SGX_CPUID, 0, &eax, &ebx, &ecx, &edx);
> > +	sgx_misc_reserved_mask = ~ebx | SGX_MISC_RESERVED_MASK;
> > +	sgx_encl_size_max_64 = 1ULL << ((edx >> 8) & 0xFF);
> > +	sgx_encl_size_max_32 = 1ULL << (edx & 0xFF);
> > +
> > +	cpuid_count(SGX_CPUID, 1, &eax, &ebx, &ecx, &edx);
> > +
> > +	attr_mask = (((u64)ebx) << 32) + (u64)eax;
> > +	sgx_attributes_reserved_mask = ~attr_mask | SGX_ATTR_RESERVED_MASK;
> > +
> > +	if (boot_cpu_has(X86_FEATURE_OSXSAVE)) {
> > +		xfrm_mask = (((u64)edx) << 32) + (u64)ecx;
> > +
> > +		for (i = 2; i < 64; i++) {
> > +			cpuid_count(0x0D, i, &eax, &ebx, &ecx, &edx);
> > +			if ((1UL << i) & xfrm_mask)
> 
> Any reason not to use BIT()?  The max size computations are arguably not
> bit operation, but XFRM is a set of bits.

AFAIK, yes.

If you have bandwidth drop a patch for this and provision thing. I'm
busy with the documentation. If not, that's fine, I'll do it once I'm
able to.

Thanks.

/Jarkko


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-09-28 14:04                                                   ` Dave Hansen
  2020-09-28 16:19                                                     ` Jarkko Sakkinen
@ 2020-10-18  8:49                                                     ` Dr. Greg
  2020-10-19 21:31                                                       ` Sean Christopherson
  1 sibling, 1 reply; 81+ messages in thread
From: Dr. Greg @ 2020-10-18  8:49 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Jarkko Sakkinen, Sean Christopherson, Haitao Huang,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Sep 28, 2020 at 07:04:38AM -0700, Dave Hansen wrote:

Good morning, I hope the weekend is going well for everyone.

> On 9/27/20 5:53 PM, Jarkko Sakkinen wrote:
> > On Fri, Sep 25, 2020 at 12:53:35PM -0700, Dave Hansen wrote:
> >> On 9/25/20 12:43 PM, Sean Christopherson wrote:
> >>>> That means that the intent argument (SGX_PROT_*) is currently unused.
> >>> No, the intent argument is used (eventually) by SGX's ->mprotect()
> >>> implementation, i.e. sgx_mprotect() enforces that the actual protections are a
> >>> subset of the declared/intended protections.
> >>>
> >>> If ->mprotect() is not merged, then it yes, it will be unused.
> >>
> >> OK, I think I've got it.
> >>
> >> I think I'm OK with adding ->mprotect().  As long as folks buy into the
> >> argument that intent needs to be checked at mmap() time, they obviously
> >> need to be checked at mprotect() too.
> >>
> >> Jarkko, if you want to try and rewrite the changelog, capturing the
> >> discussion here and reply, I think I can ack the resulting patch.  I
> >> don't know if that will satisfy the request from Boris from an ack from
> >> a "mm person", but we can at least start there. :)
> > 
> > I think what it needs, based on what I've read, is the step by step
> > description of the EMODPE scenarion without this callback and with it.
> 
> EMODPE is virtually irrelevant for this whole thing.  The x86 PTE
> permissions still specify the most restrictive permissions, which is
> what matters the most.
> 
> We care about the _worst_ the enclave can do, not what it imposes on
> itself on top of that.
> 
> > I think other important thing to underline is that an LSM or any other
> > security measure can only do a sane decision when the enclave is loaded.
> > At that point we know the source (vm_file).
> 
> Right, you know the source, but it can be anonymous or a file.

Or it could be loaded over the network in encrypted form by the
enclave itself.

Sean, admirably, wants to peer into the future and set the driver up
from an architectural perspective, to future proof it for the
imposition of security controls.  So it would seem helpful to peer a
bit.

If I can paraphrase/simplify the discussion to date; the best the
kernel can do with respect to SGX is to impose controls, via mprotect,
that limit the maximum permissions of an enclave page to whatever was
specified when the enclave was loaded/initialized.

So here is the question that would seem to need answering:

Is this even a relevant control if we cede the notion of dynamically
loadable enclave code, which is the objective of SGX2 hardware, which
will in all likelihood be the only relevant hardware implementation in
the future?

The answer to this could very well be yes if the objective is to
provide a method for a platform owner to explicitly block dynamically
loadable enclave code.  Since there seems to be a desire for immense
clarity in the changelogs surrounding all of this, framing the
discussion in something practical like this may be of assistance.

One of the desires of the SGX user community is to not allow
visibility into enclave code, this is one of the notions/objectives of
confidential computing.  The Protected Code Loader that was added by
Intel to their PSW is an acknowledgement of this fact.  EDMM and
dynamically loadable code makes doing this much more efficient so that
would seem to be the face of the future.

My apologies for 'delaying' the driver even more.  I was accused of
that about a year ago but it appears I didn't do too much
damage... :-)

Best wishes for a productive week.

Dr. Greg

As always,
Dr. Greg Wettstein, Ph.D, Worker      Autonomously self-defensive
Enjellic Systems Development, LLC     IOT platforms and edge devices.
4206 N. 19th Ave.
Fargo, ND  58102
PH: 701-281-1686                      EMAIL: greg@enjellic.com
------------------------------------------------------------------------------
"If you get to thinkin' you're a person of some influence, try
 orderin' somebody else's dog around."
                                -- Cowboy Wisdom


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-18  8:49                                                     ` Dr. Greg
@ 2020-10-19 21:31                                                       ` Sean Christopherson
  2020-10-20 10:01                                                         ` Dr. Greg
  0 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-10-19 21:31 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Dave Hansen, Jarkko Sakkinen, Haitao Huang, Andy Lutomirski,
	X86 ML, linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Sun, Oct 18, 2020 at 03:49:20AM -0500, Dr. Greg wrote:
> Is this even a relevant control if we cede the notion of dynamically
> loadable enclave code, which is the objective of SGX2 hardware, which
> will in all likelihood be the only relevant hardware implementation in
> the future?

Yes, it's still relevant.  Giving the thumbs up to dynamically loadable code is
not a purely binary decision, e.g. a user/admin can allow RW->RX transitions
but still disallow full RWX permissions.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-19 21:31                                                       ` Sean Christopherson
@ 2020-10-20 10:01                                                         ` Dr. Greg
  2020-10-20 16:40                                                           ` Sean Christopherson
  0 siblings, 1 reply; 81+ messages in thread
From: Dr. Greg @ 2020-10-20 10:01 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Dave Hansen, Jarkko Sakkinen, Haitao Huang, Andy Lutomirski,
	X86 ML, linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Oct 19, 2020 at 02:31:05PM -0700, Sean Christopherson wrote:

Good morning, I hope the day is starting well for everyone.

> On Sun, Oct 18, 2020 at 03:49:20AM -0500, Dr. Greg wrote:
> > Is this even a relevant control if we cede the notion of dynamically
> > loadable enclave code, which is the objective of SGX2 hardware, which
> > will in all likelihood be the only relevant hardware implementation in
> > the future?

> Yes, it's still relevant.  Giving the thumbs up to dynamically
> loadable code is not a purely binary decision, e.g. a user/admin can
> allow RW->RX transitions but still disallow full RWX permissions.

With respect to the security issue at hand, the only relevant issue
would seem to be if a page had write permissions at one time in its
trajectory to having execute permisions, isn't this correct?

The next paragraph of my reply wasn't included in your reply, but I
did state that the mprotect hook would be relevant if its purpose was
to disallow this permission trajectory and in the process disable
enclave dynamic code loading and execution.

So to assist everyone in understanding this issue and the security
implications involved, is the ultimate purpose of the mprotect hook to
disable dynamic code loading?

Have a good day.

Dr. Greg

As always,
Dr. Greg Wettstein, Ph.D, Worker      Autonomously self-defensive
Enjellic Systems Development, LLC     IOT platforms and edge devices.
4206 N. 19th Ave.
Fargo, ND  58102
PH: 701-281-1686                      EMAIL: dg@enjellic.com
------------------------------------------------------------------------------
"Those who will not study history are doomed to debug it."
                                -- Barry Shein


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-20 10:01                                                         ` Dr. Greg
@ 2020-10-20 16:40                                                           ` Sean Christopherson
  2020-10-24 14:37                                                             ` Dr. Greg
  0 siblings, 1 reply; 81+ messages in thread
From: Sean Christopherson @ 2020-10-20 16:40 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Dave Hansen, Jarkko Sakkinen, Haitao Huang, Andy Lutomirski,
	X86 ML, linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Oct 20, 2020 at 05:01:18AM -0500, Dr. Greg wrote:
> On Mon, Oct 19, 2020 at 02:31:05PM -0700, Sean Christopherson wrote:
> 
> Good morning, I hope the day is starting well for everyone.
> 
> > On Sun, Oct 18, 2020 at 03:49:20AM -0500, Dr. Greg wrote:
> > > Is this even a relevant control if we cede the notion of dynamically
> > > loadable enclave code, which is the objective of SGX2 hardware, which
> > > will in all likelihood be the only relevant hardware implementation in
> > > the future?
> 
> > Yes, it's still relevant.  Giving the thumbs up to dynamically
> > loadable code is not a purely binary decision, e.g. a user/admin can
> > allow RW->RX transitions but still disallow full RWX permissions.
> 
> With respect to the security issue at hand, the only relevant issue
> would seem to be if a page had write permissions at one time in its
> trajectory to having execute permisions, isn't this correct?

No.  RW->RX has different properties than RWX.  E.g. an enclave that
dynamically loads code is not the same thing as an enclave that allows
simultaneously writing and executing a page.

> The next paragraph of my reply wasn't included in your reply, but I
> did state that the mprotect hook would be relevant if its purpose was
> to disallow this permission trajectory and in the process disable
> enclave dynamic code loading and execution.
> 
> So to assist everyone in understanding this issue and the security
> implications involved, is the ultimate purpose of the mprotect hook to
> disable dynamic code loading?

No, it's to provide line of sight to enforcing granular LSM checks on enclave
pages.  Jumping back to the RWX thing, as a defense in depth measure, a policy
owner could set an SELinux policy to never allow RWX, even for enclaves that
dynamically load code.

Whether or not having per-page granluarity on enclave permission checks is
valuable/interesting is debatable, e.g. it's why LSM integration is notably
absent from the this series.  But, adding the ->mprotect() hook is relatively
cheap and can always be removed if it's deemed unnecessary in the long run.
The reverse is not true; omitting ->mprotect() commits the kernel to an ABI
that is either ugly and potentially painful (require all enclaves to declare
full RWX permissions), or flat out prevents adding granular LSM support in
the future (do nothing).


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-20 16:40                                                           ` Sean Christopherson
@ 2020-10-24 14:37                                                             ` Dr. Greg
  2020-10-24 15:33                                                               ` Andy Lutomirski
  0 siblings, 1 reply; 81+ messages in thread
From: Dr. Greg @ 2020-10-24 14:37 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Dave Hansen, Jarkko Sakkinen, Haitao Huang, Andy Lutomirski,
	X86 ML, linux-sgx, LKML, Linux-MM, Andrew Morton, Matthew Wilcox,
	Jethro Beekman, Darren Kenny, Andy Shevchenko, asapek,
	Borislav Petkov, Xing, Cedric, chenalexchen, Conrad Parker,
	cyhanish, Huang, Haitao, Josh Triplett, Huang, Kai, Svahn, Kai,
	Keith Moyer, Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Tue, Oct 20, 2020 at 09:40:00AM -0700, Sean Christopherson wrote:

Good morning, I hope the week has gone well for everyone.

> On Tue, Oct 20, 2020 at 05:01:18AM -0500, Dr. Greg wrote:
> >
> > With respect to the security issue at hand, the only relevant issue
> > would seem to be if a page had write permissions at one time in its
> > trajectory to having execute permisions, isn't this correct?

> No.  RW->RX has different properties than RWX.  E.g. an enclave that
> dynamically loads code is not the same thing as an enclave that
> allows simultaneously writing and executing a page.

Yes, it is certainly correct that a platform administrator may want to
restrict RWX, given that it makes an enclave susceptible to potential
arbitrary code execution if there is a programming error in the
enclave.

However, I think it is important for everyone interested in these
issues, to reflect back on what started all of this and that was
Andy's concern that the initial incantations of the driver allowed
execution of arbitrary memory without the ability of the LSM to get a
'look' at the code/memory.

My point in all of this is that a permissions trajectory for an
enclave that allows for write permissions on a path that terminates in
X permissions opens the door for arbitrary memory execution that the
platform security architect has no insight into or that the LSM will
have any control over.

There is no guarantee that dynamically loaded code has to come into
the enclave via anything that the operating system has visibility
into.  If the enclave can toggle RW->RX it is free to dynamically load
code, in encrypted form over the network and then execute it.

In fact, I would posit that this model will be a primary use for
dynamic code loading.  The SGX user community views 'confidential
computing' as much about protecting visibility into algorithms and
code as it is about data that is being operated on.  In certain
unnamed venues where I have consulted it is the primary concern.

So in the broadest sense, we have spent a year worrying about if and
how the LSM will have visibility into enclave based code and in the
end the only really relevant security mechanism available is limiting
page permission transitions that prevent dynamic code loading.  Modulo
of course the issue with RWX, where a platform owner may elect to try
and prevent an enclave writer from shooting themselves in the foot.

The issue at hand is that the primary security threat of the
technology is the same as what the user community wants to use it for.
Joanna Rutkowska called that out a half decade ago when she first
reviewed the technology.

> > The next paragraph of my reply wasn't included in your reply, but I
> > did state that the mprotect hook would be relevant if its purpose was
> > to disallow this permission trajectory and in the process disable
> > enclave dynamic code loading and execution.
> > 
> > So to assist everyone in understanding this issue and the security
> > implications involved, is the ultimate purpose of the mprotect hook to
> > disable dynamic code loading?

> No, it's to provide line of sight to enforcing granular LSM checks
> on enclave pages.  Jumping back to the RWX thing, as a defense in
> depth measure, a policy owner could set an SELinux policy to never
> allow RWX, even for enclaves that dynamically load code.
>
> Whether or not having per-page granluarity on enclave permission
> checks is valuable/interesting is debatable, e.g. it's why LSM
> integration is notably absent from the this series.  But, adding the
> ->mprotect() hook is relatively cheap and can always be removed if
> it's deemed unnecessary in the long run.  The reverse is not true;
> omitting ->mprotect() commits the kernel to an ABI that is either
> ugly and potentially painful (require all enclaves to declare full
> RWX permissions), or flat out prevents adding granular LSM support
> in the future (do nothing).

I believe your analysis with respect to the ability to remove
->mprotect is flawed.  The long standing consensus has been that
functionality never gets broken.  Once ->mprotect is a component of
the ABI it would have to be left intact since it could potentially
break things that elected to use it.  On the other hand there is a
long standing history of adding functionality.

I can't bring myself to believe that LSM's are going to be written
that will be making enclave security decisions on a page by page
basis.  Given what I have written above, I think all of this comes
down to giving platform administrators one of three decisions, in
order of most to least secure:

1.) Block dynamic code loading and execution.

2.) Block access to RWX pages.

3.) The wild west - no restrictions on enclave page protection manipulation.

From a security perspective I would argue for the wisdom of making
option 1 unconditional via a kernel command-line parameter.

It may be that ->mprotect is the right mechanism to implement this.
If that is the case, frame the discussion and documentation so that it
reflects the actual security threat and the consideration and means
for dealing with it.

Hopefully all of this is useful to the stakeholders in this
technology.

Have a good weekend.

Dr. Greg

As always,
Dr. Greg Wettstein, Ph.D, Worker      Autonomously self-defensive
Enjellic Systems Development, LLC     IOT platforms and edge devices.
4206 19th Ave. N.
Fargo, ND  58102
PH: 701-281-1686                      EMAIL: greg@enjellic.com
------------------------------------------------------------------------------
"Politics is the business of getting power and privilege without possessing
 merit."
                                -- P.J. O'Rourke


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-24 14:37                                                             ` Dr. Greg
@ 2020-10-24 15:33                                                               ` Andy Lutomirski
  2020-10-26 10:51                                                                 ` Dr. Greg
  0 siblings, 1 reply; 81+ messages in thread
From: Andy Lutomirski @ 2020-10-24 15:33 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Sean Christopherson, Dave Hansen, Jarkko Sakkinen, Haitao Huang,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx



> On Oct 24, 2020, at 7:38 AM, Dr. Greg <greg@enjellic.com> wrote:
> 

> 
> I can't bring myself to believe that LSM's are going to be written
> that will be making enclave security decisions on a page by page
> basis.  Given what I have written above, I think all of this comes
> down to giving platform administrators one of three decisions, in
> order of most to least secure:
> 
> 1.) Block dynamic code loading and execution.
> 

I don’t understand what you’re trying to say. Unless we’re going to split enclaves into multiple VMAs with different permissions, how do you expect to block dynamic code loading unless you have separate RW and RX pages?  That would be “page-by-page”, right?

> 2.) Block access to RWX pages.
> 
> 3.) The wild west - no restrictions on enclave page protection manipulation.
> 
> From a security perspective I would argue for the wisdom of making
> option 1 unconditional via a kernel command-line parameter.
> 
> It may be that ->mprotect is the right mechanism to implement this.
> If that is the case, frame the discussion and documentation so that it
> reflects the actual security threat and the consideration and means
> for dealing with it.
> 
> Hopefully all of this is useful to the stakeholders in this
> technology.
> 
> Have a good weekend.
> 
> Dr. Greg
> 
> As always,
> Dr. Greg Wettstein, Ph.D, Worker      Autonomously self-defensive
> Enjellic Systems Development, LLC     IOT platforms and edge devices.
> 4206 19th Ave. N.
> Fargo, ND  58102
> PH: 701-281-1686                      EMAIL: greg@enjellic.com
> ------------------------------------------------------------------------------
> "Politics is the business of getting power and privilege without possessing
> merit."
>                                -- P.J. O'Rourke


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-24 15:33                                                               ` Andy Lutomirski
@ 2020-10-26 10:51                                                                 ` Dr. Greg
  2020-10-26 22:59                                                                   ` Andy Lutomirski
  0 siblings, 1 reply; 81+ messages in thread
From: Dr. Greg @ 2020-10-26 10:51 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Dave Hansen, Jarkko Sakkinen, Haitao Huang,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Sat, Oct 24, 2020 at 08:33:21AM -0700, Andy Lutomirski wrote:

Good morning, I hope the week is starting well for everyone.

> > On Oct 24, 2020, at 7:38 AM, Dr. Greg <greg@enjellic.com> wrote:
> > I can't bring myself to believe that LSM's are going to be written
> > that will be making enclave security decisions on a page by page
> > basis.  Given what I have written above, I think all of this comes
> > down to giving platform administrators one of three decisions, in
> > order of most to least secure:
> > 
> > 1.) Block dynamic code loading and execution.

> I don't understand what you're trying to say. Unless we're going to
> split enclaves into multiple VMAs with different permissions, how do
> you expect to block dynamic code loading unless you have separate RW
> and RX pages?  That would be ???page-by-page???, right?

I believe that there are multiple knobs that can be manipulated to
achieve the effects that are desired.  I am advocating that we have a
clear and reasoned understanding, with appropriate documentation, as
to what we are doing and why we are doing it.

To advance this understanding, I would advocate that anyone interested
in these issues review the papers that describe the design and use of
the SGX2 architecture instructions.  Fore convenience we have them
available on our FTP server via the following links:

ftp://ftp.enjellic.com/pub/sgx/docs/hasp4.pdf

ftp://ftp.enjellic.com/pub/sgx/docs/hasp5.pdf

They are both from HASP 2016 and are readily available elsewhere as
well.

The first paper discusses the SGX2 architecture instructions and why
they were implemented.  The second paper discusses how Enclave Dynamic
Memory Management (EDMM) can be implemented from the OS perspective
using these instructions.

Full disclosure, I've had the opportunity to have direct exchanges
with a number of the authors on those papers.

The design of all this was heavily influenced by Marcus Peinado's
group at Microsoft.  They did the first implementation of an SGX
library OS (Haven) and in the process addressed the issue of dynamic
memory and code loading.  Their work also resulted in the
documentation of a number of errata in the SGX silicon implementation.

Like the company or not, I don't think the case can be made that they
don't understand operating system design and theory.  It would thus
seem prudent to understand the prior art that went into the design of
all this.

To summarize at a high level, EDMM requires a rather intricate
choreography between enclave code and the device driver, the latter of
which needs to execute ring-0 privileged instructions in order to
expand the virtual address space of an enclave.

The easiest way to generically block dynamic code loading is to not
allow the ENCLS[EAUG] instruction to be executed, the purpose of which
is to augment a defined but sparse ELRANGE with additional physical
pages from the EPC.  It doesn't require ->mprotect or anything else,
just a physical decision by the OS to not allow execution of that
instruction.

All of which is consistent with my recomendation for a global disable
knob on the kernel command-line for sites that do not want to tolerate
completely anonymous code execution.

Since this driver does not yet support EDMM, the most immediate
situation that we are dealing with are the potential security
implications of SGX2 ENCLU instructions being executed inside of an
enclave.  The most principal issue is the ENCLU[EMODPE] instruction
that allows a running enclave to extend the current permissions of a
page.

I've been assuming that Sean's desire for ->mprotect is to block the
ability of an initialized enclave, on a non-EDMM enabled driver, to
collaborate with its untrusted component to self-modify its page
permissions and thus allow execution of code that the operating system
has no visibility into.  That would make far more sense then the
notion of someone trying to create an LSM that makes page by page
security decisions.

The open question in all of this is that the EDMM paper, as well as
the SDM, indicate the effects of an ENCLU[EMODPE] are immediate inside
of a running enclave.  I'm assuming that this does NOT mean that once
a context of execution is running in enclave mode it would be capable
of evading standard page protections but the 'immediate' is somewhat
disquieting and probably deserves clarification, despite Dave Hansen's
adament concerns about discussing the instruction... :-)

At the risk of being widely unpopular, it may be worth calling the
question if we shouldn't bite the bullet and implement full SGX2
support in the driver.  Given the trajectory that SGX is on it is what
everyone wants and will be using.  We are currently in somewhat of a
bad place since we have to be cognizant of the implications of SGX2
hardware, which is going to be the only relevant platform for this
driver, without actually addressing all of the issues it brings to the
table.

Hopefully all of the above helps advance an understanding of the
issues at hand.

Have a good day.

Dr. Greg

As always,
Dr. Greg Wettstein, Ph.D, Worker      Autonomously self-defensive
Enjellic Systems Development, LLC     IOT platforms and edge devices.
4206 N. 19th Ave.
Fargo, ND  58102
PH: 701-281-1686                      EMAIL: dg@enjellic.com
------------------------------------------------------------------------------
"Five year projections, are you kidding me.  We don't know what we are
 supposed to be doing at the 4 o'clock meeting this afternoon."
                                -- Terry Wieland
                                   Resurrection


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-26 10:51                                                                 ` Dr. Greg
@ 2020-10-26 22:59                                                                   ` Andy Lutomirski
  2020-10-27  0:40                                                                     ` Sean Christopherson
  0 siblings, 1 reply; 81+ messages in thread
From: Andy Lutomirski @ 2020-10-26 22:59 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Sean Christopherson, Dave Hansen, Jarkko Sakkinen, Haitao Huang,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx


> On Oct 26, 2020, at 3:51 AM, Dr. Greg <greg@enjellic.com> wrote:
> 
> On Sat, Oct 24, 2020 at 08:33:21AM -0700, Andy Lutomirski wrote:
> 
> The easiest way to generically block dynamic code loading is to not
> allow the ENCLS[EAUG] instruction to be executed, the purpose of which
> is to augment a defined but sparse ELRANGE with additional physical
> pages from the EPC.  It doesn't require ->mprotect or anything else,
> just a physical decision by the OS to not allow execution of that
> instruction.

I’m pretty sure that one can dynamically load code without EAUG. It
would require preallocation, but I can’t see why EAUG changes anything from a security policy perspective.

> 
> All of which is consistent with my recomendation for a global disable
> knob on the kernel command-line for sites that do not want to tolerate
> completely anonymous code execution.
> 
> Since this driver does not yet support EDMM, the most immediate
> situation that we are dealing with are the potential security
> implications of SGX2 ENCLU instructions being executed inside of an
> enclave.  The most principal issue is the ENCLU[EMODPE] instruction
> that allows a running enclave to extend the current permissions of a
> page.
> 
> I've been assuming that Sean's desire for ->mprotect is to block the
> ability of an initialized enclave, on a non-EDMM enabled driver, to
> collaborate with its untrusted component to self-modify its page
> permissions and thus allow execution of code that the operating system
> has no visibility into.  That would make far more sense then the
> notion of someone trying to create an LSM that makes page by page
> security decisions.

If you remove every mention of EDMM from that description, and you realize that the ability for LSMs to implement this sort of policy is basically the same as for the core SGX code to do so, then I agree.

The addition of EDMM will not change anything here per se, except that we’re a lot more likely to encounter enclaves doing interesting things with EMODPE once EDMM is enabled.

> 
> The open question in all of this is that the EDMM paper, as well as
> the SDM, indicate the effects of an ENCLU[EMODPE] are immediate inside
> of a running enclave.  I'm assuming that this does NOT mean that once
> a context of execution is running in enclave mode it would be capable
> of evading standard page protections but the 'immediate' is somewhat
> disquieting and probably deserves clarification, despite Dave Hansen's
> adament concerns about discussing the instruction... :-)

If EMODPE writes an entry into the TLB that violates PTE permissions, then we have a real problem. I would be very surprised if this were to be the case.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* Re: [PATCH v38 10/24] mm: Add vm_ops->mprotect()
  2020-10-26 22:59                                                                   ` Andy Lutomirski
@ 2020-10-27  0:40                                                                     ` Sean Christopherson
  0 siblings, 0 replies; 81+ messages in thread
From: Sean Christopherson @ 2020-10-27  0:40 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Dr. Greg, Dave Hansen, Jarkko Sakkinen, Haitao Huang,
	Andy Lutomirski, X86 ML, linux-sgx, LKML, Linux-MM,
	Andrew Morton, Matthew Wilcox, Jethro Beekman, Darren Kenny,
	Andy Shevchenko, asapek, Borislav Petkov, Xing, Cedric,
	chenalexchen, Conrad Parker, cyhanish, Huang, Haitao,
	Josh Triplett, Huang, Kai, Svahn, Kai, Keith Moyer,
	Christian Ludloff, Neil Horman, Nathaniel McCallum,
	Patrick Uiterwijk, David Rientjes, Thomas Gleixner, yaozhangx

On Mon, Oct 26, 2020 at 03:59:35PM -0700, Andy Lutomirski wrote:
> > On Oct 26, 2020, at 3:51 AM, Dr. Greg <greg@enjellic.com> wrote:
> > The open question in all of this is that the EDMM paper, as well as
> > the SDM, indicate the effects of an ENCLU[EMODPE] are immediate inside
> > of a running enclave.  I'm assuming that this does NOT mean that once
> > a context of execution is running in enclave mode it would be capable
> > of evading standard page protections but the 'immediate' is somewhat
> > disquieting and probably deserves clarification, despite Dave Hansen's
> > adament concerns about discussing the instruction... :-)
> 
> If EMODPE writes an entry into the TLB that violates PTE permissions, then we
> have a real problem. I would be very surprised if this were to be the case.

EMODPE only affects the EPCM, it doesn't magically change the PTEs or insert
into the TLB.  The "immediate" wording in the whitepaper is differentiating it
from EMODPR and EMODT, where the modifications only take effect after they have
been verified by the enclave via EACCEPT.


^ permalink raw reply	[flat|nested] 81+ messages in thread

* [PATCH v38 10/24] mm: Add vm_ops->mprotect()
       [not found] <20200915110522.893152-1-jarkko.sakkinen@linux.intel.com>
@ 2020-09-15 11:05 ` Jarkko Sakkinen
  0 siblings, 0 replies; 81+ messages in thread
From: Jarkko Sakkinen @ 2020-09-15 11:05 UTC (permalink / raw)
  To: x86, linux-sgx
  Cc: linux-kernel, Sean Christopherson, linux-mm, Andrew Morton,
	Matthew Wilcox, Jethro Beekman, Darren Kenny, Jarkko Sakkinen,
	andriy.shevchenko, asapek, bp, cedric.xing, chenalexchen,
	conradparker, cyhanish, dave.hansen, haitao.huang, josh,
	kai.huang, kai.svahn, kmoy, ludloff, luto, nhorman, npmccallum,
	puiterwijk, rientjes, tglx, yaozhangx

From: Sean Christopherson <sean.j.christopherson@intel.com>

Add vm_ops()->mprotect() for additional constraints for a VMA.

Intel Software Guard eXtensions (SGX) will use this callback to add two
constraints:

1. Verify that the address range does not have holes: each page address
   must be filled with an enclave page.
2. Verify that VMA permissions won't surpass the permissions of any enclave
   page within the address range. Enclave cryptographically sealed
   permissions for each page address that set the upper limit for possible
   VMA permissions. Not respecting this can cause #GP's to be emitted.

Cc: linux-mm@kvack.org
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Matthew Wilcox <willy@infradead.org>
Acked-by: Jethro Beekman <jethro@fortanix.com>
Reviewed-by: Darren Kenny <darren.kenny@oracle.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 include/linux/mm.h | 3 +++
 mm/mprotect.c      | 5 ++++-
 2 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/include/linux/mm.h b/include/linux/mm.h
index 97c83773b6f0..717726fcace6 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -547,6 +547,9 @@ struct vm_operations_struct {
 	void (*close)(struct vm_area_struct * area);
 	int (*split)(struct vm_area_struct * area, unsigned long addr);
 	int (*mremap)(struct vm_area_struct * area);
+	int (*mprotect)(struct vm_area_struct *vma,
+			struct vm_area_struct **pprev, unsigned long start,
+			unsigned long end, unsigned long newflags);
 	vm_fault_t (*fault)(struct vm_fault *vmf);
 	vm_fault_t (*huge_fault)(struct vm_fault *vmf,
 			enum page_entry_size pe_size);
diff --git a/mm/mprotect.c b/mm/mprotect.c
index ce8b8a5eacbb..f170f3da8a4f 100644
--- a/mm/mprotect.c
+++ b/mm/mprotect.c
@@ -610,7 +610,10 @@ static int do_mprotect_pkey(unsigned long start, size_t len,
 		tmp = vma->vm_end;
 		if (tmp > end)
 			tmp = end;
-		error = mprotect_fixup(vma, &prev, nstart, tmp, newflags);
+		if (vma->vm_ops && vma->vm_ops->mprotect)
+			error = vma->vm_ops->mprotect(vma, &prev, nstart, tmp, newflags);
+		else
+			error = mprotect_fixup(vma, &prev, nstart, tmp, newflags);
 		if (error)
 			goto out;
 		nstart = tmp;
-- 
2.25.1



^ permalink raw reply related	[flat|nested] 81+ messages in thread

end of thread, other threads:[~2020-10-27  0:40 UTC | newest]

Thread overview: 81+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
     [not found] <20200915112842.897265-1-jarkko.sakkinen@linux.intel.com>
2020-09-15 11:28 ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Jarkko Sakkinen
2020-09-18 12:44   ` Borislav Petkov
2020-09-18 15:09   ` Andy Lutomirski
2020-09-18 23:24     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect()' Jarkko Sakkinen
2020-09-18 23:53     ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Sean Christopherson
2020-09-19  0:15       ` Andy Lutomirski
2020-09-22 12:58         ` Jarkko Sakkinen
2020-09-22 15:11           ` Dave Hansen
2020-09-23 13:30             ` Jarkko Sakkinen
2020-09-23 13:43             ` Jarkko Sakkinen
2020-09-23 14:33             ` Jarkko Sakkinen
2020-09-24 14:50               ` Dave Hansen
2020-09-24 16:27                 ` Sean Christopherson
2020-09-24 19:35                 ` Jarkko Sakkinen
2020-09-21 12:49       ` Jarkko Sakkinen
2020-09-21 12:51         ` Jarkko Sakkinen
2020-09-21 13:14         ` Jarkko Sakkinen
2020-09-21 16:57         ` Sean Christopherson
2020-09-21 21:07           ` Jarkko Sakkinen
2020-09-21 21:18             ` Sean Christopherson
2020-09-22  5:29               ` Jarkko Sakkinen
2020-09-22  5:35                 ` Jarkko Sakkinen
2020-09-22 16:43                   ` Sean Christopherson
2020-09-23 13:50                     ` Jarkko Sakkinen
2020-09-24 19:11                       ` Haitao Huang
2020-09-24 19:28                         ` Sean Christopherson
2020-09-24 19:39                           ` Dave Hansen
2020-09-24 20:01                             ` Sean Christopherson
2020-09-24 20:10                               ` Dave Hansen
2020-09-24 20:25                                 ` Sean Christopherson
2020-09-24 20:54                                   ` Dave Hansen
2020-09-24 22:10                                     ` Jarkko Sakkinen
2020-09-24 23:05                                     ` Sean Christopherson
2020-09-24 23:09                                       ` Dave Hansen
2020-09-25  0:00                                         ` Sean Christopherson
2020-09-25 17:18                                           ` Dave Hansen
2020-09-25 19:43                                             ` Sean Christopherson
2020-09-25 19:53                                               ` Dave Hansen
2020-09-26  4:15                                                 ` Andy Lutomirski
2020-09-28  0:53                                                 ` Jarkko Sakkinen
2020-09-28 14:04                                                   ` Dave Hansen
2020-09-28 16:19                                                     ` Jarkko Sakkinen
2020-09-28 16:48                                                       ` Dave Hansen
2020-09-28 19:32                                                         ` Jarkko Sakkinen
2020-09-28 19:45                                                           ` Dave Hansen
2020-09-28 20:19                                                             ` Jarkko Sakkinen
2020-09-29  1:37                                                               ` Andy Lutomirski
2020-09-29  4:05                                                                 ` Jarkko Sakkinen
2020-09-29 14:24                                                                   ` Dave Hansen
2020-09-30  0:20                                                                     ` Jarkko Sakkinen
2020-09-30 14:35                                                                       ` Dave Hansen
2020-09-28 20:18                                                         ` Jarkko Sakkinen
2020-10-18  8:49                                                     ` Dr. Greg
2020-10-19 21:31                                                       ` Sean Christopherson
2020-10-20 10:01                                                         ` Dr. Greg
2020-10-20 16:40                                                           ` Sean Christopherson
2020-10-24 14:37                                                             ` Dr. Greg
2020-10-24 15:33                                                               ` Andy Lutomirski
2020-10-26 10:51                                                                 ` Dr. Greg
2020-10-26 22:59                                                                   ` Andy Lutomirski
2020-10-27  0:40                                                                     ` Sean Christopherson
2020-09-24 22:07                                 ` Jarkko Sakkinen
2020-09-24 21:58                           ` Jarkko Sakkinen
2020-09-24 21:55                         ` Jarkko Sakkinen
2020-09-15 11:28 ` [PATCH v38 11/24] x86/sgx: Add SGX enclave driver Jarkko Sakkinen
2020-09-21  9:30   ` Borislav Petkov
2020-09-21 12:09     ` Jarkko Sakkinen
2020-10-01 17:36   ` Sean Christopherson
2020-10-01 18:49     ` Jarkko Sakkinen
2020-09-15 11:28 ` [PATCH v38 16/24] x86/sgx: Add a page reclaimer Jarkko Sakkinen
2020-09-22 10:45   ` Borislav Petkov
2020-09-22 14:03     ` Jarkko Sakkinen
2020-09-22 14:24       ` Borislav Petkov
2020-09-23 14:52         ` Jarkko Sakkinen
2020-09-29  1:14       ` Sean Christopherson
2020-09-29  3:50         ` Jarkko Sakkinen
2020-09-29  8:35           ` Sean Christopherson
2020-09-22 16:24     ` Sean Christopherson
2020-09-22 18:02       ` Borislav Petkov
2020-09-23 15:25       ` Jarkko Sakkinen
     [not found] <20200915110522.893152-1-jarkko.sakkinen@linux.intel.com>
2020-09-15 11:05 ` [PATCH v38 10/24] mm: Add vm_ops->mprotect() Jarkko Sakkinen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).