Skip to contentSkip to conversation

Intel SGX1 support

PATCH Superseded Jarkko Sakkinen 15 participants 314 messages Apr 17, 2019 – Jul 17, 2019 1 message not in the archive Page 1 of 3

Subsystems (9)

v20 of 40 Superseded Latest is v40 →

lore
Share & tools
lore
#0 lore raw

v20 cover Intel SGX1 support

Intel(R) 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 enclave is disallowed to access the memory inside the enclave by the CPU access control. In a way you can think that SGX provides inverted sandbox. It protects the application from a malicious host.

There is a new hardware unit in the processor called Memory Encryption Engine (MEE) starting from the Skylake microacrhitecture. BIOS can define one or many MEE regions that can hold enclave data by configuring them with PRMRR registers.

The MEE automatically encrypts the data leaving the processor package to the MEE regions. The data is encrypted using a random key whose life-time is exactly one power cycle.

The current implementation requires that the firmware sets IA32_SGXLEPUBKEYHASH* MSRs as writable so that ultimately the kernel can decide what enclaves it wants run. The implementation does not create any bottlenecks to support read-only MSRs later on.

You can tell if your CPU supports SGX by looking into /proc/cpuinfo:

cat /proc/cpuinfo | grep sgx

v20:
* Fine-tune Kconfig messages and spacing and remove MMU_NOTIFIER dependency as MMU notifiers are no longer used in the driver.
* Use mm_users instead of mm_count as refcount for mm_struct as mm_count only protects from deleting mm_struct, not removing its contents.
* Sanitize EPC when the reclaimer thread starts by doing EREMOVE for all of them. They could be in initialized state when the kernel starts because it might be spawned by kexec().
* Documentation overhaul.
* Use a device /dev/sgx/provision for delivering the provision token instead of securityfs.
* Create a reference to the enclave when already when opening /dev/sgx/enclave. The file is then associated with this enclave only. mmap() can be done at free at any point and always get a reference to the enclave. To summarize the file now represents the enclave.

v19:
* Took 3-4 months but in some sense this was more like a rewrite of most of the corners of the source code. If I've forgotten to deal with some feedback, please don't shout me. Make a remark and I will fix it for the next version. Hopefully there won't be this big turnovers anymore.
* Validate SECS attributes properly against CPUID given attributes and against allowed attributes. SECS attributes are the ones that are enforced whereas SIGSTRUCT attributes tell what is required to run the enclave.
* Add KSS (Key Sharing Support) to the enclave attributes.
* Deny MAP_PRIVATE as an enclave is always a shared memory entity.
* Revert back to shmem backing storage so that it can be easily shared by multiple processes.
* Split the recognization of an ENCLS leaf failure by using three functions to detect it: encsl_faulted(), encls_returned_code() and sgx_failed(). encls_failed() is only caused by a spurious expections that should never happen. Thus, it is not defined as an inline function in order to easily insert a kprobe to it.
* Move low-level enclave management routines, page fault handler and page reclaiming routines from driver to the core. These cannot be separated from each other as they are heavily interdependent. The rationale is that the core does not call any code from the driver.
* Allow the driver to be compiled as a module now that it no code is using its routines and it only uses exported symbols. Now the driver is essentially just a thin ioctl layer.
* Reworked the driver to maintain a list of mm_struct's. The VMA callbacks add new entries to this list as the process is forked. Each entry has its own refcount because they have a different life-cycle as the enclave does. In effect @tgid and @mm have been removed from struct sgx_encl and we allow forking by removing VM_DONTCOPY from vm flags.
* Generate a cpu mask in the reclaimer from the cpu mask's of all mm_struct's. This will kick out the hardware threads out of the enclave from multiple processes. It is not a local variable because it would eat too much of the stack space but instead a field in struct sgx_encl.
* Allow forking i.e. remove VM_DONTCOPY. I did not change the API because the old API scaled to the workload that Andy described. The codebase is now mostly API independent i.e. changing the API is a small task. For me the proper trigger to chanage it is a as concrete as possible workload that cannot be fulfilled. I hope you understand my thinking here. I don't want to change anything w/o proper basis but I'm ready to change anything if there is a proper basis. I do not have any kind of attachment to any particular type of API.
* Add Sean's vDSO ENCLS(EENTER) patches and update selftest to use the new vDSO.

v18:
* Update the ioctl-number.txt.
* Move the driver under arch/x86.
* Add SGX features (SGX, SGX1, SGX2) to the disabled-features.h.
* Rename the selftest as test_sgx (previously sgx-selftest).
* In order to enable process accounting, swap EPC pages and PCMD's to a VMA instead of shmem.
* Allow only to initialize and run enclaves with a subset of {DEBUG, MODE64BIT} set.
* Add SGX_IOC_ENCLAVE_SET_ATTRIBUTE to allow an enclave to have privileged attributes e.g. PROVISIONKEY.

v17:
* Add a simple selftest.
* Fix a null pointer dereference to section->pages when its allocation fails.
* Add Sean's description of the exception handling to the documentation.

v16:
* Fixed SOB's in the commits that were a bit corrupted in v15.
* Implemented exceptio handling properly to detect_sgx().
* Use GENMASK() to define SGX_CPUID_SUB_LEAF_TYPE_MASK.
* Updated the documentation to use rst definition lists.
* Added the missing Documentation/x86/index.rst, which has a link to intel_sgx.rst. Now the SGX and uapi documentation is properly generated with 'make htmldocs'.
* While enumerating EPC sections, if an undefined section is found, fail the driver initialization instead of continuing the initialization.
* Issue a warning if there are more than %SGX_MAX_EPC_SECTIONS.
* Remove copyright notice from arch/x86/include/asm/sgx.h.
* Migrated from ioremap_cache() to memremap().

v15:
* Split into more digestable size patches.
* Lots of small fixes and clean ups.
* Signal a "plain" SIGSEGV on an EPCM violation.

v14:
* Change the comment about X86_FEATURE_SGX_LC from “SGX launch configuration” to “SGX launch control”.
* Move the SGX-related CPU feature flags as part of the Linux defined virtual leaf 8.
* Add SGX_ prefix to the constants defining the ENCLS leaf functions.
* Use GENMASK*() and BIT*() in sgx_arch.h instead of raw hex numbers.
* Refine the long description for CONFIG_INTEL_SGX_CORE.
* Do not use pr_*_ratelimited() in the driver. The use of the rate limited versions is legacy cruft from the prototyping phase.
* Detect sleep with SGX_INVALID_EINIT_TOKEN instead of counting power cycles.
* Manually prefix with “sgx:” in the core SGX code instead of redefining pr_fmt.
* Report if IA32_SGXLEPUBKEYHASHx MSRs are not writable in the driver instead of core because it is a driver requirement.
* Change prompt to bool in the entry for CONFIG_INTEL_SGX_CORE because the default is ‘n’.
* Rename struct sgx_epc_bank as struct sgx_epc_section in order to match the SDM.
* Allocate struct sgx_epc_page instances one at a time.
* Use “__iomem void *” pointers for the mapped EPC memory consistently.
* Retry once on SGX_INVALID_TOKEN in sgx_einit() instead of counting power cycles.
* Call enclave swapping operations directly from the driver instead of calling them .indirectly through struct sgx_epc_page_ops because indirect calls are not required yet as the patch set does not contain the KVM support.
* Added special signal SEGV_SGXERR to notify about SGX EPCM violation errors.

v13:
* Always use SGX_CPUID constant instead of a hardcoded value.
* Simplified and documented the macros and functions for ENCLS leaves.
* Enable sgx_free_page() to free active enclave pages on demand in order to allow sgx_invalidate() to delete enclave pages. It no longer performs EREMOVE if a page is in the process of being reclaimed.
* Use PM notifier per enclave so that we don't have to traverse the global list of active EPC pages to find enclaves.
* Removed unused SGX_LE_ROLLBACK constant from uapi/asm/sgx.h
* Always use ioremap() to map EPC banks as we only support 64-bit kernel.
* Invalidate IA32_SGXLEPUBKEYHASH cache used by sgx_einit() when going to sleep.

v12:
* Split to more narrow scoped commits in order to ease the review process and use co-developed-by tag for co-authors of commits instead of listing them in the source files.
* Removed cruft EXPORT_SYMBOL() declarations and converted to static variables.
* Removed in-kernel LE i.e. this version of the SGX software stack only supports unlocked IA32_SGXLEPUBKEYHASHx MSRs.
* Refined documentation on launching enclaves, swapping and enclave construction.
* Refined sgx_arch.h to include alignment information for every struct that requires it and removed structs that are not needed without an LE.
* Got rid of SGX_CPUID.
* SGX detection now prints log messages about firmware configuration issues.

v11:
* Polished ENCLS wrappers with refined exception handling.
* ksgxswapd was not stopped (regression in v5) in sgx_page_cache_teardown(), which causes a leaked kthread after driver deinitialization.
* Shutdown sgx_le_proxy when going to suspend because its EPC pages will be invalidated when resuming, which will cause it not function properly anymore.
* Set EINITTOKEN.VALID to zero for a token that is passed when SGXLEPUBKEYHASH matches MRSIGNER as alloc_page() does not give a zero page.
* Fixed the check in sgx_edbgrd() for a TCS page. Allowed to read offsets around the flags field, which causes a #GP. Only flags read is readable.
* On read access memcpy() call inside sgx_vma_access() had src and dest parameters in wrong order.
* The build issue with CONFIG_KASAN is now fixed. Added undefined symbols to LE even if “KASAN_SANITIZE := false” was set in the makefile.
* Fixed a regression in the #PF handler. If a page has SGX_ENCL_PAGE_RESERVED flag the #PF handler should unconditionally fail. It did not, which caused weird races when trying to change other parts of swapping code.
* EPC management has been refactored to a flat LRU cache and moved to arch/x86. The swapper thread reads a cluster of EPC pages and swaps all of them. It can now swap from multiple enclaves in the same round.
* For the sake of consistency with SGX_IOC_ENCLAVE_ADD_PAGE, return -EINVAL when an enclave is already initialized or dead instead of zero.

v10:
* Cleaned up anon inode based IPC between the ring-0 and ring-3 parts of the driver.
* Unset the reserved flag from an enclave page if EDBGRD/WR fails (regression in v6).
* Close the anon inode when LE is stopped (regression in v9).
* Update the documentation with a more detailed description of SGX.

v9:
* Replaced kernel-LE IPC based on pipes with an anonymous inode. The driver does not require anymore new exports.

v8:
* Check that public key MSRs match the LE public key hash in the driver initialization when the MSRs are read-only.
* Fix the race in VA slot allocation by checking the fullness immediately after succeesful allocation.
* Fix the race in hash mrsigner calculation between the launch enclave and user enclaves by having a separate lock for hash calculation.

v7:
* Fixed offset calculation in sgx_edbgr/wr(). Address was masked with PAGE_MASK when it should have been masked with ~PAGE_MASK.
* Fixed a memory leak in sgx_ioc_enclave_create().
* Simplified swapping code by using a pointer array for a cluster instead of a linked list.
* Squeezed struct sgx_encl_page to 32 bytes.
* Fixed deferencing of an RSA key on OpenSSL 1.1.0.
* Modified TC's CMAC to use kernel AES-NI. Restructured the code
a bit in order to better align with kernel conventions.

v6:
* Fixed semaphore underrun when accessing /dev/sgx from the launch enclave.
* In sgx_encl_create() s/IS_ERR(secs)/IS_ERR(encl)/.
* Removed virtualization chapter from the documentation.
* Changed the default filename for the signing key as signing_key.pem.
* Reworked EPC management in a way that instead of a linked list of struct sgx_epc_page instances there is an array of integers that encodes address and bank of an EPC page (the same data as 'pa' field earlier). The locking has been moved to the EPC bank level instead of a global lock.
* Relaxed locking requirements for EPC management. EPC pages can be released back to the EPC bank concurrently.
* Cleaned up ptrace() code.
* Refined commit messages for new architectural constants.
* Sorted includes in every source file.
* Sorted local variable declarations according to the line length in every function.
* Style fixes based on Darren's comments to sgx_le.c.

v5:
* Described IPC between the Launch Enclave and kernel in the commit messages.
* Fixed all relevant checkpatch.pl issues that I have forgot fix in earlier versions except those that exist in the imported TinyCrypt code.
* Fixed spelling mistakes in the documentation.
* Forgot to check the return value of sgx_drv_subsys_init().
* Encapsulated properly page cache init and teardown.
* Collect epc pages to a temp list in sgx_add_epc_bank
* Removed SGX_ENCLAVE_INIT_ARCH constant.

v4:
* Tied life-cycle of the sgx_le_proxy process to /dev/sgx.
* Removed __exit annotation from sgx_drv_subsys_exit().
* Fixed a leak of a backing page in sgx_process_add_page_req() in the case when vm_insert_pfn() fails.
* Removed unused symbol exports for sgx_page_cache.c.
* Updated sgx_alloc_page() to require encl parameter and documented the behavior (Sean Christopherson).
* Refactored a more lean API for sgx_encl_find() and documented the behavior.
* Moved #PF handler to sgx_fault.c.
* Replaced subsys_system_register() with plain bus_register().
* Retry EINIT 2nd time only if MSRs are not locked.

v3:
* Check that FEATURE_CONTROL_LOCKED and FEATURE_CONTROL_SGX_ENABLE are set.
* Return -ERESTARTSYS in __sgx_encl_add_page() when sgx_alloc_page() fails.
* Use unused bits in epc_page->pa to store the bank number.
* Removed #ifdef for WQ_NONREENTRANT.
* If mmu_notifier_register() fails with -EINTR, return -ERESTARTSYS.
* Added --remove-section=.got.plt to objcopy flags in order to prevent a dummy .got.plt, which will cause an inconsistent size for the LE.
* Documented sgx_encl_* functions.
* Added remark about AES implementation used inside the LE.
* Removed redundant sgx_sys_exit() from le/main.c.
* Fixed struct sgx_secinfo alignment from 128 to 64 bytes.
* Validate miscselect in sgx_encl_create().
* Fixed SSA frame size calculation to take the misc region into account.
* Implemented consistent exception handling to __encls() and __encls_ret().
* Implemented a proper device model in order to allow sysfs attributes and in-kernel API.
* Cleaned up various "find enclave" implementations to the unified sgx_encl_find().
* Validate that vm_pgoff is zero.
* Discard backing pages with shmem_truncate_range() after EADD.
* Added missing EEXTEND operations to LE signing and launch.
* Fixed SSA size for GPRS region from 168 to 184 bytes.
* Fixed the checks for TCS flags. Now DBGOPTIN is allowed.
* Check that TCS addresses are in ELRANGE and not just page aligned.
* Require kernel to be compiled with X64_64 and CPU_SUP_INTEL.
* Fixed an incorrect value for SGX_ATTR_DEBUG from 0x01 to 0x02.

v2:
* get_rand_uint32() changed the value of the pointer instead of value where it is pointing at.
* Launch enclave incorrectly used sigstruct attributes-field instead of enclave attributes-field.
* Removed unused struct sgx_add_page_req from sgx_ioctl.c
* Removed unused sgx_has_sgx2.
* Updated arch/x86/include/asm/sgx.h so that it provides stub implementations when sgx in not enabled.
* Removed cruft rdmsr-calls from sgx_set_pubkeyhash_msrs().
* return -ENOMEM in sgx_alloc_page() when VA pages consume too much space
* removed unused global sgx_nr_pids
* moved sgx_encl_release to sgx_encl.c
* return -ERESTARTSYS instead of -EINTR in sgx_encl_init()

Jarkko Sakkinen (11):
x86/sgx: Add ENCLS architectural error codes x86/sgx: Add SGX1 and SGX2 architectural data structures x86/sgx: Add wrappers for ENCLS leaf functions x86/sgx: Add functions to allocate and free EPC pages x86/sgx: Add the Linux SGX Enclave Driver x86/sgx: Add provisioning
x86/sgx: Add swapping code to the core and SGX driver x86/sgx: ptrace() support for the SGX driver selftests/x86: Add a selftest for SGX
x86/sgx: Update MAINTAINERS
docs: x86/sgx: Document the enclave API

Kai Huang (2):
x86/cpufeatures: Add Intel-defined SGX feature bit x86/cpufeatures: Add Intel-defined SGX_LC feature bit

Sean Christopherson (15):
x86/cpufeatures: Add SGX sub-features (as Linux-defined bits) x86/msr: Add IA32_FEATURE_CONTROL.SGX_ENABLE definition x86/msr: Add SGX Launch Control MSR definitions
x86/mm: x86/sgx: Add new 'PF_SGX' page fault error code bit x86/mm: x86/sgx: Signal SIGSEGV for userspace #PFs w/ PF_SGX x86/cpu/intel: Detect SGX support and update caps appropriately x86/sgx: Enumerate and track EPC sections
x86/sgx: Add sgx_einit() for initializing enclaves x86/vdso: Add support for exception fixup in vDSO functions x86/fault: Add helper function to sanitize error code x86/fault: Attempt to fixup unhandled #PF in vDSO before signaling x86/traps: Attempt to fixup exceptions in vDSO before signaling x86/vdso: Add __vdso_sgx_enter_enclave() to wrap SGX enclave
transitions
docs: x86/sgx: Add Architecture documentation
docs: x86/sgx: Document kernel internals

 Documentation/index.rst                       |   1 +
 Documentation/ioctl/ioctl-number.txt          |   1 +
 Documentation/x86/index.rst                   |  10 +
 Documentation/x86/sgx/1.Architecture.rst      | 431 +++++++++
 Documentation/x86/sgx/2.Kernel-internals.rst  |  56 ++
 Documentation/x86/sgx/3.API.rst               |  27 +
 Documentation/x86/sgx/index.rst               |  18 +
 MAINTAINERS                                   |  12 +
 arch/x86/Kconfig                              |  27 +
 arch/x86/entry/vdso/Makefile                  |   6 +-
 arch/x86/entry/vdso/extable.c                 |  37 +
 arch/x86/entry/vdso/extable.h                 |  29 +
 arch/x86/entry/vdso/vdso-layout.lds.S         |   9 +-
 arch/x86/entry/vdso/vdso.lds.S                |   1 +
 arch/x86/entry/vdso/vdso2c.h                  |  58 +-
 arch/x86/entry/vdso/vsgx_enter_enclave.S      | 101 +++
 arch/x86/include/asm/cpufeatures.h            |  24 +-
 arch/x86/include/asm/disabled-features.h      |  14 +-
 arch/x86/include/asm/msr-index.h              |   8 +
 arch/x86/include/asm/traps.h                  |   1 +
 arch/x86/include/asm/vdso.h                   |   5 +
 arch/x86/include/uapi/asm/sgx.h               |  86 ++
 arch/x86/include/uapi/asm/sgx_errno.h         |  91 ++
 arch/x86/kernel/cpu/Makefile                  |   1 +
 arch/x86/kernel/cpu/intel.c                   |  39 +
 arch/x86/kernel/cpu/scattered.c               |   2 +
 arch/x86/kernel/cpu/sgx/Makefile              |   2 +
 arch/x86/kernel/cpu/sgx/arch.h                | 424 +++++++++
 arch/x86/kernel/cpu/sgx/driver/Makefile       |   3 +
 arch/x86/kernel/cpu/sgx/driver/driver.h       |  38 +
 arch/x86/kernel/cpu/sgx/driver/ioctl.c        | 850 ++++++++++++++++++
 arch/x86/kernel/cpu/sgx/driver/main.c         | 368 ++++++++
 arch/x86/kernel/cpu/sgx/encl.c                | 709 +++++++++++++++
 arch/x86/kernel/cpu/sgx/encl.h                | 136 +++
 arch/x86/kernel/cpu/sgx/encls.c               |  22 +
 arch/x86/kernel/cpu/sgx/encls.h               | 244 +++++
 arch/x86/kernel/cpu/sgx/main.c                | 360 ++++++++
 arch/x86/kernel/cpu/sgx/reclaim.c             | 482 ++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h                 |  90 ++
 arch/x86/kernel/traps.c                       |  14 +
 arch/x86/mm/fault.c                           |  44 +-
 tools/arch/x86/include/asm/cpufeatures.h      |  21 +-
 tools/testing/selftests/x86/Makefile          |  10 +
 tools/testing/selftests/x86/sgx/Makefile      |  48 +
 tools/testing/selftests/x86/sgx/defines.h     |  39 +
 tools/testing/selftests/x86/sgx/encl.c        |  20 +
 tools/testing/selftests/x86/sgx/encl.lds      |  33 +
 .../selftests/x86/sgx/encl_bootstrap.S        |  94 ++
 tools/testing/selftests/x86/sgx/encl_piggy.S  |  18 +
 tools/testing/selftests/x86/sgx/encl_piggy.h  |  14 +
 tools/testing/selftests/x86/sgx/main.c        | 279 ++++++
 tools/testing/selftests/x86/sgx/sgx_call.S    |  15 +
 tools/testing/selftests/x86/sgx/sgxsign.c     | 508 +++++++++++
 .../testing/selftests/x86/sgx/signing_key.pem |  39 +
 54 files changed, 5987 insertions(+), 32 deletions(-)
 create mode 100644 Documentation/x86/index.rst
 create mode 100644 Documentation/x86/sgx/1.Architecture.rst
 create mode 100644 Documentation/x86/sgx/2.Kernel-internals.rst
 create mode 100644 Documentation/x86/sgx/3.API.rst
 create mode 100644 Documentation/x86/sgx/index.rst
 create mode 100644 arch/x86/entry/vdso/extable.c
 create mode 100644 arch/x86/entry/vdso/extable.h
 create mode 100644 arch/x86/entry/vdso/vsgx_enter_enclave.S
 create mode 100644 arch/x86/include/uapi/asm/sgx.h
 create mode 100644 arch/x86/include/uapi/asm/sgx_errno.h
 create mode 100644 arch/x86/kernel/cpu/sgx/Makefile
 create mode 100644 arch/x86/kernel/cpu/sgx/arch.h
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/Makefile
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/driver.h
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/ioctl.c
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/main.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.h
 create mode 100644 arch/x86/kernel/cpu/sgx/encls.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encls.h
 create mode 100644 arch/x86/kernel/cpu/sgx/main.c
 create mode 100644 arch/x86/kernel/cpu/sgx/reclaim.c
 create mode 100644 arch/x86/kernel/cpu/sgx/sgx.h
 create mode 100644 tools/testing/selftests/x86/sgx/Makefile
 create mode 100644 tools/testing/selftests/x86/sgx/defines.h
 create mode 100644 tools/testing/selftests/x86/sgx/encl.c
 create mode 100644 tools/testing/selftests/x86/sgx/encl.lds
 create mode 100644 tools/testing/selftests/x86/sgx/encl_bootstrap.S
 create mode 100644 tools/testing/selftests/x86/sgx/encl_piggy.S
 create mode 100644 tools/testing/selftests/x86/sgx/encl_piggy.h
 create mode 100644 tools/testing/selftests/x86/sgx/main.c
 create mode 100644 tools/testing/selftests/x86/sgx/sgx_call.S
 create mode 100644 tools/testing/selftests/x86/sgx/sgxsign.c
 create mode 100644 tools/testing/selftests/x86/sgx/signing_key.pem
Signature · 1 line
2.19.1
#1 lore raw

PATCH v20 1/28 x86/cpufeatures: Add Intel-defined SGX feature bit

From: Kai Huang <[email protected]>

X86_FEATURE_SGX reflects whether or not the CPU supports Intel's Software Guard eXtensions (SGX).

---
 arch/x86/include/asm/cpufeatures.h       | 1 +
 arch/x86/include/asm/disabled-features.h | 8 +++++++-
 2 files changed, 8 insertions(+), 1 deletion(-)
arch/x86/include/asm/cpufeatures.h +1 -0
index 981ff9479648..a16325db4cff 100644
@@ -236,6 +236,7 @@
 /* Intel-defined CPU features, CPUID level 0x00000007:0 (EBX), word 9 */
 #define X86_FEATURE_FSGSBASE		( 9*32+ 0) /* RDFSBASE, WRFSBASE, RDGSBASE, WRGSBASE instructions*/
 #define X86_FEATURE_TSC_ADJUST		( 9*32+ 1) /* TSC adjustment MSR 0x3B */
+#define X86_FEATURE_SGX			( 9*32+ 2) /* Software Guard Extensions */
 #define X86_FEATURE_BMI1		( 9*32+ 3) /* 1st group bit manipulation extensions */
 #define X86_FEATURE_HLE			( 9*32+ 4) /* Hardware Lock Elision */
 #define X86_FEATURE_AVX2		( 9*32+ 5) /* AVX2 instructions */
arch/x86/include/asm/disabled-features.h +7 -1
index a5ea841cc6d2..74de07d0f390 100644
@@ -62,6 +62,12 @@
 # define DISABLE_PTI		(1 << (X86_FEATURE_PTI & 31))
 #endif
 
+#ifdef CONFIG_INTEL_SGX
+# define DISABLE_SGX_CORE	0
+#else
+# define DISABLE_SGX_CORE	(1 << (X86_FEATURE_SGX & 31))
+#endif
+
 /*
  * Make sure to add features to the correct mask
  */
@@ -74,7 +80,7 @@
 #define DISABLED_MASK6	0
 #define DISABLED_MASK7	(DISABLE_PTI)
 #define DISABLED_MASK8	0
-#define DISABLED_MASK9	(DISABLE_MPX|DISABLE_SMAP)
+#define DISABLED_MASK9	(DISABLE_MPX|DISABLE_SMAP|DISABLE_SGX_CORE)
 #define DISABLED_MASK10	0
 #define DISABLED_MASK11	0
 #define DISABLED_MASK12	0
Signature · 1 line
2.19.1
#2 lore raw

PATCH v20 2/28 x86/cpufeatures: Add SGX sub-features (as Linux-defined bits)

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

CPUID_12_EAX is an Intel-defined feature bits leaf dedicated for SGX that enumerates the SGX instruction sets that are supported by the CPU, e.g. SGX1, SGX2, etc... Because Linux currently only cares about two bits (SGX1 and SGX2) and there are currently only four documented bits in total, relocate the bits to Linux-defined word 8 to conserve space.

But, keep the bit positions identical between the Intel-defined value and the Linux-defined value, e.g. keep SGX1 at bit 0. This allows KVM to use its existing code for probing guest CPUID bits using Linux's X86_FEATURE_* definitions. To do so, shift around some existing bits to effectively reserve bits 0-7 of word 8 for SGX sub-features.

---
 arch/x86/include/asm/cpufeatures.h       | 22 ++++++++++++++++------
 arch/x86/include/asm/disabled-features.h |  6 +++++-
 arch/x86/kernel/cpu/scattered.c          |  2 ++
 tools/arch/x86/include/asm/cpufeatures.h | 21 +++++++++++++++------
 4 files changed, 38 insertions(+), 13 deletions(-)
arch/x86/include/asm/cpufeatures.h +16 -6
index a16325db4cff..313c58c04b51 100644
@@ -222,12 +222,22 @@
 #define X86_FEATURE_L1TF_PTEINV		( 7*32+29) /* "" L1TF workaround PTE inversion */
 #define X86_FEATURE_IBRS_ENHANCED	( 7*32+30) /* Enhanced IBRS */
 
-/* Virtualization flags: Linux defined, word 8 */
-#define X86_FEATURE_TPR_SHADOW		( 8*32+ 0) /* Intel TPR Shadow */
-#define X86_FEATURE_VNMI		( 8*32+ 1) /* Intel Virtual NMI */
-#define X86_FEATURE_FLEXPRIORITY	( 8*32+ 2) /* Intel FlexPriority */
-#define X86_FEATURE_EPT			( 8*32+ 3) /* Intel Extended Page Table */
-#define X86_FEATURE_VPID		( 8*32+ 4) /* Intel Virtual Processor ID */
+/*
+ * Scattered Intel features: Linux defined, word 8.
+ *
+ * Note that the bit location of the SGX features is meaningful as KVM expects
+ * the Linux defined bit to match the Intel defined bit, e.g. X86_FEATURE_SGX1
+ * must remain at bit 0, SGX2 at bit 1, etc...
+ */
+#define X86_FEATURE_SGX1		( 8*32+ 0) /* SGX1 leaf functions */
+#define X86_FEATURE_SGX2		( 8*32+ 1) /* SGX2 leaf functions */
+/* Bits [0:7] are reserved for SGX */
+
+#define X86_FEATURE_TPR_SHADOW		( 8*32+ 8) /* Intel TPR Shadow */
+#define X86_FEATURE_VNMI		( 8*32+ 9) /* Intel Virtual NMI */
+#define X86_FEATURE_FLEXPRIORITY	( 8*32+10) /* Intel FlexPriority */
+#define X86_FEATURE_EPT			( 8*32+11) /* Intel Extended Page Table */
+#define X86_FEATURE_VPID		( 8*32+12) /* Intel Virtual Processor ID */
 
 #define X86_FEATURE_VMMCALL		( 8*32+15) /* Prefer VMMCALL to VMCALL */
 #define X86_FEATURE_XENPV		( 8*32+16) /* "" Xen paravirtual guest */
arch/x86/include/asm/disabled-features.h +5 -1
index 74de07d0f390..926f9dc4d75a 100644
@@ -34,12 +34,16 @@
 # define DISABLE_CYRIX_ARR	(1<<(X86_FEATURE_CYRIX_ARR & 31))
 # define DISABLE_CENTAUR_MCR	(1<<(X86_FEATURE_CENTAUR_MCR & 31))
 # define DISABLE_PCID		0
+# define DISABLE_SGX1		0
+# define DISABLE_SGX2		0
 #else
 # define DISABLE_VME		0
 # define DISABLE_K6_MTRR	0
 # define DISABLE_CYRIX_ARR	0
 # define DISABLE_CENTAUR_MCR	0
 # define DISABLE_PCID		(1<<(X86_FEATURE_PCID & 31))
+# define DISABLE_SGX1		(1<<(X86_FEATURE_SGX1 & 31))
+# define DISABLE_SGX2		(1<<(X86_FEATURE_SGX2 & 31))
 #endif /* CONFIG_X86_64 */
 
 #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS
@@ -79,7 +83,7 @@
 #define DISABLED_MASK5	0
 #define DISABLED_MASK6	0
 #define DISABLED_MASK7	(DISABLE_PTI)
-#define DISABLED_MASK8	0
+#define DISABLED_MASK8	(DISABLE_SGX1|DISABLE_SGX2)
 #define DISABLED_MASK9	(DISABLE_MPX|DISABLE_SMAP|DISABLE_SGX_CORE)
 #define DISABLED_MASK10	0
 #define DISABLED_MASK11	0
arch/x86/kernel/cpu/scattered.c +2 -0
index 94aa1c72ca98..9a5f6cf947b9 100644
@@ -31,6 +31,8 @@ static const struct cpuid_bit cpuid_bits[] = {
 	{ X86_FEATURE_CDP_L3,		CPUID_ECX,  2, 0x00000010, 1 },
 	{ X86_FEATURE_CDP_L2,		CPUID_ECX,  2, 0x00000010, 2 },
 	{ X86_FEATURE_MBA,		CPUID_EBX,  3, 0x00000010, 0 },
+	{ X86_FEATURE_SGX1,             CPUID_EAX,  0, 0x00000012, 0 },
+	{ X86_FEATURE_SGX2,             CPUID_EAX,  1, 0x00000012, 0 },
 	{ X86_FEATURE_HW_PSTATE,	CPUID_EDX,  7, 0x80000007, 0 },
 	{ X86_FEATURE_CPB,		CPUID_EDX,  9, 0x80000007, 0 },
 	{ X86_FEATURE_PROC_FEEDBACK,    CPUID_EDX, 11, 0x80000007, 0 },
tools/arch/x86/include/asm/cpufeatures.h +15 -6
index 981ff9479648..748180a4a1f5 100644
@@ -222,12 +222,21 @@
 #define X86_FEATURE_L1TF_PTEINV		( 7*32+29) /* "" L1TF workaround PTE inversion */
 #define X86_FEATURE_IBRS_ENHANCED	( 7*32+30) /* Enhanced IBRS */
 
-/* Virtualization flags: Linux defined, word 8 */
-#define X86_FEATURE_TPR_SHADOW		( 8*32+ 0) /* Intel TPR Shadow */
-#define X86_FEATURE_VNMI		( 8*32+ 1) /* Intel Virtual NMI */
-#define X86_FEATURE_FLEXPRIORITY	( 8*32+ 2) /* Intel FlexPriority */
-#define X86_FEATURE_EPT			( 8*32+ 3) /* Intel Extended Page Table */
-#define X86_FEATURE_VPID		( 8*32+ 4) /* Intel Virtual Processor ID */
+/*
+ * Scattered Intel features: Linux defined, word 8.
+ *
+ * Note that the bit numbers of the SGX features are meaningful as KVM expects
+ * the Linux defined bit to match the Intel defined bit, e.g. X86_FEATURE_SGX1
+ * must remain at bit 0, SGX2 at bit 1, etc...
+ */
+#define X86_FEATURE_SGX1		( 8*32+ 0) /* SGX1 leaf functions */
+#define X86_FEATURE_SGX2		( 8*32+ 1) /* SGX2 leaf functions */
+
+#define X86_FEATURE_TPR_SHADOW		( 8*32+ 8) /* Intel TPR Shadow */
+#define X86_FEATURE_VNMI		( 8*32+ 9) /* Intel Virtual NMI */
+#define X86_FEATURE_FLEXPRIORITY	( 8*32+10) /* Intel FlexPriority */
+#define X86_FEATURE_EPT			( 8*32+11) /* Intel Extended Page Table */
+#define X86_FEATURE_VPID		( 8*32+12) /* Intel Virtual Processor ID */
 
 #define X86_FEATURE_VMMCALL		( 8*32+15) /* Prefer VMMCALL to VMCALL */
 #define X86_FEATURE_XENPV		( 8*32+16) /* "" Xen paravirtual guest */
Signature · 1 line
2.19.1
#3 lore raw

PATCH v20 3/28 x86/msr: Add IA32_FEATURE_CONTROL.SGX_ENABLE definition

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Add a new IA32_FEATURE_CONTROL bit, SGX_ENABLE, which must be set in order to execute SGX instructions, i.e. ENCL{S,U,V}. The existence of the bit is enumerated by CPUID as X86_FEATURE_SGX. Like all other flags in IA32_FEATURE_CONTROL, the MSR must be locked for SGX_ENABLE to take effect.

---
 arch/x86/include/asm/msr-index.h | 1 +
 1 file changed, 1 insertion(+)
arch/x86/include/asm/msr-index.h +1 -0
index ca5bc0eacb95..6efaa8026c64 100644
@@ -525,6 +525,7 @@
 #define FEATURE_CONTROL_LOCKED				(1<<0)
 #define FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX	(1<<1)
 #define FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX	(1<<2)
+#define FEATURE_CONTROL_SGX_ENABLE			(1<<18)
 #define FEATURE_CONTROL_LMCE				(1<<20)
 
 #define MSR_IA32_APICBASE		0x0000001b
Signature · 1 line
2.19.1
#4 lore raw

PATCH v20 4/28 x86/cpufeatures: Add Intel-defined SGX_LC feature bit

In reply to Jarkko Sakkinen

From: Kai Huang <[email protected]>

X86_FEATURE_SGX_LC reflects whether or not the CPU supports SGX Launch Control, i.e. enumerates the existence of IA32_FEATURE_CONTROL's SGX_LE_WR bit and the IA32_SGXLEPUBKEYHASH MSRs.

---
 arch/x86/include/asm/cpufeatures.h | 1 +
 1 file changed, 1 insertion(+)
arch/x86/include/asm/cpufeatures.h +1 -0
index 313c58c04b51..c5080842ecad 100644
@@ -346,6 +346,7 @@
 #define X86_FEATURE_CLDEMOTE		(16*32+25) /* CLDEMOTE instruction */
 #define X86_FEATURE_MOVDIRI		(16*32+27) /* MOVDIRI instruction */
 #define X86_FEATURE_MOVDIR64B		(16*32+28) /* MOVDIR64B instruction */
+#define X86_FEATURE_SGX_LC		(16*32+30) /* Software Guard Extensions Launch Control */
 
 /* AMD-defined CPU features, CPUID level 0x80000007 (EBX), word 17 */
 #define X86_FEATURE_OVERFLOW_RECOV	(17*32+ 0) /* MCA overflow recovery support */
Signature · 1 line
2.19.1
#5 lore raw

PATCH v20 5/28 x86/msr: Add SGX Launch Control MSR definitions

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Add a new IA32_FEATURE_CONTROL bit, SGX_LE_WR. When set, SGX_LE_WR allows software to write the SGXLEPUBKEYHASH MSRs (see below). The The existence of the bit is enumerated by CPUID as X86_FEATURE_SGX_LC. Like all other flags in IA32_FEATURE_CONTROL, the MSR must be locked for SGX_LE_WR to take effect.

Add four MSRs, SGXLEPUBKEYHASH{0,1,2,3}, or in human readable form, the SGX Launch Enclave Public Key Hash MSRs. These MSRs correspond to the key that is used by the CPU to determine whether or not to allow software to enter an enclave. When ENCLS[EINIT] is executed, which is a prerequisite to entering the enclave, the CPU compares the key (technically its hash) used to sign the enclave with the key hash stored in the MSRs, and will reject EINIT if the keys do not match.

Enclaves can also be blessed by proxy, in which case a Launch Enclave generates and signs an EINIT TOKEN. If a valid token is provided, ENCLS[EINIT] compares the signer of the token against the MSRs instead of the signer of the enclave. The SGXLEPUBKEYHASH MSRs only exist on CPUs that support SGX Launch Control, enumerated by X86_FEATURE_SGX_LC. CPUs without Launch Control use a hardcoded key for the ENCLS[EINIT] checks. An internal hardcoded key is also used as the reset value for the hash MSRs when they exist.

As a final note, the SGX_LEPUBKEYHASH MSRs can also be written by pre-boot firmware prior to activating SGX (SGX activation is done by setting bit 0 in MSR 0x7A). Thus, firmware can lock the MSRs to a non-Intel value by writing the MSRs and locking IA32_FEATURE_CONTROL without setting SGX_LE_WR.

---
 arch/x86/include/asm/msr-index.h | 7 +++++++
 1 file changed, 7 insertions(+)
arch/x86/include/asm/msr-index.h +7 -0
index 6efaa8026c64..a4a22441d000 100644
@@ -525,6 +525,7 @@
 #define FEATURE_CONTROL_LOCKED				(1<<0)
 #define FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX	(1<<1)
 #define FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX	(1<<2)
+#define FEATURE_CONTROL_SGX_LE_WR			(1<<17)
 #define FEATURE_CONTROL_SGX_ENABLE			(1<<18)
 #define FEATURE_CONTROL_LMCE				(1<<20)
 
@@ -538,6 +539,12 @@
 #define MSR_IA32_UCODE_WRITE		0x00000079
 #define MSR_IA32_UCODE_REV		0x0000008b
 
+/* Intel SGX Launch Enclave Public Key Hash MSRs */
+#define MSR_IA32_SGXLEPUBKEYHASH0	0x0000008C
+#define MSR_IA32_SGXLEPUBKEYHASH1	0x0000008D
+#define MSR_IA32_SGXLEPUBKEYHASH2	0x0000008E
+#define MSR_IA32_SGXLEPUBKEYHASH3	0x0000008F
+
 #define MSR_IA32_SMM_MONITOR_CTL	0x0000009b
 #define MSR_IA32_SMBASE			0x0000009e
 
Signature · 1 line
2.19.1
#6 lore raw

PATCH v20 6/28 x86/mm: x86/sgx: Add new 'PF_SGX' page fault error code bit

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

The SGX bit is set in the #PF error code if and only if the fault is detected by the Enclave Page Cache Map (EPCM), a hardware-managed table that enforces the paging permissions defined by the enclave, e.g. to prevent the kernel from changing the permissions of an enclave's page(s).

Despite triggering a #PF, a #PF with PF_SGX has nothing to do with paging.

---
 arch/x86/include/asm/traps.h | 1 +
 1 file changed, 1 insertion(+)
arch/x86/include/asm/traps.h +1 -0
index 7d6f3f3fad78..c3e02912e9c7 100644
@@ -171,5 +171,6 @@ enum x86_pf_error_code {
 	X86_PF_RSVD	=		1 << 3,
 	X86_PF_INSTR	=		1 << 4,
 	X86_PF_PK	=		1 << 5,
+	X86_PF_SGX	=		1 << 15,
 };
 #endif /* _ASM_X86_TRAPS_H */
Signature · 1 line
2.19.1
#7 lore raw

PATCH v20 7/28 x86/mm: x86/sgx: Signal SIGSEGV for userspace #PFs w/ PF_SGX

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

The PF_SGX bit is set if and only if the #PF is detected by the SGX Enclave Page Cache Map (EPCM). The EPCM is a hardware-managed table that enforces accesses to an enclave's EPC pages in addition to the software-managed kernel page tables, i.e. the effective permissions for an EPC page are a logical AND of the kernel's page tables and the corresponding EPCM entry.

The EPCM is consulted only after an access walks the kernel's page tables, i.e.:

a. the access was allowed by the kernel
b. the kernel's tables have become less restrictive than the EPCM c. the kernel cannot fixup the cause of the fault

Noteably, (b) implies that either the kernel has botched the EPC mappings or the EPCM has been invalidated (see below). Regardless of why the fault occurred, userspace needs to be alerted so that it can take appropriate action, e.g. restart the enclave. This is reinforced by (c) as the kernel doesn't really have any other reasonable option, i.e. signalling SIGSEGV is actually the least severe action possible.

Although the primary purpose of the EPCM is to prevent a malicious or compromised kernel from attacking an enclave, e.g. by modifying the enclave's page tables, do not WARN on a #PF w/ PF_SGX set. The SGX architecture effectively allows the CPU to invalidate all EPCM entries at will and requires that software be prepared to handle an EPCM fault at any time. The architecture defines this behavior because the EPCM is encrypted with an ephemeral key that isn't exposed to software. As such, the EPCM entries cannot be preserved across transitions that result in a new key being used, e.g. CPU power down as part of an S3 transition or when a VM is live migrated to a new physical system.

---
 arch/x86/mm/fault.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
arch/x86/mm/fault.c +13 -0
index 667f1da36208..78e2807fbede 100644
@@ -1214,6 +1214,19 @@ access_error(unsigned long error_code, struct vm_area_struct *vma)
 	if (error_code & X86_PF_PK)
 		return 1;
 
+	/*
+	 * Access is blocked by the Enclave Page Cache Map (EPCM), i.e. the
+	 * access is allowed by the PTE but not the EPCM.  This usually happens
+	 * when the EPCM is yanked out from under us, e.g. by hardware after a
+	 * suspend/resume cycle.  In any case, software, i.e. the kernel, can't
+	 * fix the source of the fault as the EPCM can't be directly modified
+	 * by software.  Handle the fault as an access error in order to signal
+	 * userspace, e.g. so that userspace can rebuild their enclave(s), even
+	 * though userspace may not have actually violated access permissions.
+	 */
+	if (unlikely(error_code & X86_PF_SGX))
+		return 1;
+
 	/*
 	 * Make sure to check the VMA so that we do not perform
 	 * faults just to hit a X86_PF_PK as soon as we fill in a
Signature · 1 line
2.19.1
#8 lore raw

PATCH v20 8/28 x86/cpu/intel: Detect SGX support and update caps appropriately

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Similar to other large Intel features such as VMX and TXT, SGX must be explicitly enabled in IA32_FEATURE_CONTROL MSR to be truly usable. Clear all SGX related capabilities if SGX is not fully enabled in IA32_FEATURE_CONTROL or if the SGX1 instruction set isn't supported (impossible on bare metal, theoretically possible in a VM if the VMM is doing something weird).

Like SGX itself, SGX Launch Control must be explicitly enabled via a flag in IA32_FEATURE_CONTROL. Clear the SGX_LC capability if Launch Control is not fully enabled (or obviously if SGX itself is disabled).

Note that clearing X86_FEATURE_SGX_LC creates a bit of a conundrum regarding the SGXLEPUBKEYHASH MSRs, as it may be desirable to read the MSRs even if they are not writable, e.g. to query the configured key, but clearing the capability leaves no breadcrum for discerning whether or not the MSRs exist. But, such usage will be rare (KVM is the only known case at this time) and not performance critical, so it's not unreasonable to require the use of rdmsr_safe(). Clearing the cap bit eliminates the need for an additional flag to track whether or not Launch Control is truly enabled, which is what we care about the vast majority of the time.

---
 arch/x86/kernel/cpu/intel.c | 39 +++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)
arch/x86/kernel/cpu/intel.c +39 -0
index fc3c07fe7df5..702497f34a96 100644
@@ -596,6 +596,42 @@ static void detect_tme(struct cpuinfo_x86 *c)
 	c->x86_phys_bits -= keyid_bits;
 }
 
+static void __maybe_unused detect_sgx(struct cpuinfo_x86 *c)
+{
+	unsigned long long fc;
+
+	rdmsrl(MSR_IA32_FEATURE_CONTROL, fc);
+	if (!(fc & FEATURE_CONTROL_LOCKED)) {
+		pr_err_once("sgx: The feature control MSR is not locked\n");
+		goto err_unsupported;
+	}
+
+	if (!(fc & FEATURE_CONTROL_SGX_ENABLE)) {
+		pr_err_once("sgx: SGX is not enabled in IA32_FEATURE_CONTROL MSR\n");
+		goto err_unsupported;
+	}
+
+	if (!cpu_has(c, X86_FEATURE_SGX1)) {
+		pr_err_once("sgx: SGX1 instruction set is not supported\n");
+		goto err_unsupported;
+	}
+
+	if (!(fc & FEATURE_CONTROL_SGX_LE_WR)) {
+		pr_info_once("sgx: The launch control MSRs are not writable\n");
+		goto err_msrs_rdonly;
+	}
+
+	return;
+
+err_unsupported:
+	setup_clear_cpu_cap(X86_FEATURE_SGX);
+	setup_clear_cpu_cap(X86_FEATURE_SGX1);
+	setup_clear_cpu_cap(X86_FEATURE_SGX2);
+
+err_msrs_rdonly:
+	setup_clear_cpu_cap(X86_FEATURE_SGX_LC);
+}
+
 static void init_intel_energy_perf(struct cpuinfo_x86 *c)
 {
 	u64 epb;
@@ -763,6 +799,9 @@ static void init_intel(struct cpuinfo_x86 *c)
 	if (cpu_has(c, X86_FEATURE_TME))
 		detect_tme(c);
 
+	if (IS_ENABLED(CONFIG_INTEL_SGX) && cpu_has(c, X86_FEATURE_SGX))
+		detect_sgx(c);
+
 	init_intel_energy_perf(c);
 
 	init_intel_misc_features(c);
Signature · 1 line
2.19.1
#9 lore raw

PATCH v20 9/28 x86/sgx: Add ENCLS architectural error codes

In reply to Jarkko Sakkinen

The SGX architecture defines an extensive set of error codes that are used by ENCL{S,U,V} instructions to provide software with (somewhat) precise error information. Though they are architectural, define the known error codes in a separate file from sgx_arch.h so that they can be exposed to userspace. For some ENCLS leafs, e.g. EINIT, returning the exact error code on failure can enable userspace to make informed decisions when an operation fails.

---
 arch/x86/include/uapi/asm/sgx_errno.h | 91 +++++++++++++++++++++++++++
 1 file changed, 91 insertions(+)
 create mode 100644 arch/x86/include/uapi/asm/sgx_errno.h
arch/x86/include/uapi/asm/sgx_errno.h new file +91 -0
new file mode 100644
index 000000000000..48b87aed58d7
@@ -0,0 +1,91 @@
+/* SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause */
+/*
+ * Copyright(c) 2018 Intel Corporation.
+ *
+ * Contains the architecturally defined error codes that are returned by SGX
+ * instructions, e.g. ENCLS, and may be propagated to userspace via errno.
+ */
+
+#ifndef _UAPI_ASM_X86_SGX_ERRNO_H
+#define _UAPI_ASM_X86_SGX_ERRNO_H
+
+/**
+ * enum sgx_encls_leaves - return codes for ENCLS, ENCLU and ENCLV
+ * %SGX_SUCCESS:		No error.
+ * %SGX_INVALID_SIG_STRUCT:	SIGSTRUCT contains an invalid value.
+ * %SGX_INVALID_ATTRIBUTE:	Enclave is not attempting to access a resource
+ *				for which it is not authorized.
+ * %SGX_BLKSTATE:		EPC page is already blocked.
+ * %SGX_INVALID_MEASUREMENT:	SIGSTRUCT or EINITTOKEN contains an incorrect
+ *				measurement.
+ * %SGX_NOTBLOCKABLE:		EPC page type is not one which can be blocked.
+ * %SGX_PG_INVLD:		EPC page is invalid (and cannot be blocked).
+ * %SGX_EPC_PAGE_CONFLICT:	EPC page in use by another SGX instruction.
+ * %SGX_INVALID_SIGNATURE:	Enclave's signature does not validate with
+ *				public key enclosed in SIGSTRUCT.
+ * %SGX_MAC_COMPARE_FAIL:	MAC check failed when reloading EPC page.
+ * %SGX_PAGE_NOT_BLOCKED:	EPC page is not marked as blocked.
+ * %SGX_NOT_TRACKED:		ETRACK has not been completed on the EPC page.
+ * %SGX_VA_SLOT_OCCUPIED:	Version array slot contains a valid entry.
+ * %SGX_CHILD_PRESENT:		Enclave has child pages present in the EPC.
+ * %SGX_ENCLAVE_ACT:		Logical processors are currently executing
+ *				inside the enclave.
+ * %SGX_ENTRYEPOCH_LOCKED:	SECS locked for EPOCH update, i.e. an ETRACK is
+ *				currently executing on the SECS.
+ * %SGX_INVALID_EINITTOKEN:	EINITTOKEN is invalid and enclave signer's
+ *				public key does not match IA32_SGXLEPUBKEYHASH.
+ * %SGX_PREV_TRK_INCMPL:	All processors did not complete the previous
+ *				tracking sequence.
+ * %SGX_PG_IS_SECS:		Target EPC page is an SECS and cannot be
+ *				blocked.
+ * %SGX_PAGE_ATTRIBUTES_MISMATCH:	Attributes of the EPC page do not match
+ *					the expected values.
+ * %SGX_PAGE_NOT_MODIFIABLE:	EPC page cannot be modified because it is in
+ *				the PENDING or MODIFIED state.
+ * %SGX_PAGE_NOT_DEBUGGABLE:	EPC page cannot be modified because it is in
+ *				the PENDING or MODIFIED state.
+ * %SGX_INVALID_COUNTER:	{In,De}crementing a counter would cause it to
+ *				{over,under}flow.
+ * %SGX_PG_NONEPC:		Target page is not an EPC page.
+ * %SGX_TRACK_NOT_REQUIRED:	Target page type does not require tracking.
+ * %SGX_INVALID_CPUSVN:		Security version number reported by CPU is less
+ *				than what is required by the enclave.
+ * %SGX_INVALID_ISVSVN:		Security version number of enclave is less than
+ *				what is required by the KEYREQUEST struct.
+ * %SGX_UNMASKED_EVENT:		An unmasked event, e.g. INTR, was received
+ *				while the instruction was executing.
+ * %SGX_INVALID_KEYNAME:	Requested key is not supported by hardware.
+ */
+enum sgx_return_codes {
+	SGX_SUCCESS			= 0,
+	SGX_INVALID_SIG_STRUCT		= 1,
+	SGX_INVALID_ATTRIBUTE		= 2,
+	SGX_BLKSTATE			= 3,
+	SGX_INVALID_MEASUREMENT		= 4,
+	SGX_NOTBLOCKABLE		= 5,
+	SGX_PG_INVLD			= 6,
+	SGX_EPC_PAGE_CONFLICT		= 7,
+	SGX_INVALID_SIGNATURE		= 8,
+	SGX_MAC_COMPARE_FAIL		= 9,
+	SGX_PAGE_NOT_BLOCKED		= 10,
+	SGX_NOT_TRACKED			= 11,
+	SGX_VA_SLOT_OCCUPIED		= 12,
+	SGX_CHILD_PRESENT		= 13,
+	SGX_ENCLAVE_ACT			= 14,
+	SGX_ENTRYEPOCH_LOCKED		= 15,
+	SGX_INVALID_EINITTOKEN		= 16,
+	SGX_PREV_TRK_INCMPL		= 17,
+	SGX_PG_IS_SECS			= 18,
+	SGX_PAGE_ATTRIBUTES_MISMATCH	= 19,
+	SGX_PAGE_NOT_MODIFIABLE		= 20,
+	SGX_PAGE_NOT_DEBUGGABLE		= 21,
+	SGX_INVALID_COUNTER		= 25,
+	SGX_PG_NONEPC			= 26,
+	SGX_TRACK_NOT_REQUIRED		= 27,
+	SGX_INVALID_CPUSVN		= 32,
+	SGX_INVALID_ISVSVN		= 64,
+	SGX_UNMASKED_EVENT		= 128,
+	SGX_INVALID_KEYNAME		= 256,
+};
+
+#endif /* _UAPI_ASM_X86_SGX_ERRNO_H */
Signature · 1 line
2.19.1
#10 lore raw

Re: [PATCH v20 09/28] x86/sgx: Add ENCLS architectural error codes

Quoted 8 lines · Jarkko Sakkinen

The SGX architecture defines an extensive set of error codes that are used by ENCL{S,U,V} instructions to provide software with (somewhat) precise error information. Though they are architectural, define the known error codes in a separate file from sgx_arch.h so that they can be exposed to userspace. For some ENCLS leafs, e.g. EINIT, returning the exact error code on failure can enable userspace to make informed decisions when an operation fails.

Quoted 4 lines

---

Your SOB needs to be last. Several other patches have the same issue, e.g. 10-13, 15 and 17.

See commit 24a2bb90741b ("docs: Clarify the usage and sign-off requirements for Co-developed-by") in branch docs-next of git://git.lwn.net/linux.git.

#11 lore raw

PATCH v20 10/28 x86/sgx: Add SGX1 and SGX2 architectural data structures

In reply to Jarkko Sakkinen

Define the data structures used by various ENCLS functions needed for Linux to support all SGX1 and SGX2 ENCLS leaf functions. This is not an exhaustive representation of all SGX data structures as several are only consumed by ENCLU (userspace), e.g. REPORT and KEYREQUEST, while others are only consumed by future features, e.g. RDINFO.

---
 arch/x86/kernel/cpu/sgx/arch.h | 424 +++++++++++++++++++++++++++++++++
 1 file changed, 424 insertions(+)
 create mode 100644 arch/x86/kernel/cpu/sgx/arch.h
arch/x86/kernel/cpu/sgx/arch.h new file +424 -0
new file mode 100644
index 000000000000..39f731580ea8
@@ -0,0 +1,424 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/**
+ * Copyright(c) 2016-18 Intel Corporation.
+ *
+ * Contains data structures defined by the SGX architecture.  Data structures
+ * defined by the Linux software stack should not be placed here.
+ */
+#ifndef _ASM_X86_SGX_ARCH_H
+#define _ASM_X86_SGX_ARCH_H
+
+#include <linux/types.h>
+
+#define SGX_CPUID				0x12
+#define SGX_CPUID_FIRST_VARIABLE_SUB_LEAF	2
+
+/**
+ * enum sgx_sub_leaf_types - SGX CPUID variable sub-leaf types
+ * %SGX_CPUID_SUB_LEAF_INVALID:		Indicates this sub-leaf is invalid.
+ * %SGX_CPUID_SUB_LEAF_EPC_SECTION:	Sub-leaf enumerates an EPC section.
+ */
+enum sgx_sub_leaf_types {
+	SGX_CPUID_SUB_LEAF_INVALID	= 0x0,
+	SGX_CPUID_SUB_LEAF_EPC_SECTION	= 0x1,
+};
+
+#define SGX_CPUID_SUB_LEAF_TYPE_MASK	GENMASK(3, 0)
+
+/**
+ * enum sgx_encls_leaves - ENCLS leaf functions
+ * %SGX_ECREATE:	Create an enclave.
+ * %SGX_EADD:		Add a page to an uninitialized enclave.
+ * %SGX_EINIT:		Initialize an enclave, i.e. launch an enclave.
+ * %SGX_EREMOVE:	Remove a page from an enclave.
+ * %SGX_EDBGRD:		Read a word from an enclve (peek).
+ * %SGX_EDBGWR:		Write a word to an enclave (poke).
+ * %SGX_EEXTEND:	Measure 256 bytes of an added enclave page.
+ * %SGX_ELDB:		Load a swapped page in blocked state.
+ * %SGX_ELDU:		Load a swapped page in unblocked state.
+ * %SGX_EBLOCK:		Change page state to blocked i.e. entering hardware
+ *			threads cannot access it and create new TLB entries.
+ * %SGX_EPA:		Create a Version Array (VA) page used to store isvsvn
+ *			number for a swapped EPC page.
+ * %SGX_EWB:		Swap an enclave page to the regular memory. Checks that
+ *			all threads have exited that were in the previous
+ *			shoot-down sequence.
+ * %SGX_ETRACK:		Start a new shoot down sequence. Used to together with
+ *			EBLOCK to make sure that a page is safe to swap.
+ * %SGX_EAUG:		Add a page to an initialized enclave.
+ * %SGX_EMODPR:		Restrict an EPC page's permissions.
+ * %SGX_EMODT:		Modify the page type of an EPC page.
+ */
+enum sgx_encls_leaves {
+	SGX_ECREATE	= 0x00,
+	SGX_EADD	= 0x01,
+	SGX_EINIT	= 0x02,
+	SGX_EREMOVE	= 0x03,
+	SGX_EDGBRD	= 0x04,
+	SGX_EDGBWR	= 0x05,
+	SGX_EEXTEND	= 0x06,
+	SGX_ELDB	= 0x07,
+	SGX_ELDU	= 0x08,
+	SGX_EBLOCK	= 0x09,
+	SGX_EPA		= 0x0A,
+	SGX_EWB		= 0x0B,
+	SGX_ETRACK	= 0x0C,
+	SGX_EAUG	= 0x0D,
+	SGX_EMODPR	= 0x0E,
+	SGX_EMODT	= 0x0F,
+};
+
+#define SGX_MODULUS_SIZE 384
+
+/**
+ * enum sgx_miscselect - additional information to an SSA frame
+ * %SGX_MISC_EXINFO:	Report #PF or #GP to the SSA frame.
+ *
+ * Save State Area (SSA) is a stack inside the enclave used to store processor
+ * state when an exception or interrupt occurs. This enum defines additional
+ * information stored to an SSA frame.
+ */
+enum sgx_miscselect {
+	SGX_MISC_EXINFO		= BIT(0),
+};
+
+#define SGX_MISC_RESERVED_MASK	GENMASK_ULL(63, 1)
+
+#define SGX_SSA_GPRS_SIZE		182
+#define SGX_SSA_MISC_EXINFO_SIZE	16
+
+/**
+ * enum sgx_attributes - the attributes field in &struct sgx_secs
+ * %SGX_ATTR_INIT:		Enclave can be entered (is initialized).
+ * %SGX_ATTR_DEBUG:		Allow ENCLS(EDBGRD) and ENCLS(EDBGWR).
+ * %SGX_ATTR_MODE64BIT:		Tell that this a 64-bit enclave.
+ * %SGX_ATTR_PROVISIONKEY:      Allow to use provisioning keys for remote
+ *				attestation.
+ * %SGX_ATTR_KSS:		Allow to use key separation and sharing (KSS).
+ * %SGX_ATTR_EINITTOKENKEY:	Allow to use token signing key that is used to
+ *				sign cryptographic tokens that can be passed to
+ *				EINIT as an authorization to run an enclave.
+ */
+enum sgx_attribute {
+	SGX_ATTR_INIT		= BIT(0),
+	SGX_ATTR_DEBUG		= BIT(1),
+	SGX_ATTR_MODE64BIT	= BIT(2),
+	SGX_ATTR_PROVISIONKEY	= BIT(4),
+	SGX_ATTR_EINITTOKENKEY	= BIT(5),
+	SGX_ATTR_KSS		= BIT(7),
+};
+
+#define SGX_ATTR_RESERVED_MASK	(BIT_ULL(3) | BIT_ULL(7) | GENMASK_ULL(63, 8))
+#define SGX_ATTR_ALLOWED_MASK	(SGX_ATTR_DEBUG | SGX_ATTR_MODE64BIT | \
+				 SGX_ATTR_KSS)
+#define SGX_SECS_RESERVED1_SIZE 24
+#define SGX_SECS_RESERVED2_SIZE 32
+#define SGX_SECS_RESERVED3_SIZE 96
+#define SGX_SECS_RESERVED4_SIZE 3836
+
+/**
+ * struct sgx_secs - SGX Enclave Control Structure (SECS)
+ * @size:		size of the address space
+ * @base:		base address of the  address space
+ * @ssa_frame_size:	size of an SSA frame
+ * @miscselect:		additional information stored to an SSA frame
+ * @attributes:		attributes for enclave
+ * @xfrm:		XSave-Feature Request Mask (subset of XCR0)
+ * @mrenclave:		SHA256-hash of the enclave contents
+ * @mrsigner:		SHA256-hash of the public key used to sign the SIGSTRUCT
+ * @isvprodid:		a user-defined value that is used in key derivation
+ * @isvsvn:		a user-defined value that is used in key derivation
+ *
+ * SGX Enclave Control Structure (SECS) is a special enclave page that is not
+ * visible in the address space. In fact, this structure defines the address
+ * range and other global attributes for the enclave and it is the first EPC
+ * page created for any enclave. It is moved from a temporary buffer to an EPC
+ * by the means of ENCLS(ECREATE) leaf.
+ */
+struct sgx_secs {
+	u64 size;
+	u64 base;
+	u32 ssa_frame_size;
+	u32 miscselect;
+	u8  reserved1[SGX_SECS_RESERVED1_SIZE];
+	u64 attributes;
+	u64 xfrm;
+	u32 mrenclave[8];
+	u8  reserved2[SGX_SECS_RESERVED2_SIZE];
+	u32 mrsigner[8];
+	u8  reserved3[SGX_SECS_RESERVED3_SIZE];
+	u16 isvprodid;
+	u16 isvsvn;
+	u8  reserved4[SGX_SECS_RESERVED4_SIZE];
+} __packed;
+
+/**
+ * enum sgx_tcs_flags - execution flags for TCS
+ * %SGX_TCS_DBGOPTIN:	If enabled allows single-stepping and breakpoints
+ *			inside an enclave. It is cleared by EADD but can
+ *			be set later with EDBGWR.
+ */
+enum sgx_tcs_flags {
+	SGX_TCS_DBGOPTIN	= 0x01,
+};
+
+#define SGX_TCS_RESERVED_MASK	GENMASK_ULL(63, 1)
+#define SGX_TCS_RESERVED_SIZE	4024
+
+/**
+ * struct sgx_tcs - Thread Control Structure (TCS)
+ * @state:		used to mark an entered TCS
+ * @flags:		execution flags (cleared by EADD)
+ * @ssa_offset:		SSA stack offset relative to the enclave base
+ * @ssa_index:		the current SSA frame index (cleard by EADD)
+ * @nr_ssa_frames:	the number of frame in the SSA stack
+ * @entry_offset:	entry point offset relative to the enclave base
+ * @exit_addr:		address outside the enclave to exit on an exception or
+ *			interrupt
+ * @fs_offset:		offset relative to the enclave base to become FS
+ *			segment inside the enclave
+ * @gs_offset:		offset relative to the enclave base to become GS
+ *			segment inside the enclave
+ * @fs_limit:		size to become a new FS-limit (only 32-bit enclaves)
+ * @gs_limit:		size to become a new GS-limit (only 32-bit enclaves)
+ *
+ * Thread Control Structure (TCS) is an enclave page visible in its address
+ * space that defines an entry point inside the enclave. A thread enters inside
+ * an enclave by supplying address of TCS to ENCLU(EENTER). A TCS can be entered
+ * by only one thread at a time.
+ */
+struct sgx_tcs {
+	u64 state;
+	u64 flags;
+	u64 ssa_offset;
+	u32 ssa_index;
+	u32 nr_ssa_frames;
+	u64 entry_offset;
+	u64 exit_addr;
+	u64 fs_offset;
+	u64 gs_offset;
+	u32 fs_limit;
+	u32 gs_limit;
+	u8  reserved[SGX_TCS_RESERVED_SIZE];
+} __packed;
+
+/**
+ * struct sgx_pageinfo - an enclave page descriptor
+ * @addr:	address of the enclave page
+ * @contents:	pointer to the page contents
+ * @metadata:	pointer either to a SECINFO or PCMD instance
+ * @secs:	address of the SECS page
+ */
+struct sgx_pageinfo {
+	u64 addr;
+	u64 contents;
+	u64 metadata;
+	u64 secs;
+} __packed __aligned(32);
+
+
+/**
+ * enum sgx_page_type - bits in the SECINFO flags defining the page type
+ * %SGX_PAGE_TYPE_SECS:	a SECS page
+ * %SGX_PAGE_TYPE_TCS:	a TCS page
+ * %SGX_PAGE_TYPE_REG:	a regular page
+ * %SGX_PAGE_TYPE_VA:	a VA page
+ * %SGX_PAGE_TYPE_TRIM:	a page in trimmed state
+ */
+enum sgx_page_type {
+	SGX_PAGE_TYPE_SECS,
+	SGX_PAGE_TYPE_TCS,
+	SGX_PAGE_TYPE_REG,
+	SGX_PAGE_TYPE_VA,
+	SGX_PAGE_TYPE_TRIM,
+};
+
+#define SGX_NR_PAGE_TYPES	5
+#define SGX_PAGE_TYPE_MASK	GENMASK(7, 0)
+
+/**
+ * enum sgx_secinfo_flags - the flags field in &struct sgx_secinfo
+ * %SGX_SECINFO_R:	allow read
+ * %SGX_SECINFO_W:	allow write
+ * %SGX_SECINFO_X:	allow execution
+ * %SGX_SECINFO_SECS:	a SECS page
+ * %SGX_SECINFO_TCS:	a TCS page
+ * %SGX_SECINFO_REG:	a regular page
+ * %SGX_SECINFO_VA:	a VA page
+ * %SGX_SECINFO_TRIM:	a page in trimmed state
+ */
+enum sgx_secinfo_flags {
+	SGX_SECINFO_R			= BIT(0),
+	SGX_SECINFO_W			= BIT(1),
+	SGX_SECINFO_X			= BIT(2),
+	SGX_SECINFO_SECS		= (SGX_PAGE_TYPE_SECS << 8),
+	SGX_SECINFO_TCS			= (SGX_PAGE_TYPE_TCS << 8),
+	SGX_SECINFO_REG			= (SGX_PAGE_TYPE_REG << 8),
+	SGX_SECINFO_VA			= (SGX_PAGE_TYPE_VA << 8),
+	SGX_SECINFO_TRIM		= (SGX_PAGE_TYPE_TRIM << 8),
+};
+
+#define SGX_SECINFO_PERMISSION_MASK	GENMASK_ULL(2, 0)
+#define SGX_SECINFO_PAGE_TYPE_MASK	(SGX_PAGE_TYPE_MASK << 8)
+#define SGX_SECINFO_RESERVED_MASK	~(SGX_SECINFO_PERMISSION_MASK | \
+					  SGX_SECINFO_PAGE_TYPE_MASK)
+#define SGX_SECINFO_RESERVED_SIZE	56
+
+/**
+ * struct sgx_secinfo - describes attributes of an EPC page
+ * @flags:	permissions and type
+ *
+ * Used together with ENCLS leaves that add or modify an EPC page to an
+ * enclave to define page permissions and type.
+ */
+struct sgx_secinfo {
+	u64 flags;
+	u8  reserved[SGX_SECINFO_RESERVED_SIZE];
+} __packed __aligned(64);
+
+#define SGX_PCMD_RESERVED_SIZE 40
+
+/**
+ * struct sgx_pcmd - Paging Crypto Metadata (PCMD)
+ * @enclave_id:	enclave identifier
+ * @mac:	MAC over PCMD, page contents and isvsvn
+ *
+ * PCMD is stored for every swapped page to the regular memory. When ELDU loads
+ * the page back it recalculates the MAC by using a isvsvn number stored in a
+ * VA page. Together these two structures bring integrity and rollback
+ * protection.
+ */
+struct sgx_pcmd {
+	struct sgx_secinfo secinfo;
+	u64 enclave_id;
+	u8  reserved[SGX_PCMD_RESERVED_SIZE];
+	u8  mac[16];
+} __packed __aligned(128);
+
+#define SGX_SIGSTRUCT_RESERVED1_SIZE 84
+#define SGX_SIGSTRUCT_RESERVED2_SIZE 20
+#define SGX_SIGSTRUCT_RESERVED3_SIZE 32
+#define SGX_SIGSTRUCT_RESERVED4_SIZE 12
+
+/**
+ * struct sgx_sigstruct_header -  defines author of the enclave
+ * @header1:		constant byte string
+ * @vendor:		must be either 0x0000 or 0x8086
+ * @date:		YYYYMMDD in BCD
+ * @header2:		costant byte string
+ * @swdefined:		software defined value
+ */
+struct sgx_sigstruct_header {
+	u64 header1[2];
+	u32 vendor;
+	u32 date;
+	u64 header2[2];
+	u32 swdefined;
+	u8  reserved1[84];
+} __packed;
+
+/**
+ * struct sgx_sigstruct_body - defines contents of the enclave
+ * @miscselect:		additional information stored to an SSA frame
+ * @misc_mask:		required miscselect in SECS
+ * @attributes:		attributes for enclave
+ * @xfrm:		XSave-Feature Request Mask (subset of XCR0)
+ * @attributes_mask:	required attributes in SECS
+ * @xfrm_mask:		required XFRM in SECS
+ * @mrenclave:		SHA256-hash of the enclave contents
+ * @isvprodid:		a user-defined value that is used in key derivation
+ * @isvsvn:		a user-defined value that is used in key derivation
+ */
+struct sgx_sigstruct_body {
+	u32 miscselect;
+	u32 misc_mask;
+	u8  reserved2[20];
+	u64 attributes;
+	u64 xfrm;
+	u64 attributes_mask;
+	u64 xfrm_mask;
+	u8  mrenclave[32];
+	u8  reserved3[32];
+	u16 isvprodid;
+	u16 isvsvn;
+} __packed;
+
+/**
+ * struct sgx_sigstruct - an enclave signature
+ * @header:		defines author of the enclave
+ * @modulus:		the modulus of the public key
+ * @exponent:		the exponent of the public key
+ * @signature:		the signature calculated over the fields except modulus,
+ * @body:		defines contents of the enclave
+ * @q1:			a value used in RSA signature verification
+ * @q2:			a value used in RSA signature verification
+ *
+ * Header and body are the parts that are actual signed. The remaining fields
+ * define the signature of the enclave.
+ */
+struct sgx_sigstruct {
+	struct sgx_sigstruct_header header;
+	u8  modulus[SGX_MODULUS_SIZE];
+	u32 exponent;
+	u8  signature[SGX_MODULUS_SIZE];
+	struct sgx_sigstruct_body body;
+	u8  reserved4[12];
+	u8  q1[SGX_MODULUS_SIZE];
+	u8  q2[SGX_MODULUS_SIZE];
+} __packed;
+
+#define SGX_EINITTOKEN_RESERVED1_SIZE 11
+#define SGX_EINITTOKEN_RESERVED2_SIZE 32
+#define SGX_EINITTOKEN_RESERVED3_SIZE 32
+#define SGX_EINITTOKEN_RESERVED4_SIZE 24
+
+/**
+ * struct sgx_einittoken - a token permitting to launch an enclave
+ * @valid:			one if valid and zero if invalid
+ * @attributes:			attributes for enclave
+ * @xfrm:			XSave-Feature Request Mask (subset of XCR0)
+ * @mrenclave:			SHA256-hash of the enclave contents
+ * @mrsigner:			SHA256-hash of the public key used to sign the
+ *				SIGSTRUCT
+ * @le_cpusvn:			a value that reflects the SGX implementation
+ *				running in in the CPU
+ * @le_isvprodid:		a user-defined value that is used in key
+ *				derivation
+ * @le_isvsvn:			a user-defined value that is used in key
+ *				derivation
+ * @le_keyed_miscselect:	LE's miscselect masked with the token keys
+ *				miscselect
+ * @le_keyed_attributes:	LE's attributes masked with the token keys
+ *				attributes
+ * @le_keyed_xfrm:		LE's XFRM masked with the token keys xfrm
+ * @salt:			random salt for wear-out protection
+ * @mac:			CMAC over the preceding fields
+ *
+ * An enclave with EINITTOKENKEY attribute can access a key with the same name
+ * by using ENCLS(EGETKEY) and use this to sign cryptographic tokens that can
+ * be passed to ENCLS(EINIT) to permit the launch of other enclaves. This is
+ * the only viable way to launch enclaves if IA32_SGXLEPUBKEYHASHn MSRs are
+ * locked assuming that there is a Launch Enclave (LE) available that can be
+ * used for generating these tokens.
+ */
+struct sgx_einittoken {
+	u32 valid;
+	u32 reserved1[SGX_EINITTOKEN_RESERVED1_SIZE];
+	u64 attributes;
+	u64 xfrm;
+	u8  mrenclave[32];
+	u8  reserved2[SGX_EINITTOKEN_RESERVED2_SIZE];
+	u8  mrsigner[32];
+	u8  reserved3[SGX_EINITTOKEN_RESERVED3_SIZE];
+	u8  le_cpusvn[16];
+	u16 le_isvprodid;
+	u16 le_isvsvn;
+	u8  reserved4[SGX_EINITTOKEN_RESERVED4_SIZE];
+	u32 le_keyed_miscselect;
+	u64 le_keyed_attributes;
+	u64 le_keyed_xfrm;
+	u8  salt[32];
+	u8  mac[16];
+} __packed __aligned(512);
+
+#endif /* _ASM_X86_SGX_ARCH_H */
Signature · 1 line
2.19.1
#12 lore raw

PATCH v20 11/28 x86/sgx: Add wrappers for ENCLS leaf functions

In reply to Jarkko Sakkinen

ENCLS is an umbrella instruction for a variety of cpl0 SGX functions. The ENCLS function that is executed is specified in EAX, with each function potentially having more leaf-specific operands beyond EAX. ENCLS introduces its own (positive value) error codes that (some) leafs use to return failure information in EAX. Leafs that return an error code also modify RFLAGS. And finally, ENCLS generates ENCLS-specific non-fatal #GPs and #PFs, i.e. a bug-free kernel may encounter faults on ENCLS that must be handled gracefully.

Because of the complexity involved in encoding ENCLS and handling its assortment of failure paths, executing any given leaf is not a simple matter of emitting ENCLS.

To enable adding support for ENCLS leafs with minimal fuss, add a two-layer macro system along with an encoding scheme to allow wrappers to return trap numbers along ENCLS-specific error codes. The bottom layer of the macro system splits between the leafs that return an error code and those that do not. The second layer generates the correct input/output annotations based on the number of operands for each leaf function.

---
 arch/x86/kernel/cpu/sgx/Makefile |   1 +
 arch/x86/kernel/cpu/sgx/encls.c  |  21 +++
 arch/x86/kernel/cpu/sgx/encls.h  | 244 +++++++++++++++++++++++++++++++
 3 files changed, 266 insertions(+)
 create mode 100644 arch/x86/kernel/cpu/sgx/Makefile
 create mode 100644 arch/x86/kernel/cpu/sgx/encls.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encls.h
arch/x86/kernel/cpu/sgx/Makefile new file +1 -0
new file mode 100644
index 000000000000..4432d935894e
@@ -0,0 +1 @@
+obj-y += encls.o
arch/x86/kernel/cpu/sgx/encls.c new file +21 -0
new file mode 100644
index 000000000000..5045f1365e07
@@ -0,0 +1,21 @@
+#include <asm/cpufeature.h>
+#include <asm/traps.h>
+#include "encls.h"
+#include "sgx.h"
+
+/**
+ * encls_failed() - Check if an ENCLS leaf function failed
+ * @ret:	the return value of an ENCLS leaf function call
+ *
+ * Check if an ENCLS leaf function failed. This is a condition where the leaf
+ * function causes a fault that is not caused by an EPCM conflict.
+ *
+ * Return: true if there was a fault other than an EPCM conflict
+ */
+bool encls_failed(int ret)
+{
+	int epcm_trapnr = boot_cpu_has(X86_FEATURE_SGX2) ?
+			  X86_TRAP_PF : X86_TRAP_GP;
+
+	return encls_faulted(ret) && ENCLS_TRAPNR(ret) != epcm_trapnr;
+}
arch/x86/kernel/cpu/sgx/encls.h new file +244 -0

244 lines not on this page · raw message

Signature · 1 line
2.19.1
#13 lore raw

PATCH v20 12/28 x86/sgx: Enumerate and track EPC sections

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Enumerate Enclave Page Cache (EPC) sections via CPUID and add the data structures necessary to track EPC pages so that they can be allocated, freed and managed. As a system may have multiple EPC sections, invoke CPUID on SGX sub-leafs until an invalid leaf is encountered.

On NUMA systems, a node can have at most one bank. A bank can be at most part of two nodes. SGX supports both nodes with a single memory controller and also sub-cluster nodes with severals memory controllers on a single die.

For simplicity, support a maximum of eight EPC sections. Current client hardware supports only a single section, while upcoming server hardware will support at most eight sections. Bounding the number of sections also allows the section ID to be embedded along with a page's offset in a single unsigned long, enabling easy retrieval of both the VA and PA for a given page.

---
 arch/x86/Kconfig                  |  12 +++
 arch/x86/kernel/cpu/Makefile      |   1 +
 arch/x86/kernel/cpu/sgx/Makefile  |   2 +-
 arch/x86/kernel/cpu/sgx/main.c    | 158 ++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/reclaim.c |  84 ++++++++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h     |  67 +++++++++++++
 6 files changed, 323 insertions(+), 1 deletion(-)
 create mode 100644 arch/x86/kernel/cpu/sgx/main.c
 create mode 100644 arch/x86/kernel/cpu/sgx/reclaim.c
 create mode 100644 arch/x86/kernel/cpu/sgx/sgx.h
arch/x86/Kconfig +12 -0
index 5ad92419be19..5d90a20621cb 100644
@@ -1921,6 +1921,18 @@ config X86_INTEL_MEMORY_PROTECTION_KEYS
 
 	  If unsure, say y.
 
+config INTEL_SGX
+	bool "Intel SGX core functionality"
+	depends on X86_64 && CPU_SUP_INTEL
+	---help---
+	  Intel(R) SGX is a set of CPU instructions that can be used by
+	  applications to set aside private regions of code and data, referred
+	  to as enclaves. An enclave's private memory can only be accessed by
+	  code running within the enclave. Accesses from outside the enclave,
+	  including other enclaves, are disallowed by hardware.
+
+	  If unsure, say N.
+
 config EFI
 	bool "EFI runtime service support"
 	depends on ACPI
arch/x86/kernel/cpu/Makefile +1 -0
index cfd24f9f7614..d1163c0fd5d6 100644
@@ -40,6 +40,7 @@ obj-$(CONFIG_X86_MCE)			+= mce/
 obj-$(CONFIG_MTRR)			+= mtrr/
 obj-$(CONFIG_MICROCODE)			+= microcode/
 obj-$(CONFIG_X86_CPU_RESCTRL)		+= resctrl/
+obj-$(CONFIG_INTEL_SGX)			+= sgx/
 
 obj-$(CONFIG_X86_LOCAL_APIC)		+= perfctr-watchdog.o
 
arch/x86/kernel/cpu/sgx/Makefile +1 -1
index 4432d935894e..fa930e292110 100644
@@ -1 +1 @@
-obj-y += encls.o
+obj-y += encls.o main.o reclaim.o
arch/x86/kernel/cpu/sgx/main.c new file +158 -0

158 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/reclaim.c new file +84 -0

84 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/sgx.h new file +67 -0

67 lines not on this page · raw message

Signature · 1 line
2.19.1
#14 lore raw

PATCH v20 13/28 x86/sgx: Add functions to allocate and free EPC pages

In reply to Jarkko Sakkinen

At this time there is no support for reclaiming pages prior to the owner explicitly freeing the page. As for freeing pages, because freeing a page is expected to succeed in the vast majority of cases and because most call sites will not be equipped to handle failure, provide a variant for freeing a page that warns on failure, e.g. due to ENCLS[EREMOVE] failing.

---
 arch/x86/kernel/cpu/sgx/main.c | 90 ++++++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h  |  4 ++
 2 files changed, 94 insertions(+)
arch/x86/kernel/cpu/sgx/main.c +90 -0
index e2317f6e4374..6b4727df72ca 100644
@@ -9,6 +9,7 @@
 #include <linux/sched/signal.h>
 #include <linux/slab.h>
 #include "arch.h"
+#include "encls.h"
 #include "sgx.h"
 
 struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
@@ -16,6 +17,95 @@ EXPORT_SYMBOL_GPL(sgx_epc_sections);
 
 int sgx_nr_epc_sections;
 
+static struct sgx_epc_page *sgx_section_get_page(
+	struct sgx_epc_section *section)
+{
+	struct sgx_epc_page *page;
+
+	if (!section->free_cnt)
+		return NULL;
+
+	page = list_first_entry(&section->page_list,
+				struct sgx_epc_page, list);
+	list_del_init(&page->list);
+	section->free_cnt--;
+	return page;
+}
+
+/**
+ * sgx_alloc_page - Allocate an EPC page
+ *
+ * Try to grab a page from the free EPC page list.
+ *
+ * Return:
+ *   a pointer to a &struct sgx_epc_page instance,
+ *   -errno on error
+ */
+struct sgx_epc_page *sgx_alloc_page(void)
+{
+	struct sgx_epc_section *section;
+	struct sgx_epc_page *page;
+	int i;
+
+	for (i = 0; i < sgx_nr_epc_sections; i++) {
+		section = &sgx_epc_sections[i];
+		spin_lock(&section->lock);
+		page = sgx_section_get_page(section);
+		spin_unlock(&section->lock);
+
+		if (page)
+			return page;
+	}
+
+	return ERR_PTR(-ENOMEM);
+}
+EXPORT_SYMBOL_GPL(sgx_alloc_page);
+
+/**
+ * __sgx_free_page - Free an EPC page
+ * @page:	pointer a previously allocated EPC page
+ *
+ * EREMOVE an EPC page and insert it back to the list of free pages.
+ *
+ * Return:
+ *   0 on success
+ *   SGX error code if EREMOVE fails
+ */
+int __sgx_free_page(struct sgx_epc_page *page)
+{
+	struct sgx_epc_section *section = sgx_epc_section(page);
+	int ret;
+
+	ret = __eremove(sgx_epc_addr(page));
+	if (ret)
+		return ret;
+
+	spin_lock(&section->lock);
+	list_add_tail(&page->list, &section->page_list);
+	section->free_cnt++;
+	spin_unlock(&section->lock);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(__sgx_free_page);
+
+/**
+ * sgx_free_page - Free an EPC page and WARN on failure
+ * @page:	pointer to a previously allocated EPC page
+ *
+ * EREMOVE an EPC page and insert it back to the list of free pages, and WARN
+ * if EREMOVE fails.  For use when the call site cannot (or chooses not to)
+ * handle failure, i.e. the page is leaked on failure.
+ */
+void sgx_free_page(struct sgx_epc_page *page)
+{
+	int ret;
+
+	ret = __sgx_free_page(page);
+	WARN(ret > 0, "sgx: EREMOVE returned %d (0x%x)", ret, ret);
+}
+EXPORT_SYMBOL_GPL(sgx_free_page);
+
 static __init void sgx_free_epc_section(struct sgx_epc_section *section)
 {
 	struct sgx_epc_page *page;
arch/x86/kernel/cpu/sgx/sgx.h +4 -0
index 3009ec816339..210510a28ce0 100644
@@ -64,4 +64,8 @@ extern int sgx_nr_epc_sections;
 
 int sgx_page_reclaimer_init(void);
 
+struct sgx_epc_page *sgx_alloc_page(void);
+int __sgx_free_page(struct sgx_epc_page *page);
+void sgx_free_page(struct sgx_epc_page *page);
+
 #endif /* _X86_SGX_H */
Signature · 1 line
2.19.1
#15 lore raw

PATCH v20 14/28 x86/sgx: Add sgx_einit() for initializing enclaves

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Add a helper function to perform ENCLS(EINIT) with the correct LE hash MSR values. ENCLS[EINIT] initializes an enclave, verifying the enclave's measurement and preparing it for execution, i.e. the enclave cannot be run until it has been initialized. The measurement aspect of EINIT references the MSR_IA32_SGXLEPUBKEYHASH* MSRs, with the CPU comparing CPU compares the key (technically its hash) used to sign the enclave[1] with the key hash stored in the MSRs, and will reject EINIT if the keys do not match.

A per-cpu cache is used to avoid writing the MSRs as writing the MSRs is extraordinarily expensive, e.g. 300-400 cycles per MSR. Because the cache may become stale, force update the MSRs and retry EINIT if the first EINIT fails due to an "invalid token". An invalid token error does not necessarily mean the MSRs need to be updated, but the cost of an unnecessary write is minimal relative to the cost of EINIT itself.

[1] For EINIT's purposes, the effective signer of the enclave may be the enclave's owner, or a separate Launch Enclave that has created an EINIT token for the target enclave. When using an EINIT token, the key used to sign the token must match the MSRs in order for EINIT to succeed.

---
 arch/x86/kernel/cpu/sgx/main.c | 51 ++++++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h  |  2 ++
 2 files changed, 53 insertions(+)
arch/x86/kernel/cpu/sgx/main.c +51 -0
index 6b4727df72ca..d3ed742e90fe 100644
@@ -17,6 +17,9 @@ EXPORT_SYMBOL_GPL(sgx_epc_sections);
 
 int sgx_nr_epc_sections;
 
+/* 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_epc_page *sgx_section_get_page(
 	struct sgx_epc_section *section)
 {
@@ -106,6 +109,54 @@ void sgx_free_page(struct sgx_epc_page *page)
 }
 EXPORT_SYMBOL_GPL(sgx_free_page);
 
+static void sgx_update_lepubkeyhash_msrs(u64 *lepubkeyhash, bool enforce)
+{
+	u64 *cache;
+	int i;
+
+	cache = per_cpu(sgx_lepubkeyhash_cache, smp_processor_id());
+	for (i = 0; i < 4; i++) {
+		if (enforce || (lepubkeyhash[i] != cache[i])) {
+			wrmsrl(MSR_IA32_SGXLEPUBKEYHASH0 + i, lepubkeyhash[i]);
+			cache[i] = lepubkeyhash[i];
+		}
+	}
+}
+
+/**
+ * sgx_einit - initialize an enclave
+ * @sigstruct:		a pointer a SIGSTRUCT
+ * @token:		a pointer an EINITTOKEN (optional)
+ * @secs:		a pointer a SECS
+ * @lepubkeyhash:	the desired value for IA32_SGXLEPUBKEYHASHx MSRs
+ *
+ * Execute ENCLS[EINIT], writing the IA32_SGXLEPUBKEYHASHx MSRs according
+ * to @lepubkeyhash (if possible and necessary).
+ *
+ * Return:
+ *   0 on success,
+ *   -errno or SGX error on failure
+ */
+int sgx_einit(struct sgx_sigstruct *sigstruct, struct sgx_einittoken *token,
+	      struct sgx_epc_page *secs, u64 *lepubkeyhash)
+{
+	int ret;
+
+	if (!boot_cpu_has(X86_FEATURE_SGX_LC))
+		return __einit(sigstruct, token, sgx_epc_addr(secs));
+
+	preempt_disable();
+	sgx_update_lepubkeyhash_msrs(lepubkeyhash, false);
+	ret = __einit(sigstruct, token, sgx_epc_addr(secs));
+	if (ret == SGX_INVALID_EINITTOKEN) {
+		sgx_update_lepubkeyhash_msrs(lepubkeyhash, true);
+		ret = __einit(sigstruct, token, sgx_epc_addr(secs));
+	}
+	preempt_enable();
+	return ret;
+}
+EXPORT_SYMBOL(sgx_einit);
+
 static __init void sgx_free_epc_section(struct sgx_epc_section *section)
 {
 	struct sgx_epc_page *page;
arch/x86/kernel/cpu/sgx/sgx.h +2 -0
index 210510a28ce0..41d4130c33a2 100644
@@ -67,5 +67,7 @@ int sgx_page_reclaimer_init(void);
 struct sgx_epc_page *sgx_alloc_page(void);
 int __sgx_free_page(struct sgx_epc_page *page);
 void sgx_free_page(struct sgx_epc_page *page);
+int sgx_einit(struct sgx_sigstruct *sigstruct, struct sgx_einittoken *token,
+	      struct sgx_epc_page *secs, u64 *lepubkeyhash);
 
 #endif /* _X86_SGX_H */
Signature · 1 line
2.19.1
#16 lore raw

PATCH v20 15/28 x86/sgx: Add the Linux SGX Enclave Driver

In reply to Jarkko Sakkinen

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 enclave is disallowed to access the memory inside the enclave by the CPU access control.

This commit adds the Linux SGX Enclave Driver that provides an ioctl API to manage enclaves. The address range for an enclave, commonly referred as ELRANGE in the documentation (e.g. Intel SDM), is reserved with mmap() against /dev/sgx/enclave. After that a set ioctls is used to build the enclave to the ELRANGE.

---
 Documentation/ioctl/ioctl-number.txt    |   1 +
 arch/x86/Kconfig                        |  15 +
 arch/x86/include/uapi/asm/sgx.h         |  57 ++
 arch/x86/kernel/cpu/sgx/Makefile        |   3 +-
 arch/x86/kernel/cpu/sgx/driver/Makefile |   3 +
 arch/x86/kernel/cpu/sgx/driver/driver.h |  38 ++
 arch/x86/kernel/cpu/sgx/driver/ioctl.c  | 750 ++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/driver/main.c   | 358 +++++++++++
 arch/x86/kernel/cpu/sgx/encl.c          | 349 +++++++++++
 arch/x86/kernel/cpu/sgx/encl.h          |  98 ++++
 arch/x86/kernel/cpu/sgx/encls.c         |   1 +
 arch/x86/kernel/cpu/sgx/main.c          |   3 +
 arch/x86/kernel/cpu/sgx/sgx.h           |   1 +
 13 files changed, 1676 insertions(+), 1 deletion(-)
 create mode 100644 arch/x86/include/uapi/asm/sgx.h
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/Makefile
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/driver.h
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/ioctl.c
 create mode 100644 arch/x86/kernel/cpu/sgx/driver/main.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.h
Documentation/ioctl/ioctl-number.txt +1 -0
index c9558146ac58..ef2694221cd0 100644
@@ -312,6 +312,7 @@ Code  Seq#(hex)	Include File		Comments
 					<mailto:[email protected]>
 0xA3	90-9F	linux/dtlk.h
 0xA4	00-1F	uapi/linux/tee.h	Generic TEE subsystem
+0xA4	00-02	uapi/asm/sgx.h		conflict!
 0xAA	00-3F	linux/uapi/linux/userfaultfd.h
 0xAB	00-1F	linux/nbd.h
 0xAC	00-1F	linux/raw.h
arch/x86/Kconfig +15 -0
index 5d90a20621cb..adea370b331f 100644
@@ -1933,6 +1933,21 @@ config INTEL_SGX
 
 	  If unsure, say N.
 
+config INTEL_SGX_DRIVER
+	tristate "Intel(R) SGX Driver"
+	default n
+	depends on X86_64 && CPU_SUP_INTEL && INTEL_SGX
+	select CRYPTO
+	select CRYPTO_SHA256
+	---help---
+	  This options enables the kernel SGX driver that allows to construct
+	  enclaves to the process memory by using a device node (by default
+	  /dev/sgx) and a set of ioctls. The driver requires that the MSRs
+	  specifying the public key hash for the launch enclave are writable so
+	  that Linux has the full control to run enclaves.
+
+	  If unsure, say N.
+
 config EFI
 	bool "EFI runtime service support"
 	depends on ACPI
arch/x86/include/uapi/asm/sgx.h new file +57 -0

57 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/Makefile +2 -1
index fa930e292110..e5d1e862969c 100644
@@ -1 +1,2 @@
-obj-y += encls.o main.o reclaim.o
+obj-y += encl.o encls.o main.o reclaim.o
+obj-$(CONFIG_INTEL_SGX_DRIVER) += driver/
arch/x86/kernel/cpu/sgx/driver/Makefile new file +3 -0
new file mode 100644
index 000000000000..01ebbbb06a47
@@ -0,0 +1,3 @@
+obj-$(CONFIG_INTEL_SGX_DRIVER) += sgx.o
+sgx-$(CONFIG_INTEL_SGX_DRIVER) += ioctl.o
+sgx-$(CONFIG_INTEL_SGX_DRIVER) += main.o
arch/x86/kernel/cpu/sgx/driver/driver.h new file +38 -0
new file mode 100644
index 000000000000..507712eb0a68
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/**
+ * Copyright(c) 2016-19 Intel Corporation.
+ */
+#ifndef __ARCH_INTEL_SGX_H__
+#define __ARCH_INTEL_SGX_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 <uapi/asm/sgx.h>
+#include "../arch.h"
+#include "../encl.h"
+#include "../encls.h"
+#include "../sgx.h"
+
+#define SGX_DRV_NR_DEVICES	2
+#define SGX_EINIT_SPIN_COUNT	20
+#define SGX_EINIT_SLEEP_COUNT	50
+#define SGX_EINIT_SLEEP_TIME	20
+
+extern struct workqueue_struct *sgx_encl_wq;
+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];
+
+extern const struct file_operations sgx_fs_provision_fops;
+
+long sgx_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
+
+#endif /* __ARCH_X86_INTEL_SGX_H__ */
arch/x86/kernel/cpu/sgx/driver/ioctl.c new file +750 -0

750 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/driver/main.c new file +358 -0

358 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/encl.c new file +349 -0

349 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/encl.h new file +98 -0

98 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/encls.c +1 -0
index 5045f1365e07..698cc526bfbf 100644
@@ -19,3 +19,4 @@ bool encls_failed(int ret)
 
 	return encls_faulted(ret) && ENCLS_TRAPNR(ret) != epcm_trapnr;
 }
+EXPORT_SYMBOL_GPL(encls_failed);
arch/x86/kernel/cpu/sgx/main.c +3 -0
index d3ed742e90fe..d911a1038712 100644
@@ -14,6 +14,8 @@
 
 struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
 EXPORT_SYMBOL_GPL(sgx_epc_sections);
+bool sgx_enabled;
+EXPORT_SYMBOL_GPL(sgx_enabled);
 
 int sgx_nr_epc_sections;
 
@@ -293,6 +295,7 @@ static __init int sgx_init(void)
 		return ret;
 	}
 
+	sgx_enabled = true;
 	return 0;
 }
 
arch/x86/kernel/cpu/sgx/sgx.h +1 -0
index 41d4130c33a2..62a574ed230a 100644
@@ -35,6 +35,7 @@ struct sgx_epc_section {
 #define SGX_MAX_EPC_SECTIONS	8
 
 extern struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
+extern bool sgx_enabled;
 
 /**
  * enum sgx_epc_page_desc - bits and masks for an EPC page's descriptor
Signature · 1 line
2.19.1
#17 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

+Cc Jethro

Quoted 21 lines · Jarkko Sakkinen

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 enclave is disallowed to access the memory inside the enclave by the CPU access control.

This commit adds the Linux SGX Enclave Driver that provides an ioctl API to manage enclaves. The address range for an enclave, commonly referred as ELRANGE in the documentation (e.g. Intel SDM), is reserved with mmap() against /dev/sgx/enclave. After that a set ioctls is used to build the enclave to the ELRANGE.

---

...

Quoted 6 lines
arch/x86/kernel/cpu/sgx/driver/main.c new file +6 -0
+#ifdef CONFIG_ACPI
+static struct acpi_device_id sgx_device_ids[] = {
+	{"INT0E0C", 0},
+	{"", 0},
+};
+MODULE_DEVICE_TABLE(acpi, sgx_device_ids);

arch/x86/kernel/cpu/sgx/driver/main.c line 312

Quoted 10 lines
arch/x86/kernel/cpu/sgx/driver/main.c new file +10 -0
+#endif
+
+static struct platform_driver sgx_drv = {
+	.probe = sgx_drv_probe,
+	.remove = sgx_drv_remove,
+	.driver = {
+		.name			= "sgx",
+		.acpi_match_table	= ACPI_PTR(sgx_device_ids),
+	},
+};

Where do we stand on removing the ACPI and platform_driver dependencies? Can we get rid of them sooner rather than later?

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

Quoted 45 lines
arch/x86/kernel/cpu/sgx/driver/main.c new file +45 -0
+static int __init sgx_drv_subsys_init(void)
+{
+	int ret;
+
+	ret = bus_register(&sgx_bus_type);
+	if (ret)
+		return ret;
+
+	ret = alloc_chrdev_region(&sgx_devt, 0, SGX_DRV_NR_DEVICES, "sgx");
+	if (ret < 0) {
+		bus_unregister(&sgx_bus_type);
+		return ret;
+	}
+
+	return 0;
+}
+
+static void sgx_drv_subsys_exit(void)
+{
+	bus_unregister(&sgx_bus_type);
+	unregister_chrdev_region(sgx_devt, SGX_DRV_NR_DEVICES);
+}
+
+static int __init sgx_drv_init(void)
+{
+	int ret;
+
+	ret = sgx_drv_subsys_init();
+	if (ret)
+		return ret;
+
+	ret = platform_driver_register(&sgx_drv);
+	if (ret)
+		sgx_drv_subsys_exit();
+
+	return ret;
+}
+module_init(sgx_drv_init);
+
+static void __exit sgx_drv_exit(void)
+{
+	platform_driver_unregister(&sgx_drv);
+	sgx_drv_subsys_exit();
+}
+module_exit(sgx_drv_exit);
#18 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

Quoted 38 lines · Sean Christopherson

+Cc Jethro

Quoted 21 lines · Jarkko Sakkinen

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 enclave is disallowed to access the memory inside the enclave by the CPU access control.

This commit adds the Linux SGX Enclave Driver that provides an ioctl API to manage enclaves. The address range for an enclave, commonly referred as ELRANGE in the documentation (e.g. Intel SDM), is reserved with mmap() against /dev/sgx/enclave. After that a set ioctls is used to build the enclave to the ELRANGE.

---

...

Quoted 11 lines
arch/x86/kernel/cpu/sgx/driver/main.c new file +11 -0
+#ifdef CONFIG_ACPI
+static struct acpi_device_id sgx_device_ids[] = {
+	{"INT0E0C", 0},
+	{"", 0},
+};
+MODULE_DEVICE_TABLE(acpi, sgx_device_ids);
+#endif
+
+static struct platform_driver sgx_drv = {
+	.probe = sgx_drv_probe,
+	.remove = sgx_drv_remove,
Quoted 8 lines

arch/x86/kernel/cpu/sgx/driver/main.c line 312

Quoted 5 lines
arch/x86/kernel/cpu/sgx/driver/main.c new file +5 -0
+	.driver = {
+		.name			= "sgx",
+		.acpi_match_table	= ACPI_PTR(sgx_device_ids),
+	},
+};

Where do we stand on removing the ACPI and platform_driver dependencies? Can we get rid of them sooner rather than later?

You know my position on this... https://www.spinics.net/lists/linux-sgx/msg00624.html . I don't really have any new arguments.

Considering the amount of planned changes for the driver post-merge, I think it's crucial that the driver part can be swapped out with alternative implementations.

Quoted 6 lines

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

What kind of changes? Wouldn't KVM just be another consumer of the same API used by the driver?

--
Jethro Beekman | Fortanix

#19 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

Quoted 48 lines · Jethro Beekman
Quoted 38 lines · Sean Christopherson

+Cc Jethro

Quoted 21 lines · Jarkko Sakkinen

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 enclave is disallowed to access the memory inside the enclave by the CPU access control.

This commit adds the Linux SGX Enclave Driver that provides an ioctl API to manage enclaves. The address range for an enclave, commonly referred as ELRANGE in the documentation (e.g. Intel SDM), is reserved with mmap() against /dev/sgx/enclave. After that a set ioctls is used to build the enclave to the ELRANGE.

---

...

Quoted 11 lines
arch/x86/kernel/cpu/sgx/driver/main.c new file +11 -0
+#ifdef CONFIG_ACPI
+static struct acpi_device_id sgx_device_ids[] = {
+	{"INT0E0C", 0},
+	{"", 0},
+};
+MODULE_DEVICE_TABLE(acpi, sgx_device_ids);
+#endif
+
+static struct platform_driver sgx_drv = {
+	.probe = sgx_drv_probe,
+	.remove = sgx_drv_remove,
Quoted 8 lines

arch/x86/kernel/cpu/sgx/driver/main.c line 312

Quoted 5 lines
arch/x86/kernel/cpu/sgx/driver/main.c new file +5 -0
+	.driver = {
+		.name			= "sgx",
+		.acpi_match_table	= ACPI_PTR(sgx_device_ids),
+	},
+};

Where do we stand on removing the ACPI and platform_driver dependencies? Can we get rid of them sooner rather than later?

Quoted 7 lines

You know my position on this...
https://www.spinics.net/lists/linux-sgx/msg00624.html . I don't really have any new arguments.

Considering the amount of planned changes for the driver post-merge, I think it's crucial that the driver part can be swapped out with alternative implementations.

This gets far outside of my area of expertise as I think this is more of a policy question as opposed to a technical question, e.g. do we export function simply to allow out-of-tree alternatives.

Quoted 9 lines
Quoted 6 lines

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

What kind of changes? Wouldn't KVM just be another consumer of the same API used by the driver?

Nope, userspace "only" needs to be able to mmap() arbitrary chunks of EPC. Except for EPC management, which is already in built into the kernel, the EPC virtualization code has effectively zero overlap with the driver. Of course this is all technically speculative since none of this is upstream...

#20 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

Quoted 9 lines · Sean Christopherson
Quoted 8 lines · Jethro Beekman
Quoted 6 lines · Sean Christopherson

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

Quoted 4 lines
Quoted 2 lines

What kind of changes? Wouldn't KVM just be another consumer of the same API used by the driver?

Nope, userspace "only" needs to be able to mmap() arbitrary chunks of EPC.

I don't think this is sufficient. Don't you need enclave tracking in order to support paging?

--
Jethro Beekman | Fortanix

#21 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

Quoted 10 lines · Jethro Beekman
Quoted 9 lines · Sean Christopherson
Quoted 8 lines · Jethro Beekman
Quoted 6 lines · Sean Christopherson

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

What kind of changes? Wouldn't KVM just be another consumer of the same API used by the driver?

Nope, userspace "only" needs to be able to mmap() arbitrary chunks of EPC.

I don't think this is sufficient. Don't you need enclave tracking in order to support paging?

The plan is to not support graceful EPC reclaim in the host on platforms without VMM oversubscription extensions, e.g. ENCLV, ERDINFO, etc..., due to the complexity and performance overhead. Mostly the complexity.

And if reclaim were to be supported without the extensions, it would be done without exiting to userspace on every ENCLS instruction.

#22 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

In reply to Sean Christopherson
Quoted 24 lines · Sean Christopherson
Quoted 11 lines · Jethro Beekman
Quoted 2 lines · Sean Christopherson

Where do we stand on removing the ACPI and platform_driver dependencies? Can we get rid of them sooner rather than later?

You know my position on this...
https://www.spinics.net/lists/linux-sgx/msg00624.html . I don't really have any new arguments.

Considering the amount of planned changes for the driver post-merge, I think it's crucial that the driver part can be swapped out with alternative implementations.

This gets far outside of my area of expertise as I think this is more of a policy question as opposed to a technical question, e.g. do we export function simply to allow out-of-tree alternatives.

Quoted 7 lines
Quoted 6 lines

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

Quoted 7 lines
Quoted 2 lines

What kind of changes? Wouldn't KVM just be another consumer of the same API used by the driver?

Nope, userspace "only" needs to be able to mmap() arbitrary chunks of EPC. Except for EPC management, which is already in built into the kernel, the EPC virtualization code has effectively zero overlap with the driver. Of course this is all technically speculative since none of this is upstream...

Jarkko, can you weigh in with your thoughts on the ACPI stuff?

#23 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

Quoted 28 lines · Sean Christopherson
Quoted 27 lines · Sean Christopherson
Quoted 11 lines · Jethro Beekman
Quoted 2 lines · Sean Christopherson

Where do we stand on removing the ACPI and platform_driver dependencies? Can we get rid of them sooner rather than later?

You know my position on this...
https://www.spinics.net/lists/linux-sgx/msg00624.html . I don't really have any new arguments.

Considering the amount of planned changes for the driver post-merge, I think it's crucial that the driver part can be swapped out with alternative implementations.

This gets far outside of my area of expertise as I think this is more of a policy question as opposed to a technical question, e.g. do we export function simply to allow out-of-tree alternatives.

Quoted 9 lines
Quoted 6 lines

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

What kind of changes? Wouldn't KVM just be another consumer of the same API used by the driver?

Quoted 6 lines
Quoted 4 lines

Nope, userspace "only" needs to be able to mmap() arbitrary chunks of EPC. Except for EPC management, which is already in built into the kernel, the EPC virtualization code has effectively zero overlap with the driver. Of course this is all technically speculative since none of this is upstream...

Jarkko, can you weigh in with your thoughts on the ACPI stuff?

If there is LKM, then it is required (for loading the LKM).

I think we should see how the access control gets implemented first and see what constraints it introduces. It might help with to make the right decision whether to allow LKM or not.

/Jarkko

#24 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

Quoted 34 lines · Jarkko Sakkinen
Quoted 33 lines · Sean Christopherson
Quoted 31 lines · Sean Christopherson
Quoted 11 lines · Jethro Beekman
Quoted 2 lines · Sean Christopherson

Where do we stand on removing the ACPI and platform_driver dependencies? Can we get rid of them sooner rather than later?

You know my position on this...
https://www.spinics.net/lists/linux-sgx/msg00624.html . I don't really have any new arguments.

Considering the amount of planned changes for the driver post-merge, I think it's crucial that the driver part can be swapped out with alternative implementations.

This gets far outside of my area of expertise as I think this is more of a policy question as opposed to a technical question, e.g. do we export function simply to allow out-of-tree alternatives.

Quoted 9 lines
Quoted 6 lines

Now that the core SGX code is approaching stability, I'd like to start sending RFCs for the EPC virtualization and KVM bits to hash out that side of things. The ACPI crud is the last chunk of code that would require non-trivial changes to the core SGX code for the proposed virtualization implementation. I'd strongly prefer to get it out of the way before sending the KVM RFCs.

What kind of changes? Wouldn't KVM just be another consumer of the same API used by the driver?

Nope, userspace "only" needs to be able to mmap() arbitrary chunks of EPC. Except for EPC management, which is already in built into the kernel, the EPC virtualization code has effectively zero overlap with the driver. Of course this is all technically speculative since none of this is upstream...

Quoted 7 lines
Quoted 1 line

Jarkko, can you weigh in with your thoughts on the ACPI stuff?

If there is LKM, then it is required (for loading the LKM).

I think we should see how the access control gets implemented first and see what constraints it introduces. It might help with to make the right decision whether to allow LKM or not.

At this point I don't see the access control stuff impacting the LKM decision.

Irrespetive of the access control thing, there are (at least) two issues with using ACPI to probe the driver:

- ACPI probing breaks if there are multiple device, i.e. when KVM adds a raw EPC device. We could do something like probe the driver via ACPI but manually load the raw EPC device from core SGX code, but IMO taking that approach should be a concious decision.

- ACPI probing means core SGX will consume resources for EPC management even if there is no end consumer, e.g. the driver refuses to load due to lack of FLC support.

It would be very helpful for us to make a decision about LKM support sooner rather than later, e.g. to start reworking the core code now and so that I can send RFCs for KVM support. IMO we're just delaying the inevitable and slowing down upstreaming in the process.

#25 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

On Wed, Jun 05, 2019 at 07:52:19AM -0700, Sean Christopherson wrote:

Good afternoon to everyone.

Quoted 10 lines

At this point I don't see the access control stuff impacting the LKM decision.

Irrespetive of the access control thing, there are (at least) two issues with using ACPI to probe the driver:

- ACPI probing breaks if there are multiple device, i.e. when KVM adds a raw EPC device. We could do something like probe the driver via ACPI but manually load the raw EPC device from core SGX code, but IMO taking that approach should be a concious decision.

If that is the case, I assume that ACPI probing will also be problematic for kernels that will be running on systems that have the SGX accelerator cards that Intel has announced in them.

We haven't seen a solid technical description regarding how SGX functionality is to be surfaced via these cards. However, since the SDM/SGX specification indicates that multiple PRM/EPC's are supported, the logical assumption would be that each card would be surfaced as a separate EPC's.

The focus of this driver will be largely cloud based environments and the accelerator cards are designed to fill the gap until multi-socket SGX support is available, which has been 'real soon now' for about three years. So it would seem to be a requirement for the driver to deal with these cards if it is to be relevant.

Quoted 3 lines

- ACPI probing means core SGX will consume resources for EPC management even if there is no end consumer, e.g. the driver refuses to load due to lack of FLC support.

It isn't relevant to these conversations but there will be a version of this driver supported that runs on non-FLC platforms and that will support full hardware root of trust via launch enclaves.

Have a good evening.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.

PH: 701-281-1686
FAX: 701-281-3949 EMAIL: [email protected]
------------------------------------------------------------------------------
"System Administration is a few hours of boredom followed by several
moments of intense fear."
-- Tom ONeil

#26 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

Quoted 10 lines · Dr. Greg

On Wed, Jun 05, 2019 at 07:52:19AM -0700, Sean Christopherson wrote:

Good afternoon to everyone.

Quoted 6 lines

At this point I don't see the access control stuff impacting the LKM decision.

Irrespetive of the access control thing, there are (at least) two issues with using ACPI to probe the driver:

Quoted 8 lines
Quoted 4 lines

- ACPI probing breaks if there are multiple device, i.e. when KVM adds a raw EPC device. We could do something like probe the driver via ACPI but manually load the raw EPC device from core SGX code, but IMO taking that approach should be a concious decision.

If that is the case, I assume that ACPI probing will also be problematic for kernels that will be running on systems that have the SGX accelerator cards that Intel has announced in them.

Just to make sure we're all on the same page, by "multiple devices" I was referring to multiple char devices in the kernel, not multiple EPC "devices".

Quoted 5 lines

We haven't seen a solid technical description regarding how SGX functionality is to be surfaced via these cards. However, since the SDM/SGX specification indicates that multiple PRM/EPC's are supported, the logical assumption would be that each card would be surfaced as a separate EPC's.

I haven't seen the details for the cards, but for multi-socket systems with multiple EPC sections, the ACPI tables will enumerate a single EPC "device" without any size or location information. I.e. ACPI can be used to detect that the system has EPC, but software will need to use CPUID to enumerate the number of sections and their size/location.

#27 lore raw

Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver

In reply to Sean Christopherson
Quoted 11 lines · Sean Christopherson

At this point I don't see the access control stuff impacting the LKM decision.

Irrespetive of the access control thing, there are (at least) two issues with using ACPI to probe the driver:

- ACPI probing breaks if there are multiple device, i.e. when KVM adds a raw EPC device. We could do something like probe the driver via ACPI but manually load the raw EPC device from core SGX code, but IMO taking that approach should be a concious decision.

Quoted 8 lines

- ACPI probing means core SGX will consume resources for EPC management even if there is no end consumer, e.g. the driver refuses to load due to lack of FLC support.

It would be very helpful for us to make a decision about LKM support sooner rather than later, e.g. to start reworking the core code now and so that I can send RFCs for KVM support. IMO we're just delaying the inevitable and slowing down upstreaming in the process.

I think a good reason to not have LKM is that it can be added after reaching the mainline if there ever becomes strong enough reasons to do so.

I have similar situation with TPM where TPM core would better be just part of the core but since tristate was introduced, it is hard to revert that decision.

I would prefer do this update myself rather than taking patches as it takes me probably shorter time to implement the change rather than reviewing and squashing patches. I'll get it done ASAP.

/Jarkko

#28 lore raw

PATCH v20 16/28 x86/sgx: Add provisioning

In reply to Jarkko Sakkinen

In order to provide a mechanism for devilering provisoning rights:

1. Add a new device file /dev/sgx/provision that works as a token for allowing an enclave to have the provisioning privileges.
2. Add a new ioctl called SGX_IOC_ENCLAVE_SET_ATTRIBUTE that accepts the following data structure:

   struct sgx_enclave_set_attribute {
           __u64 addr;
           __u64 attribute_fd;
   };

A daemon could sit on top of /dev/sgx/provision and send a file descriptor of this file to a process that needs to be able to provision enclaves.

The way this API is used is straight-forward. Lets assume that dev_fd is a handle to /dev/sgx/enclave and prov_fd is a handle to /dev/sgx/provision. You would allow SGX_IOC_ENCLAVE_CREATE to initialize an enclave with the PROVISIONKEY attribute by

params.addr = <enclave address>;
params.token_fd = prov_fd;

ioctl(dev_fd, SGX_IOC_ENCLAVE_SET_ATTRIBUTE, &params);

---
 arch/x86/include/uapi/asm/sgx.h         | 11 ++++++
 arch/x86/kernel/cpu/sgx/driver/driver.h |  2 +-
 arch/x86/kernel/cpu/sgx/driver/ioctl.c  | 51 +++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/driver/main.c   | 11 +++++-
 4 files changed, 73 insertions(+), 2 deletions(-)
arch/x86/include/uapi/asm/sgx.h +11 -0
index 7bf627ac4958..3b80acde8671 100644
@@ -16,6 +16,8 @@
 	_IOW(SGX_MAGIC, 0x01, struct sgx_enclave_add_page)
 #define SGX_IOC_ENCLAVE_INIT \
 	_IOW(SGX_MAGIC, 0x02, struct sgx_enclave_init)
+#define SGX_IOC_ENCLAVE_SET_ATTRIBUTE \
+	_IOW(SGX_MAGIC, 0x03, struct sgx_enclave_set_attribute)
 
 /* IOCTL return values */
 #define SGX_POWER_LOST_ENCLAVE		0x40000000
@@ -54,4 +56,13 @@ struct sgx_enclave_init {
 	__u64	sigstruct;
 };
 
+/**
+ * struct sgx_enclave_set_attribute - parameter structure for the
+ *				      %SGX_IOC_ENCLAVE_SET_ATTRIBUTE ioctl
+ * @attribute_fd:	file handle of the attribute file in the securityfs
+ */
+struct sgx_enclave_set_attribute {
+	__u64	attribute_fd;
+};
+
 #endif /* _UAPI_ASM_X86_SGX_H */
arch/x86/kernel/cpu/sgx/driver/driver.h +1 -1
index 507712eb0a68..153b4a48aa6f 100644
@@ -31,7 +31,7 @@ extern u64 sgx_attributes_reserved_mask;
 extern u64 sgx_xfrm_reserved_mask;
 extern u32 sgx_xsave_size_tbl[64];
 
-extern const struct file_operations sgx_fs_provision_fops;
+extern const struct file_operations sgx_provision_fops;
 
 long sgx_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
 
arch/x86/kernel/cpu/sgx/driver/ioctl.c +51 -0

63 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/driver/main.c +10 -1
index d371add399cd..8b79c4a60037 100644
@@ -103,7 +103,7 @@ static const struct file_operations sgx_encl_fops = {
 	.get_unmapped_area	= sgx_get_unmapped_area,
 };
 
-static const struct file_operations sgx_provision_fops = {
+const struct file_operations sgx_provision_fops = {
 	.owner			= THIS_MODULE,
 };
 
@@ -261,8 +261,16 @@ static int sgx_dev_init(struct device *parent)
 	if (ret)
 		goto err_encl_dev_add;
 
+	ret = cdev_device_add(&sgx_dev->provision_cdev,
+			      &sgx_dev->provision_dev);
+	if (ret)
+		goto err_provision_dev_add;
+
 	return 0;
 
+err_provision_dev_add:
+	cdev_device_del(&sgx_dev->encl_cdev, &sgx_dev->encl_dev);
+
 err_encl_dev_add:
 	destroy_workqueue(sgx_encl_wq);
 
@@ -289,6 +297,7 @@ static int sgx_drv_remove(struct platform_device *pdev)
 	struct sgx_dev_ctx *ctx = dev_get_drvdata(&pdev->dev);
 
 	cdev_device_del(&ctx->encl_cdev, &ctx->encl_dev);
+	cdev_device_del(&ctx->provision_cdev, &ctx->provision_dev);
 	destroy_workqueue(sgx_encl_wq);
 
 	return 0;
Signature · 1 line
2.19.1
#29 lore raw

Re: [PATCH v20 16/28] x86/sgx: Add provisioning

Quoted 16 lines · Jarkko Sakkinen

In order to provide a mechanism for devilering provisoning rights:

1. Add a new device file /dev/sgx/provision that works as a token for allowing an enclave to have the provisioning privileges.
2. Add a new ioctl called SGX_IOC_ENCLAVE_SET_ATTRIBUTE that accepts the following data structure:

   struct sgx_enclave_set_attribute {
           __u64 addr;
           __u64 attribute_fd;
   };

A daemon could sit on top of /dev/sgx/provision and send a file descriptor of this file to a process that needs to be able to provision enclaves.

Quoted 8 lines

The way this API is used is straight-forward. Lets assume that dev_fd is a handle to /dev/sgx/enclave and prov_fd is a handle to /dev/sgx/provision. You would allow SGX_IOC_ENCLAVE_CREATE to initialize an enclave with the PROVISIONKEY attribute by

params.addr = <enclave address>;
params.token_fd = prov_fd;

Should be params.attribute_fd = prov_fd;

Thanks,
-Kai

#30 lore raw

Re: [PATCH v20 16/28] x86/sgx: Add provisioning

Quoted 22 lines · Kai
Quoted 21 lines · Jarkko Sakkinen

In order to provide a mechanism for devilering provisoning rights:

1. Add a new device file /dev/sgx/provision that works as a token for allowing an enclave to have the provisioning privileges.
2. Add a new ioctl called SGX_IOC_ENCLAVE_SET_ATTRIBUTE that accepts the following data structure:

   struct sgx_enclave_set_attribute {
           __u64 addr;
           __u64 attribute_fd;
   };

A daemon could sit on top of /dev/sgx/provision and send a file descriptor of this file to a process that needs to be able to provision enclaves.

The way this API is used is straight-forward. Lets assume that dev_fd is a handle to /dev/sgx/enclave and prov_fd is a handle to /dev/sgx/provision. You would allow SGX_IOC_ENCLAVE_CREATE to initialize an enclave with the PROVISIONKEY attribute by

Quoted 7 lines
Quoted 3 lines

params.addr = <enclave address>;
params.token_fd = prov_fd;

Should be params.attribute_fd = prov_fd;

Thanks,
-Kai

Thanks.

/Jarkko

#31 lore raw

Re: [PATCH v20 16/28] x86/sgx: Add provisioning

In reply to Jarkko Sakkinen

arch/x86/include/uapi/asm/sgx.h line 20

Quoted 10 lines · Jarkko Sakkinen
arch/x86/include/uapi/asm/sgx.h +2 -0
index 7bf627ac4958..3b80acde8671 100644
@@ -16,6 +16,8 @@
  	_IOW(SGX_MAGIC, 0x01, struct sgx_enclave_add_page)
  #define SGX_IOC_ENCLAVE_INIT \
  	_IOW(SGX_MAGIC, 0x02, struct sgx_enclave_init)
+#define SGX_IOC_ENCLAVE_SET_ATTRIBUTE \
+	_IOW(SGX_MAGIC, 0x03, struct sgx_enclave_set_attribute)

Need to update Documentation/ioctl/ioctl-number.txt as well

--
Jethro Beekman | Fortanix

#32 lore raw

Re: [PATCH v20 16/28] x86/sgx: Add provisioning

Quoted 13 lines · Jethro Beekman

arch/x86/include/uapi/asm/sgx.h line 20

Quoted 10 lines · Jarkko Sakkinen
arch/x86/include/uapi/asm/sgx.h +2 -0
index 7bf627ac4958..3b80acde8671 100644
@@ -16,6 +16,8 @@
  	_IOW(SGX_MAGIC, 0x01, struct sgx_enclave_add_page)
  #define SGX_IOC_ENCLAVE_INIT \
  	_IOW(SGX_MAGIC, 0x02, struct sgx_enclave_init)
+#define SGX_IOC_ENCLAVE_SET_ATTRIBUTE \
+	_IOW(SGX_MAGIC, 0x03, struct sgx_enclave_set_attribute)

Need to update Documentation/ioctl/ioctl-number.txt as well

Tha patch contains ioctl update. Can you be more specific?

/Jarkko

#33 lore raw

PATCH v20 17/28 x86/sgx: Add swapping code to the core and SGX driver

In reply to Jarkko Sakkinen

Because the kernel is untrusted, swapping pages in/out of the Enclave Page Cache (EPC) has specialized requirements:

* The kernel cannot directly access EPC memory, i.e. cannot copy data to/from the EPC.
* To evict a page from the EPC, the kernel must "prove" to hardware that are no valid TLB entries for said page since a stale TLB entry would allow an attacker to bypass SGX access controls.
* When loading a page back into the EPC, hardware must be able to verify the integrity and freshness of the data.
* When loading an enclave page, e.g. regular pages and Thread Control Structures (TCS), hardware must be able to associate the page with a Secure Enclave Control Structure (SECS).

To satisfy the above requirements, the CPU provides dedicated ENCLS functions to support paging data in/out of the EPC:

* EBLOCK: Mark a page as blocked in the EPC Map (EPCM). Attempting
to access a blocked page that misses the TLB will fault.
* ETRACK: Activate blocking tracking. Hardware verifies that all
translations for pages marked as "blocked" have been flushed from the TLB.
* EPA: Add version array page to the EPC. As the name suggests, a
VA page is an 512-entry array of version numbers that are used to uniquely identify pages evicted from the EPC.
* EWB: Write back a page from EPC to memory, e.g. RAM. Software
must supply a VA slot, memory to hold the a Paging Crypto Metadata (PCMD) of the page and obviously backing for the evicted page.
* ELD{B,U}: Load a page in {un}blocked state from memory to EPC. The driver only uses the ELDU variant as there is no use case for loading a page as "blocked" in a bare metal environment.

To top things off, all of the above ENCLS functions are subject to strict concurrency rules, e.g. many operations will #GP fault if two or more operations attempt to access common pages/structures.

To put it succinctly, paging in/out of the EPC requires coordinating with the SGX driver where all of an enclave's tracking resides. But, simply shoving all reclaim logic into the driver is not desirable as doing so has unwanted long term implications:

* Oversubscribing EPC to KVM guests, i.e. virtualizing SGX in KVM and swapping a guest's EPC pages (without the guest's cooperation) needs the same high level flows for reclaim but has painfully different semantics in the details.
* Accounting EPC, i.e. adding an EPC cgroup controller, is desirable as EPC is effectively a specialized memory type and even more scarce than system memory. Providing a single touchpoint for EPC accounting regardless of end consumer greatly simplifies the EPC controller.
* Allowing the userspace-facing driver to be built as a loaded module is desirable, e.g. for debug, testing and development. The cgroup infrastructure does not support dependencies on loadable modules.
* Separating EPC swapping from the driver once it has been tightly coupled to the driver is non-trivial (speaking from experience).

So, although the SGX driver is currently the sole consumer of EPC, encapsulate EPC swapping in the driver to minimize the dependencies between the core SGX code and driver, and do so in a way that can be extended to an abstracted interface with minimal effort.

To that end, add functions to swap EPC pages to the driver. The user of these functions will be the core SGX subsystem, which will be enabled in a future patch.

* sgx_encl_page_{get,put}() - Attempt to pin/unpin (the owner of) an EPC page so that it can be operated on by a reclaimer.
* sgx_encl_page_reclaim() - Mark a page as being reclaimed. The
page is considered reclaimable if it hasn't been accessed recently and it isn't reserved by the driver for other use.
* sgx_encl_page_block() - EBLOCK an EPC page
* sgx_encl_page_write() - Evict an EPC page to the regular memory via
EWB. Activates ETRACK (via sgx_encl_track()) if necessary.

Since we also need to be able to fault pages back into the EPC, add a page fault handler to allocate an EPC page and ELDU a previously evicted page.

Wire up the EPC manager's reclaim flow to the SGX driver's swapping functionality. In the long term there will be multiple users of the EPC manager, e.g. SGX driver and KVM, thus the interface between the EPC manager and the driver is fairly genericized and decoupled. But to avoid adding unusued infrastructure, do not add any indirection between the EPC manager and the SGX driver. This has the unfortunate and odd side effect of preventing the SGX driver from being compiled as a loadable module. However, this should be a temporary situation that is remedied when a second user of EPC is added, i.e. KVM.

The swapper 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.

Pages are reclaimed in LRU fashion from a global list. The consumers take care of calling EBLOCK (block page from new accesses), ETRACK (restart counting the entering hardware threads) and EWB (write page to the regular memory) because executing these operations usually (if not always) requires to do some subsystem-internal locking operations.

---
 arch/x86/kernel/cpu/sgx/driver/ioctl.c |  65 +++-
 arch/x86/kernel/cpu/sgx/driver/main.c  |   1 +
 arch/x86/kernel/cpu/sgx/encl.c         | 267 ++++++++++++++++-
 arch/x86/kernel/cpu/sgx/encl.h         |  38 +++
 arch/x86/kernel/cpu/sgx/main.c         |  92 ++++--
 arch/x86/kernel/cpu/sgx/reclaim.c      | 400 ++++++++++++++++++++++++-
 arch/x86/kernel/cpu/sgx/sgx.h          |  18 +-
 7 files changed, 852 insertions(+), 29 deletions(-)
arch/x86/kernel/cpu/sgx/driver/ioctl.c +57 -8
index 65c9fb7b2a95..3a01c3dd579d 100644
@@ -21,6 +21,51 @@ struct sgx_add_page_req {
 	struct list_head list;
 };
 
+static int sgx_encl_grow(struct sgx_encl *encl)
+{
+	struct sgx_va_page *va_page;
+	int ret;
+
+	BUILD_BUG_ON(SGX_VA_SLOT_COUNT !=
+		(SGX_ENCL_PAGE_VA_OFFSET_MASK >> 3) + 1);
+
+	mutex_lock(&encl->lock);
+	if (encl->flags & SGX_ENCL_DEAD) {
+		mutex_unlock(&encl->lock);
+		return -EFAULT;
+	}
+
+	if (!(encl->page_cnt % SGX_VA_SLOT_COUNT)) {
+		mutex_unlock(&encl->lock);
+
+		va_page = kzalloc(sizeof(*va_page), GFP_KERNEL);
+		if (!va_page)
+			return -ENOMEM;
+		va_page->epc_page = sgx_alloc_va_page();
+		if (IS_ERR(va_page->epc_page)) {
+			ret = PTR_ERR(va_page->epc_page);
+			kfree(va_page);
+			return ret;
+		}
+
+		mutex_lock(&encl->lock);
+		if (encl->flags & SGX_ENCL_DEAD) {
+			sgx_free_page(va_page->epc_page);
+			kfree(va_page);
+			mutex_unlock(&encl->lock);
+			return -EFAULT;
+		} else if (encl->page_cnt % SGX_VA_SLOT_COUNT) {
+			sgx_free_page(va_page->epc_page);
+			kfree(va_page);
+		} else {
+			list_add(&va_page->list, &encl->va_pages);
+		}
+	}
+	encl->page_cnt++;
+	mutex_unlock(&encl->lock);
+	return 0;
+}
+
 static bool sgx_process_add_page_req(struct sgx_add_page_req *req,
 				     struct sgx_epc_page *epc_page)
 {
@@ -79,6 +124,7 @@ static bool sgx_process_add_page_req(struct sgx_add_page_req *req,
 	encl_page->encl = encl;
 	encl_page->epc_page = epc_page;
 	encl->secs_child_cnt++;
+	sgx_mark_page_reclaimable(encl_page->epc_page);
 
 	return true;
 }
@@ -109,7 +155,7 @@ static void sgx_add_page_worker(struct work_struct *work)
 		if (skip_rest)
 			goto next;
 
-		epc_page = sgx_alloc_page();
+		epc_page = sgx_alloc_page(req->encl_page, true);
 
 		mutex_lock(&encl->lock);
 
@@ -237,6 +283,10 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
 	struct file *backing;
 	long ret;
 
+	ret = sgx_encl_grow(encl);
+	if (ret)
+		return ret;
+
 	mutex_lock(&encl->lock);
 
 	if (encl->flags & SGX_ENCL_CREATED) {
@@ -267,7 +317,7 @@ static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
 		goto err_out;
 	}
 
-	secs_epc = sgx_alloc_page();
+	secs_epc = sgx_alloc_page(&encl->secs, true);
 	if (IS_ERR(secs_epc)) {
 		ret = PTR_ERR(secs_epc);
 		goto err_out;
@@ -495,6 +545,10 @@ static int sgx_encl_add_page(struct sgx_encl *encl, unsigned long addr,
 			return ret;
 	}
 
+	ret = sgx_encl_grow(encl);
+	if (ret)
+		return ret;
+
 	mutex_lock(&encl->lock);
 
 	if (!(encl->flags & SGX_ENCL_CREATED) ||
@@ -737,8 +791,8 @@ static long sgx_ioc_enclave_set_attribute(struct file *filep, unsigned int cmd,
 					  unsigned long arg)
 {
 	struct sgx_enclave_set_attribute *params = (void *)arg;
+	struct sgx_encl *encl = filep->private_data;
 	struct file *attribute_file;
-	struct sgx_encl *encl;
 	int ret;
 
 	attribute_file = fget(params->attribute_fd);
@@ -750,12 +804,7 @@ static long sgx_ioc_enclave_set_attribute(struct file *filep, unsigned int cmd,
 		goto out;
 	}
 
-	ret = sgx_encl_get(params->addr, &encl);
-	if (ret)
-		goto out;
-
 	encl->allowed_attributes |= SGX_ATTR_PROVISIONKEY;
-	kref_put(&encl->refcount, sgx_encl_release);
 
 out:
 	fput(attribute_file);
arch/x86/kernel/cpu/sgx/driver/main.c +1 -0
index 8b79c4a60037..afe844aa81d6 100644
@@ -32,6 +32,7 @@ static int sgx_open(struct inode *inode, struct file *file)
 
 	kref_init(&encl->refcount);
 	INIT_LIST_HEAD(&encl->add_page_reqs);
+	INIT_LIST_HEAD(&encl->va_pages);
 	INIT_RADIX_TREE(&encl->page_tree, GFP_KERNEL);
 	mutex_init(&encl->lock);
 	INIT_LIST_HEAD(&encl->mm_list);
arch/x86/kernel/cpu/sgx/encl.c +265 -2

307 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/encl.h +38 -0
index 1f96991839ad..c557f0374d74 100644
@@ -17,6 +17,10 @@
 /**
  * enum sgx_encl_page_desc - defines bits for an enclave page's descriptor
  * %SGX_ENCL_PAGE_TCS:			The page is a TCS page.
+ * %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
@@ -25,6 +29,8 @@
 enum sgx_encl_page_desc {
 	SGX_ENCL_PAGE_TCS		= BIT(0),
 	/* 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,
 };
 
@@ -36,6 +42,7 @@ enum sgx_encl_page_desc {
 struct sgx_encl_page {
 	unsigned long desc;
 	struct sgx_epc_page *epc_page;
+	struct sgx_va_page *va_page;
 	struct sgx_encl *encl;
 };
 
@@ -68,15 +75,37 @@ struct sgx_encl {
 	unsigned long base;
 	unsigned long size;
 	unsigned long ssaframesize;
+	struct list_head va_pages;
 	struct radix_tree_root page_tree;
 	struct list_head add_page_reqs;
 	struct work_struct work;
 	struct sgx_encl_page secs;
 	struct notifier_block pm_notifier;
+	cpumask_t cpumask;
+};
+
+#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;
 
+static inline pgoff_t sgx_pcmd_index(struct sgx_encl *encl,
+				     pgoff_t page_index)
+{
+	return PFN_DOWN(encl->size) + 1 + (page_index >> 5);
+}
+
+static inline unsigned long sgx_pcmd_offset(pgoff_t page_index)
+{
+	return (page_index & (PAGE_SIZE / sizeof(struct sgx_pcmd) - 1)) *
+	       sizeof(struct sgx_pcmd);
+}
+
 enum sgx_encl_mm_iter {
 	SGX_ENCL_MM_ITER_DONE		= 0,
 	SGX_ENCL_MM_ITER_NEXT		= 1,
@@ -94,5 +123,14 @@ struct sgx_encl_mm *sgx_encl_next_mm(struct sgx_encl *encl,
 struct sgx_encl_mm *sgx_encl_mm_add(struct sgx_encl *encl,
 				    struct mm_struct *mm);
 void sgx_encl_mm_release(struct kref *ref);
+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 */
arch/x86/kernel/cpu/sgx/main.c +75 -17

141 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/reclaim.c +399 -1

423 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/sgx.h +17 -1
index 62a574ed230a..8a1dff1e5e8a 100644
@@ -12,6 +12,7 @@
 
 struct sgx_epc_page {
 	unsigned long desc;
+	struct sgx_encl_page *owner;
 	struct list_head list;
 };
 
@@ -43,9 +44,14 @@ extern bool sgx_enabled;
  *				physical memory. The existing and near-future
  *				hardware defines at most eight sections, hence
  *				three bits to hold a section.
+ * %SGX_EPC_PAGE_RECLAIMABLE:	The page has been been marked as reclaimable.
+ *				Pages need to be colored this way because a page
+ *				can be out of the active page list in the
+ *				process of being swapped out.
  */
 enum sgx_epc_page_desc {
 	SGX_EPC_SECTION_MASK			= GENMASK_ULL(3, 0),
+	SGX_EPC_PAGE_RECLAIMABLE		= BIT(4),
 	/* bits 12-63 are reserved for the physical page address of the page */
 };
 
@@ -61,11 +67,21 @@ static inline void *sgx_epc_addr(struct sgx_epc_page *page)
 	return section->va + (page->desc & PAGE_MASK) - section->pa;
 }
 
+#define SGX_NR_TO_SCAN		16
+#define SGX_NR_LOW_PAGES	32
+#define SGX_NR_HIGH_PAGES	64
+
 extern int sgx_nr_epc_sections;
+extern struct list_head sgx_active_page_list;
+extern spinlock_t sgx_active_page_list_lock;
+extern struct wait_queue_head(ksgxswapd_waitq);
 
 int sgx_page_reclaimer_init(void);
+void sgx_mark_page_reclaimable(struct sgx_epc_page *page);
+unsigned long sgx_calc_free_cnt(void);
+void sgx_reclaim_pages(void);
 
-struct sgx_epc_page *sgx_alloc_page(void);
+struct sgx_epc_page *sgx_alloc_page(void *owner, bool reclaim);
 int __sgx_free_page(struct sgx_epc_page *page);
 void sgx_free_page(struct sgx_epc_page *page);
 int sgx_einit(struct sgx_sigstruct *sigstruct, struct sgx_einittoken *token,
Signature · 1 line
2.19.1
#34 lore raw

PATCH v20 18/28 x86/sgx: ptrace() support for the SGX driver

In reply to Jarkko Sakkinen

Add VMA callbacks for ptrace() that can be used with debug enclaves. With debug enclaves data can be read and write the memory word at a time by using ENCLS(EDBGRD) and ENCLS(EDBGWR) leaf instructions.

---
 arch/x86/kernel/cpu/sgx/encl.c | 97 ++++++++++++++++++++++++++++++++++
 1 file changed, 97 insertions(+)
arch/x86/kernel/cpu/sgx/encl.c +97 -0
index 16e8524687c1..7216bdf07bd0 100644
@@ -273,10 +273,107 @@ static unsigned int sgx_vma_fault(struct vm_fault *vmf)
 	return ret;
 }
 
+static int sgx_edbgrd(struct sgx_encl *encl, struct sgx_encl_page *page,
+		      unsigned long addr, void *data)
+{
+	unsigned long offset;
+	int ret;
+
+	offset = addr & ~PAGE_MASK;
+
+	if ((page->desc & SGX_ENCL_PAGE_TCS) &&
+	    offset > offsetof(struct sgx_tcs, gs_limit))
+		return -ECANCELED;
+
+	ret = __edbgrd(sgx_epc_addr(page->epc_page) + offset, data);
+	if (ret)
+		return -EIO;
+
+	return 0;
+}
+
+static int sgx_edbgwr(struct sgx_encl *encl, struct sgx_encl_page *page,
+		      unsigned long addr, void *data)
+{
+	unsigned long offset;
+	int ret;
+
+	offset = addr & ~PAGE_MASK;
+
+	/* Writing anything else than flags will cause #GP */
+	if ((page->desc & SGX_ENCL_PAGE_TCS) &&
+	    offset != offsetof(struct sgx_tcs, flags))
+		return -ECANCELED;
+
+	ret = __edbgwr(sgx_epc_addr(page->epc_page) + offset, data);
+	if (ret)
+		return -EIO;
+
+	return 0;
+}
+
+static int sgx_vma_access(struct vm_area_struct *vma, unsigned long addr,
+			  void *buf, int len, int write)
+{
+	struct sgx_encl *encl = vma->vm_private_data;
+	struct sgx_encl_page *entry = NULL;
+	unsigned long align;
+	char data[sizeof(unsigned long)];
+	int offset;
+	int cnt;
+	int ret = 0;
+	int i;
+
+	/* If process was forked, VMA is still there but vm_private_data is set
+	 * to NULL.
+	 */
+	if (!encl)
+		return -EFAULT;
+
+	if (!(encl->flags & SGX_ENCL_DEBUG) ||
+	    !(encl->flags & SGX_ENCL_INITIALIZED) ||
+	    (encl->flags & SGX_ENCL_DEAD))
+		return -EFAULT;
+
+	for (i = 0; i < len; i += cnt) {
+		entry = sgx_encl_reserve_page(encl, (addr + i) & PAGE_MASK);
+		if (IS_ERR(entry)) {
+			ret = PTR_ERR(entry);
+			break;
+		}
+
+		align = ALIGN_DOWN(addr + i, sizeof(unsigned long));
+		offset = (addr + i) & (sizeof(unsigned long) - 1);
+		cnt = sizeof(unsigned long) - offset;
+		cnt = min(cnt, len - i);
+
+		ret = sgx_edbgrd(encl, entry, align, data);
+		if (ret)
+			goto out;
+
+		if (write) {
+			memcpy(data + offset, buf + i, cnt);
+			ret = sgx_edbgwr(encl, entry, align, data);
+			if (ret)
+				goto out;
+		} else
+			memcpy(buf + i, data + offset, cnt);
+
+out:
+		mutex_unlock(&encl->lock);
+
+		if (ret)
+			break;
+	}
+
+	return ret < 0 ? ret : i;
+}
+
 const struct vm_operations_struct sgx_vm_ops = {
 	.close = sgx_vma_close,
 	.open = sgx_vma_open,
 	.fault = sgx_vma_fault,
+	.access = sgx_vma_access,
 };
 EXPORT_SYMBOL_GPL(sgx_vm_ops);
 
Signature · 1 line
2.19.1
#35 lore raw

PATCH v20 19/28 x86/vdso: Add support for exception fixup in vDSO functions

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

The basic concept and implementation is very similar to the kernel's exception fixup mechanism. The key differences are that the kernel handler is hardcoded and the fixup entry addresses are relative to the overall table as opposed to individual entries.

Hardcoding the kernel handler avoids the need to figure out how to get userspace code to point at a kernel function. Given that the expected usage is to propagate information to userspace, dumping all fault information into registers is likely the desired behavior for the vast majority of yet-to-be-created functions. Use registers DI, SI and DX to communicate fault information, which follows Linux's ABI for register consumption and hopefully avoids conflict with hardware features that might leverage the fixup capabilities, e.g. register usage for SGX instructions was at least partially designed with calling conventions in mind.

Making fixup addresses relative to the overall table allows the table to be stripped from the final vDSO image (it's a kernel construct) without complicating the offset logic, e.g. entry-relative addressing would also need to account for the table's location relative to the image.

Regarding stripping the table, modify vdso2c to extract the table from the raw, a.k.a. unstripped, data and dump it as a standalone byte array in the resulting .c file. The original base of the table, its length and a pointer to the byte array are captured in struct vdso_image. Alternatively, the table could be dumped directly into the struct, but because the number of entries can vary per image, that would require either hardcoding a max sized table into the struct definition or defining the table as a flexible length array. The flexible length array approach has zero benefits, e.g. the base/size are still needed, and prevents reusing the extraction code, while hardcoding the max size adds ongoing maintenance just to avoid exporting the explicit size.

The immediate use case is for Intel Software Guard Extensions (SGX). SGX introduces a new CPL3-only "enclave" mode that runs as a sort of black box shared object that is hosted by an untrusted "normal" CPl3 process.

Entering an enclave can only be done through SGX-specific instructions, EENTER and ERESUME, and is a non-trivial process. Because of the complexity of transitioning to/from an enclave, the vast majority of enclaves are expected to utilize a library to handle the actual transitions. This is roughly analogous to how e.g. libc implementations are used by most applications.

Another crucial characteristic of SGX enclaves is that they can generate exceptions as part of their normal (at least as "normal" as SGX can be) operation that need to be handled *in* the enclave and/or are unique to SGX.

And because they are essentially fancy shared objects, a process can host any number of enclaves, each of which can execute multiple threads simultaneously.

Putting everything together, userspace enclaves will utilize a library that must be prepared to handle any and (almost) all exceptions any time at least one thread may be executing in an enclave. Leveraging signals to handle the enclave exceptions is unpleasant, to put it mildly, e.g. the SGX library must constantly (un)register its signal handler based on whether or not at least one thread is executing in an enclave, and filter and forward exceptions that aren't related to its enclaves. This becomes particularly nasty when using multiple levels of libraries that register signal handlers, e.g. running an enclave via cgo inside of the Go runtime.

Enabling exception fixup in vDSO allows the kernel to provide a vDSO function that wraps the low-level transitions to/from the enclave, i.e. the EENTER and ERESUME instructions. The vDSO function can intercept exceptions that would otherwise generate a signal and return the fault information directly to its caller, thus avoiding the need to juggle signal handlers.

Note that unlike the kernel's _ASM_EXTABLE_HANDLE implementation, the 'C' version of _ASM_VDSO_EXTABLE_HANDLE doesn't use a pre-compiled assembly macro. Duplicating four lines of code is simpler than adding the necessary infrastructure to generate pre-compiled assembly and the intended benefit of massaging GCC's inlining algorithm is unlikely to realized in the vDSO any time soon, if ever.

Cc Andy Lutomirski <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Josh Triplett <[email protected]>
---
 arch/x86/entry/vdso/Makefile          |  4 +-
 arch/x86/entry/vdso/extable.c         | 37 +++++++++++++++++
 arch/x86/entry/vdso/extable.h         | 29 ++++++++++++++
 arch/x86/entry/vdso/vdso-layout.lds.S |  9 ++++-
 arch/x86/entry/vdso/vdso2c.h          | 58 +++++++++++++++++++++++----
 arch/x86/include/asm/vdso.h           |  5 +++
 6 files changed, 131 insertions(+), 11 deletions(-)
 create mode 100644 arch/x86/entry/vdso/extable.c
 create mode 100644 arch/x86/entry/vdso/extable.h
arch/x86/entry/vdso/Makefile +2 -2
index 5bfe2243a08f..34bcf87d358c 100644
@@ -20,7 +20,7 @@ VDSO32-$(CONFIG_IA32_EMULATION)	:= y
 vobjs-y := vdso-note.o vclock_gettime.o vgetcpu.o
 
 # files to link into kernel
-obj-y				+= vma.o
+obj-y				+= vma.o extable.o
 OBJECT_FILES_NON_STANDARD_vma.o	:= n
 
 # vDSO images to build
@@ -115,7 +115,7 @@ $(obj)/%-x32.o: $(obj)/%.o FORCE
 
 targets += vdsox32.lds $(vobjx32s-y)
 
-$(obj)/%.so: OBJCOPYFLAGS := -S
+$(obj)/%.so: OBJCOPYFLAGS := -S --remove-section __ex_table
 $(obj)/%.so: $(obj)/%.so.dbg
 	$(call if_changed,objcopy)
 
arch/x86/entry/vdso/extable.c new file +37 -0
new file mode 100644
index 000000000000..49284d560d36
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/err.h>
+#include <linux/mm.h>
+#include <asm/current.h>
+#include <asm/vdso.h>
+
+struct vdso_exception_table_entry {
+	int insn, fixup;
+};
+
+bool fixup_vdso_exception(struct pt_regs *regs, int trapnr,
+			  unsigned long error_code, unsigned long fault_addr)
+{
+	const struct vdso_image *image = current->mm->context.vdso_image;
+	const struct vdso_exception_table_entry *extable;
+	unsigned int nr_entries, i;
+	unsigned long base;
+
+	if (!current->mm->context.vdso)
+		return false;
+
+	base =  (unsigned long)current->mm->context.vdso + image->extable_base;
+	nr_entries = image->extable_len / (sizeof(*extable));
+	extable = image->extable;
+
+	for (i = 0; i < nr_entries; i++) {
+		if (regs->ip == base + extable[i].insn) {
+			regs->ip = base + extable[i].fixup;
+			regs->di = trapnr;
+			regs->si = error_code;
+			regs->dx = fault_addr;
+			return true;
+		}
+	}
+
+	return false;
+}
arch/x86/entry/vdso/extable.h new file +29 -0
new file mode 100644
index 000000000000..aafdac396948
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __VDSO_EXTABLE_H
+#define __VDSO_EXTABLE_H
+
+/*
+ * Inject exception fixup for vDSO code.  Unlike normal exception fixup,
+ * vDSO uses a dedicated handler the addresses are relative to the overall
+ * exception table, not each individual entry.
+ */
+#ifdef __ASSEMBLY__
+#define _ASM_VDSO_EXTABLE_HANDLE(from, to)	\
+	ASM_VDSO_EXTABLE_HANDLE from to
+
+.macro ASM_VDSO_EXTABLE_HANDLE from:req to:req
+	.pushsection __ex_table, "a"
+	.long (\from) - __ex_table
+	.long (\to) - __ex_table
+	.popsection
+.endm
+#else
+#define _ASM_VDSO_EXTABLE_HANDLE(from, to)	\
+	".pushsection __ex_table, \"a\"\n"      \
+	".long (" #from ") - __ex_table\n"      \
+	".long (" #to ") - __ex_table\n"        \
+	".popsection\n"
+#endif
+
+#endif /* __VDSO_EXTABLE_H */
+
arch/x86/entry/vdso/vdso-layout.lds.S +8 -1
index 93c6dc7812d0..8ef849064501 100644
@@ -63,11 +63,18 @@ SECTIONS
 	 * stuff that isn't used at runtime in between.
 	 */
 
-	.text		: { *(.text*) }			:text	=0x90909090,
+	.text		: {
+		*(.text*)
+		*(.fixup)
+	}						:text	=0x90909090,
+
+
 
 	.altinstructions	: { *(.altinstructions) }	:text
 	.altinstr_replacement	: { *(.altinstr_replacement) }	:text
 
+	__ex_table		: { *(__ex_table) }		:text
+
 	/DISCARD/ : {
 		*(.discard)
 		*(.discard.*)
arch/x86/entry/vdso/vdso2c.h +50 -8

90 lines not on this page · raw message

arch/x86/include/asm/vdso.h +5 -0
index 27566e57e87d..1c8a6a8f7b59 100644
@@ -15,6 +15,8 @@ struct vdso_image {
 	unsigned long size;   /* Always a multiple of PAGE_SIZE */
 
 	unsigned long alt, alt_len;
+	unsigned long extable_base, extable_len;
+	const void *extable;
 
 	long sym_vvar_start;  /* Negative offset to the vvar area */
 
@@ -45,6 +47,9 @@ extern void __init init_vdso_image(const struct vdso_image *image);
 
 extern int map_vdso_once(const struct vdso_image *image, unsigned long addr);
 
+extern bool fixup_vdso_exception(struct pt_regs *regs, int trapnr,
+				 unsigned long error_code,
+				 unsigned long fault_addr);
 #endif /* __ASSEMBLER__ */
 
 #endif /* _ASM_X86_VDSO_H */
Signature · 1 line
2.19.1
#36 lore raw

PATCH v20 20/28 x86/fault: Add helper function to sanitize error code

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

...to prepare for vDSO exception fixup, which will expose the error code to userspace and runs before set_signal_archinfo(), i.e. suppresses the signal when fixup is successful.

---
 arch/x86/mm/fault.c | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)
arch/x86/mm/fault.c +17 -7
index 78e2807fbede..5babd515f616 100644
@@ -719,6 +719,18 @@ pgtable_bad(struct pt_regs *regs, unsigned long error_code,
 	oops_end(flags, regs, sig);
 }
 
+static void sanitize_error_code(unsigned long address,
+				unsigned long *error_code)
+{
+	/*
+	 * To avoid leaking information about the kernel page
+	 * table layout, pretend that user-mode accesses to
+	 * kernel addresses are always protection faults.
+	 */
+	if (address >= TASK_SIZE_MAX)
+		*error_code |= X86_PF_PROT;
+}
+
 static void set_signal_archinfo(unsigned long address,
 				unsigned long error_code)
 {
@@ -771,6 +783,8 @@ no_context(struct pt_regs *regs, unsigned long error_code,
 		 * faulting through the emulate_vsyscall() logic.
 		 */
 		if (current->thread.sig_on_uaccess_err && signal) {
+			sanitize_error_code(address, &error_code);
+
 			set_signal_archinfo(address, error_code);
 
 			/* XXX: hwpoison faults will set the wrong code. */
@@ -920,13 +934,7 @@ __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
 		if (is_errata100(regs, address))
 			return;
 
-		/*
-		 * To avoid leaking information about the kernel page table
-		 * layout, pretend that user-mode accesses to kernel addresses
-		 * are always protection faults.
-		 */
-		if (address >= TASK_SIZE_MAX)
-			error_code |= X86_PF_PROT;
+		sanitize_error_code(address, &error_code);
 
 		if (likely(show_unhandled_signals))
 			show_signal_msg(regs, error_code, address, tsk);
@@ -1045,6 +1053,8 @@ do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
 	if (is_prefetch(regs, error_code, address))
 		return;
 
+	sanitize_error_code(address, &error_code);
+
 	set_signal_archinfo(address, error_code);
 
 #ifdef CONFIG_MEMORY_FAILURE
Signature · 1 line
2.19.1
#37 lore raw

PATCH v20 21/28 x86/fault: Attempt to fixup unhandled #PF in vDSO before signaling

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

vDSO functions can now leverage an exception fixup mechanism similar to kernel exception fixup. For vDSO exception fixup, the initial user is Intel's Software Guard Extensions (SGX), which will wrap the low-level transitions to/from the enclave, i.e. EENTER and ERESUME instructions, in a vDSO function and leverage fixup to intercept exceptions that would otherwise generate a signal. This allows the vDSO wrapper to return the fault information directly to its caller, obviating the need for SGX applications and libraries to juggle signal handlers.

Attempt to fixup vDSO exceptions immediately prior to populating and sending signal information. Except for the delivery mechanism, an exception in a vDSO function should be treated like any other exception in userspace, e.g. any fault that is successfully handled by the kernel should not be directly visible to userspace.

Cc Andy Lutomirski <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Josh Triplett <[email protected]>
---
 arch/x86/mm/fault.c | 7 +++++++
 1 file changed, 7 insertions(+)
arch/x86/mm/fault.c +7 -0
index 5babd515f616..13be0c67379e 100644
@@ -28,6 +28,7 @@
 #include <asm/mmu_context.h>		/* vma_pkey()			*/
 #include <asm/efi.h>			/* efi_recover_from_page_fault()*/
 #include <asm/desc.h>			/* store_idt(), ...		*/
+#include <asm/vdso.h>			/* fixup_vdso_exception()	*/
 
 #define CREATE_TRACE_POINTS
 #include <asm/trace/exceptions.h>
@@ -936,6 +937,9 @@ __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
 
 		sanitize_error_code(address, &error_code);
 
+		if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
+			return;
+
 		if (likely(show_unhandled_signals))
 			show_signal_msg(regs, error_code, address, tsk);
 
@@ -1055,6 +1059,9 @@ do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
 
 	sanitize_error_code(address, &error_code);
 
+	if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
+		return;
+
 	set_signal_archinfo(address, error_code);
 
 #ifdef CONFIG_MEMORY_FAILURE
Signature · 1 line
2.19.1
#38 lore raw

PATCH v20 22/28 x86/traps: Attempt to fixup exceptions in vDSO before signaling

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

vDSO functions can now leverage an exception fixup mechanism similar to kernel exception fixup. For vDSO exception fixup, the initial user is Intel's Software Guard Extensions (SGX), which will wrap the low-level transitions to/from the enclave, i.e. EENTER and ERESUME instructions, in a vDSO function and leverage fixup to intercept exceptions that would otherwise generate a signal. This allows the vDSO wrapper to return the fault information directly to its caller, obviating the need for SGX applications and libraries to juggle signal handlers.

Attempt to fixup vDSO exceptions immediately prior to populating and sending signal information. Except for the delivery mechanism, an exception in a vDSO function should be treated like any other exception in userspace, e.g. any fault that is successfully handled by the kernel should not be directly visible to userspace.

Although it's debatable whether or not all exceptions are of interest to enclaves, defer to the vDSO fixup to decide whether to do fixup or generate a signal. Future users of vDSO fixup, if there ever are any, will undoubtedly have different requirements than SGX enclaves, e.g. the fixup vs. signal logic can be made function specific if/when necessary.

Cc Andy Lutomirski <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Josh Triplett <[email protected]>
---
 arch/x86/kernel/traps.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
arch/x86/kernel/traps.c +14 -0
index d26f9e9c3d83..02eda456c119 100644
@@ -61,6 +61,7 @@
 #include <asm/mpx.h>
 #include <asm/vm86.h>
 #include <asm/umip.h>
+#include <asm/vdso.h>
 
 #ifdef CONFIG_X86_64
 #include <asm/x86_init.h>
@@ -210,6 +211,9 @@ do_trap_no_signal(struct task_struct *tsk, int trapnr, const char *str,
 		tsk->thread.error_code = error_code;
 		tsk->thread.trap_nr = trapnr;
 		die(str, regs, error_code);
+	} else {
+		if (fixup_vdso_exception(regs, trapnr, error_code, 0))
+			return 0;
 	}
 
 	/*
@@ -561,6 +565,9 @@ do_general_protection(struct pt_regs *regs, long error_code)
 		return;
 	}
 
+	if (fixup_vdso_exception(regs, X86_TRAP_GP, error_code, 0))
+		return;
+
 	tsk->thread.error_code = error_code;
 	tsk->thread.trap_nr = X86_TRAP_GP;
 
@@ -775,6 +782,10 @@ dotraplinkage void do_debug(struct pt_regs *regs, long error_code)
 							SIGTRAP) == NOTIFY_STOP)
 		goto exit;
 
+	if (user_mode(regs) &&
+	    fixup_vdso_exception(regs, X86_TRAP_DB, error_code, 0))
+		goto exit;
+
 	/*
 	 * Let others (NMI) know that the debug stack is in use
 	 * as we may switch to the interrupt stack.
@@ -855,6 +866,9 @@ static void math_error(struct pt_regs *regs, int error_code, int trapnr)
 	if (!si_code)
 		return;
 
+	if (fixup_vdso_exception(regs, trapnr, error_code, 0))
+		return;
+
 	force_sig_fault(SIGFPE, si_code,
 			(void __user *)uprobe_get_trap_addr(regs), task);
 }
Signature · 1 line
2.19.1
#39 lore raw

Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling

Quoted 23 lines · Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

vDSO functions can now leverage an exception fixup mechanism similar to kernel exception fixup. For vDSO exception fixup, the initial user is Intel's Software Guard Extensions (SGX), which will wrap the low-level transitions to/from the enclave, i.e. EENTER and ERESUME instructions, in a vDSO function and leverage fixup to intercept exceptions that would otherwise generate a signal. This allows the vDSO wrapper to return the fault information directly to its caller, obviating the need for SGX applications and libraries to juggle signal handlers.

Attempt to fixup vDSO exceptions immediately prior to populating and sending signal information. Except for the delivery mechanism, an exception in a vDSO function should be treated like any other exception in userspace, e.g. any fault that is successfully handled by the kernel should not be directly visible to userspace.

Although it's debatable whether or not all exceptions are of interest to enclaves, defer to the vDSO fixup to decide whether to do fixup or generate a signal. Future users of vDSO fixup, if there ever are any, will undoubtedly have different requirements than SGX enclaves, e.g. the fixup vs. signal logic can be made function specific if/when necessary.

Quoted 6 lines
Cc Andy Lutomirski <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Josh Triplett <[email protected]>

I went through the vDSO changes just to revisit couple of details that I had forgotten. Sean, if you don't mind I'd squash this and prepending patch.

Is there any obvious reason why #PF fixup is in its own patch and the rest are collected to the same patch? I would not find it confusing if there was one patch per exception but really don't get this division.

/Jarkko

#40 lore raw

RE: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling

Quoted 7 lines

From: [email protected] [mailto:linux-sgx- [email protected]] On Behalf Of Jarkko Sakkinen
Sent: Tuesday, June 25, 2019 8:44 AM

I went through the vDSO changes just to revisit couple of details that I had forgotten. Sean, if you don't mind I'd squash this and prepending patch.

Just a reminder that #DB/#BP shall be treated differently because they are used by debuggers. So instead of branching to the fixup address, the kernel shall just signal the process.

Quoted 6 lines

Is there any obvious reason why #PF fixup is in its own patch and the rest are collected to the same patch? I would not find it confusing if there was one patch per exception but really don't get this division.

/Jarkko

#41 lore raw

Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling

Quoted 3 lines · Cedric

Just a reminder that #DB/#BP shall be treated differently because they are used by debuggers. So instead of branching to the fixup address, the kernel shall just signal the process.

More importantly, doing fixup on #DB and #BP simply doesn't work.

Quoted 21 lines · Sean Christopherson
Quoted 7 lines · Andy Lutomirski

What's not tested here is running this code with EFLAGS.TF set and making sure that it unwinds correctly. Also, Jarkko, unless I missed something, the vDSO extable code likely has a bug. If you run the instruction right before ENCLU with EFLAGS.TF set, then do_debug() will eat the SIGTRAP and skip to the exception handler. Similarly, if you put an instruction breakpoint on ENCLU, it'll get skipped. Or is the code actually correct and am I just remembering wrong?

The code is indeed broken, and I don't see a sane way to make it not broken other than to never do vDSO fixup on #DB or #BP. But that's probably the right thing to do anyways since an attached debugger is likely the intended recipient the 99.9999999% of the time.

The crux of the matter is that it's impossible to identify whether or not a #DB/#BP originated from within an enclave, e.g. an INT3 in an enclave will look identical to an INT3 at the AEP. Even if hardware provided a magic flag, #DB still has scenarios where the intended recipient is ambiguous, e.g. data breakpoint encountered in the enclave but on an address outside of the enclave, breakpoint encountered in the enclave and a code breakpoint on the AEP, etc...

#42 lore raw

Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling

Quoted 6 lines · Sean Christopherson
Quoted 3 lines · Cedric

Just a reminder that #DB/#BP shall be treated differently because they are used by debuggers. So instead of branching to the fixup address, the kernel shall just signal the process.

More importantly, doing fixup on #DB and #BP simply doesn't work.

What's really needed is a signal, as if the fixup entry didn't exist.

You don't have to care whether a debugger is attached or not.

Quoted 22 lines · Sean Christopherson
Quoted 21 lines · Andy Lutomirski
Quoted 7 lines

What's not tested here is running this code with EFLAGS.TF set and making sure that it unwinds correctly. Also, Jarkko, unless I missed something, the vDSO extable code likely has a bug. If you run the instruction right before ENCLU with EFLAGS.TF set, then do_debug() will eat the SIGTRAP and skip to the exception handler. Similarly, if you put an instruction breakpoint on ENCLU, it'll get skipped. Or is the code actually correct and am I just remembering wrong?

The code is indeed broken, and I don't see a sane way to make it not broken other than to never do vDSO fixup on #DB or #BP. But that's probably the right thing to do anyways since an attached debugger is likely the intended recipient the 99.9999999% of the time.

The crux of the matter is that it's impossible to identify whether or not a #DB/#BP originated from within an enclave, e.g. an INT3 in an enclave will look identical to an INT3 at the AEP. Even if hardware provided a magic flag, #DB still has scenarios where the intended recipient is ambiguous, e.g. data breakpoint encountered in the enclave but on an address outside of the enclave, breakpoint encountered in the enclave and a code breakpoint on the AEP, etc...

#43 lore raw

Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling

In reply to Jarkko Sakkinen
Quoted 3 lines · Jarkko Sakkinen

Is there any obvious reason why #PF fixup is in its own patch and the rest are collected to the same patch? I would not find it confusing if there was one patch per exception but really don't get this division.

I split them due to SGX's funky #PF behavior with respect to th EPCM. I'm ok with them being squashed.

#44 lore raw

Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling

Quoted 7 lines · Sean Christopherson
Quoted 3 lines · Jarkko Sakkinen

Is there any obvious reason why #PF fixup is in its own patch and the rest are collected to the same patch? I would not find it confusing if there was one patch per exception but really don't get this division.

I split them due to SGX's funky #PF behavior with respect to th EPCM. I'm ok with them being squashed.

Right, better to add a note to the commit message if anything.

/Jarkko

#45 lore raw

PATCH v20 23/28 x86/vdso: Add __vdso_sgx_enter_enclave() to wrap SGX enclave transitions

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Intel Software Guard Extensions (SGX) introduces a new CPL3-only enclave mode that runs as a sort of black box shared object that is hosted by an untrusted normal CPL3 process.

Skipping over a great deal of gory architecture details[1], SGX was designed in such a way that the host process can utilize a library to build, launch and run an enclave. This is roughly analogous to how e.g. libc implementations are used by most applications so that the application can focus on its business logic.

The big gotcha is that because enclaves can generate *and* handle exceptions, any SGX library must be prepared to handle nearly any exception at any time (well, any time a thread is executing in an enclave). In Linux, this means the SGX library must register a signal handler in order to intercept relevant exceptions and forward them to the enclave (or in some cases, take action on behalf of the enclave). Unfortunately, Linux's signal mechanism doesn't mesh well with libraries, e.g. signal handlers are process wide, are difficult to chain, etc... This becomes particularly nasty when using multiple levels of libraries that register signal handlers, e.g. running an enclave via cgo inside of the Go runtime.

In comes vDSO to save the day. Now that vDSO can fixup exceptions, add a function, __vdso_sgx_enter_enclave(), to wrap enclave transitions and intercept any exceptions that occur when running the enclave.

__vdso_sgx_enter_enclave() does NOT adhere to the x86-64 ABI and instead uses a custom calling convention. The primary motivation is to avoid issues that arise due to asynchronous enclave exits. The x86-64 ABI requires that EFLAGS.DF, MXCSR and FCW be preserved by the callee, and unfortunately for the vDSO, the aformentioned registers/bits are not restored after an asynchronous exit, e.g. EFLAGS.DF is in an unknown state while MXCSR and FCW are reset to their init values. So the vDSO cannot simply pass the buck by requiring enclaves to adhere to the x86-64 ABI. That leaves three somewhat reasonable options:

1) Save/restore non-volatile GPRs, MXCSR and FCW, and clear EFLAGS.DF

+ 100% compliant with the x86-64 ABI
+ Callable from any code
+ Minimal documentation required
- Restoring MXCSR/FCW is likely unnecessary 99% of the time
- Slow

2) Save/restore non-volatile GPRs and clear EFLAGS.DF

+ Mostly compliant with the x86-64 ABI
+ Callable from any code that doesn't use SIMD registers
- Need to document deviations from x86-64 ABI, i.e. MXCSR and FCW

3) Require the caller to save/restore everything.

+ Fast
+ Userspace can pass all GPRs to the enclave (minus EAX, RBX and RCX)
- Custom ABI
- For all intents and purposes must be called from an assembly wrapper

__vdso_sgx_enter_enclave() implements option (3). The custom ABI is mostly a documentation issue, and even that is offset by the fact that being more similar to hardware's ENCLU[EENTER/ERESUME] ABI reduces the amount of documentation needed for the vDSO, e.g. options (2) and (3) would need to document which registers are marshalled to/from enclaves. Requiring an assembly wrapper imparts minimal pain on userspace as SGX libraries and/or applications need a healthy chunk of assembly, e.g. in the enclave, regardless of the vDSO's implementation.

Note, the C-like pseudocode describing the assembly routine is wrapped in a non-existent macro instead of in a comment to trick kernel-doc into auto-parsing the documentation and function prototype. This is a double win as the pseudocode is intended to aid kernel developers, not userland enclave developers.

[1] Documentation/x86/sgx/1.Architecture.rst

Cc Andy Lutomirski <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Josh Triplett <[email protected]>
Cc Haitao Huang <[email protected]>
Cc Jethro Beekman <[email protected]>
Cc Dr. Greg Wettstein <[email protected]>
---
 arch/x86/entry/vdso/Makefile             |   2 +
 arch/x86/entry/vdso/vdso.lds.S           |   1 +
 arch/x86/entry/vdso/vsgx_enter_enclave.S | 101 +++++++++++++++++++++++
 arch/x86/include/uapi/asm/sgx.h          |  18 ++++
 4 files changed, 122 insertions(+)
 create mode 100644 arch/x86/entry/vdso/vsgx_enter_enclave.S
arch/x86/entry/vdso/Makefile +2 -0
index 34bcf87d358c..fb5b9960b192 100644
@@ -18,6 +18,7 @@ VDSO32-$(CONFIG_IA32_EMULATION)	:= y
 
 # files to link into the vdso
 vobjs-y := vdso-note.o vclock_gettime.o vgetcpu.o
+vobjs-$(VDSO64-y)		+= vsgx_enter_enclave.o
 
 # files to link into kernel
 obj-y				+= vma.o extable.o
@@ -85,6 +86,7 @@ CFLAGS_REMOVE_vdso-note.o = -pg
 CFLAGS_REMOVE_vclock_gettime.o = -pg
 CFLAGS_REMOVE_vgetcpu.o = -pg
 CFLAGS_REMOVE_vvar.o = -pg
+CFLAGS_REMOVE_vsgx_enter_enclave.o = -pg
 
 #
 # X32 processes use x32 vDSO to access 64bit kernel data.
arch/x86/entry/vdso/vdso.lds.S +1 -0
index d3a2dce4cfa9..50952a995a6c 100644
@@ -25,6 +25,7 @@ VERSION {
 		__vdso_getcpu;
 		time;
 		__vdso_time;
+		__vdso_sgx_enter_enclave;
 	local: *;
 	};
 }
arch/x86/entry/vdso/vsgx_enter_enclave.S new file +101 -0

101 lines not on this page · raw message

arch/x86/include/uapi/asm/sgx.h +18 -0
index 3b80acde8671..9ed690a38c70 100644
@@ -65,4 +65,22 @@ struct sgx_enclave_set_attribute {
 	__u64	attribute_fd;
 };
 
+/**
+ * struct sgx_enclave_exception - structure to report exceptions encountered in
+ *				  __vdso_sgx_enter_enclave()
+ *
+ * @leaf:	ENCLU leaf from \%eax at time of exception
+ * @trapnr:	exception trap number, a.k.a. fault vector
+ * @error_code:	exception error code
+ * @address:	exception address, e.g. CR2 on a #PF
+ * @reserved:	reserved for future use
+ */
+struct sgx_enclave_exception {
+	__u32 leaf;
+	__u16 trapnr;
+	__u16 error_code;
+	__u64 address;
+	__u64 reserved[2];
+};
+
 #endif /* _UAPI_ASM_X86_SGX_H */
Signature · 1 line
2.19.1
#46 lore raw

PATCH v20 24/28 selftests/x86: Add a selftest for SGX

In reply to Jarkko Sakkinen

Add a selftest for SGX. It is a trivial test where a simple enclave copies one 64-bit word of memory between two memory locations given to the enclave as arguments.

---
 tools/testing/selftests/x86/Makefile          |  10 +
 tools/testing/selftests/x86/sgx/Makefile      |  48 ++
 tools/testing/selftests/x86/sgx/defines.h     |  39 ++
 tools/testing/selftests/x86/sgx/encl.c        |  20 +
 tools/testing/selftests/x86/sgx/encl.lds      |  33 ++
 .../selftests/x86/sgx/encl_bootstrap.S        |  94 ++++
 tools/testing/selftests/x86/sgx/encl_piggy.S  |  18 +
 tools/testing/selftests/x86/sgx/encl_piggy.h  |  14 +
 tools/testing/selftests/x86/sgx/main.c        | 279 ++++++++++
 tools/testing/selftests/x86/sgx/sgx_call.S    |  15 +
 tools/testing/selftests/x86/sgx/sgxsign.c     | 508 ++++++++++++++++++
 .../testing/selftests/x86/sgx/signing_key.pem |  39 ++
 12 files changed, 1117 insertions(+)
 create mode 100644 tools/testing/selftests/x86/sgx/Makefile
 create mode 100644 tools/testing/selftests/x86/sgx/defines.h
 create mode 100644 tools/testing/selftests/x86/sgx/encl.c
 create mode 100644 tools/testing/selftests/x86/sgx/encl.lds
 create mode 100644 tools/testing/selftests/x86/sgx/encl_bootstrap.S
 create mode 100644 tools/testing/selftests/x86/sgx/encl_piggy.S
 create mode 100644 tools/testing/selftests/x86/sgx/encl_piggy.h
 create mode 100644 tools/testing/selftests/x86/sgx/main.c
 create mode 100644 tools/testing/selftests/x86/sgx/sgx_call.S
 create mode 100644 tools/testing/selftests/x86/sgx/sgxsign.c
 create mode 100644 tools/testing/selftests/x86/sgx/signing_key.pem
tools/testing/selftests/x86/Makefile +10 -0
index 186520198de7..4fc9a42f56ea 100644
@@ -1,4 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
+
+SUBDIRS_64 := sgx
+
 all:
 
 include ../lib.mk
@@ -67,6 +70,13 @@ all_32: $(BINARIES_32)
 
 all_64: $(BINARIES_64)
 
+all_64: $(SUBDIRS_64)
+	@for DIR in $(SUBDIRS_64); do			\
+		BUILD_TARGET=$(OUTPUT)/$$DIR;		\
+		mkdir $$BUILD_TARGET  -p;		\
+		make OUTPUT=$$BUILD_TARGET -C $$DIR $@;	\
+	done
+
 EXTRA_CLEAN := $(BINARIES_32) $(BINARIES_64)
 
 $(BINARIES_32): $(OUTPUT)/%_32: %.c
tools/testing/selftests/x86/sgx/Makefile new file +48 -0

48 lines not on this page · raw message

tools/testing/selftests/x86/sgx/defines.h new file +39 -0
new file mode 100644
index 000000000000..3ff73a9d9b93
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright(c) 2016-19 Intel Corporation.
+ */
+
+#ifndef TYPES_H
+#define TYPES_H
+
+#include <stdint.h>
+
+typedef uint8_t u8;
+typedef uint16_t u16;
+typedef uint32_t u32;
+typedef uint64_t u64;
+
+#define __aligned(x) __attribute__((__aligned__(x)))
+#define __packed __attribute__((packed))
+
+/* Derived from asm-generic/bitsperlong.h. */
+#if __x86_64__
+#define BITS_PER_LONG 64
+#else
+#define BITS_PER_LONG 32
+#endif
+#define BITS_PER_LONG_LONG 64
+
+/* Taken from linux/bits.h. */
+#define BIT(nr)	(1UL << (nr))
+#define BIT_ULL(nr) (1ULL << (nr))
+#define GENMASK(h, l) \
+	(((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
+#define GENMASK_ULL(h, l) \
+	(((~0ULL) - (1ULL << (l)) + 1) & \
+	 (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
+
+#include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
+#include "../../../../../arch/x86/include/uapi/asm/sgx.h"
+
+#endif /* TYPES_H */
tools/testing/selftests/x86/sgx/encl.c new file +20 -0
new file mode 100644
index 000000000000..ede915399742
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-18 Intel Corporation.
+
+#include <stddef.h>
+#include "defines.h"
+
+static void *memcpy(void *dest, const void *src, size_t n)
+{
+	size_t i;
+
+	for (i = 0; i < n; i++)
+		((char *)dest)[i] = ((char *)src)[i];
+
+	return dest;
+}
+
+void encl_body(void *rdi, void *rsi)
+{
+	memcpy(rsi, rdi, 8);
+}
tools/testing/selftests/x86/sgx/encl.lds new file +33 -0
new file mode 100644
index 000000000000..2ee01ac3ec79
@@ -0,0 +1,33 @@
+OUTPUT_FORMAT(elf64-x86-64)
+
+SECTIONS
+{
+	. = 0;
+	.tcs : {
+		*(.tcs*)
+	}
+
+	. = ALIGN(4096);
+	.text : {
+		*(.text*)
+		*(.rodata*)
+	}
+
+	. = ALIGN(4096);
+	.data : {
+		*(.data*)
+	}
+
+	/DISCARD/ : {
+		*(.data*)
+		*(.comment*)
+		*(.note*)
+		*(.debug*)
+		*(.eh_frame*)
+	}
+}
+
+ASSERT(!DEFINED(.altinstructions), "ALTERNATIVES are not supported in enclaves")
+ASSERT(!DEFINED(.altinstr_replacement), "ALTERNATIVES are not supported in enclaves")
+ASSERT(!DEFINED(.discard.retpoline_safe), "RETPOLINE ALTERNATIVES are not supported in enclaves")
+ASSERT(!DEFINED(.discard.nospec), "RETPOLINE ALTERNATIVES are not supported in enclaves")
tools/testing/selftests/x86/sgx/encl_bootstrap.S new file +94 -0

94 lines not on this page · raw message

tools/testing/selftests/x86/sgx/encl_piggy.S new file +18 -0
new file mode 100644
index 000000000000..542001658afb
@@ -0,0 +1,18 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/*
+ * Copyright(c) 2016-18 Intel Corporation.
+ */
+
+	.section ".rodata", "a"
+
+encl_bin:
+	.globl encl_bin
+	.incbin	"encl.bin"
+encl_bin_end:
+	.globl encl_bin_end
+
+encl_ss:
+	.globl encl_ss
+	.incbin	"encl.ss"
+encl_ss_end:
+	.globl encl_ss_end
tools/testing/selftests/x86/sgx/encl_piggy.h new file +14 -0
new file mode 100644
index 000000000000..ee8224f8cc8d
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/*
+ * Copyright(c) 2016-18 Intel Corporation.
+ */
+
+#ifndef ENCL_PIGGY_H
+#define ENCL_PIGGY_H
+
+extern unsigned char encl_bin[];
+extern unsigned char encl_bin_end[];
+extern unsigned char encl_ss[];
+extern unsigned char encl_ss_end[];
+
+#endif /* ENCL_PIGGY_H */
tools/testing/selftests/x86/sgx/main.c new file +279 -0

279 lines not on this page · raw message

tools/testing/selftests/x86/sgx/sgx_call.S new file +15 -0
new file mode 100644
index 000000000000..14bd0a044199
@@ -0,0 +1,15 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/**
+* Copyright(c) 2016-18 Intel Corporation.
+*/
+
+	.text
+
+	.global sgx_call
+sgx_call:
+	push	%rbx
+	mov	$0x02, %rax
+	mov	%rdx, %rbx
+	call	*%r8
+	pop	%rbx
+	ret
tools/testing/selftests/x86/sgx/sgxsign.c new file +508 -0

508 lines not on this page · raw message

tools/testing/selftests/x86/sgx/signing_key.pem new file +39 -0
new file mode 100644
index 000000000000..d76f21f19187
@@ -0,0 +1,39 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIG4wIBAAKCAYEApalGbq7Q+usM91CPtksu3D+b0Prc8gAFL6grM3mg85A5Bx8V
+cfMXPgtrw8EYFwQxDAvzZWwl+9VfOX0ECrFRBkOHcOiG0SnADN8+FLj1UiNUQwbp
+S6OzhNWuRcSbGraSOyUlVlV0yMQSvewyzGklOaXBe30AJqzIBc8QfdSxKuP8rs0Z
+ga6k/Bl73osrYKByILJTUUeZqjLERsE6GebsdzbWgKn8qVqng4ZS4yMNg6LeRlH3
++9CIPgg4jwpSLHcp7dq2qTIB9a0tGe9ayp+5FbucpB6U7ePold0EeRN6RlJGDF9k
+L93v8P5ykz5G5gYZ2g0K1X2sHIWV4huxPgv5PXgdyQYbK+6olqj0d5rjYuwX57Ul
+k6SroPS1U6UbdCjG5txM+BNGU0VpD0ZhrIRw0leQdnNcCO9sTJuInZrgYacSVJ7u
+mtB+uCt+uzUesc+l+xPRYA+9e14lLkZp7AAmo9FvL816XDI09deehJ3i/LmHKCRN
+tuqC5TprRjFwUr6dAgEDAoIBgG5w2Z8fNfycs0+LCnmHdJLVEotR6KFVWMpwHMz7
+wKJgJgS/Y6FMuilc8oKAuroCy11dTO5IGVKOP3uorVx2NgQtBPXwWeDGgAiU1A3Q
+o4wXjYIEm4fCd63jyYPYZ2ckYXzDbjmOTdstYdPyzIhGGNEZK6eoqsRzMAPfYFPj
+IMdCqHSIu6vJw1K7p+myHOsVoWshjODaZnF3LYSA0WaZ8vokjwBxUxuRxQJZjJds
+s60XPtmL+qfgWtQFewoG4XL6GuD8FcXccynRRtzrLtFNPIl9BQfWfjBBhTC1/Te1
+0Z6XbZvpdUTD9OfLB7SbR2OUFNpKQgriO0iYVdbW3cr7uu38Zwp4W1TX73DPjoi6
+KNooP6SGWd4mRJW2+dUmSYS4QNG8eVVZswKcploEIXlAKRsOe4kzJJ1iETugIe85
+uX8nd1WYEp65xwoRUg8hqng0MeyveVbXqNKuJG6tzNDt9kgFYo+hmC/oouAW2Dtc
+T9jdRAwKJXqA2Eg6OkgXCEv+kwKBwQDYaQiFMlFhsmLlqI+EzCUh7c941/cL7m6U
+7j98+8ngl0HgCEcrc10iJVCKakQW3YbPzAx3XkKTaGjWazvvrFarXIGlOud64B8a
+iWyQ7VdlnmZnNEdk+C83tI91OQeaTKqRLDGzKh29Ry/jL8Pcbazt+kDgxa0H7qJp
+roADUanLQuNkYubpbhFBh3xpa2EExaVq6rF7nIVsD8W9TrbmPKA4LgH7z0iy544D
+kVCNYsTjYDdUWP+WiSor8kCnnpjnN9sCgcEAw/eNezUD1UDf6OYFC9+5JZJFn4Tg
+mZMyN93JKIb199ffwnjtHUSjcyiWeesXucpzwtGbTcwQnDisSW4oneYKLSEBlBaq
+scqiUugyGZZOthFSCbdXYXMViK2vHrKlkse7GxVlROKcEhM/pRBrmjaGO8eWR+D4
+FO2wCXzVs3KgV6j779frw0vC54oHOxc9+Lu1rSHp4i+600koyvL/zF6U/5tZXIvN
+YW2yoiQJnjCmVA1pwbwV6KAUTPDTMnBK+YjnAoHBAJBGBa4hi5Z27JkbCliIGMFJ
+NPs6pLKe9GNJf6in2+sPgUAFhMeiPhbDiwbxgrnpBIqICE+ULGJFmzmc0p/IOceT
+ARjR76dAFLxbnbXzj5kURETNhO36yiUjCk4mBRGIcbYddndxaSjaH+zKgpLzyJ6m
+1esuc1qfFvEfAAI2cTIsl5hB70ZJYNZaUvDyQK3ZGPHxy6e9rkgKg9OJz0QoatAe
+q/002yHvtAJg4F5B2JeVejg7VQ8GHB1MKxppu0TP5wKBwQCCpQj8zgKOKz/wmViy
+lSYZDC5qWJW7t3bP6TDFr06lOpUsUJ4TgxeiGw778g/RMaKB4RIz3WBoJcgw9BsT
+7rFza1ZiucchMcGMmswRDt8kC4wGejpA92Owc8oUdxkMhSdnY5jYlxK2t3/DYEe8
+JFl9L7mFQKVjSSAGUzkiTGrlG1Kf5UfXh9dFBq98uilQfSPIwUaWynyM23CHTKqI
+Pw3/vOY9sojrnncWwrEUIG7is5vWfWPwargzSzd29YdRBe8CgcEAuRVewK/YeNOX
+B7ZG6gKKsfsvrGtY7FPETzLZAHjoVXYNea4LVZ2kn4hBXXlvw/4HD+YqcTt4wmif
+5JQlDvjNobUiKJZpzy7hklVhF7wZFl4pCF7Yh43q9iQ7gKTaeUG7MiaK+G8Zz8aY
+HW9rsiihbdZkccMvnPfO9334XMxl3HtBRzLstjUlbLB7Sdh+7tZ3JQidCOFNs5pE
+XyWwnASPu4tKfDahH1UUTp1uJcq/6716CSWg080avYxFcn75qqsb
+-----END RSA PRIVATE KEY-----
Signature · 1 line
2.19.1
#47 lore raw

PATCH v20 25/28 x86/sgx: Update MAINTAINERS

In reply to Jarkko Sakkinen

Add the maintainer information for the SGX subsystem.

---
 MAINTAINERS | 12 ++++++++++++
 1 file changed, 12 insertions(+)
MAINTAINERS +12 -0
index 3671fdea5010..eb3b80811653 100644
@@ -8044,6 +8044,18 @@ L:	[email protected]
 S:	Maintained
 F:	drivers/gpio/gpio-intel-mid.c
 
+INTEL SGX
+M:	Jarkko Sakkinen <[email protected]>
+M:	Sean Christopherson <[email protected]>
+L:	[email protected]
+S:	Maintained
+Q:	https://patchwork.kernel.org/project/intel-sgx/list/
+T:	git https://github.com/jsakkine-intel/linux-sgx.git
+F:	arch/x86/include/asm/sgx.h
+F:	arch/x86/include/uapi/asm/sgx.h
+F:	arch/x86/kernel/cpu/sgx/*
+K:	\bSGX_
+
 INTERCONNECT API
 M:	Georgi Djakov <[email protected]>
 S:	Maintained
Signature · 1 line
2.19.1
#48 lore raw

PATCH v20 26/28 docs: x86/sgx: Add Architecture documentation

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Document microarchitectural features of SGX relevant to the kernel. They are documented in detail enough to understand the implementation.

---
 Documentation/index.rst                  |   1 +
 Documentation/x86/index.rst              |  10 +
 Documentation/x86/sgx/1.Architecture.rst | 431 +++++++++++++++++++++++
 Documentation/x86/sgx/index.rst          |  16 +
 4 files changed, 458 insertions(+)
 create mode 100644 Documentation/x86/index.rst
 create mode 100644 Documentation/x86/sgx/1.Architecture.rst
 create mode 100644 Documentation/x86/sgx/index.rst
Documentation/index.rst +1 -0
index 80a421cb935e..3511400dc092 100644
@@ -102,6 +102,7 @@ implementation.
    :maxdepth: 2
 
    sh/index
+   x86/index
 
 Filesystem Documentation
 ------------------------
Documentation/x86/index.rst new file +10 -0
new file mode 100644
index 000000000000..6f3251c4b7b9
@@ -0,0 +1,10 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=================
+x86 Documentation
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   sgx/index
Documentation/x86/sgx/1.Architecture.rst new file +431 -0

431 lines not on this page · raw message

Documentation/x86/sgx/index.rst new file +16 -0
new file mode 100644
index 000000000000..c5dfef62e612
@@ -0,0 +1,16 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=========================
+Software Guard Extensions
+=========================
+
+Intel(R) SGX is a set of architectural extensions that enables applications to
+establish secure containers, a.k.a. enclaves.  SGX enclaves provide security
+guarantees such as integrity and confidentiality, even when running on a system
+where privileged software, e.g. kernel, hypervisor, etc... is untrusted and
+potentially malicious.
+
+.. toctree::
+   :maxdepth: 1
+
+   1.Architecture
Signature · 1 line
2.19.1
#49 lore raw

PATCH v20 27/28 docs: x86/sgx: Document kernel internals

In reply to Jarkko Sakkinen

From: Sean Christopherson <[email protected]>

Document some of the more tricky parts of the kernel implementation internals.

---
 Documentation/x86/sgx/2.Kernel-internals.rst | 56 ++++++++++++++++++++
 Documentation/x86/sgx/index.rst              |  1 +
 2 files changed, 57 insertions(+)
 create mode 100644 Documentation/x86/sgx/2.Kernel-internals.rst
Documentation/x86/sgx/2.Kernel-internals.rst new file +56 -0
new file mode 100644
index 000000000000..de359bf605ca
@@ -0,0 +1,56 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================
+Kernel Internals
+================
+
+CPU configuration
+=================
+
+Because SGX has an ever evolving and expanding feature set, it's possible for
+a BIOS or VMM to configure a system in such a way that not all CPUs are equal,
+e.g. where Launch Control is only enabled on a subset of CPUs.  Linux does
+*not* support such a heterogeneous system configuration, nor does it even
+attempt to play nice in the face of a misconfigured system.  With the exception
+of Launch Control's hash MSRs, which can vary per CPU, Linux assumes that all
+CPUs have a configuration that is identical to the boot CPU.
+
+EPC oversubscription
+====================
+
+SGX allows to have larger enclaves than amount of available EPC by providing a
+subset of leaf instruction for swapping EPC pages to the system memory.  The
+details of these instructions are discussed in the architecture document. Due
+to the unique requirements for swapping EPC pages, and because EPC pages do not
+have associated page structures, management of the EPC is not handled by the
+standard memory subsystem.
+
+SGX directly handles swapping of EPC pages, including a thread to initiate the
+reclaiming process and a rudimentary LRU mechanism. When the amount of free EPC
+pages goes below a low watermark the swapping thread starts reclaiming pages.
+The pages that have not been recently accessed (i.e. do not have the A bit set)
+are selected as victim pages. Each enclave holds an shmem file as a backing
+storage for reclaimed pages.
+
+Launch Control
+==============
+
+The current kernel implementation supports only writable MSRs. The launch is
+performed by setting the MSRs to the hash of the public key modulus of the
+enclave signer and a token with the valid bit set to zero. Because kernel makes
+ultimately all the launch decisions token are not needed for anything.  We
+don't need or have a launch enclave for generating them as the MSRs must always
+be writable.
+
+Provisioning
+============
+
+The use of provisioning must be controlled because it allows to get access to
+the provisioning keys to attest to a remote party that the software is running
+inside a legit enclave. This could be used by a malware network to ensure that
+its nodes are running inside legit enclaves.
+
+The driver introduces a special device file /dev/sgx/provision and a special
+ioctl SGX_IOC_ENCLAVE_SET_ATTRIBUTE to accomplish this. A file descriptor
+pointing to /dev/sgx/provision is passed to ioctl from which kernel authorizes
+the PROVISION_KEY attribute to the enclave.
Documentation/x86/sgx/index.rst +1 -0
index c5dfef62e612..5d660e83d984 100644
@@ -14,3 +14,4 @@ potentially malicious.
    :maxdepth: 1
 
    1.Architecture
+   2.Kernel-internals
Signature · 1 line
2.19.1
#50 lore raw

PATCH v20 28/28 docs: x86/sgx: Document the enclave API

In reply to Jarkko Sakkinen

Document the enclave driver API i.e. the set of ioctl's used to create and manage enclaves and set their privileges

---
 Documentation/x86/sgx/3.API.rst | 27 +++++++++++++++++++++++++++
 Documentation/x86/sgx/index.rst |  1 +
 2 files changed, 28 insertions(+)
 create mode 100644 Documentation/x86/sgx/3.API.rst
Documentation/x86/sgx/3.API.rst new file +27 -0
new file mode 100644
index 000000000000..b113aeb05f54
@@ -0,0 +1,27 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===
+API
+===
+
+The enclave life-cycle starts by opening `/dev/sgx/enclave`. After this there is
+already a data structure inside kernel tracking the enclave that is initially
+uncreated. After this a set of ioctl's can be used to create, populate and
+initialize the enclave.
+
+You can close (if you want) the fd after you've mmap()'d. As long as the file is
+open the enclave stays alive so you might want to do that after you don't need
+it anymore. Even munmap() won't destruct the enclave if the file is open.
+Neither will closing the fd as long as you have mmap() done over the fd (even
+if it does not across the range defined in SECS).
+
+Finally, there is ioctl to authorize priviliged attributes:
+`SGX_IOC_ENCLAVE_SET_ATTRIBUTE`. Each of them is presented by a file inside
+`/dev/sgx/`. Right now there is only one such file `/dev/sgx/provision`, which
+controls the `PROVISON_KEY` attribute.
+
+.. kernel-doc:: arch/x86/kernel/cpu/sgx/driver/ioctl.c
+   :functions: sgx_ioc_enclave_create
+               sgx_ioc_enclave_add_page
+               sgx_ioc_enclave_init
+               sgx_ioc_enclave_set_attribute
Documentation/x86/sgx/index.rst +1 -0
index 5d660e83d984..de0b78328611 100644
@@ -15,3 +15,4 @@ potentially malicious.
 
    1.Architecture
    2.Kernel-internals
+   3.API
Signature · 1 line
2.19.1
#51 lore raw
In reply to Jarkko Sakkinen

On Wed, Apr 17, 2019 at 01:39:10PM +0300, Jarkko Sakkinen wrote:

Good morning, I hope this note finds the impending end of the work week going well for everyone.

First of all, a thank you to Jarkko for his efforts in advancing this driver, a process that can be decidedly thankless. Our apologies in advance for contributing to this phenomenon.

Quoted 6 lines

Intel(R) 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 enclave is disallowed to access the memory inside the enclave by the CPU access control. In a way you can think that SGX provides inverted sandbox. It protects the application from a malicious host.

Unfortunately, in its current implementation, the driver will not protect a host from malicious enclaves. If it advances in its current form, the mainline Linux kernel will be implementing a driver with known and documented security issues.

In addition, the driver breaks all existing SGX software by breaking compatibility with what is a 3+ year ABI provided by the existing driver. This seems to contravene the well understood philosophy that Linux doesn't, if at all possible, break existing applications, something that we believe can be easily prevented if those interested in these issues choose to read on.

The following reflections and code come from a team that has been active in SGX development, since before hardware was even publically available. A team that has authored a complete re-implementation of all of the SGX runtime infrastructure, which is the only consumer of the services provided by an SGX driver. A team that has also authored and maintains a significant cohort of SGX based applications. So I believe we speak from a vantage point of experience with respect to these issues and not from a 'bike-shedding' or political perspective.

The fundamental problem is that the proposed driver lacks an enclave initialization policy mechanism consistent with the security guarantees that SGX hardware is designed to deliver. SGX is designed to provide system architects a framework for building IAGO resistent security architectures through the use of cryptographically defined identities.

Other then an attempt to limit acccess to the PROVISION attribute, the driver makes no attempt to regulate, in a cryptographically secure fashion, what enclaves can be initialized, who can initialize them or what characteristics they can be initialized with. The security implications of this were recently documented in a paper by researchers at Graz, here is the link for those interested:

https://arxiv.org/pdf/1702.08719.pdf

Both the current controls for enclave access to the PROVISION attribute and the security controls that are being proposed to emerge for the driver, sometime in the future, suffer from being dependent on discretionary access controls, ie. file privileges, that can be defeated by a privilege escalation attack. Those of us building architectures on top of this technology have a need to certify that an application will provide security contracts robust in the face of a privilege escalation event or platform compromise.

To be very blunt, and my apologies for doing so, the design for this driver has been driven by idealogy rather then by technology. Our focus with this e-mail and proposed driver modification is an attempt to satisfy both technical requirements and political idealogy, if that is even possible.

When we raised these issues six months ago, we were told that we were handwaving bloat into the kernel. We take a criticism like that very seriously so we are returning with code, in what we believe is 'bloat-free' form.

The attached patch, against the jarkko-sgx/master branch of Jarkko's driver repository, provides a framework that implements cryptographically secure enclave initialization policies. The patch and it's signature are also available from the following URL's:

ftp://ftp.idfusion.net/pub/idfusion/jarkko-master-SFLC.patch

ftp://ftp.idfusion.net/pub/idfusion/jarkko-master-SFLC.patch.asc

The modification, in series form, is also available in the following GIT repository:

git://git.idfusion.net/src/linux-sgx/in-tree jarkko-master-SFLC

The driver modification implements cryptographically secure enclave initialization only if the platform owner chooses to do so and does not limit the development of alternative strategies in the future. It also allows the platform owner to choose the ability to remain compatible with existing runtimes and applications.

The policy architecture allows just about any conceivable initialization policy to be implemented and in any combination. It supports both a plurality of launch enclaves as well as support for multiple signing keys if a token-less approach is desired. It also provides cryptographically secure control of access to the PROVISION attribute and the ability to completely block access to the attribute if that is desired.

The driver modification has been extensively tested in all of these scenarios, including combinations thereof. We just completed a major round of development that was based on Flexible Launch Control platforms and deployed onto fixed launch control platforms using the out-of-tree driver, without a need to maintain disparate runtimes.

On that note, given that the new driver API is completely incompatible with all of the existing runtime software in the field, we believe the issue of proper testing of this driver is an open problem. I'm assuming that Intel has a yet to be released PSW/SDK that supports the driver, otherwise our enhancements to the driver is the only way that it can experience legitimate field testing.

The interface for using the policy management framework is straight forward. The following three pseudo-files are available:

/sys/kernel/security/sgx/launch_keys

/sys/kernel/security/sgx/provisioning_keys

/sys/kernel/security/sgx/signing_keys

The SHA256 hashes of the cryptographic keys used to sign enclaves (MRSIGNER values) are written into these files, ie, the following command:

echo "SHA256_HASH" >| /sys/kernel/security/sgx/signing_keys

Would only allow enclaves to be initialized whose MRSIGNER value matches the SHA256_HASH value.

The 'launch_keys' file maintains a list of signer signatures that are allowed to initialize enclaves with the EINITTOKEN attribute set.

The 'provisioning_keys' file maintains a list of signer signatures that are allowed to initialize enclaves with the PROVISION attribute set.

Writing the 'lock' keyword to a file permanently blocks any further directives from being recognized. At that point, a very targeted ring-0 attack would need to be conducted to circumvent the enclave initialization policies. This provides a framework that allows a flexible launch control platform to attain the approximate security guarantees offered by a fixed launch control platform.

If the platform owner chooses to do nothing, the driver will initialize any enclave that is presented to it. FWIW, we have close to a century of enterprise system's administration experience on our team and we could not envision any competent system's administrator, concerned about security, who would allow such a configuration.

So that is how it all works, the changelogs in the GIT repository have much more extensive documentation. We fit the entire architecture into approximately one page of memory, which seems to be a minor amount of bloat for everyone getting to do whatever they want to do, including leaving Linux mainline with a secure driver implementation.

Here is the diffstat:

---------------------------------------------------------------------------

 arch/x86/include/uapi/asm/sgx.h         |   2 +
 arch/x86/kernel/cpu/sgx/driver/Makefile |   1 +
 arch/x86/kernel/cpu/sgx/driver/driver.h |   7 +
 arch/x86/kernel/cpu/sgx/driver/ioctl.c  |  88 ++++-
 arch/x86/kernel/cpu/sgx/driver/main.c   |   5 +
 arch/x86/kernel/cpu/sgx/driver/policy.c | 584 ++++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/main.c          |  27 +-
 arch/x86/kernel/cpu/sgx/sgx.h           |   3 +-
 8 files changed, 704 insertions(+), 13 deletions(-)

---------------------------------------------------------------------------

With respect to a mainline Linux driver at large, an issue that we believe needs clarification is whether or not a mandate will be issued by Intel to OEM's that Flexible Launch Control is mandatory on all platforms that are henceforth shipped. Otherwise the mainline Linux driver will be in the unenviable position of only working sporadically and will not be a universal solution for all hardware.

We have a solution for that as well, but the above is probably enough cannon fodder for debate so we will leave that sleeping dog lie for the time being.

Hopefully all of the above is helpful for enhancing the quality of the Linux SGX eco-system.

Best wishes for a productive weekend.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.

PH: 701-281-1686
FAX: 701-281-3949 EMAIL: [email protected]
------------------------------------------------------------------------------
"I can only provide the information, I can't make you hear it."
-- Shelley Bainter

 arch/x86/include/uapi/asm/sgx.h         |   2 +
 arch/x86/kernel/cpu/sgx/driver/Makefile |   1 +
 arch/x86/kernel/cpu/sgx/driver/driver.h |   7 +
 arch/x86/kernel/cpu/sgx/driver/ioctl.c  |  88 ++++-
 arch/x86/kernel/cpu/sgx/driver/main.c   |   5 +
 arch/x86/kernel/cpu/sgx/driver/policy.c | 584 ++++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/main.c          |  27 +-
 arch/x86/kernel/cpu/sgx/sgx.h           |   3 +-
 8 files changed, 704 insertions(+), 13 deletions(-)
arch/x86/include/uapi/asm/sgx.h +2 -0
index 9ed690a38c70..694981e03c65 100644
@@ -53,7 +53,9 @@ struct sgx_enclave_add_page {
  * @sigstruct:	address for the SIGSTRUCT data
  */
 struct sgx_enclave_init {
+	__u64	addr;
 	__u64	sigstruct;
+	__u64	einittoken;
 };
 
 /**
arch/x86/kernel/cpu/sgx/driver/Makefile +1 -0
index 01ebbbb06a47..ac7702201229 100644
@@ -1,3 +1,4 @@
 obj-$(CONFIG_INTEL_SGX_DRIVER) += sgx.o
 sgx-$(CONFIG_INTEL_SGX_DRIVER) += ioctl.o
 sgx-$(CONFIG_INTEL_SGX_DRIVER) += main.o
+sgx-$(CONFIG_INTEL_SGX_DRIVER) += policy.o
arch/x86/kernel/cpu/sgx/driver/driver.h +7 -0
index 153b4a48aa6f..d5994c4aa65d 100644
@@ -33,6 +33,13 @@ extern u32 sgx_xsave_size_tbl[64];
 
 extern const struct file_operations sgx_provision_fops;
 
+uint8_t * sgx_get_launch_signer(uint8_t *signature);
+int sgx_get_key_hash(const void *modulus, void *hash);
+bool sgx_launch_control(uint8_t *modulus);
+bool sgx_provisioning_control(uint8_t *modulus);
+bool sgx_signing_control(uint8_t *modulus);
+int sgx_policy_fs(void);
+void sgx_policy_fs_remove(void);
 long sgx_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
 
 #endif /* __ARCH_X86_INTEL_SGX_H__ */
arch/x86/kernel/cpu/sgx/driver/ioctl.c +80 -8

141 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/driver/main.c +5 -0
index afe844aa81d6..503c2a9728ec 100644
@@ -348,6 +348,10 @@ static int __init sgx_drv_init(void)
 {
 	int ret;
 
+	ret = sgx_policy_fs();
+	if (ret)
+		return ret;
+
 	ret = sgx_drv_subsys_init();
 	if (ret)
 		return ret;
@@ -362,6 +366,7 @@ module_init(sgx_drv_init);
 
 static void __exit sgx_drv_exit(void)
 {
+	sgx_policy_fs_remove();
 	platform_driver_unregister(&sgx_drv);
 	sgx_drv_subsys_exit();
 }
arch/x86/kernel/cpu/sgx/driver/policy.c new file +584 -0

584 lines not on this page · raw message

arch/x86/kernel/cpu/sgx/main.c +23 -4
index 07adb35c260b..c5a9df27702c 100644
@@ -189,6 +189,8 @@ static void sgx_update_lepubkeyhash_msrs(u64 *lepubkeyhash, bool enforce)
  * @token:		a pointer an EINITTOKEN (optional)
  * @secs:		a pointer a SECS
  * @lepubkeyhash:	the desired value for IA32_SGXLEPUBKEYHASHx MSRs
+ * @launch_signer:	a pointer to a function returning possible
+ *			launch signers
  *
  * Execute ENCLS[EINIT], writing the IA32_SGXLEPUBKEYHASHx MSRs according
  * to @lepubkeyhash (if possible and necessary).
@@ -198,13 +200,30 @@ static void sgx_update_lepubkeyhash_msrs(u64 *lepubkeyhash, bool enforce)
  *   -errno or SGX error on failure
  */
 int sgx_einit(struct sgx_sigstruct *sigstruct, struct sgx_einittoken *token,
-	      struct sgx_epc_page *secs, u64 *lepubkeyhash)
+	      struct sgx_epc_page *secs, u64 *lepubkeyhash,
+	      uint8_t * (*launch_signer)(uint8_t *))
 {
 	int ret;
+	uint8_t *signer;
+
+	if (launch_signer) {
+		signer = (*launch_signer)(NULL);
+		while (signer) {
+			pr_debug("%s: Trying signer: %*phN\n", __FILE__, 32,
+				 signer);
+			preempt_disable();
+			sgx_update_lepubkeyhash_msrs((u64 *) signer, true);
+			ret = __einit(sigstruct, token, sgx_epc_addr(secs));
+			preempt_enable();
+			if (!ret)
+				return ret;
+			signer = (*launch_signer)(signer);
+		}
+		return ret;
+	}
 
-	if (!boot_cpu_has(X86_FEATURE_SGX_LC))
-		return __einit(sigstruct, token, sgx_epc_addr(secs));
-
+	pr_debug("%s: Setting LC register for EINIT to: %*phN.\n", __FILE__,
+		 32, lepubkeyhash);
 	preempt_disable();
 	sgx_update_lepubkeyhash_msrs(lepubkeyhash, false);
 	ret = __einit(sigstruct, token, sgx_epc_addr(secs));
arch/x86/kernel/cpu/sgx/sgx.h +2 -1
index 8a1dff1e5e8a..50fc9ee9d556 100644
@@ -85,6 +85,7 @@ struct sgx_epc_page *sgx_alloc_page(void *owner, bool reclaim);
 int __sgx_free_page(struct sgx_epc_page *page);
 void sgx_free_page(struct sgx_epc_page *page);
 int sgx_einit(struct sgx_sigstruct *sigstruct, struct sgx_einittoken *token,
-	      struct sgx_epc_page *secs, u64 *lepubkeyhash);
+	      struct sgx_epc_page *secs, u64 *lepubkeyhash,
+	      uint8_t *(*get_signer)(uint8_t *));
 
 #endif /* _X86_SGX_H */

-----BEGIN PGP SIGNATURE-----

iQEcBAABAgAGBQJct1mVAAoJEP1SNsFLeja67mYIAKWtG2bydNO9J9aMYBHegc/b 0uMms4rP6o5YRDoOVKMMyP5etoTQ2jRv1RUEukghnvHyMdEaad2JXcASiWmzrXTy lQXQlb8ejIc6C2PpCPmxB9pCV8ZtSTkoCsWgc4KvgjVtCJVbamx40CqvBoibcf+9 /nFKuqhXho163cT9PdKTWuxB5vgpaMUhtediEa2NhiTp6vfsCv9VZmWTf5OpTrIc h4ENGcHR6kJGnmbCTJlwzPgmZA2yK929MkFlOObhkexTG5xxTZlRxaveQX0QToz8 uzZ44c6a5IckNeD9yykyuC1vXdgV1tYlVJYGWhBZYMFwH2YkGsws7hlKfu51Tqw= =8RH8
-----END PGP SIGNATURE-----

#52 lore raw
Quoted 4 lines · Dr. Greg

In addition, the driver breaks all existing SGX software by breaking compatibility with what is a 3+ year ABI provided by the existing driver. This seems to contravene the well understood philosophy that Linux doesn't, if at all possible, break existing applications,

Sorry, that doesn't apply to out-of-tree modules. While we don't go out of our way to intentionally break apps who are relying on out-of-tree modules, we also don't go our of or way to keep them working.

Please stop asking about this. I don't see any route where it's going to change.

Companies ideally shouldn't be getting their customers hooked on out-of-tree ABIs and customers should consume out-of-tree ABIs *expecting* them to break in the future.

#53 lore raw

On Thu, Apr 18, 2019 at 10:24:42AM -0700, Dave Hansen wrote:

Good morning again.

Quoted 10 lines · Dr. Greg
Quoted 4 lines

In addition, the driver breaks all existing SGX software by breaking compatibility with what is a 3+ year ABI provided by the existing driver. This seems to contravene the well understood philosophy that Linux doesn't, if at all possible, break existing applications,

Sorry, that doesn't apply to out-of-tree modules. While we don't go out of our way to intentionally break apps who are relying on out-of-tree modules, we also don't go our of or way to keep them working.

Yes, there is no question that we understand this concept.

The salient point is that when given an opportunity to preserve and transition an existing development community, provide an architecturally relevant driver and to impose no restrictions on how a new, as yet untested and undesigned security architecture can emerge, the decision is made to break all compatibility.

Quoted 2 lines

Please stop asking about this. I don't see any route where it's going to change.

Which goes to my first e-mail where I noted this was about idealogy rather then technology.

Nothing wrong with that as long as we are intellectually honest.

Quoted 3 lines

Companies ideally shouldn't be getting their customers hooked on out-of-tree ABIs and customers should consume out-of-tree ABIs *expecting* them to break in the future.

At the risk of being indelicate, it was your company that hooked the SGX development community on out-of-tree driver ABI's and software.

We are just trying to find a mutually beneficial and productive path forward.

On that note.

One of the issues we have raised in multiple missives, that remains unaddressed, was the notion that the proposed driver may not work on all SGX hardware moving forward. Is there going to be an OEM mandated requirement, enforced by Intel licensing, that all SGX capable platforms will implement Flexible Launch Control?

For those following along at home, here is a link to the Intel Security announcements made at RSA-2019 in February:

https://newsroom.intel.com/news/rsa-2019-intel-partner-ecosystem-offer-new-silicon-enabled-security-solutions/

Of relevant note is the section 'Operational Control':

"Intel is delivering a new capability called flexible launch control that enables a company's data center operations to set and manage their own unique security policies for launching enclaves as well as providing controlled access to sensitive platform identification information. This capability is currently available on Intel SGX-enabled Intel Xeon E Processors and some Intel NUC's".

FLC is primarily about supporting Data-Center Attestation Services (DCAS) on XEON class servers. New technologies are released on NUC's since those are the platforms that Intel seems to target for developer experimentation.

We have had some experience with legal and liability sensitivities surrounding security in general and SGX in particular. Absent an official policy statement, it is a really open question whether this driver will be universally useful, with the end result being a fair amount of chaos for the Linux SGX community.

As opposed to Windows, which will have a known and stable ABI that works on any SGX capable hardware.

As I noted in my first e-mail yesterday, we anticipated this and our architecture provides a path forward for resolving this issue as well.

Have a good weekend.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.

PH: 701-281-1686
FAX: 701-281-3949 EMAIL: [email protected]
------------------------------------------------------------------------------
"If you get to thinkin' you're a person of some influence, try
orderin' somebody else's dog around."
-- Cowboy Wisdom

#54 lore raw
Quoted 5 lines · Dr. Greg
Quoted 3 lines

Companies ideally shouldn't be getting their customers hooked on out-of-tree ABIs and customers should consume out-of-tree ABIs *expecting* them to break in the future.

At the risk of being indelicate, it was your company that hooked the SGX development community on out-of-tree driver ABI's and software.

I would encourage anyone who has been impacted by this to communicate that back to the folks at Intel from whom they received the out-of-tree code about the impact.

Quoted 3 lines

Is there going to be an OEM mandated requirement, enforced by Intel licensing, that all SGX capable platforms will implement Flexible Launch Control?

Heck if I know. I don't think LKML is a great place to discuss Intel licensing requirements.

What I *do* know is that when builds a platform without Flexible Launch Control, Linux does not support SGX on that platform. I guess that could be spelled out in some documentation explicitly, if it isn't already.

maintainer
#55 lore raw
In reply to Dr. Greg
Quoted 17 lines · Dr. Greg

On Wed, Apr 17, 2019 at 01:39:10PM +0300, Jarkko Sakkinen wrote:

Good morning, I hope this note finds the impending end of the work week going well for everyone.

First of all, a thank you to Jarkko for his efforts in advancing this driver, a process that can be decidedly thankless. Our apologies in advance for contributing to this phenomenon.

Quoted 6 lines

Intel(R) 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 enclave is disallowed to access the memory inside the enclave by the CPU access control. In a way you can think that SGX provides inverted sandbox. It protects the application from a malicious host.

Quoted 4 lines

Unfortunately, in its current implementation, the driver will not protect a host from malicious enclaves. If it advances in its current form, the mainline Linux kernel will be implementing a driver with known and documented security issues.

"I can use this kernel or CPU feature to do something unpleasant that I could do anyway, if less nicely" is a far cry from "known and documented security issues".

We've hashed this out to death. Once SGX is upstream, feel free to submit patches.

Quoted 7 lines

In addition, the driver breaks all existing SGX software by breaking compatibility with what is a 3+ year ABI provided by the existing driver. This seems to contravene the well understood philosophy that Linux doesn't, if at all possible, break existing applications, something that we believe can be easily prevented if those interested in these issues choose to read on.

As I understand it, Cedric is going to submit a patch for this shortly, assuming I have correctly guessed what supposed ABI break you're talking about.

In the mean time, I need to correct you on a critical point. Linux has *never* had a policy that it will retain compatibility with an API that wasn't upstream in the first place.

[removed extensive verbiage. Dr. Greg, if you want your emails to be read, please try to be more concise, and please try to repeat yourself less.]

Quoted 6 lines

The attached patch, against the jarkko-sgx/master branch of Jarkko's driver repository, provides a framework that implements cryptographically secure enclave initialization policies. The patch and it's signature are also available from the following URL's:

ftp://ftp.idfusion.net/pub/idfusion/jarkko-master-SFLC.patch

I just spend several minutes trying to read your code. It would benefit dramatically from some attempt at documentation, and, at the very least, you can't have a function foo(type *ptr) that does something almost completely different when ptr == NULL and when ptr != NULL. For a concrete example, consider sgx_launch_control(). If you pass NULL, then there's a vaguely credible argument that the function does what the name suggests. If you pass non-NULL, it doesn't. The result is bug-prone and unreadable.

If I'm understanding it right, it causes the SGX ABI to be almost completely incompatible between the case where the list of launch signers is empty and the case where the list is non-empty. This is a non-starter. We're also extensively discussed how launch enclaves would be supported if we were to support them, and the generally agreed-upon solution was that the *kernel* would handle running a launch enclave. Jarkko even has code for this, but it's tabled until someone comes up with a credible argument that we *want* to support launch enclaves.

Quoted 2 lines

The policy architecture allows just about any conceivable initialization policy to be implemented and in any combination.

No it doesn't, because it requires the application (or its runtime or SDK or whatever) to bundle the launch enclave that implements the fancy policy, which means that the platform owner actually can't swap out the policy without breaking all the applications. This is the primary reason that, if Linux were to support LE-based launch control, it would do so in the kernel.

Quoted 5 lines

If the platform owner chooses to do nothing, the driver will initialize any enclave that is presented to it. FWIW, we have close to a century of enterprise system's administration experience on our team and we could not envision any competent system's administrator, concerned about security, who would allow such a configuration.

A sufficiently careful administrator who wants to protect against enclave malware might want the ability to revoke permission to run a specific enclave, which your approach can't do. Again, this has all been covered extensively.

To be crystal clear, i fully agree that we are likely to eventually want some kind of in-kernel launch policy. But I don't think that defining such a policy should block the upstreaming of the driver, and I don't think that your proposal for how the policy should work is an acceptable proposal.

#56 lore raw
In reply to Dr. Greg
Quoted 8 lines · Dr. Greg

Both the current controls for enclave access to the PROVISION attribute and the security controls that are being proposed to emerge for the driver, sometime in the future, suffer from being dependent on discretionary access controls, ie. file privileges, that can be defeated by a privilege escalation attack. Those of us building architectures on top of this technology have a need to certify that an application will provide security contracts robust in the face of a privilege escalation event or platform compromise.

I'm not following.

Are you saying that the implementation here is too permissive with the enclaves that are allowed to run? Because it's too permissive, this leaves us vulnerable to SGX being used to conceal a cache attack?

#57 lore raw

On Thu, Apr 18, 2019 at 11:01:00AM -0700, Dave Hansen wrote:

Good morning to everyone.

Quoted 10 lines · Dr. Greg
Quoted 8 lines

Both the current controls for enclave access to the PROVISION attribute and the security controls that are being proposed to emerge for the driver, sometime in the future, suffer from being dependent on discretionary access controls, ie. file privileges, that can be defeated by a privilege escalation attack. Those of us building architectures on top of this technology have a need to certify that an application will provide security contracts robust in the face of a privilege escalation event or platform compromise.

Quoted 6 lines

I'm not following.

Are you saying that the implementation here is too permissive with the enclaves that are allowed to run? Because it's too permissive, this leaves us vulnerable to SGX being used to conceal a cache attack?

I believe that would be the conclusion of a dispassionate observer who has followed this conversation and read the paper that I provided a link to.

For the benefit of those with a disinclination to read, particularly 16 page research papers, the following link provides a summary of the issues at hand.

https://www.securityweek.com/intel-sgx-can-be-abused-hide-advanced-malware-researchers

Of relevance to this conversation is Intel Security's official response to the paper, which is as follows:

"The value of Intel SGX is to execute code in a protected enclave; however, Intel SGX does not guarantee that the code executed in the enclave is from a trusted source. In all cases, we recommend utilizing programs, files, apps and plugins from trusted sources," Intel said.

The issue is not as much the ABI break but the following facts that are at hand:

1.) The proposed mainline driver offers no cryptographic or architecturally relevant security controls for ensuring that enclaves are from a trusted source.

2.) Based on Andy's comments there may be a disinclination to ever provide those controls.

3.) The approach we propose addresses these issues while imposing no functional limitations on how Linux platform owners can use enclave technology.

Seems like a win.

There you go, one sentence replies.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.

PH: 701-281-1686
FAX: 701-281-3949 EMAIL: [email protected]
------------------------------------------------------------------------------
"Laugh now but you won't be laughing when we find you laying on the
side of the road dead."
-- Betty Wettstein
At the Lake

maintainer
#58 lore raw
Quoted 9 lines · Dr. Greg

On Thu, Apr 18, 2019 at 11:01:00AM -0700, Dave Hansen wrote:

"The value of Intel SGX is to execute code in a protected enclave; however, Intel SGX does not guarantee that the code executed in the enclave is from a trusted source. In all cases, we recommend utilizing programs, files, apps and plugins from trusted sources," Intel said.

Linux *has* mechanisms to enforce the provenance of code, and they have nothing to do with SGX. Off the top of my head, there’s IMA, SELinux (depending on policy), and dm-verity.

So it seems to me that our bases are already pretty well covered. I see two cases where some additional protection for SGX might make sense:

1. You care more about the provenance of enclaves than the provenance of normal code. (“You” is the platform owner, not a remote party verifying SGX quotes.”) There are any number of solutions that could work here, and not all of them involve crypto.

2. You care about the case where the kernel is compromised. In this case, nothing that's been discussed helps much on an FLC system, and even the pre-LC systems aren't a whole lot better given the lack of init token revocation.

But I think we may be missing a much bigger issue that does need consideration before the driver gets merged. We're all focusing on *additional* SGX protections, but I'm not even sure we have the SGX protections up to snuff with the rest of the system. There are many, many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable. (Obviously, JITs either don't work or need special permissions on these systems.)

Unless I'm missing it, the current SGX API is entirely incompatible with this model -- the host process supplies text *bytes* to the kernel, and the kernel merrily loads those bytes into executable enclave memory. Whoops!

I think we may need to change the API so that enclaves are loaded from a file where the contents of the file are in some appropriate format. (The file should, at least, contain MRENCLAVE, but various antivirus tools would much prefer if the actual enclave contents were in the file.) It's not entirely clear that the enclave text and data need to be in the file, since they're covered by the hash.) Then, to start an enclave, you pass an fd to the file to the SGX driver, and the SGX driver parses out the relevant data initializes the enclave. Before this happens, the driver could call into IMA and LSM hooks, and the driver would also verify that the file didn't come from a noexec filesystem.

I suppose another approach would be to treat SGX the same way that ld.so is treated, mostly by requiring that the buffers passed to the driver that contain text be marked executable. This seems quite a bit weakter to me.

What do you all think?

#59 lore raw
Quoted 5 lines · Andy Lutomirski

There are many,
many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable.

How is this implemented on those systems? AFAIK there's no kernel config option that changes the semantics of mmap as you describe.

--
Jethro Beekman | Fortanix

#60 lore raw
Quoted 9 lines · Jethro Beekman
Quoted 5 lines · Andy Lutomirski

There are many,
many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable.

How is this implemented on those systems? AFAIK there's no kernel config option that changes the semantics of mmap as you describe.

That has nothing to do with mmap() semantics. You mmap() writeable memory and then you change the permissions via mprotect(). mprotect() calls into LSM and depending on policy and security model this will reject the request.

Andy was pointing out that the SGX ioctl bypasses the LSM mechanics which is obviously a bad thing.

Thanks,

tglx

#61 lore raw
Quoted 12 lines · Thomas Gleixner
Quoted 9 lines · Jethro Beekman
Quoted 5 lines · Andy Lutomirski

There are many,
many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable.

How is this implemented on those systems? AFAIK there's no kernel config option that changes the semantics of mmap as you describe.

Quoted 7 lines

That has nothing to do with mmap() semantics. You mmap() writeable memory and then you change the permissions via mprotect(). mprotect() calls into LSM and depending on policy and security model this will reject the request.

Andy was pointing out that the SGX ioctl bypasses the LSM mechanics which is obviously a bad thing.

We could modify the driver such that when you call ioctl EADD, the page table permissions need to be the PAGEINFO.SECINFO.FLAGS | PROT_WRITE, otherwise you get EPERM or so. After EADD, if you want, you can restrict the page table permissions again using mprotect but the page table permissions don't really matter for SGX.

--
Jethro Beekman | Fortanix

#62 lore raw
Quoted 18 lines · Jethro Beekman
Quoted 17 lines · Thomas Gleixner
Quoted 9 lines · Jethro Beekman
Quoted 5 lines · Andy Lutomirski

There are many,
many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable.

How is this implemented on those systems? AFAIK there's no kernel config option that changes the semantics of mmap as you describe.

That has nothing to do with mmap() semantics. You mmap() writeable memory and then you change the permissions via mprotect(). mprotect() calls into LSM and depending on policy and security model this will reject the request.

Quoted 8 lines
Quoted 2 lines

Andy was pointing out that the SGX ioctl bypasses the LSM mechanics which is obviously a bad thing.

We could modify the driver such that when you call ioctl EADD, the page table permissions need to be the PAGEINFO.SECINFO.FLAGS | PROT_WRITE, otherwise you get EPERM or so. After EADD, if you want, you can restrict the page table permissions again using mprotect but the page table permissions don't really matter for SGX.

And the point of that is? That you still can cirumvent LSM for feeding executable code into SGX.

No, we are not making special cases and exceptions for SGX.

Thanks,

tglx

#63 lore raw
Quoted 22 lines · Thomas Gleixner
Quoted 21 lines · Jethro Beekman
Quoted 19 lines · Thomas Gleixner
Quoted 9 lines · Jethro Beekman
Quoted 5 lines · Andy Lutomirski

There are many,
many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable.

How is this implemented on those systems? AFAIK there's no kernel config option that changes the semantics of mmap as you describe.

That has nothing to do with mmap() semantics. You mmap() writeable memory and then you change the permissions via mprotect(). mprotect() calls into LSM and depending on policy and security model this will reject the request.

Andy was pointing out that the SGX ioctl bypasses the LSM mechanics which is obviously a bad thing.

Quoted 8 lines
Quoted 5 lines

We could modify the driver such that when you call ioctl EADD, the page table permissions need to be the PAGEINFO.SECINFO.FLAGS | PROT_WRITE, otherwise you get EPERM or so. After EADD, if you want, you can restrict the page table permissions again using mprotect but the page table permissions don't really matter for SGX.

And the point of that is? That you still can cirumvent LSM for feeding executable code into SGX.

How? LSM would see that you're trying to map a page RWX so you can do your ioctl?

Quoted 1 line

No, we are not making special cases and exceptions for SGX.

Maybe I didn't express myself clearly? I don't think I was suggesting anything like that.

--
Jethro Beekman | Fortanix

#64 lore raw
Quoted 35 lines · Jethro Beekman
Quoted 30 lines · Thomas Gleixner
Quoted 27 lines · Jethro Beekman
Quoted 13 lines · Thomas Gleixner
Quoted 11 lines · Jethro Beekman
Quoted 7 lines · Andy Lutomirski

There are many,
many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable.

How is this implemented on those systems? AFAIK there's no kernel config option that changes the semantics of mmap as you describe.

Quoted 7 lines

That has nothing to do with mmap() semantics. You mmap() writeable memory and then you change the permissions via mprotect(). mprotect() calls into LSM and depending on policy and security model this will reject the request.

Andy was pointing out that the SGX ioctl bypasses the LSM mechanics which is obviously a bad thing.

We could modify the driver such that when you call ioctl EADD, the page table permissions need to be the PAGEINFO.SECINFO.FLAGS | PROT_WRITE, otherwise you get EPERM or so. After EADD, if you want, you can restrict the page table permissions again using mprotect but the page table permissions don't really matter for SGX.

Quoted 5 lines
Quoted 2 lines

And the point of that is? That you still can cirumvent LSM for feeding executable code into SGX.

How? LSM would see that you're trying to map a page RWX so you can do your ioctl?

With plain mmap() + mprotect(), the LSM will prevent you from making memory that *was* writable executable. This is by design and SELinux supports it. I don’t remember the name of the associated SELinux permission off the top of my head.

If we start enforcing equivalent rules on SGX, then the current API will simply not allow enclaves to be loaded — no matter how you slice it, loading an enclave with the current API is indistinguishable from making arbitrary data executable.

Put another way, you can compile your enclave, ship it as a file, and get it appropriately verified (by LSM attribute, IMA, dm-verity, whatever) and run it, but, with the current API, the kernel has no way of knowing that the userspace enclave loader is actually reading it from the file in question.

So I think we need to work on the API.

Quoted 8 lines
Quoted 2 lines

No, we are not making special cases and exceptions for SGX.

Maybe I didn't express myself clearly? I don't think I was suggesting anything like that.

--
Jethro Beekman | Fortanix

#65 lore raw

Jethro Beekman | Fortanix

Quoted 38 lines · Andy Lutomirski
Quoted 38 lines · Jethro Beekman
Quoted 32 lines · Thomas Gleixner
Quoted 19 lines · Jethro Beekman
Quoted 18 lines · Thomas Gleixner
Quoted 11 lines · Jethro Beekman
Quoted 7 lines · Andy Lutomirski

There are many,
many Linux systems that enforce a policy that *all* executable text needs to come from a verified source. On these systems, you can't mmap some writable memory, write to it, and then change it to executable.

How is this implemented on those systems? AFAIK there's no kernel config option that changes the semantics of mmap as you describe.

That has nothing to do with mmap() semantics. You mmap() writeable memory and then you change the permissions via mprotect(). mprotect() calls into LSM and depending on policy and security model this will reject the request.

Quoted 8 lines
Quoted 2 lines

Andy was pointing out that the SGX ioctl bypasses the LSM mechanics which is obviously a bad thing.

We could modify the driver such that when you call ioctl EADD, the page table permissions need to be the PAGEINFO.SECINFO.FLAGS | PROT_WRITE, otherwise you get EPERM or so. After EADD, if you want, you can restrict the page table permissions again using mprotect but the page table permissions don't really matter for SGX.

And the point of that is? That you still can cirumvent LSM for feeding executable code into SGX.

Quoted 6 lines
Quoted 2 lines

How? LSM would see that you're trying to map a page RWX so you can do your ioctl?

With plain mmap() + mprotect(), the LSM will prevent you from making memory that *was* writable executable. This is by design and SELinux supports it. I don’t remember the name of the associated SELinux permission off the top of my head.

If we start enforcing equivalent rules on SGX, then the current API will simply not allow enclaves to be loaded — no matter how you slice it, loading an enclave with the current API is indistinguishable from making arbitrary data executable.

Yes this is exactly what I intended here: a very simple change that stops SGX from confusing LSM. Just by enforcing that everything that looks like a memory write (EADD, EAUG, EDBGWR, etc.) actually requires write permissions, reality and LSM should be on the same page.

If you want to go further and actually allow this behavior when your LSM would otherwise prohibit it, presumably the same workarounds that exist for JITs can be used for SGX.

--
Jethro Beekman | Fortanix

#66 lore raw
Quoted 8 lines · Jethro Beekman
Quoted 4 lines

.

If we start enforcing equivalent rules on SGX, then the current API will simply not allow enclaves to be loaded — no matter how you slice it, loading an enclave with the current API is indistinguishable from making arbitrary data executable.

Quoted 10 lines

Yes this is exactly what I intended here: a very simple change that stops SGX from confusing LSM. Just by enforcing that everything that looks like a memory write (EADD, EAUG, EDBGWR, etc.) actually requires write permissions, reality and LSM should be on the same page.

If you want to go further and actually allow this behavior when your LSM would otherwise prohibit it, presumably the same workarounds that exist for JITs can be used for SGX.

I do think we need to follow LSM rules. But my bigger point is that there are policies that don’t allow JIT at all. I think we should arrange the SGX API so it’s still usable when such a policy is in effect.

#67 lore raw
Quoted 1 line · Andy Lutomirski

I do think we need to follow LSM rules. But my bigger point is that there are policies that don’t allow JIT at all. I think we should arrange the SGX API so it’s still usable when such a policy is in effect.

I don't think we need to arrange that right now. This patch set needs to be merged after more than 2 years of development. I'd like to avoid introducing any more big changes. Let's just do what I described to make LSM not broken, which is a minimal change to the current approach. We can adjust the API later to support the use case you describe.

--
Jethro Beekman | Fortanix

#68 lore raw
Quoted 8 lines · Jethro Beekman
Quoted 4 lines · Andy Lutomirski

I do think we need to follow LSM rules. But my bigger point is that there are policies that don’t allow JIT at all. I think we should arrange the SGX API so it’s still usable when such a policy is in effect.

I don't think we need to arrange that right now. This patch set needs to be merged after more than 2 years of development. I'd like to avoid

We merge stuff when it is ready and not when someone declares that it needs to be merged.

Quoted 3 lines

introducing any more big changes. Let's just do what I described to make LSM not broken, which is a minimal change to the current approach. We can adjust the API later to support the use case you describe.

You are working around LSM nothing else and that's just not going to fly.

Thanks,

tglx

#69 lore raw
Quoted 3 lines · Thomas Gleixner

And how so? You create writeable AND executable memory. That's a nono and you can argue in circles, that's not going to change with any of your proposed changes.

Quoted 1 line · Thomas Gleixner

You are working around LSM nothing else and that's just not going to fly.

Based on your comments, I'm still unsure if we're on the same page with regards to what I'm proposing.

Here's a regular non-SGX flow that LSM would likely prevent:

mmap(PROT_READ|PROT_WRITE)
memcpy()
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

Or just something based on regular PT permissions:

mmap(PROT_READ|PROT_EXEC)
memcpy() <-- SIGSEGV

Now, the equivalent for SGX:

mmap(PROT_READ|PROT_WRITE)
ioctl(EADD)
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

This works fine with v20 as-is. However, consider the equivalent of the PT-based flow:

mmap(PROT_READ|PROT_EXEC)
ioctl(EADD) <-- no error!

It's not me that's working around the LSM, it's the SGX driver! It's writing to memory that's not marked writable! The fundamental issue here is that the SGX instruction set has several instructions that bypass the page table permission bits, and this is (naturally) confusing to any kind of reference monitor like the LSM framework. You can come up with similar scenarios that involve PROT_READ|PROT_WRITE|PROT_EXEC or ptrace(PTRACE_POKETEXT). So, clearly, the proper way to fix this failure of complete mediation is by enforcing appropriate page-table permissions even on the SGX instructions that don't do it themselves. Just make any implicit memory access look like a regular memory access and now everyone is on the same page (pun intended).

--
Jethro Beekman | Fortanix

#70 lore raw
Quoted 19 lines · Jethro Beekman
Quoted 3 lines · Thomas Gleixner

And how so? You create writeable AND executable memory. That's a nono and you can argue in circles, that's not going to change with any of your proposed changes.

Quoted 1 line · Thomas Gleixner

You are working around LSM nothing else and that's just not going to fly.

Based on your comments, I'm still unsure if we're on the same page with regards to what I'm proposing.

Here's a regular non-SGX flow that LSM would likely prevent:

mmap(PROT_READ|PROT_WRITE)
memcpy()
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

Or just something based on regular PT permissions:

Quoted 8 lines

mmap(PROT_READ|PROT_EXEC)
memcpy() <-- SIGSEGV

Now, the equivalent for SGX:

mmap(PROT_READ|PROT_WRITE)
ioctl(EADD)
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

This is completely irrelevant, really.

The point is that the SGX driver loads and executes arbitrary data which is handed in from user space via an ioctl w/o any chance of verifying where that comes from.

What Andy proposed is to open a file with the SGX payload and hand in the file descriptor. That way LSM can decide whether this is allowed or denied based on the file descriptor and whatever the security model/policy is in a particular setup.

Right know the SGX driver and its proposed API prevent any form of LSM auditing and whatever permission checks you had in mind won't change that at all.

Thanks,

tglx

#71 lore raw

On Sat, Apr 20, 2019 at 07:42:13AM +0200, Thomas Gleixner wrote:

Good morning/weekend to everyone.

Quoted 35 lines · Jethro Beekman
Quoted 19 lines · Thomas Gleixner
Quoted 3 lines

And how so? You create writeable AND executable memory. That's a nono and you can argue in circles, that's not going to change with any of your proposed changes.

Quoted 1 line · Thomas Gleixner

You are working around LSM nothing else and that's just not going to fly.

Based on your comments, I'm still unsure if we're on the same page with regards to what I'm proposing.

Here's a regular non-SGX flow that LSM would likely prevent:

mmap(PROT_READ|PROT_WRITE)
memcpy()
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

Or just something based on regular PT permissions:

Quoted 8 lines

mmap(PROT_READ|PROT_EXEC)
memcpy() <-- SIGSEGV

Now, the equivalent for SGX:

mmap(PROT_READ|PROT_WRITE)
ioctl(EADD)
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

This is completely irrelevant, really.

The point is that the SGX driver loads and executes arbitrary data which is handed in from user space via an ioctl w/o any chance of verifying where that comes from.

Quoted 8 lines

What Andy proposed is to open a file with the SGX payload and hand in the file descriptor. That way LSM can decide whether this is allowed or denied based on the file descriptor and whatever the security model/policy is in a particular setup.

Right know the SGX driver and its proposed API prevent any form of LSM auditing and whatever permission checks you had in mind won't change that at all.

I don't even want to remotely get in the middle of this arguement, since we are probably already persona-non-grata for having stimulated a discussion that has slowed upstreaming, but some comments to assist and clarify further progress on the driver.

We understand and support the need for the LSM to trap these events, but what does LSM provenance mean if the platform is compromised? That is, technically, the target application for SGX technology.

This issue is what drove our concern for having ring-0 based enforcement of who can initialize an enclave. As Andy has pointed out, the mmap semantics of the SGX driver allow the introduction of executable code that bypasses LSM enforcement, but the platform owner, with appropriate enforcements on an FLC platform, has cryptographic verification and trust for the origin and provenance of that executable code.

It may be possible to load the executable code into enclave memory but the processor will refuse to access the memory until the EINIT instruction validates that the loaded code is compliant with the enclave metadata and measurement. That is why we were argueing for, simple, ring-0 based verification of the key signature that authorizes the EINIT instruction to complete.

From a more practical perspective, an enclave shared image is a rather complex beast, that contains a lot of metadata. An application has to open the shared image file and parse the metadata in order to properly construct the enclave image from the text in the image file. I believe in practice that will effectively activate LSM recognition of the executable code.

That obviously leaves a cunning adversary an opportunity to teleport a simple binary file or network stream onto a platform and load and execute the contents. But that takes us back to the need for ring-0 enforcement of enclave initialization... :-)

We wrote a major enhancement to the Linux IMA architecture to implement introspection of behavioral namespaces. The actor/subject events get forwarded up into a modeling engine running inside of a namespace specific SGX enclave instance that issues a system call to instruct an LSM that we wrote, and that pairs with the IMA extension, to 'discipline' the process if it is acting outside its behavioral specification.

We will verify with Jarkko's current HEAD, but I believe it is consistently trapping access to the shared image file and hence the text of the enclave.

Quoted 3 lines

Thanks,

tglx

Have a good weekend.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.

PH: 701-281-1686
FAX: 701-281-3949 EMAIL: [email protected]
------------------------------------------------------------------------------
"Simplicity is prerequisite for reliability."
-- Edsger W. Dijkstra

#72 lore raw
Quoted 3 lines · Dr. Greg

We understand and support the need for the LSM to trap these events, but what does LSM provenance mean if the platform is compromised? That is, technically, the target application for SGX technology.

No, it's not. Protecting the kernel/platform from a malicious entity is outside the scope of SGX.

#73 lore raw

On Mon, Apr 22, 2019 at 08:01:19AM -0700, Sean Christopherson wrote:

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

Quoted 8 lines · Dr. Greg
Quoted 4 lines

We understand and support the need for the LSM to trap these events, but what does LSM provenance mean if the platform is compromised? That is, technically, the target application for SGX technology.

No, it's not. Protecting the kernel/platform from a malicious entity is outside the scope of SGX.

You must have misinterpreted my statement, providing security guarantees in the face of a compromised platform is exactly what SGX was designed to do and is how Intel is marketing the technology.

From the first paragraph (Introduction) in the following document:

https://software.intel.com/sites/default/files/managed/50/8c/Intel-SGX-Product-Brief.pdf

"Intel Software Guard Extensions (Intel SGX) protects selected code and data from disclosure or modification. Developers can partition their application into CPU hardened 'enclaves' or protected areas of execution that increase security even on compromised platforms".

In addition, one of the major use cases for this technology is the ability to push data and application code up onto cloud platforms with a guarantee that not even the platform owner or administrators can compromise the integrity or confidentiality of the code and data.

As I've noted before, from an OS driver perspective, security and privacy models which are dependent on an uncompromised platform and user privileges are inconsistent with the SGX security architecture. Doing SGX right is about applying cryptographically defined provenance and integrity models.

Our autonomous introspection technology uses SGX to protect the platform at large but we are unique with respect to how the technology is being applied.

Have a good day.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.

PH: 701-281-1686
FAX: 701-281-3949 EMAIL: [email protected]
------------------------------------------------------------------------------
"You and Uncle Pete drank the whole thing? That was a $250.00 bottle
of whisky.

Yeah, it was good."
-- Rick Engen
Resurrection.

#74 lore raw
Quoted 10 lines · Dr. Greg

On Mon, Apr 22, 2019 at 08:01:19AM -0700, Sean Christopherson wrote:

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

Quoted 5 lines · Dr. Greg
Quoted 4 lines

We understand and support the need for the LSM to trap these events, but what does LSM provenance mean if the platform is compromised? That is, technically, the target application for SGX technology.

Quoted 6 lines
Quoted 2 lines

No, it's not. Protecting the kernel/platform from a malicious entity is outside the scope of SGX.

You must have misinterpreted my statement, providing security guarantees in the face of a compromised platform is exactly what SGX was designed to do and is how Intel is marketing the technology.

Right, and loading a malicious enclave doesn't change those guarantees (for other enclaves). Ergo, restricting which enclaves can execute is orthogonal to the security provided by SGX.

#75 lore raw
Quoted 4 lines · Sean Christopherson

Right, and loading a malicious enclave doesn't change those guarantees (for other enclaves). Ergo, restricting which enclaves can execute is orthogonal to the security provided by SGX.

But it is absolutely worth noting that TSX made a lot of attacks both easier to _do_, and also easier to _hide_.

All while being basically completely worthless technology to everybody except for some silly SAP benchmark.

So it is definitely worth at least discussing the downsides of SGX. If it ends up being another technology that makes it easier to create malware, without actually having a lot of _good_ software use it, the patches to enable it should make damn sure that the upsides actually outweigh the downsides.

And if the current setup basically is "you have to disable reasonable SElinux protections that lots of distros use today", I think it's entirely reasonable saying "the downsides are bigger than the upsides".

Linus

#76 lore raw
Quoted 19 lines · Linus Torvalds
Quoted 4 lines · Sean Christopherson

Right, and loading a malicious enclave doesn't change those guarantees (for other enclaves). Ergo, restricting which enclaves can execute is orthogonal to the security provided by SGX.

But it is absolutely worth noting that TSX made a lot of attacks both easier to _do_, and also easier to _hide_.

All while being basically completely worthless technology to everybody except for some silly SAP benchmark.

So it is definitely worth at least discussing the downsides of SGX. If it ends up being another technology that makes it easier to create malware, without actually having a lot of _good_ software use it, the patches to enable it should make damn sure that the upsides actually outweigh the downsides.

Quoted 4 lines

And if the current setup basically is "you have to disable reasonable SElinux protections that lots of distros use today", I think it's entirely reasonable saying "the downsides are bigger than the upsides".

I'm not arguing against SGX playing nice with SELinux/LSMs, actually the opposite. I completely agree that enclaves should be subject to LSM restrictions.

AIUI, Dr. Greg is proposing a framework that uses SGX's launch control mechanism to restrict what enclaves can run. My point is that restricting what enclaves can run is about protecting the kernel and/or platform, not the enclaves themselves, i.e. using launch control instead of, or in addition to, LSMs doesn't change the security guarantees of SGX.

#77 lore raw

On Mon, Apr 22, 2019 at 10:17:15AM -0700, Sean Christopherson wrote:

Good morning to everyone.

Quoted 20 lines · Linus Torvalds
Quoted 19 lines
Quoted 4 lines · Sean Christopherson

Right, and loading a malicious enclave doesn't change those guarantees (for other enclaves). Ergo, restricting which enclaves can execute is orthogonal to the security provided by SGX.

But it is absolutely worth noting that TSX made a lot of attacks both easier to _do_, and also easier to _hide_.

All while being basically completely worthless technology to everybody except for some silly SAP benchmark.

So it is definitely worth at least discussing the downsides of SGX. If it ends up being another technology that makes it easier to create malware, without actually having a lot of _good_ software use it, the patches to enable it should make damn sure that the upsides actually outweigh the downsides.

Quoted 8 lines
Quoted 4 lines

And if the current setup basically is "you have to disable reasonable SElinux protections that lots of distros use today", I think it's entirely reasonable saying "the downsides are bigger than the upsides".

I'm not arguing against SGX playing nice with SELinux/LSMs, actually the opposite. I completely agree that enclaves should be subject to LSM restrictions.

As do we.

The point we have been making is that depending on the LSM's are depending on the fact that the platform has not been compromised. SGX is designed to provide a trusted execution environment in the face of a compromised platform.

Quoted 6 lines

AIUI, Dr. Greg is proposing a framework that uses SGX's launch control mechanism to restrict what enclaves can run. My point is that restricting what enclaves can run is about protecting the kernel and/or platform, not the enclaves themselves, i.e. using launch control instead of, or in addition to, LSMs doesn't change the security guarantees of SGX.

I believe current research suggests that this is not the case.

From the paper we have previously cited:

https://arxiv.org/pdf/1702.08719.pdf

In the second paragraph of the abstract:

"In this paper, we demonstrate fine-grained software-based side-channel attacks from a malicious SGX enclave targeting co-located enclaves. Our attack is the first malware running on real SGX hardware, abusing SGX protection features to conceal itself. Furthermore, we demonstrate our attack both in a native environment and across multiple Docker containers".

To be perfectly clear, Dr. Greg, technically IDfusion, is not proposing the use of SGX's launch control to restrict which enclaves can run, although there are perfectly legitimate and required use cases for that technology.

Dr. Greg is proposing that the kernel driver expend 1.2 pages of kernel memory to implement, at the discretion of the platform owner, cryptographically verified enclave initialization. The design we proposed is the strongest guarantee that a platform owner can implement, on FLC hardware, that only code and data of known provenance can be loaded and executed.

There are only two companies that have written the entire stack of software needed to make practical SGX applications work, us and Intel. We can go into intimate detail on the issues involved but will embrace bevity at this point.

Have a good day.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.

PH: 701-281-1686
FAX: 701-281-3949 EMAIL: [email protected]
------------------------------------------------------------------------------
"Because the innovator has for enemies all those who have done well
under the old conditions, and lukewarm defenders in those who may do well under the new."
-- Niccolo Machiavelli
_The Prince_, Chapter VI

maintainer
#78 lore raw
In reply to Jethro Beekman
Quoted 30 lines · Jethro Beekman
Quoted 8 lines · Thomas Gleixner

And how so? You create writeable AND executable memory. That's a nono and you can argue in circles, that's not going to change with any of your proposed changes.

On 2019-04-19 14:38, Thomas Gleixner wrote:
You are working around LSM nothing else and that's just not going to fly.

Based on your comments, I'm still unsure if we're on the same page with regards to what I'm proposing.

Here's a regular non-SGX flow that LSM would likely prevent:

mmap(PROT_READ|PROT_WRITE)
memcpy()
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

Or just something based on regular PT permissions:

mmap(PROT_READ|PROT_EXEC)
memcpy() <-- SIGSEGV

Now, the equivalent for SGX:

mmap(PROT_READ|PROT_WRITE)
ioctl(EADD)
mmap(PROT_READ|PROT_EXEC) <-- denied by LSM

Quoted 5 lines

This works fine with v20 as-is. However, consider the equivalent of the PT-based flow:

mmap(PROT_READ|PROT_EXEC)
ioctl(EADD) <-- no error!

Indeed!

Quoted 13 lines

It's not me that's working around the LSM, it's the SGX driver! It's writing to memory that's not marked writable! The fundamental issue here is that the SGX instruction set has several instructions that bypass the page table permission bits, and this is (naturally) confusing to any kind of reference monitor like the LSM framework. You can come up with similar scenarios that involve PROT_READ|PROT_WRITE|PROT_EXEC or ptrace(PTRACE_POKETEXT). So, clearly, the proper way to fix this failure of complete mediation is by enforcing appropriate page-table permissions even on the SGX instructions that don't do it themselves. Just make any implicit memory access look like a regular memory access and now everyone is on the same page (pun intended).

I agree that we should do this. But then what? Once this gets fixed, the ioctl(EADD) fails and the driver becomes rather less useful, and we feel rather silly if we’ve merged it in this state.

So I think we need a better EADD ioctl that explicitly does work on PROT_READ|PROT_EXEC enclave memory but makes up for by validating the *source* of the data. The effect will be similar to mapping a labeled, appraised, etc file as PROT_EXEC. Maybe, in extreme pseudocode:

fd = open(“/dev/sgx/enclave”);
ioctl(fd, SGX_CREATE_FROM_FILE, file_fd);
// fd now inherits the LSM label from the file, or is otherwise marked. mmap(fd, PROT_READ|PROT_EXEC, ...);

I suppose that an alternative would be to delegate all the EADD calls to a privileged daemon, but that’s nasty.

#79 lore raw
Quoted 23 lines · Andy Lutomirski
Quoted 6 lines · Jethro Beekman

This works fine with v20 as-is. However, consider the equivalent of the PT-based flow:

mmap(PROT_READ|PROT_EXEC)
ioctl(EADD) <-- no error!

Indeed!

Quoted 13 lines

It's not me that's working around the LSM, it's the SGX driver! It's writing to memory that's not marked writable! The fundamental issue here is that the SGX instruction set has several instructions that bypass the page table permission bits, and this is (naturally) confusing to any kind of reference monitor like the LSM framework. You can come up with similar scenarios that involve PROT_READ|PROT_WRITE|PROT_EXEC or ptrace(PTRACE_POKETEXT). So, clearly, the proper way to fix this failure of complete mediation is by enforcing appropriate page-table permissions even on the SGX instructions that don't do it themselves. Just make any implicit memory access look like a regular memory access and now everyone is on the same page (pun intended).

Quoted 1 line

I agree that we should do this. But then what?

Then, we have a minimum viable SGX implementation that doesn't make things worse than they are today from a userspace code loading/LSM perspective. People without LSMs can use SGX and people with LSMs are not more vulnerable than before. I agree that we should do something along the following lines...

Quoted 4 lines

So I think we need a better EADD ioctl that explicitly does work on PROT_READ|PROT_EXEC enclave memory but makes up for by validating the *source* of the data. The effect will be similar to mapping a labeled, appraised, etc file as PROT_EXEC.

... but I don't see why this would need to be in the initial patch set. We need to take some time to explore the design space here (see additional comments below), and I don't think it's necessary to wait for it.

Quoted 10 lines

Maybe, in extreme pseudocode:

fd = open(“/dev/sgx/enclave”);
ioctl(fd, SGX_CREATE_FROM_FILE, file_fd);
// fd now inherits the LSM label from the file, or is otherwise marked. mmap(fd, PROT_READ|PROT_EXEC, ...);

I suppose that an alternative would be to delegate all the EADD calls to a privileged daemon, but that’s nasty.

What file format should this be in? I have worked with several different binary enclave formats and I don't really like any of them.

# ELF

Pros:
* People know about ELF.
* Allows storing additional metadata that is only used by userspace, not the enclave itself.

Cons:
* ELF generally loads all kinds of stuff in memory that is not necessary for enclaves, such as the ELF header.
* Special tools are needed to calculate ENCLAVEHASH, for signing & verification.
* All tools need to agree on the exact transformation.
* Unclear how to specify things such as: which 256-byte chunks of memory should be measured, heap, TCS pages, stacks, SSAs, etc.

Questions:
* If using ELF, should this be the same format that the Intel Linux SDK uses (not documented, but source code is available) or something newly standardized?

# PE (Windows Intel SDK format)

Andy suggested this in another email. I'm not sure why exactly?

Pros:
* Used by Windows enclaves?
* Allows storing additional metadata that is only used by userspace, not the enclave itself.

Cons:
* The format is not documented. I did some RE on this format a long time ago. See https://github.com/fortanix/rust-sgx/blob/master/doc/WINTEL-SGX-ABI.md and https://github.com/fortanix/rust-sgx/blob/master/sgxs-tools/src/bin/isgx-pe2sgx.rs.
* PE is not really used on Linux.
* All same cons as ELF above.

# CPU-native (hash stream) "SGXS"

The security properties of an enclave are completely defined by the hash that's calculated by the processor while loading the enclave. The exact hashed data is what I call the "SGX stream" format (SGXS). This is fully described by the Intel SDM. I've written down some notes about this at https://github.com/fortanix/rust-sgx/blob/master/doc/SGXS.md. That document also defines a notion of canonicality for streams. You can ignore the section on "Enhanced SGXS", which is a failed experiment.

Pros:
* Computing ENCLAVEHASH is a simple SHA256 of the file.
* No complex transformations needed to load enclave.

Cons:
* No way to specify memory contents of non-measured memory.
* No space for non-enclave metadata (including SIGSTRUCT).
* Not a standard format for transporting binaries.

# CPU-native (instruction stream)

An enclave's memory contents is fully defined by the set of ECREATE/EADD/EEXTEND/EINIT instructions that the OS needs to execute. One could envision a format that describes exactly those instructions. One difference with the SGXS format described above is that the enclave memory is described as part of EADD, not EEXTEND. This allows including specific values for non-measured memory.

Pros:
* No complex transformations needed to load enclave.
* Obvious place to store SIGSTRUCT.

Cons:
* Special tools are needed to calculate ENCLAVEHASH, for signing & verification.
* No obvious space for non-enclave metadata.
* Not a standard format for transporting binaries.

---

We've been using the SGXS format for a couple of years, and also the "Enhanced SGXS" format. I think SGXS make a lot of sense for SGX software, Enhanced SGXS not so much. I've recently been pondering developing a new format that is basically an archive (tar? but preferably something with an index) of SGXS, SIGSTRUCT, some file describing non-measured memory contents (format TBD), and additional non-enclave metadata.

I'd be interested in hearing people's thoughts on file formats.

--
Jethro Beekman | Fortanix

#80 lore raw
In reply to Andy Lutomirski

Hi Andy,

Quoted 6 lines

So I think we need a better EADD ioctl that explicitly does work on PROT_READ|PROT_EXEC enclave memory but makes up for by validating the *source* of the data. The effect will be similar to mapping a labeled, appraised, etc file as PROT_EXEC. Maybe, in extreme pseudocode:

Quoted 7 lines

fd = open(“/dev/sgx/enclave”);
ioctl(fd, SGX_CREATE_FROM_FILE, file_fd); // fd now inherits the LSM label from the file, or is otherwise marked.
mmap(fd, PROT_READ|PROT_EXEC, ...);

I suppose that an alternative would be to delegate all the EADD calls to a privileged daemon, but that’s nasty.

I agree with you that *source* of EPC pages shall be validated. But instead of doing it in the driver, I think an alternative could be to treat an enclave file as a regular shared object so all IMA/LSM checks could be triggered/performed as part of the loading process, then let the driver "copy" those pages to EPC. By "copy", I mean both the page content and _permissions_ are copied, which differs from the current driver's behavior of copying page content only (while permissions are taken from ioctl parameters). That said, if an adversary cannot inject any code into a process in regular pages, then it cannot inject any code to any EPC pages in that process either, simply because the latter depends on the former.

Security wise, it is also assumed that duplicating (both content and permissions of) an existing page within a process will not threaten the security of that process. That assumption may not always be true but in practice, the current LSM architecture doesn't seem to have that in scope, so this proposal I think still aligns with LSM in that sense.

If compared to the idea of "enclave loader inside kernel", I think this alternative is much simpler and more flexible. In particular,
* It requires minimal change to the driver - just take EPCM permissions from source pages' VMA instead of from ioctl parameter.
* It requires little change to user mode enclave loader - just mmap() enclave file in the same way as dlopen() would do, then all IMA/LSM checks applicable to shared objects will be triggered/performed transparently.
* It doesn't assume/tie to specific enclave formats.
* It is extensible - Today every regular page within a process is allowed implicitly to be the source for an EPC page. In future, if at all desirable/necessary, IMA/LSM could be extended to leave a flag somewhere (e.g. in VMA) to indicate explicitly whether a regular page (or range) could be a source for EPC. Then SGX specific hooks/policies could be supported easily.

How do you think?

-Cedric

#81 lore raw
Quoted 6 lines · Cedric

... I think an alternative could be to treat an enclave file as a regular shared object so all IMA/LSM checks could be triggered/performed as part of the loading process, then let the driver "copy" those pages to EPC. ...

If compared to the idea of "enclave loader inside kernel", I think this alternative is much simpler and more flexible. In particular,
* It requires minimal change to the driver - just take EPCM permissions from source pages' VMA instead of from ioctl parameter.
* It requires little change to user mode enclave loader - just mmap() enclave file in the same way as dlopen() would do, then all IMA/LSM checks applicable to shared objects will be triggered/performed transparently.
* It doesn't assume/tie to specific enclave formats.

It does assume a specific format, namely, that the memory layout (including page types/permissions) of the enclave can be represented in a "flat file" on disk, or at least that the enclave memory contents consist of 4096-byte chunks in that file.

Of the formats I have described in my other email, the only format that satisfies this property is the "CPU-native (instruction stream)" format which is not in use today. The ELF/PE formats in use today don't satisfy this property as the files don't contain the TCS contents. The SGXS format doesn't satisfy this property because the enclave memory is represented with 256-byte chunks.

Quoted 6 lines

* It is extensible - Today every regular page within a process is allowed implicitly to be the source for an EPC page. In future, if at all desirable/necessary, IMA/LSM could be extended to leave a flag somewhere (e.g. in VMA) to indicate explicitly whether a regular page (or range) could be a source for EPC. Then SGX specific hooks/policies could be supported easily.

How do you think?

-Cedric

--
Jethro Beekman | Fortanix

#82 lore raw
Quoted 4 lines · Jethro Beekman

It does assume a specific format, namely, that the memory layout (including page types/permissions) of the enclave can be represented in a "flat file" on disk, or at least that the enclave memory contents consist of 4096-byte chunks in that file.

I _think_ Cedric's point is that, to the kernel, /lib/x86_64-linux-gnu/libc.so.6 is a "flat file" because the kernel doesn't have any part in parsing the executable format of a shared library.

I actually don't know how it works, though. Do we just just trust that the userspace parsing of the .so format is correct? Do we just assume that any part of a file passing IMA checks can be PROT_EXEC?

#83 lore raw
Quoted 6 lines · Dave Hansen
Quoted 4 lines · Jethro Beekman

It does assume a specific format, namely, that the memory layout (including page types/permissions) of the enclave can be represented in a "flat file" on disk, or at least that the enclave memory contents consist of 4096-byte chunks in that file.

Quoted 8 lines

I _think_ Cedric's point is that, to the kernel, /lib/x86_64-linux-gnu/libc.so.6 is a "flat file" because the kernel doesn't have any part in parsing the executable format of a shared library.

I actually don't know how it works, though. Do we just just trust that the userspace parsing of the .so format is correct? Do we just assume that any part of a file passing IMA checks can be PROT_EXEC?

ELF files are explicitly designed such that you can map them (with mmap) in 4096-byte chunks. However, sometimes there's overlap and you will sometimes see that a particular offset is mapped twice because the first half of the page in the file belongs to an RX range and the second half to an R-only range. Also, ELF files don't (normally) describe stack, heap, etc. which you do need for enclaves.

--
Jethro Beekman | Fortanix

#84 lore raw

Hi Jethro,

Quoted 6 lines

ELF files are explicitly designed such that you can map them (with mmap) in 4096-byte chunks. However, sometimes there's overlap and you will sometimes see that a particular offset is mapped twice because the first half of the page in the file belongs to an RX range and the second half to an R-only range. Also, ELF files don't (normally) describe stack, heap, etc. which you do need for enclaves.

You have probably misread my email. By mmap(), I meant the enclave file would be mapped via *multiple* mmap() calls, in the same way as what dlopen() would do in loading regular shared object. The intention here is to make the enclave file subject to the same checks as regular shared objects.

The other enclave components (e.g. TCS, heap, stack, etc.) will be created from writable pages within the calling process's address space as before. Similar to heaps/stacks in a regular process, those components don't have to be backed by disk files.

The core idea is for SGX driver to "copy" not only the content but also permissions from a source page to the target EPC page. Given the existence of the source page, it can be concluded that the combination of content and permissions of that page has passed all IMA/LSM checks applicable to that page, hence "copying" that page to EPC with the same (or less) permission is *not* a circumvention of IMA/LSM policies.

-Cedric

#85 lore raw
Quoted 10 lines · Cedric

Hi Jethro,

Quoted 6 lines

ELF files are explicitly designed such that you can map them (with mmap) in 4096-byte chunks. However, sometimes there's overlap and you will sometimes see that a particular offset is mapped twice because the first half of the page in the file belongs to an RX range and the second half to an R-only range. Also, ELF files don't (normally) describe stack, heap, etc. which you do need for enclaves.

You have probably misread my email. By mmap(), I meant the enclave file would be mapped via *multiple* mmap() calls, in the same way as what dlopen() would do in loading regular shared object. The intention here is to make the enclave file subject to the same checks as regular shared objects.

No, I didn't misread your email. My original point still stands: requiring that an enclave's memory is created from one or more mmap calls of a file puts significant restrictions on the enclave's on-disk representation.

--
Jethro Beekman | Fortanix

maintainer
#86 lore raw
Quoted 11 lines · Jethro Beekman
Quoted 9 lines · Cedric

Hi Jethro,

Quoted 6 lines

ELF files are explicitly designed such that you can map them (with mmap) in 4096-byte chunks. However, sometimes there's overlap and you will sometimes see that a particular offset is mapped twice because the first half of the page in the file belongs to an RX range and the second half to an R-only range. Also, ELF files don't (normally) describe stack, heap, etc. which you do need for enclaves.

Quoted 7 lines
Quoted 1 line

You have probably misread my email. By mmap(), I meant the enclave file would be mapped via *multiple* mmap() calls, in the same way as what dlopen() would do in loading regular shared object. The intention here is to make the enclave file subject to the same checks as regular shared objects.

No, I didn't misread your email. My original point still stands:
requiring that an enclave's memory is created from one or more mmap calls of a file puts significant restrictions on the enclave's on-disk representation.

For a tiny bit of background, Linux (AFAIK*) makes no effort to ensure the complete integrity of DSOs. What Linux *does* do (if so configured) is to make sure that only approved data is mapped executable. So, if you want to have some bytes be executable, those bytes have to come from a file that passes the relevant LSM and IMA checks. So we have two valid approaches, I think.

Approach 1: we treat SGX exactly the same way and make it so that only bytes that pass the relevant checks can be mapped as code within an enclave. This imposes no particular restrictions on the file format -- we just need some API that takes an fd, an offset, and a length, and adds those bytes as code to an enclave. (It could also take a pointer and a length and make sure that the pointer points to executable memory -- same effect.)

Approach 2: we decide that we want a stronger guarantee and that we *will* ensure the integrity of the enclave. This means:

2a) that we either need to load the entire thing from some approved file, and we commit to supporting one or more file formats.

2b) we need to check that the eventual enclave hash is approved. Or we could have a much shorter file that is just the hash and we check that. At its simplest, the file could be *only* the hash, and there could be an LSM callback to check it. In the future, if someone wants to allow enclaves to be embedded in DSOs, we could have a special ELF note or similar that contains an enclave hash or similar.

2c) same as 2b except that we expose the whole SIGSTRUCT, not just the hash.

Here are some pros and cons of various bits:

1 and 2a allow anti-virus software to scan the enclave code, and 2a allows it to scan the whole enclave. I don't know if this is actually imporant.

2a is by far the most complicated kernel implementation.

2b and 2c are almost file-format agnostic. 1 is completely file format agnostic but, in exchange, it's much weaker.

2b and 2c should solve most (but not all) of the launch control complaints that Dr. Greg cares about, in the sense that the LSM policy quite literally validates that the enclave is approved.

As a straw man design, I propose the following, which is mostly 2c. The whole loading process works almost as in Jarkko's current driver, but the actual ioctl that triggers EINIT changes. When you issue the ioctl, you pass in an fd and the SIGSTRUCT is loaded and checked from the fd. The idea is that software that ships an enclave will ship a .sgxsig file that is literally a SIGSTRUCT for the enclave. With SELinux, that file gets labeled something like sgx_enclave_sigstruct_t. And we have the following extra twist: if you're calling the EADD ioctl to add *code* to the enclave, the driver checks that the code being loaded is mapped executable. This way existing code-signing policies don't get subverted, and policies that want to impose full verification on the enclave can do so by verifying the .sigstruct file.

What do you all think?

* It's certainly the case that Linux does not *succeed* at preserving the overall integrity of shared objects. If nothing else, you can freely mremap() them however you like. And you can jump into them wherever you like.

#87 lore raw

Hi Andy and Jethro,

Quoted 11 lines
Quoted 1 line
Quoted 1 line

You have probably misread my email. By mmap(), I meant the enclave

file would be mapped via *multiple* mmap() calls, in the same way as what dlopen() would do in loading regular shared object. The intention here is to make the enclave file subject to the same checks as regular shared objects.

Quoted 6 lines

No, I didn't misread your email. My original point still stands:
requiring that an enclave's memory is created from one or more mmap calls of a file puts significant restrictions on the enclave's on-disk representation.

I was talking in the context of ELF, with the assumption that changing RW pages to RX is disallowed by LSM. And in that case mmap()would be the only way to load a page from disk without having to "write" to it. But that's just an example but not the focus of the discussion.

The point I was trying to make was, that the driver is going to copy both content and permissions from the source so the security properties established (by IMA/LSM) around that source page would be carried onto the EPC page being EADD'ed. The driver doesn't care how that source page came into existence. It could be mapped from an ELF file as in the example, or it could be a result from JIT as long as LSM allows it. The driver will be file format agnostic.

Quoted 8 lines

For a tiny bit of background, Linux (AFAIK*) makes no effort to ensure the complete integrity of DSOs. What Linux *does* do (if so configured) is to make sure that only approved data is mapped executable. So, if you want to have some bytes be executable, those bytes have to come from a file that passes the relevant LSM and IMA checks. So we have two valid approaches, I think.

Quoted 7 lines

Approach 1: we treat SGX exactly the same way and make it so that only bytes that pass the relevant checks can be mapped as code within an enclave. This imposes no particular restrictions on the file format -- we just need some API that takes an fd, an offset, and a length, and adds those bytes as code to an enclave. (It could also take a pointer and a length and make sure that the pointer points to executable memory -- same effect.)

I assume "some API" is some user mode API so this approach is the same as what I suggested in my last email. Am I correct?

Quoted 14 lines

Approach 2: we decide that we want a stronger guarantee and that we *will* ensure the integrity of the enclave. This means:

2a) that we either need to load the entire thing from some approved file, and we commit to supporting one or more file formats.

2b) we need to check that the eventual enclave hash is approved. Or we could have a much shorter file that is just the hash and we check that. At its simplest, the file could be *only* the hash, and there could be an LSM callback to check it. In the future, if someone wants to allow enclaves to be embedded in DSOs, we could have a special ELF note or similar that contains an enclave hash or similar.

Quoted 8 lines

2c) same as 2b except that we expose the whole SIGSTRUCT, not just the hash.

Here are some pros and cons of various bits:

1 and 2a allow anti-virus software to scan the enclave code, and 2a allows it to scan the whole enclave. I don't know if this is actually imporant.

I guess anti-virus software can scan any enclave file in *all* cases as long as it understands the format of that enclave. It doesn't necessary mean the kernel has to understand that enclave format (as enclave file could be parsed in user mode) or the anti-virus software has to understand all formats (if any) supported natively by the kernel.

Quoted 3 lines

2a is by far the most complicated kernel implementation.

Agreed. I don't see any reason 2a would be necessary.

Quoted 2 lines

2b and 2c are almost file-format agnostic. 1 is completely file format agnostic but, in exchange, it's much weaker.

I'd say 1 and (variants of) 2 are orthogonal. SGX always enforces integrities so not doing integrity checks at EADD doesn't mean the enclave integrity is not being enforced. 1 and 2 are basically 2 different checkpoints where LSM hooks could be placed. And a given LSM implementation/policy may enforce either 1 or 2, or both, or neither.

Quoted 5 lines

2b and 2c should solve most (but not all) of the launch control complaints that Dr. Greg cares about, in the sense that the LSM policy quite literally validates that the enclave is approved.

Quoted 13 lines

As a straw man design, I propose the following, which is mostly 2c. The whole loading process works almost as in Jarkko's current driver, but the actual ioctl that triggers EINIT changes. When you issue the ioctl, you pass in an fd and the SIGSTRUCT is loaded and checked from the fd. The idea is that software that ships an enclave will ship a .sgxsig file that is literally a SIGSTRUCT for the enclave. With SELinux, that file gets labeled something like sgx_enclave_sigstruct_t. And we have the following extra twist: if you're calling the EADD ioctl to add *code* to the enclave, the driver checks that the code being loaded is mapped executable. This way existing code-signing policies don't get subverted, and policies that want to impose full verification on the enclave can do so by verifying the .sigstruct file.

I'm with you that it's desirable/necessary to add an LSM hook at EINIT, but don't see the need for .sigstruct file or its fd as input to EINIT ioctl.

Generally speaking, LSM needs to decide whether or not to launch the enclave in question. And that decision could be based upon either the enclave itself (i.e. bytes comprising the enclave, or its MRENCLAVE, or its signature, all equivalent from cryptographic standpoint), or some external attributes associated with the enclave (e.g. DAC/MAC context associated with the enclave file), or both. In the former case, what matters is the content of the SIGSTRUCT but not where it came from; while in the latter case it could be gated at open() syscall so that no fd to SIGSTRUCT (or the enclave image file) could ever be obtained by the calling process if it was not allowed to launch that enclave at all. In either case, no fd is necessary to be passed to EINIT ioctl. That said, by providing a SIGSTRUCT to EINIT ioctl, the calling process has implicitly proven its access to needed file(s) at the file system level, so only the content (i.e. MRENCLAVE or signing key) of the SIGSTRUCT needs to be checked by LSM, while the integrity of the enclave will be enforced by SGX hardware.

Quoted 3 lines

What do you all think?

I think approach 1 and (variants of) 2 are orthogonal so I wouldn't skip either to make the other mandatory from architecture perspective; while an LSM policy may opt to enforce either one, or both.

Putting everything together, I'd suggest to:
- Change EADD ioctl to take source page's VMA permission as ("upper bound" of) EPCM permission. This make sure no one can circumvent LSM to generate executable code on the fly using SGX driver.
- Change EINIT ioctl to invoke (new?) LSM hook to validate SIGSTRUCT before issuing EINIT.

Quoted 4 lines

* It's certainly the case that Linux does not *succeed* at preserving the overall integrity of shared objects. If nothing else, you can freely mremap() them however you like. And you can jump into them wherever you like.

-Cedric

maintainer
#88 lore raw
Quoted 35 lines · Cedric

Hi Andy and Jethro,

Quoted 11 lines
Quoted 1 line
Quoted 1 line

You have probably misread my email. By mmap(), I meant the enclave

file would be mapped via *multiple* mmap() calls, in the same way as what dlopen() would do in loading regular shared object. The intention here is to make the enclave file subject to the same checks as regular shared objects.

Quoted 6 lines

No, I didn't misread your email. My original point still stands:
requiring that an enclave's memory is created from one or more mmap calls of a file puts significant restrictions on the enclave's on-disk representation.

I was talking in the context of ELF, with the assumption that changing RW pages to RX is disallowed by LSM. And in that case mmap()would be the only way to load a page from disk without having to "write" to it. But that's just an example but not the focus of the discussion.

The point I was trying to make was, that the driver is going to copy both content and permissions from the source so the security properties established (by IMA/LSM) around that source page would be carried onto the EPC page being EADD'ed. The driver doesn't care how that source page came into existence. It could be mapped from an ELF file as in the example, or it could be a result from JIT as long as LSM allows it. The driver will be file format agnostic.

Quoted 8 lines

For a tiny bit of background, Linux (AFAIK*) makes no effort to ensure the complete integrity of DSOs. What Linux *does* do (if so configured) is to make sure that only approved data is mapped executable. So, if you want to have some bytes be executable, those bytes have to come from a file that passes the relevant LSM and IMA checks. So we have two valid approaches, I think.

Quoted 7 lines

Approach 1: we treat SGX exactly the same way and make it so that only bytes that pass the relevant checks can be mapped as code within an enclave. This imposes no particular restrictions on the file format -- we just need some API that takes an fd, an offset, and a length, and adds those bytes as code to an enclave. (It could also take a pointer and a length and make sure that the pointer points to executable memory -- same effect.)

Quoted 1 line

I assume "some API" is some user mode API so this approach is the same as what I suggested in my last email. Am I correct?

I meant kernel, but SGX_IOC_ADD_ENCLAVE_PAGE could be that API.

The only benefit I can see to making the kernel API take an fd instead of a pointer is that it allows loading an enclave without mapping it first, but that seems unlikely to be very important.

Quoted 18 lines
Quoted 18 lines

Approach 2: we decide that we want a stronger guarantee and that we *will* ensure the integrity of the enclave. This means:

2a) that we either need to load the entire thing from some approved file, and we commit to supporting one or more file formats.

2b) we need to check that the eventual enclave hash is approved. Or we could have a much shorter file that is just the hash and we check that. At its simplest, the file could be *only* the hash, and there could be an LSM callback to check it. In the future, if someone wants to allow enclaves to be embedded in DSOs, we could have a special ELF note or similar that contains an enclave hash or similar.

2c) same as 2b except that we expose the whole SIGSTRUCT, not just the hash.

Quoted 7 lines
Quoted 5 lines

Here are some pros and cons of various bits:

1 and 2a allow anti-virus software to scan the enclave code, and 2a allows it to scan the whole enclave. I don't know if this is actually imporant.

I guess anti-virus software can scan any enclave file in *all* cases as long as it understands the format of that enclave. It doesn't necessary mean the kernel has to understand that enclave format (as enclave file could be parsed in user mode) or the anti-virus software has to understand all formats (if any) supported natively by the kernel.

True, but in 2a it can be scanned even without understanding the format. That's probably not terribly important.

Quoted 11 lines
Quoted 4 lines

2a is by far the most complicated kernel implementation.

Agreed. I don't see any reason 2a would be necessary.

Quoted 2 lines

2b and 2c are almost file-format agnostic. 1 is completely file format agnostic but, in exchange, it's much weaker.

I'd say 1 and (variants of) 2 are orthogonal. SGX always enforces integrities so not doing integrity checks at EADD doesn't mean the enclave integrity is not being enforced. 1 and 2 are basically 2 different checkpoints where LSM hooks could be placed. And a given LSM implementation/policy may enforce either 1 or 2, or both, or neither.

They're not orthogonal in the sense that verifying the SIGSTRUCT implicitly verifies the executable contents.

Quoted 20 lines
Quoted 6 lines

2b and 2c should solve most (but not all) of the launch control complaints that Dr. Greg cares about, in the sense that the LSM policy quite literally validates that the enclave is approved.

Quoted 13 lines

As a straw man design, I propose the following, which is mostly 2c. The whole loading process works almost as in Jarkko's current driver, but the actual ioctl that triggers EINIT changes. When you issue the ioctl, you pass in an fd and the SIGSTRUCT is loaded and checked from the fd. The idea is that software that ships an enclave will ship a .sgxsig file that is literally a SIGSTRUCT for the enclave. With SELinux, that file gets labeled something like sgx_enclave_sigstruct_t. And we have the following extra twist: if you're calling the EADD ioctl to add *code* to the enclave, the driver checks that the code being loaded is mapped executable. This way existing code-signing policies don't get subverted, and policies that want to impose full verification on the enclave can do so by verifying the .sigstruct file.

Quoted 4 lines

I'm with you that it's desirable/necessary to add an LSM hook at EINIT, but don't see the need for .sigstruct file or its fd as input to EINIT ioctl.

Generally speaking, LSM needs to decide whether or not to launch the enclave in question. And that decision could be based upon either the enclave itself (i.e. bytes comprising the enclave, or its MRENCLAVE, or its signature, all equivalent from cryptographic standpoint), or some external attributes associated with the enclave (e.g. DAC/MAC context associated with the enclave file), or both. In the former case, what matters is the content of the SIGSTRUCT but not where it came from; while in the latter case it could be gated at open() syscall so that no fd to SIGSTRUCT (or the enclave image file) could ever be obtained by the calling process if it was not allowed to launch that enclave at all. In either case, no fd is necessary to be passed to EINIT ioctl. That said, by providing a SIGSTRUCT to EINIT ioctl, the calling process has implicitly proven its access to needed file(s) at the file system level, so only the content (i.e. MRENCLAVE or signing key) of the SIGSTRUCT needs to be checked by LSM, while the integrity of the enclave will be enforced by SGX hardware.

I agree with you except that there's a difference in how the configuration works. If the whole .sigstruct is in a file, then teaching your policy to accept an enclave works just like teaching your policy to accept a new ELF program -- you just put it in a file and mark the file trusted (by labeling it, for example). If the .sigstruct comes from unverifiable application memory, then an out-of-band mechanism will likely be needed.

Quoted 3 lines

Putting everything together, I'd suggest to:
- Change EADD ioctl to take source page's VMA permission as ("upper bound" of) EPCM permission. This make sure no one can circumvent LSM to generate executable code on the fly using SGX driver.
- Change EINIT ioctl to invoke (new?) LSM hook to validate SIGSTRUCT before issuing EINIT.

I'm okay with this if the consensus is that having a .sigstruct file is too annoying.

(Note that a .sigstruct file does not, strictly speaking, require that it comes from a real file. It could come from memfd, and it will then fail to load if the LSM doesn't like it. So you can still easily download and run an enclave if you think that's a good idea.)

#89 lore raw
Quoted 6 lines · Andy Lutomirski
Quoted 3 lines

Putting everything together, I'd suggest to:
- Change EADD ioctl to take source page's VMA permission as ("upper bound" of) EPCM permission. This make sure no one can circumvent LSM to generate executable code on the fly using SGX driver.
- Change EINIT ioctl to invoke (new?) LSM hook to validate SIGSTRUCT before issuing EINIT.

I'm okay with this if the consensus is that having a .sigstruct file is too annoying.

SIGSTRUCT has two nice properties from kernel perspective:

- Static structure
- Fully defines enclave contents including the page permissions as they are part of the measurement.

Making it as the "root of trust" really is the right thing and the most robust way to deal with this.

/Jarkko

A message that is not in the archive (sent off-list or not yet received): [email protected]

#91 lore raw
Quoted 8 lines · Jarkko Sakkinen

I did study through SDK's file format and realized that it does not does make sense after all to embed one.

To implement it properly you would probably need a new syscall (lets say sgx_load_enclave) and also that enclaves are not just executables binaries. It is hard to find a generic format for them as applications range from simply protecting part of an application to running a containter inside enclave.

When I looked at SDK's data structures embedded to the ELF they contain data that is also used by the run-time. Thus, run-time would anyway need to also parse the file containing the enclave.

There is not same way a single rigid structure of what executable means as for normal application and in many cases enclave could be just used to seal a portion of the code. In extreme case you might construct enclave even on run-time.

I think SIGSTRUCT in a file is the right choice. It is the lowest common denominator for enclaves that locks in its contents and is same for any enclave. Practicing access control to that file should be enough to define whatever security policy required.

I'm still puzzling what kind of changes you were discussing considering SGX_IOC_ENCLAVE_ADD_PAGE.

/Jarkko

maintainer
#92 lore raw
Quoted 5 lines · Jarkko Sakkinen
Quoted 3 lines · Jarkko Sakkinen

I did study through SDK's file format and realized that it does not does make sense after all to embed one.

Quoted 8 lines
Quoted 5 lines

To implement it properly you would probably need a new syscall (lets say sgx_load_enclave) and also that enclaves are not just executables binaries. It is hard to find a generic format for them as applications range from simply protecting part of an application to running a containter inside enclave.

I'm still puzzling what kind of changes you were discussing considering SGX_IOC_ENCLAVE_ADD_PAGE.

I think it's as simple as requiring that, if SECINFO.X is set, then the src pointer points to the appropriate number of bytes of executable memory. (Unless there's some way for an enclave to change SECINFO after the fact -- is there?) Sadly, we don't really have the a nice in-kernel API for that right now. You could do down_read(mmap_sem) and find_vma(). Arguably there is no value to checking that PKRU allows execute to the data.

Hey, Dave, if you're still paying attention to this thread, should we have copy_from_user_exec() that does the right thing wrt the page permissions and PKRU.

#93 lore raw
Quoted 13 lines · Andy Lutomirski
Quoted 11 lines · Jarkko Sakkinen
Quoted 8 lines · Jarkko Sakkinen

I did study through SDK's file format and realized that it does not does make sense after all to embed one.

To implement it properly you would probably need a new syscall (lets say sgx_load_enclave) and also that enclaves are not just executables binaries. It is hard to find a generic format for them as applications range from simply protecting part of an application to running a containter inside enclave.

Quoted 7 lines
Quoted 2 lines

I'm still puzzling what kind of changes you were discussing considering SGX_IOC_ENCLAVE_ADD_PAGE.

I think it's as simple as requiring that, if SECINFO.X is set, then the src pointer points to the appropriate number of bytes of executable memory. (Unless there's some way for an enclave to change SECINFO after the fact -- is there?)

Nit: SECINFO is just the struct passed to EADD, I think what you're really asking is "can the EPCM permissions be changed after the fact".

And the answer is, yes.

On SGX2 hardware, the enclave can extend the EPCM permissions at runtime via ENCLU[EMODPE], e.g. to make a page writable.

Hardware also doesn't prevent doing EADD to the same virtual address multiple times, e.g. an enclave could EADD a RX page, and then EADD a RW page at the same virtual address with different data. The second EADD will affect MRENCLAVE, but so long as it's accounted for by the enclave's signer, it's "legal". SGX_IOC_ENCLAVE_ADD_PAGE *does* prevent adding the "same" page to an enclave multiple times, so effectively this scenario is blocked by the current implementation, but it's more of a side effect (of a sane implementation) as opposed to deliberately preventing shenanigans.

Regarding EMODPE, the kernel doesn't rely on EPCM permissions in any way shape or form (the EPCM permissions are purely to protect the enclave from the kernel), e.g. adding +X to a page in the EPCM doesn't magically change the kernel's page tables and attempting to execute from the page will still generate a (non-SGX) #PF.

So rather than check SECINFO.X, I think we'd want to have EADD check that the permissions in SECINFO are a subset of the VMA's perms (IIUC, this is essentially what Cedric proposed). That would prevent using EMODPE to gain executable permissions, and would explicitly deny the scenario of a double EADD to load non-executable data into an executable page.

Oh, and EADD should probably also require EEXTEND for executable pages.

Quoted 7 lines

Sadly, we don't really have the a nice in-kernel API for that right now. You could do down_read(mmap_sem) and find_vma(). Arguably there is no value to checking that PKRU allows execute to the data.

Hey, Dave, if you're still paying attention to this thread, should we have copy_from_user_exec() that does the right thing wrt the page permissions and PKRU.

maintainer
#94 lore raw
Quoted 46 lines · Sean Christopherson
Quoted 13 lines · Andy Lutomirski
Quoted 11 lines · Jarkko Sakkinen
Quoted 8 lines · Jarkko Sakkinen

I did study through SDK's file format and realized that it does not does make sense after all to embed one.

To implement it properly you would probably need a new syscall (lets say sgx_load_enclave) and also that enclaves are not just executables binaries. It is hard to find a generic format for them as applications range from simply protecting part of an application to running a containter inside enclave.

Quoted 7 lines
Quoted 2 lines

I'm still puzzling what kind of changes you were discussing considering SGX_IOC_ENCLAVE_ADD_PAGE.

I think it's as simple as requiring that, if SECINFO.X is set, then the src pointer points to the appropriate number of bytes of executable memory. (Unless there's some way for an enclave to change SECINFO after the fact -- is there?)

Nit: SECINFO is just the struct passed to EADD, I think what you're really asking is "can the EPCM permissions be changed after the fact".

And the answer is, yes.

On SGX2 hardware, the enclave can extend the EPCM permissions at runtime via ENCLU[EMODPE], e.g. to make a page writable.

Hardware also doesn't prevent doing EADD to the same virtual address multiple times, e.g. an enclave could EADD a RX page, and then EADD a RW page at the same virtual address with different data. The second EADD will affect MRENCLAVE, but so long as it's accounted for by the enclave's signer, it's "legal". SGX_IOC_ENCLAVE_ADD_PAGE *does* prevent adding the "same" page to an enclave multiple times, so effectively this scenario is blocked by the current implementation, but it's more of a side effect (of a sane implementation) as opposed to deliberately preventing shenanigans.

Regarding EMODPE, the kernel doesn't rely on EPCM permissions in any way shape or form (the EPCM permissions are purely to protect the enclave from the kernel), e.g. adding +X to a page in the EPCM doesn't magically change the kernel's page tables and attempting to execute from the page will still generate a (non-SGX) #PF.

Quoted 5 lines

So rather than check SECINFO.X, I think we'd want to have EADD check that the permissions in SECINFO are a subset of the VMA's perms (IIUC, this is essentially what Cedric proposed). That would prevent using EMODPE to gain executable permissions, and would explicitly deny the scenario of a double EADD to load non-executable data into an executable page.

Let me make sure I'm understanding this correctly: when an enclave tries to execute code, it only works if *both* the EPCM and the page tables grant the access, right? This seems to be that 37.3 is trying to say. So we should probably just ignore SECINFO for these purposes.

But thinking this all through, it's a bit more complicated than any of this. Looking at the SELinux code for inspiration, there are quite a few paths, but they boil down to two cases: EXECUTE is the right to map an unmodified file executably, and EXECMOD/EXECMEM (the distinction seems mostly irrelevant) is the right to create (via mmap or mprotect) a modified anonymous file mapping or a non-file-backed mapping that is executable. So, if we do nothing, then mapping an enclave with execute permission will require either EXECUTE on the enclave inode or EXECMOD/EXECMEM, depending on exactly how this gets set up.

So all is well, sort of. The problem is that I expect there will be people who want enclaves to work in a process that does not have these rights. To make this work, we probably need do some surgery on SELinux. ISTM the act of copying (via the EADD ioctl) data from a PROT_EXEC mapping to an enclave should not be construed as "modifying" the enclave for SELinux purposes. Actually doing this could be awkward, since the same inode will have executable parts and non-executable parts, and SELinux can't really tell the difference.

Maybe the enclave should track a bitmap of which pages have ever been either mapped for write or EADDed with a *source* that wasn't PROT_EXEC. And then SELinux could learn to allow those pages (and only those pages) to be mapped executably without EXECUTE or EXECMOD or whatever permission.

Does this seem at all reasonable?

I suppose it's not the end of the world if the initially merged version doesn't do this, as long as there's some reasonable path to adding a mechanism like this when there's demand for it.

#95 lore raw

Hi Andy,

Quoted 15 lines

Let me make sure I'm understanding this correctly: when an enclave tries to execute code, it only works if *both* the EPCM and the page tables grant the access, right? This seems to be that 37.3 is trying to say. So we should probably just ignore SECINFO for these purposes.

But thinking this all through, it's a bit more complicated than any of this. Looking at the SELinux code for inspiration, there are quite a few paths, but they boil down to two cases: EXECUTE is the right to map an unmodified file executably, and EXECMOD/EXECMEM (the distinction seems mostly irrelevant) is the right to create (via mmap or mprotect) a modified anonymous file mapping or a non-file-backed mapping that is executable. So, if we do nothing, then mapping an enclave with execute permission will require either EXECUTE on the enclave inode or EXECMOD/EXECMEM, depending on exactly how this gets set up.

Quoted 9 lines

So all is well, sort of. The problem is that I expect there will be people who want enclaves to work in a process that does not have these rights. To make this work, we probably need do some surgery on SELinux. ISTM the act of copying (via the EADD ioctl) data from a PROT_EXEC mapping to an enclave should not be construed as "modifying" the enclave for SELinux purposes. Actually doing this could be awkward, since the same inode will have executable parts and non-executable parts, and SELinux can't really tell the difference.

Enclave files are pretty much like shared objects in that they both contain executable code mapped into the host process's address space. Do shared objects need EXECUTE to be mapped executable? If so, why would people not want EXECUTE in enclave files?

Wrt to which part of an executable file is executable, the limitation resides in security_mmap_file(), which doesn't take the range of bytes as input. It isn't SGX specific. I'd say just let enclaves inherit applicable checks for shared objects. Then it will also inherit all future enhancements transparently.

Quoted 5 lines

Maybe the enclave should track a bitmap of which pages have ever been either mapped for write or EADDed with a *source* that wasn't PROT_EXEC. And then SELinux could learn to allow those pages (and only those pages) to be mapped executably without EXECUTE or EXECMOD or whatever permission.

What do you mean by "enclave" here? The enclave range (ELRANGE) created by mmap()'ing /dev/sgx/enclave device? My argument is, an enclave's sanity/insanity is determined at load time (EADD/EEXTEND and EINIT) and all page accesses are enforced by EPCM, so PTE permissions really don't matter. As I discussed in an earlier email, I'd allow RWX for any range backed by /dev/sgx/enclave device file by default, unless an SGX-aware LSM module/policy objects to that (e.g. via a new security_sgx_mprotect() LSM hook).

Quoted 6 lines

Does this seem at all reasonable?

I suppose it's not the end of the world if the initially merged version doesn't do this, as long as there's some reasonable path to adding a mechanism like this when there's demand for it.

Agreed!

-Cedric

#96 lore raw
In reply to Andy Lutomirski
Quoted 54 lines · Andy Lutomirski
Quoted 46 lines · Sean Christopherson
Quoted 13 lines · Andy Lutomirski
Quoted 11 lines · Jarkko Sakkinen
Quoted 8 lines · Jarkko Sakkinen

I did study through SDK's file format and realized that it does not does make sense after all to embed one.

To implement it properly you would probably need a new syscall (lets say sgx_load_enclave) and also that enclaves are not just executables binaries. It is hard to find a generic format for them as applications range from simply protecting part of an application to running a containter inside enclave.

Quoted 7 lines
Quoted 2 lines

I'm still puzzling what kind of changes you were discussing considering SGX_IOC_ENCLAVE_ADD_PAGE.

I think it's as simple as requiring that, if SECINFO.X is set, then the src pointer points to the appropriate number of bytes of executable memory. (Unless there's some way for an enclave to change SECINFO after the fact -- is there?)

Nit: SECINFO is just the struct passed to EADD, I think what you're really asking is "can the EPCM permissions be changed after the fact".

And the answer is, yes.

On SGX2 hardware, the enclave can extend the EPCM permissions at runtime via ENCLU[EMODPE], e.g. to make a page writable.

Hardware also doesn't prevent doing EADD to the same virtual address multiple times, e.g. an enclave could EADD a RX page, and then EADD a RW page at the same virtual address with different data. The second EADD will affect MRENCLAVE, but so long as it's accounted for by the enclave's signer, it's "legal". SGX_IOC_ENCLAVE_ADD_PAGE *does* prevent adding the "same" page to an enclave multiple times, so effectively this scenario is blocked by the current implementation, but it's more of a side effect (of a sane implementation) as opposed to deliberately preventing shenanigans.

Regarding EMODPE, the kernel doesn't rely on EPCM permissions in any way shape or form (the EPCM permissions are purely to protect the enclave from the kernel), e.g. adding +X to a page in the EPCM doesn't magically change the kernel's page tables and attempting to execute from the page will still generate a (non-SGX) #PF.

Quoted 5 lines

So rather than check SECINFO.X, I think we'd want to have EADD check that the permissions in SECINFO are a subset of the VMA's perms (IIUC, this is essentially what Cedric proposed). That would prevent using EMODPE to gain executable permissions, and would explicitly deny the scenario of a double EADD to load non-executable data into an executable page.

Quoted 4 lines

Let me make sure I'm understanding this correctly: when an enclave tries to execute code, it only works if *both* the EPCM and the page tables grant the access, right? This seems to be that 37.3 is trying to say. So we should probably just ignore SECINFO for these purposes.

Yep. More specifically, the EPCM is consulted if and only if the access is allowed by the page tables.

I agree on ignoring SECINFO.

Quoted 10 lines

But thinking this all through, it's a bit more complicated than any of this. Looking at the SELinux code for inspiration, there are quite a few paths, but they boil down to two cases: EXECUTE is the right to map an unmodified file executably, and EXECMOD/EXECMEM (the distinction seems mostly irrelevant) is the right to create (via mmap or mprotect) a modified anonymous file mapping or a non-file-backed mapping that is executable. So, if we do nothing, then mapping an enclave with execute permission will require either EXECUTE on the enclave inode or EXECMOD/EXECMEM, depending on exactly how this gets set up.

If we do literally nothing, then I'm pretty sure mapping an enclave will require PROCESS__EXECMEM. The mmap() for the actual enclave is done using an anon inode, e.g. from /dev/sgx/enclave. Anon inodes are marked private, which means inode_has_perm() will always return "success". The only effective check is in file_map_prot_check() when default_noexec is true, in which case requesting PROT_EXEC on private inodes requires PROCESS__EXECMEM.

Quoted 8 lines

So all is well, sort of. The problem is that I expect there will be people who want enclaves to work in a process that does not have these rights. To make this work, we probably need do some surgery on SELinux. ISTM the act of copying (via the EADD ioctl) data from a PROT_EXEC mapping to an enclave should not be construed as "modifying" the enclave for SELinux purposes. Actually doing this could be awkward, since the same inode will have executable parts and non-executable parts, and SELinux can't really tell the difference.

Rather the do surgery on SELinux, why not go with Cedric's original proposal and propagate the permissions from the source VMA to the EPC VMA? The enclave mmap() from userspace could then be done with RO permissions so as to not run afoul of LSMs. Adding PROT_EXEC after EADD would require PROCESS__EXECMEM, but that's in line with mprotect() on regular memory. It also punts the EMODPE hiccup to userspace, e.g. any enclave that wants to do fancy things with PROT_EXEC needs PROCESS__EXECMEM.

The only downside I see is that SGX would be doing a bit of magic with enclave VMAs.

Quoted 7 lines

Maybe the enclave should track a bitmap of which pages have ever been either mapped for write or EADDed with a *source* that wasn't PROT_EXEC. And then SELinux could learn to allow those pages (and only those pages) to be mapped executably without EXECUTE or EXECMOD or whatever permission.

Does this seem at all reasonable?

No? I don't understand why you want to special case enclaves from an LSM perspective. Enforcing LSM policies on the source provides the same security for enclaves as it does for normal code, no more, no less.

Quoted 3 lines

I suppose it's not the end of the world if the initially merged version doesn't do this, as long as there's some reasonable path to adding a mechanism like this when there's demand for it.

maintainer
#97 lore raw

SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Hi, LSM and SELinux people-

We're trying to figure out how SGX fits in with LSMs. For background, an SGX library is functionally a bit like a DSO, except that it's nominally resistant to attack from outside and the process of loading it is complicated. To load an enclave, a program can open /dev/sgx/enclave, do some ioctls to load the code and data segments into the enclave, call a special ioctl to "initialize" the enclave, and then call into the enclave (using special CPU instructions).

One nastiness is that there is not actually a universally agreed upon, documented file format for enclaves. Windows has an undocumented format, and there are probably a few others out there. No one really wants to teach the kernel to parse enclave files.

There are two issues with how this interacts with LSMs:

1) LSMs might want to be able to whitelist, blacklist, or otherwise restrict what enclaves can run at all. The current proposal that everyone seems to dislike the least is to have a .sigstruct file on disk that contains a hash and signature of the enclave in a CPU-defined format. To initialize an enclave, a program will pass an fd to this file, and a new LSM hook can be called to allow or disallow the operation. In a SELinux context, the idea is that policy could require the .sigstruct file to be labeled with a type like sgx_sigstruct_t, and only enclaves that have a matching .sigstruct with such a label could run.

2) Just like any other DSO, there are potential issues with how enclaves deal with writable vs executable memory. This takes two forms. First, a task should probably require EXECMEM, EXECMOD, or similar permission to run an enclave that can modify its own text. Second, it would be nice if a task that did *not* have EXECMEM, EXECMOD, or similar could still run the enclave if it had EXECUTE permission on the file containing the enclave.

Currently, this all works because DSOs are run by mmapping the file to create multiple VMAs, some of which are executable, non-writable, and non-CoWed, and some of which are writable but not executable. With SGX, there's only really one inode per enclave (the anon_inode that comes form /dev/sgx/enclave), and it can only be sensibly mapped MAP_SHARED.

With the current version of the SGX driver, to run an enclave, I think you'll need either EXECUTE rights to /dev/sgx/enclave or EXECMOD or similar, all of which more or less mean that you can run any modified code you want, and none of which is useful to prevent enclaves from contain RWX segments.

So my question is: what, if anything, should change to make this work better?

Here's a very vague proposal that's kind of like what I've been thinking over the past few days. The SGX inode could track, for each page, a "safe-to-execute" bit. When you first open /dev/sgx/enclave, you get a blank enclave and all pages are safe-to-execute. When you do the ioctl to load context (which could be code, data, or anything else), the kernel will check whether the *source* VMA is executable and, if not, mark the page of the enclave being loaded as unsafe. Once the enclave is initialized, the driver will clear the safe-to-execute bit for any page that is successfully mapped writably.

The intent is that a page of the enclave is safe-to-execute if that page was populated from executable memory and not modified since then. LSMs could then enforce a policy that you can map an enclave page RX if the page is safe-to-execute, you can map any page you want for write if there are no executable mappings, and you can only map a page for write and execute simultaneously if you can EXECMOD permission. This should allow an enclave to be loaded by userspace from a file with EXECUTE rights.

So here are my questions:

Are the goals I mentioned reasonable?

Is the design I just outlined reasonable? Would SELinux support this?

Is there a better solution that works well enough?

Thanks, all!

Quoted 31 lines · Sean Christopherson
Quoted 12 lines

But thinking this all through, it's a bit more complicated than any of this. Looking at the SELinux code for inspiration, there are quite a few paths, but they boil down to two cases: EXECUTE is the right to map an unmodified file executably, and EXECMOD/EXECMEM (the distinction seems mostly irrelevant) is the right to create (via mmap or mprotect) a modified anonymous file mapping or a non-file-backed mapping that is executable. So, if we do nothing, then mapping an enclave with execute permission will require either EXECUTE on the enclave inode or EXECMOD/EXECMEM, depending on exactly how this gets set up.

If we do literally nothing, then I'm pretty sure mapping an enclave will require PROCESS__EXECMEM. The mmap() for the actual enclave is done using an anon inode, e.g. from /dev/sgx/enclave. Anon inodes are marked private, which means inode_has_perm() will always return "success". The only effective check is in file_map_prot_check() when default_noexec is true, in which case requesting PROT_EXEC on private inodes requires PROCESS__EXECMEM.

Quoted 8 lines

So all is well, sort of. The problem is that I expect there will be people who want enclaves to work in a process that does not have these rights. To make this work, we probably need do some surgery on SELinux. ISTM the act of copying (via the EADD ioctl) data from a PROT_EXEC mapping to an enclave should not be construed as "modifying" the enclave for SELinux purposes. Actually doing this could be awkward, since the same inode will have executable parts and non-executable parts, and SELinux can't really tell the difference.

Quoted 3 lines

Rather the do surgery on SELinux, why not go with Cedric's original proposal and propagate the permissions from the source VMA to the EPC VMA?

Which EPC VMA? Users can map the enclave fd again after EADD, resulting in a new VMA. And any realistic enclave will presumably have RO, RW, and RX pages.

Quoted 4 lines

The enclave mmap() from userspace could then be done with RO
permissions so as to not run afoul of LSMs. Adding PROT_EXEC after EADD would require PROCESS__EXECMEM, but that's in line with mprotect() on regular memory.

How does this help anything? The driver currently only works with EXECMEM and, with this change, it still needs EXECMEM.

I think that, if we’re going to make changes along these lines, the goal should be that you can have an enclave serialized in a file on disk such that you have EXECUTE on the file, and you should be able to load and run the enclave without needing EXECMEM. (Unless the enclave is self-modifying, of course.)

maintainer
#98 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 12 lines · Andy Lutomirski

There are two issues with how this interacts with LSMs:

1) LSMs might want to be able to whitelist, blacklist, or otherwise restrict what enclaves can run at all. The current proposal that everyone seems to dislike the least is to have a .sigstruct file on disk that contains a hash and signature of the enclave in a CPU-defined format. To initialize an enclave, a program will pass an fd to this file, and a new LSM hook can be called to allow or disallow the operation. In a SELinux context, the idea is that policy could require the .sigstruct file to be labeled with a type like sgx_sigstruct_t, and only enclaves that have a matching .sigstruct with such a label could run.

The .sigstruct file is for the CPU to consume, not the kernel correct?

How is it bound to the enclave file?

Why not just use an xattr, like security.sgx ?

Quoted 16 lines

2) Just like any other DSO, there are potential issues with how enclaves deal with writable vs executable memory. This takes two forms. First, a task should probably require EXECMEM, EXECMOD, or similar permission to run an enclave that can modify its own text. Second, it would be nice if a task that did *not* have EXECMEM, EXECMOD, or similar could still run the enclave if it had EXECUTE permission on the file containing the enclave.

Currently, this all works because DSOs are run by mmapping the file to create multiple VMAs, some of which are executable, non-writable, and non-CoWed, and some of which are writable but not executable. With SGX, there's only really one inode per enclave (the anon_inode that comes form /dev/sgx/enclave), and it can only be sensibly mapped MAP_SHARED.

Quoted 7 lines

With the current version of the SGX driver, to run an enclave, I think you'll need either EXECUTE rights to /dev/sgx/enclave or EXECMOD or similar, all of which more or less mean that you can run any modified code you want, and none of which is useful to prevent enclaves from contain RWX segments.

So my question is: what, if anything, should change to make this work better?

Would it be possible to provide multiple fds (perhaps via a pseudo fs interface) which can be mapped to different types of VMAs?

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

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 17 lines · James Morris
Quoted 12 lines · Andy Lutomirski

There are two issues with how this interacts with LSMs:

1) LSMs might want to be able to whitelist, blacklist, or otherwise restrict what enclaves can run at all. The current proposal that everyone seems to dislike the least is to have a .sigstruct file on disk that contains a hash and signature of the enclave in a CPU-defined format. To initialize an enclave, a program will pass an fd to this file, and a new LSM hook can be called to allow or disallow the operation. In a SELinux context, the idea is that policy could require the .sigstruct file to be labeled with a type like sgx_sigstruct_t, and only enclaves that have a matching .sigstruct with such a label could run.

Quoted 1 line

The .sigstruct file is for the CPU to consume, not the kernel correct?

Yes, unless an LSM wants to examine it to make a decision.

Quoted 2 lines

How is it bound to the enclave file?

It's not bound to the enclave *file* at all, but it contains a hash that covers the enclave, so two different files in two different formats representing exactly the same enclave would get the same hash, but any change to the enclave would get a different hash.

Quoted 2 lines

Why not just use an xattr, like security.sgx ?

Wouldn't this make it so that only someone with CAP_MAC_ADMIN could install an enclave? I think that this decision should be left up the administrator, and it should be easy to set up a loose policy where anyone can load whatever enclave they want. That's what would happen in my proposal if there was no LSM loaded or of the LSM policy didn't restrict what .sigstruct files were acceptable.

Quoted 23 lines
Quoted 23 lines

2) Just like any other DSO, there are potential issues with how enclaves deal with writable vs executable memory. This takes two forms. First, a task should probably require EXECMEM, EXECMOD, or similar permission to run an enclave that can modify its own text. Second, it would be nice if a task that did *not* have EXECMEM, EXECMOD, or similar could still run the enclave if it had EXECUTE permission on the file containing the enclave.

Currently, this all works because DSOs are run by mmapping the file to create multiple VMAs, some of which are executable, non-writable, and non-CoWed, and some of which are writable but not executable. With SGX, there's only really one inode per enclave (the anon_inode that comes form /dev/sgx/enclave), and it can only be sensibly mapped MAP_SHARED.

With the current version of the SGX driver, to run an enclave, I think you'll need either EXECUTE rights to /dev/sgx/enclave or EXECMOD or similar, all of which more or less mean that you can run any modified code you want, and none of which is useful to prevent enclaves from contain RWX segments.

Quoted 4 lines
Quoted 1 line

So my question is: what, if anything, should change to make this work better?

Would it be possible to provide multiple fds (perhaps via a pseudo fs interface) which can be mapped to different types of VMAs?

Maybe. The tricky bit is that, even if there was a separate inode for the writable and the executable parts of the enclave, I think that both would have to be mapped MAP_SHARED since MAP_ANONYMOUS is nonsensical for SGX. This would certainly push more complexity into the user code. Jarkko?

maintainer
#100 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 9 lines · Andy Lutomirski
Quoted 1 line

Why not just use an xattr, like security.sgx ?

Wouldn't this make it so that only someone with CAP_MAC_ADMIN could install an enclave? I think that this decision should be left up the administrator, and it should be easy to set up a loose policy where anyone can load whatever enclave they want. That's what would happen in my proposal if there was no LSM loaded or of the LSM policy didn't restrict what .sigstruct files were acceptable.

You could try user.sigstruct, which does not require any privs.

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

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 13 lines · James Morris
Quoted 9 lines · Andy Lutomirski
Quoted 1 line

Why not just use an xattr, like security.sgx ?

Wouldn't this make it so that only someone with CAP_MAC_ADMIN could install an enclave? I think that this decision should be left up the administrator, and it should be easy to set up a loose policy where anyone can load whatever enclave they want. That's what would happen in my proposal if there was no LSM loaded or of the LSM policy didn't restrict what .sigstruct files were acceptable.

Quoted 2 lines

You could try user.sigstruct, which does not require any privs.

I don't think I understand your proposal. What file would this attribute be on? What would consume it?

I'm imagining that there's some enclave in a file crypto_thingy.enclave. There's also a file crypto_thingy.sigstruct. crypto_thingy.enclave has type lib_t or similar so that it's executable. crypto_thingy.sigstruct has type sgx_sigstruct_t. The enclave loader does, in effect:

void *source_data = mmap(crypto_thingy.enclave, PROT_READ | PROT_EXEC, ...); int sigstruct_fd = open("crypto_thingy.sigstruct", O_RDONLY); int enclave_fd = open("/dev/sgx/enclave", O_RDWR);

ioctl(enclave_fd, SGX_IOC_ADD_SOME_DATA, source_data + source_offset, enclave_offset, len, ...);
ioctl(enclave_fd, SGX_IOC_ADD_SOME_DATA, source_data + source_offset2, enclave_offset2, len, ...);
etc.

/* Here's where LSMs get to check that the sigstruct is acceptable. The CPU will check that the sigstruct matches the enclave. */ ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, sigstruct_fd);

/* Actually map the thing */
mmap(enclave_fd RO section, PROT_READ, ...); mmap(enclave_fd RW section, PROT_READ | PROT_WRITE, ...); mmap(enclave_fd RX section, PROT_READ | PROT_EXEC, ...);

/* This should fail unless EXECMOD is available, I think */ mmap(enclave_fd RWX section, PROT_READ | PROT_WRITE | PROT_EXEC);

And the idea here is that, if the .enclave file isn't mapped PROT_EXEC, then mmapping the RX section will also require EXECMEM or EXECMOD.

#102 lore raw

RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Hi Andy,

Quoted 38 lines

From: Andy Lutomirski [mailto:[email protected]]

Quoted 13 lines · James Morris
Quoted 9 lines · Andy Lutomirski
Quoted 1 line

Why not just use an xattr, like security.sgx ?

Wouldn't this make it so that only someone with CAP_MAC_ADMIN could install an enclave? I think that this decision should be left up the administrator, and it should be easy to set up a loose policy where anyone can load whatever enclave they want. That's what would happen in my proposal if there was no LSM loaded or of the LSM policy didn't restrict what .sigstruct files were acceptable.

Quoted 2 lines

You could try user.sigstruct, which does not require any privs.

I don't think I understand your proposal. What file would this attribute be on? What would consume it?

I'm imagining that there's some enclave in a file crypto_thingy.enclave. There's also a file crypto_thingy.sigstruct. crypto_thingy.enclave has type lib_t or similar so that it's executable. crypto_thingy.sigstruct has type sgx_sigstruct_t. The enclave loader does, in effect:

void *source_data = mmap(crypto_thingy.enclave, PROT_READ | PROT_EXEC, ...); int sigstruct_fd = open("crypto_thingy.sigstruct", O_RDONLY); int enclave_fd = open("/dev/sgx/enclave", O_RDWR);

ioctl(enclave_fd, SGX_IOC_ADD_SOME_DATA, source_data + source_offset, enclave_offset, len, ...);
ioctl(enclave_fd, SGX_IOC_ADD_SOME_DATA, source_data + source_offset2, enclave_offset2, len, ...);
etc.

Quoted 3 lines

/* Here's where LSMs get to check that the sigstruct is acceptable. The CPU will check that the sigstruct matches the enclave. */ ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, sigstruct_fd);

SIGSTRUCT isn't necessarily stored on disk so may not always have a fd. How about the following? void *ss_pointer = mmap(sigstruct_fd, PROT_READ,...);
ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, ss_pointer);

The idea here is SIGSTRUCT will still be passed in memory so it works the same way when no LSM modules are loaded or basing its decision on the .sigstruct file. Otherwise, an LSM module can figure out the backing file (and offset within that file) by looking into the VMA covering ss_pointer.

Quoted 6 lines

/* Actually map the thing */
mmap(enclave_fd RO section, PROT_READ, ...); mmap(enclave_fd RW section, PROT_READ | PROT_WRITE, ...); mmap(enclave_fd RX section, PROT_READ | PROT_EXEC, ...);

Quoted 6 lines

/* This should fail unless EXECMOD is available, I think */ mmap(enclave_fd RWX section, PROT_READ | PROT_WRITE | PROT_EXEC);

And the idea here is that, if the .enclave file isn't mapped PROT_EXEC, then mmapping the RX section will also require EXECMEM or EXECMOD.

From security perspective, I think it reasonable to give EXECMEM and EXECMOD to /dev/sgx/enclave because the actual permissions are guarded by EPCM permissions, which are "inherited" from the source pages, whose permissions have passed LSM checks.

Alternatively, I think we could mark enclave VMAs somewhat differently, such as defining a new VM_SGX flag. The reason behind that is, enclave ranges differ from "regular" virtual ranges in terms of both functionality (i.e. #PF will have to be handled quite differently) and security, so I believe demand will come up to distinguish them eventually - e.g., LSM modules can then enforce different policies on them (by a new security_sgx_mprot() hook?).

-Cedric

maintainer
#103 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 46 lines · Cedric

Hi Andy,

Quoted 38 lines

From: Andy Lutomirski [mailto:[email protected]]

Quoted 14 lines · James Morris
Quoted 9 lines · Andy Lutomirski
Quoted 1 line

Why not just use an xattr, like security.sgx ?

Wouldn't this make it so that only someone with CAP_MAC_ADMIN could install an enclave? I think that this decision should be left up the administrator, and it should be easy to set up a loose policy where anyone can load whatever enclave they want. That's what would happen in my proposal if there was no LSM loaded or of the LSM policy didn't restrict what .sigstruct files were acceptable.

Quoted 2 lines

You could try user.sigstruct, which does not require any privs.

I don't think I understand your proposal. What file would this attribute be on? What would consume it?

I'm imagining that there's some enclave in a file crypto_thingy.enclave. There's also a file crypto_thingy.sigstruct. crypto_thingy.enclave has type lib_t or similar so that it's executable. crypto_thingy.sigstruct has type sgx_sigstruct_t. The enclave loader does, in effect:

void *source_data = mmap(crypto_thingy.enclave, PROT_READ | PROT_EXEC, ...); int sigstruct_fd = open("crypto_thingy.sigstruct", O_RDONLY); int enclave_fd = open("/dev/sgx/enclave", O_RDWR);

ioctl(enclave_fd, SGX_IOC_ADD_SOME_DATA, source_data + source_offset, enclave_offset, len, ...);
ioctl(enclave_fd, SGX_IOC_ADD_SOME_DATA, source_data + source_offset2, enclave_offset2, len, ...);
etc.

Quoted 3 lines

/* Here's where LSMs get to check that the sigstruct is acceptable. The CPU will check that the sigstruct matches the enclave. */ ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, sigstruct_fd);

Quoted 5 lines

SIGSTRUCT isn't necessarily stored on disk so may not always have a fd. How about the following? void *ss_pointer = mmap(sigstruct_fd, PROT_READ,...);
ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, ss_pointer);

The idea here is SIGSTRUCT will still be passed in memory so it works the same way when no LSM modules are loaded or basing its decision on the .sigstruct file. Otherwise, an LSM module can figure out the backing file (and offset within that file) by looking into the VMA covering ss_pointer.

I don’t love this approach. Application authors seem likely to use read() instead of mmap(), and it’ll still work in many cares. It would also complicate the kernel implementation, and looking at the inode backing the vma that backs a pointer is at least rather unusual. Instead, if the sigstruct isn’t on disk because it’s dynamic or came from a network, the application can put it in a memfd.

Quoted 7 lines
Quoted 7 lines

/* Actually map the thing */
mmap(enclave_fd RO section, PROT_READ, ...); mmap(enclave_fd RW section, PROT_READ | PROT_WRITE, ...); mmap(enclave_fd RX section, PROT_READ | PROT_EXEC, ...);

Quoted 8 lines
Quoted 6 lines

/* This should fail unless EXECMOD is available, I think */ mmap(enclave_fd RWX section, PROT_READ | PROT_WRITE | PROT_EXEC);

And the idea here is that, if the .enclave file isn't mapped PROT_EXEC, then mmapping the RX section will also require EXECMEM or EXECMOD.

From security perspective, I think it reasonable to give EXECMEM and EXECMOD to /dev/sgx/enclave because the actual permissions are guarded by EPCM permissions, which are "inherited" from the source pages, whose permissions have passed LSM checks.

I disagree. If you deny a program EXECMOD, it’s not because you distrust the program. It’s because you want to enforce good security practices. (Or you’re Apple and want to disallow third-party JITs.) A policy that accepts any sigstruct but requires that enclaves come from disk and respect W^X seems entirely reasonable.

I think that blocking EXECMOD has likely served two very real security purposes. It helps force application and library developers to write and compile their code in a way that doesn’t rely on dangerous tricks like putting executable trampolines on the stack. It also makes it essentially impossible for an exploit to run actual downloaded machine code — if there is no way to run code that isn’t appropriately labeled, then attackers are more limited in what they can do.

I don’t think that SGX should become an exception to either of these. Code should not have an excuse to use WX memory just because it’s in an enclave. Similarly, an exploit should not be able to run an attacker-supplied enclave as a way around a policy that would otherwise prevent downloaded code from running.

—Andy

#104 lore raw

RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Hi Andy,

Quoted 11 lines
Quoted 1 line

SIGSTRUCT isn't necessarily stored on disk so may not always have a fd.

How about the following?

Quoted 4 lines

void *ss_pointer = mmap(sigstruct_fd, PROT_READ,...); ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, ss_pointer);

The idea here is SIGSTRUCT will still be passed in memory so it works

the same way when no LSM modules are loaded or basing its decision on the .sigstruct file. Otherwise, an LSM module can figure out the backing file (and offset within that file) by looking into the VMA covering ss_pointer.

Quoted 6 lines

I don’t love this approach. Application authors seem likely to use read() instead of mmap(), and it’ll still work in many cares. It would also complicate the kernel implementation, and looking at the inode backing the vma that backs a pointer is at least rather unusual. Instead, if the sigstruct isn’t on disk because it’s dynamic or came from a network, the application can put it in a memfd.

I understand your concern here. But I guess we are making too much assumption on how enclaves are structured/packaged. My concern is, what if a SIGSTRUCT really has to be from memory? For example, an enclave (along with its SIGSTRUCT) could be embedded inside a shared object (or even the "main" executable) so it shows up in memory to begin with. Of course it could be copied to a memfd but whatever "attributes" (e.g. path, or SELinux class/type) associated with the original file would be lost, so I'm not sure if that would work.

I'm also with you that applications tend to use read() instead of mmap() for accessing files. But in our case that'd be necessary only if .sigstruct is a separate file (hence needs to be read separately). What if (and I guess most implementations would) the SIGSTRUCT is embedded in the same file as the enclave? mmap() is the more common practice when dealing with executable images, and in that case SIGSTRUCT will have already been mmap()'d.

I'm with you again that it's kind of unprecedented to look at the backing inode. But I believe we should strive to allow as large variety of applications/usages as possible and I don't see any alternatives without losing flexibility.

Quoted 34 lines
Quoted 7 lines
Quoted 7 lines

/* Actually map the thing */
mmap(enclave_fd RO section, PROT_READ, ...); mmap(enclave_fd RW section, PROT_READ | PROT_WRITE, ...); mmap(enclave_fd RX section, PROT_READ | PROT_EXEC, ...);

Quoted 8 lines
Quoted 6 lines

/* This should fail unless EXECMOD is available, I think */ mmap(enclave_fd RWX section, PROT_READ | PROT_WRITE | PROT_EXEC);

And the idea here is that, if the .enclave file isn't mapped PROT_EXEC, then mmapping the RX section will also require EXECMEM or EXECMOD.

From security perspective, I think it reasonable to give EXECMEM and

EXECMOD to /dev/sgx/enclave because the actual permissions are guarded by EPCM permissions, which are "inherited" from the source pages, whose permissions have passed LSM checks.

I disagree. If you deny a program EXECMOD, it’s not because you distrust the program. It’s because you want to enforce good security practices. (Or you’re Apple and want to disallow third-party JITs.) A policy that accepts any sigstruct but requires that enclaves come from disk and respect W^X seems entirely reasonable.

I think that blocking EXECMOD has likely served two very real security purposes. It helps force application and library developers to write and compile their code in a way that doesn’t rely on dangerous tricks like putting executable trampolines on the stack. It also makes it essentially impossible for an exploit to run actual downloaded machine code — if there is no way to run code that isn’t appropriately labeled, then attackers are more limited in what they can do.

Quoted 5 lines

I don’t think that SGX should become an exception to either of these. Code should not have an excuse to use WX memory just because it’s in an enclave. Similarly, an exploit should not be able to run an attacker-supplied enclave as a way around a policy that would otherwise prevent downloaded code from running.

My apology for the confusion here.

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

I was not saying enclaves were exempt to good security practices. What I was trying to say was, EPC pages are *not* subject to the same attacks as regular pages so I suspect there will be a desire to enforce different policies on them, especially after new SGX2 features/applications become available. So I think it beneficial to distinguish between regular vs. enclave virtual ranges. And to do that, a new VM_SGX flag in VMA is probably a very simple/easy way. And with that VM_SGX flag, we could add a new security_sgx_mprot() hook so that LSM modules/policies could act differently.

And if you are with me on that bigger picture, the next question is: what should be the default behavior of security_sgx_mprot() for existing/non-SGX-aware LSM modules/policies? I'd say a reasonable default is to allow R, RW and RX, but not anything else. It'd suffice to get rid of EXECMEM/EXECMOD requirements on enclave applications. For SGX1, EPCM permissions are immutable so it really doesn't matter what security_sgx_mprot() does. For SGX2 and beyond, there's still time and new SGX-aware LSM modules/policies will probably have emerged by then.

-Cedric

maintainer
#105 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 14 lines · Cedric

Hi Andy,

Quoted 11 lines
Quoted 1 line

SIGSTRUCT isn't necessarily stored on disk so may not always have a fd.

How about the following?

Quoted 4 lines

void *ss_pointer = mmap(sigstruct_fd, PROT_READ,...); ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, ss_pointer);

The idea here is SIGSTRUCT will still be passed in memory so it works

the same way when no LSM modules are loaded or basing its decision on the .sigstruct file. Otherwise, an LSM module can figure out the backing file (and offset within that file) by looking into the VMA covering ss_pointer.

Quoted 8 lines
Quoted 6 lines

I don’t love this approach. Application authors seem likely to use read() instead of mmap(), and it’ll still work in many cares. It would also complicate the kernel implementation, and looking at the inode backing the vma that backs a pointer is at least rather unusual. Instead, if the sigstruct isn’t on disk because it’s dynamic or came from a network, the application can put it in a memfd.

I understand your concern here. But I guess we are making too much assumption on how enclaves are structured/packaged. My concern is, what if a SIGSTRUCT really has to be from memory? For example, an enclave (along with its SIGSTRUCT) could be embedded inside a shared object (or even the "main" executable) so it shows up in memory to begin with.

Hmm. That's a fair point, although opening /proc/self/exe could be somewhat of a workaround. It does suffer from a bit of an in-band signaling problem, though, in that it's possible that some other random bytes in the library resemble a SIGSTRUCT.

Quoted 1 line

I was not saying enclaves were exempt to good security practices. What I was trying to say was, EPC pages are *not* subject to the same attacks as regular pages so I suspect there will be a desire to enforce different policies on them, especially after new SGX2 features/applications become available. So I think it beneficial to distinguish between regular vs. enclave virtual ranges. And to do that, a new VM_SGX flag in VMA is probably a very simple/easy way. And with that VM_SGX flag, we could add a new security_sgx_mprot() hook so that LSM modules/policies could act differently.

I'm not opposed to this, but I also don't think this needs to be in the initial upstream driver. VM_SGX also isn't strictly necessary -- an LSM could inspect the VMA to decide whether it's an SGX VMA if it really wanted to.

That being said, do you have any specific behavior differences in mind aside from the oddities involved in loading the enclave.

Quoted 2 lines

And if you are with me on that bigger picture, the next question is: what should be the default behavior of security_sgx_mprot() for existing/non-SGX-aware LSM modules/policies? I'd say a reasonable default is to allow R, RW and RX, but not anything else. It'd suffice to get rid of EXECMEM/EXECMOD requirements on enclave applications. For SGX1, EPCM permissions are immutable so it really doesn't matter what security_sgx_mprot() does. For SGX2 and beyond, there's still time and new SGX-aware LSM modules/policies will probably have emerged by then.

I hadn't thought about the SGX1 vs SGX2 difference. If the driver initially only wants to support SGX1, then I guess we really could get away with constraining the EPC flags based on the source page permission and not restricting mprotect() and mmap() permissions on /dev/sgx/enclave at all.

#106 lore raw

RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 49 lines

From: Andy Lutomirski [mailto:[email protected]]

Quoted 4 lines · Cedric

Hi Andy,

Quoted 1 line
Quoted 1 line

SIGSTRUCT isn't necessarily stored on disk so may not always have

a fd.

Quoted 11 lines
Quoted 11 lines

How about the following?

Quoted 5 lines

void *ss_pointer = mmap(sigstruct_fd, PROT_READ,...); ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, ss_pointer);

The idea here is SIGSTRUCT will still be passed in memory so it works

the same way when no LSM modules are loaded or basing its decision on the .sigstruct file. Otherwise, an LSM module can figure out the backing file (and offset within that file) by looking into the VMA covering ss_pointer.

Quoted 4 lines
Quoted 4 lines

I don’t love this approach. Application authors seem likely to use read() instead of mmap(), and it’ll still work in many cares. It would also complicate the kernel implementation, and looking at the inode backing the vma that backs a pointer is at least rather

unusual.

Quoted 4 lines
Quoted 2 lines

Instead, if the sigstruct isn’t on disk because it’s dynamic or came from a network, the application can put it in a memfd.

I understand your concern here. But I guess we are making too much

assumption on how enclaves are structured/packaged. My concern is, what if a SIGSTRUCT really has to be from memory? For example, an enclave (along with its SIGSTRUCT) could be embedded inside a shared object (or even the "main" executable) so it shows up in memory to begin with.

Hmm. That's a fair point, although opening /proc/self/exe could be somewhat of a workaround. It does suffer from a bit of an in-band signaling problem, though, in that it's possible that some other random bytes in the library resemble a SIGSTRUCT.

Quoted 1 line

I was not saying enclaves were exempt to good security practices. What

I was trying to say was, EPC pages are *not* subject to the same attacks as regular pages so I suspect there will be a desire to enforce different policies on them, especially after new SGX2 features/applications become available. So I think it beneficial to distinguish between regular vs. enclave virtual ranges. And to do that, a new VM_SGX flag in VMA is probably a very simple/easy way. And with that VM_SGX flag, we could add a new security_sgx_mprot() hook so that LSM modules/policies could act differently.

Quoted 4 lines

I'm not opposed to this, but I also don't think this needs to be in the initial upstream driver. VM_SGX also isn't strictly necessary -- an LSM could inspect the VMA to decide whether it's an SGX VMA if it really wanted to.

VM_SGX is just what I think is the easiest way for any module to tell enclave VMAs from all others. I agree totally with you that doesn't have to be in the initial release!

Quoted 3 lines

That being said, do you have any specific behavior differences in mind aside from the oddities involved in loading the enclave.

The major thing is dynamically linked enclaves. Say if you want something like dlopen() inside an enclave, the driver would need to EAUG a page as RW initially, and then change to RX after it has been EACCEPTCOPY'ed by the enclave. So it's like a RW->RX transition and an LSM module/policy may want to allow it only if it's within an enclave range (ELRANGE), or deny it otherwise.

Quoted 11 lines
Quoted 3 lines

And if you are with me on that bigger picture, the next question is:

what should be the default behavior of security_sgx_mprot() for existing/non-SGX-aware LSM modules/policies? I'd say a reasonable default is to allow R, RW and RX, but not anything else. It'd suffice to get rid of EXECMEM/EXECMOD requirements on enclave applications. For SGX1, EPCM permissions are immutable so it really doesn't matter what security_sgx_mprot() does. For SGX2 and beyond, there's still time and new SGX-aware LSM modules/policies will probably have emerged by then.

Quoted 5 lines

I hadn't thought about the SGX1 vs SGX2 difference. If the driver initially only wants to support SGX1, then I guess we really could get away with constraining the EPC flags based on the source page permission and not restricting mprotect() and mmap() permissions on /dev/sgx/enclave at all.

This is exactly what I'm going after!

But I have to apologize for this silly question because I don't know much about SELinux: Wouldn't it require changes to existing SELinux policies to *not* restrict mprotect() on /dev/sgx/enclave?

-Cedric

maintainer
#107 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 55 lines · Cedric
Quoted 50 lines

From: Andy Lutomirski [mailto:[email protected]]

Quoted 4 lines · Cedric

Hi Andy,

Quoted 1 line
Quoted 1 line

SIGSTRUCT isn't necessarily stored on disk so may not always have

a fd.

Quoted 11 lines
Quoted 11 lines

How about the following?

Quoted 5 lines

void *ss_pointer = mmap(sigstruct_fd, PROT_READ,...); ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, ss_pointer);

The idea here is SIGSTRUCT will still be passed in memory so it works

the same way when no LSM modules are loaded or basing its decision on the .sigstruct file. Otherwise, an LSM module can figure out the backing file (and offset within that file) by looking into the VMA covering ss_pointer.

Quoted 4 lines
Quoted 4 lines

I don’t love this approach. Application authors seem likely to use read() instead of mmap(), and it’ll still work in many cares. It would also complicate the kernel implementation, and looking at the inode backing the vma that backs a pointer is at least rather

unusual.

Quoted 4 lines
Quoted 2 lines

Instead, if the sigstruct isn’t on disk because it’s dynamic or came from a network, the application can put it in a memfd.

I understand your concern here. But I guess we are making too much

assumption on how enclaves are structured/packaged. My concern is, what if a SIGSTRUCT really has to be from memory? For example, an enclave (along with its SIGSTRUCT) could be embedded inside a shared object (or even the "main" executable) so it shows up in memory to begin with.

Hmm. That's a fair point, although opening /proc/self/exe could be somewhat of a workaround. It does suffer from a bit of an in-band signaling problem, though, in that it's possible that some other random bytes in the library resemble a SIGSTRUCT.

Quoted 1 line

I was not saying enclaves were exempt to good security practices. What

I was trying to say was, EPC pages are *not* subject to the same attacks as regular pages so I suspect there will be a desire to enforce different policies on them, especially after new SGX2 features/applications become available. So I think it beneficial to distinguish between regular vs. enclave virtual ranges. And to do that, a new VM_SGX flag in VMA is probably a very simple/easy way. And with that VM_SGX flag, we could add a new security_sgx_mprot() hook so that LSM modules/policies could act differently.

Quoted 4 lines

I'm not opposed to this, but I also don't think this needs to be in the initial upstream driver. VM_SGX also isn't strictly necessary -- an LSM could inspect the VMA to decide whether it's an SGX VMA if it really wanted to.

Quoted 7 lines

VM_SGX is just what I think is the easiest way for any module to tell enclave VMAs from all others. I agree totally with you that doesn't have to be in the initial release!

Quoted 3 lines

That being said, do you have any specific behavior differences in mind aside from the oddities involved in loading the enclave.

The major thing is dynamically linked enclaves. Say if you want something like dlopen() inside an enclave, the driver would need to EAUG a page as RW initially, and then change to RX after it has been EACCEPTCOPY'ed by the enclave. So it's like a RW->RX transition and an LSM module/policy may want to allow it only if it's within an enclave range (ELRANGE), or deny it otherwise.

I'm not convinced. Given that the kernel has no way to tell that the dynamically loaded code wasn't dynamically generated, I don't think it makes sense to allow this in an enclave but disallow it outside an enclave.

Quoted 18 lines
Quoted 12 lines
Quoted 4 lines

And if you are with me on that bigger picture, the next question is:

what should be the default behavior of security_sgx_mprot() for existing/non-SGX-aware LSM modules/policies? I'd say a reasonable default is to allow R, RW and RX, but not anything else. It'd suffice to get rid of EXECMEM/EXECMOD requirements on enclave applications. For SGX1, EPCM permissions are immutable so it really doesn't matter what security_sgx_mprot() does. For SGX2 and beyond, there's still time and new SGX-aware LSM modules/policies will probably have emerged by then.

Quoted 5 lines

I hadn't thought about the SGX1 vs SGX2 difference. If the driver initially only wants to support SGX1, then I guess we really could get away with constraining the EPC flags based on the source page permission and not restricting mprotect() and mmap() permissions on /dev/sgx/enclave at all.

Quoted 3 lines

This is exactly what I'm going after!

But I have to apologize for this silly question because I don't know much about SELinux: Wouldn't it require changes to existing SELinux policies to *not* restrict mprotect() on /dev/sgx/enclave?

I'm assuming we'd make a small in-kernel change to SELinux to make it work without policy changes, assuming the SELinux maintainers would be okay with this.

#108 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Andy Lutomirski
Quoted 10 lines · Andy Lutomirski
Quoted 8 lines · Cedric

And if you are with me on that bigger picture, the next question is: what should be the default behavior of security_sgx_mprot() for existing/non-SGX-aware LSM modules/policies? I'd say a reasonable default is to allow R, RW and RX, but not anything else. It'd suffice to get rid of EXECMEM/EXECMOD requirements on enclave applications. For SGX1, EPCM permissions are immutable so it really doesn't matter what security_sgx_mprot() does. For SGX2 and beyond, there's still time and new SGX-aware LSM modules/policies will probably have emerged by then.

Quoted 5 lines

I hadn't thought about the SGX1 vs SGX2 difference. If the driver initially only wants to support SGX1, then I guess we really could get away with constraining the EPC flags based on the source page permission and not restricting mprotect() and mmap() permissions on /dev/sgx/enclave at all.

No, SGX1 vs SGX2 support in the kernel is irrelevant. Well, unless the driver simply refuses to load on SGX2 hardware, but I don't think anyone wants to go that route. There is no enabling or attribute bit required to execute ENCLU[EMODPE], e.g. an enclave can effect RW->RWX in the EPCM on SGX2 hardware regardless of what the kernel is doing.

IMO the kernel should ignore the EPCM from an LSM perspective.

#109 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Xing, Cedric
Quoted 66 lines · Cedric

Hi Andy,

Quoted 11 lines
Quoted 1 line

SIGSTRUCT isn't necessarily stored on disk so may not always have a fd.

How about the following?

Quoted 4 lines

void *ss_pointer = mmap(sigstruct_fd, PROT_READ,...); ioctl(enclave_fd, SGX_INIT_THE_ENCLAVE, ss_pointer);

The idea here is SIGSTRUCT will still be passed in memory so it works

the same way when no LSM modules are loaded or basing its decision on the .sigstruct file. Otherwise, an LSM module can figure out the backing file (and offset within that file) by looking into the VMA covering ss_pointer.

Quoted 6 lines

I don’t love this approach. Application authors seem likely to use read() instead of mmap(), and it’ll still work in many cares. It would also complicate the kernel implementation, and looking at the inode backing the vma that backs a pointer is at least rather unusual. Instead, if the sigstruct isn’t on disk because it’s dynamic or came from a network, the application can put it in a memfd.

I understand your concern here. But I guess we are making too much assumption on how enclaves are structured/packaged. My concern is, what if a SIGSTRUCT really has to be from memory? For example, an enclave (along with its SIGSTRUCT) could be embedded inside a shared object (or even the "main" executable) so it shows up in memory to begin with. Of course it could be copied to a memfd but whatever "attributes" (e.g. path, or SELinux class/type) associated with the original file would be lost, so I'm not sure if that would work.

I'm also with you that applications tend to use read() instead of mmap() for accessing files. But in our case that'd be necessary only if .sigstruct is a separate file (hence needs to be read separately). What if (and I guess most implementations would) the SIGSTRUCT is embedded in the same file as the enclave? mmap() is the more common practice when dealing with executable images, and in that case SIGSTRUCT will have already been mmap()'d.

I'm with you again that it's kind of unprecedented to look at the backing inode. But I believe we should strive to allow as large variety of applications/usages as possible and I don't see any alternatives without losing flexibility.

Quoted 34 lines
Quoted 7 lines
Quoted 7 lines

/* Actually map the thing */
mmap(enclave_fd RO section, PROT_READ, ...); mmap(enclave_fd RW section, PROT_READ | PROT_WRITE, ...); mmap(enclave_fd RX section, PROT_READ | PROT_EXEC, ...);

Quoted 8 lines
Quoted 6 lines

/* This should fail unless EXECMOD is available, I think */ mmap(enclave_fd RWX section, PROT_READ | PROT_WRITE | PROT_EXEC);

And the idea here is that, if the .enclave file isn't mapped PROT_EXEC, then mmapping the RX section will also require EXECMEM or EXECMOD.

From security perspective, I think it reasonable to give EXECMEM and

EXECMOD to /dev/sgx/enclave because the actual permissions are guarded by EPCM permissions, which are "inherited" from the source pages, whose permissions have passed LSM checks.

I disagree. If you deny a program EXECMOD, it’s not because you distrust the program. It’s because you want to enforce good security practices. (Or you’re Apple and want to disallow third-party JITs.) A policy that accepts any sigstruct but requires that enclaves come from disk and respect W^X seems entirely reasonable.

I think that blocking EXECMOD has likely served two very real security purposes. It helps force application and library developers to write and compile their code in a way that doesn’t rely on dangerous tricks like putting executable trampolines on the stack. It also makes it essentially impossible for an exploit to run actual downloaded machine code — if there is no way to run code that isn’t appropriately labeled, then attackers are more limited in what they can do.

Quoted 5 lines

I don’t think that SGX should become an exception to either of these. Code should not have an excuse to use WX memory just because it’s in an enclave. Similarly, an exploit should not be able to run an attacker-supplied enclave as a way around a policy that would otherwise prevent downloaded code from running.

Quoted 3 lines

My apology for the confusion here.

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Quoted 7 lines

I was not saying enclaves were exempt to good security practices. What I was trying to say was, EPC pages are *not* subject to the same attacks as regular pages so I suspect there will be a desire to enforce different policies on them, especially after new SGX2 features/applications become available. So I think it beneficial to distinguish between regular vs. enclave virtual ranges. And to do that, a new VM_SGX flag in VMA is probably a very simple/easy way. And with that VM_SGX flag, we could add a new security_sgx_mprot() hook so that LSM modules/policies could act differently.

And if you are with me on that bigger picture, the next question is: what should be the default behavior of security_sgx_mprot() for existing/non-SGX-aware LSM modules/policies? I'd say a reasonable default is to allow R, RW and RX, but not anything else. It'd suffice to get rid of EXECMEM/EXECMOD requirements on enclave applications. For SGX1, EPCM permissions are immutable so it really doesn't matter what security_sgx_mprot() does. For SGX2 and beyond, there's still time and new SGX-aware LSM modules/policies will probably have emerged by then.

-Cedric

#110 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 25 lines · Stephen Smalley
Quoted 4 lines · Cedric

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

Quoted 7 lines

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Yep, I was just typing this up in a different thread:

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode. Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs to RWX. Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

#111 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 36 lines · Sean Christopherson
Quoted 25 lines · Stephen Smalley
Quoted 4 lines · Cedric

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

Quoted 7 lines

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Yep, I was just typing this up in a different thread:

Quoted 8 lines

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode. Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs to RWX. Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified. The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

#112 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 48 lines · Stephen Smalley
Quoted 35 lines · Sean Christopherson
Quoted 26 lines · Stephen Smalley
Quoted 5 lines · Cedric

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

Quoted 7 lines

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Quoted 9 lines

Yep, I was just typing this up in a different thread:
I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode. Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs to RWX. Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 1 line

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified. The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

That agrees with my thoughts. Actually plumbing everything together so this works could be a bit interesting. I assume it’ll need a special case in SELinux or maybe a new vm_op.

#113 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Stephen Smalley
Quoted 46 lines · Stephen Smalley
Quoted 36 lines · Sean Christopherson
Quoted 25 lines · Stephen Smalley
Quoted 4 lines · Cedric

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

Quoted 7 lines

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Yep, I was just typing this up in a different thread:

Quoted 8 lines

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode. Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs to RWX.  Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 1 line

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified.  The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

Also, just to be clear, there is nothing inherently better about checking EXECMEM instead of checking both FILE__WRITE and FILE__EXECUTE to the /dev/sgx/enclave inode, so I wouldn't switch to using anon inodes for that reason. Using anon inodes also unfortunately disables SELinux inode-based checking since we no longer have any useful inode information, so you'd lose out on SELinux ioctl whitelisting on those enclave inodes if that matters.

#114 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 50 lines · Stephen Smalley
Quoted 47 lines · Stephen Smalley
Quoted 45 lines · Sean Christopherson
Quoted 26 lines · Stephen Smalley
Quoted 5 lines · Cedric

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

Quoted 7 lines

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Yep, I was just typing this up in a different thread:

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode. Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs to RWX. Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 3 lines
Quoted 1 line

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified. The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

Also, just to be clear, there is nothing inherently better about checking EXECMEM instead of checking both FILE__WRITE and FILE__EXECUTE to the /dev/sgx/enclave inode, so I wouldn't switch to using anon inodes for that reason. Using anon inodes also unfortunately disables SELinux inode-based checking since we no longer have any useful inode information, so you'd lose out on SELinux ioctl whitelisting on those enclave inodes if that matters.

How can that work? Unless the API changes fairly radically, users fundamentally need to both write and execute the enclave. Some of it will be written only from already executable pages, and some privilege should be needed to execute any enclave page that was not loaded like this.

#115 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 50 lines · Andy Lutomirski
Quoted 50 lines · Stephen Smalley
Quoted 47 lines · Stephen Smalley
Quoted 45 lines · Sean Christopherson
Quoted 26 lines · Stephen Smalley
Quoted 5 lines · Cedric

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

Quoted 7 lines

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Yep, I was just typing this up in a different thread:

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode. Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs to RWX. Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 5 lines
Quoted 3 lines
Quoted 1 line

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified. The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

Also, just to be clear, there is nothing inherently better about checking EXECMEM instead of checking both FILE__WRITE and FILE__EXECUTE to the /dev/sgx/enclave inode, so I wouldn't switch to using anon inodes for that reason. Using anon inodes also unfortunately disables SELinux inode-based checking since we no longer have any useful inode information, so you'd lose out on SELinux ioctl whitelisting on those enclave inodes if that matters.

How can that work? Unless the API changes fairly radically, users fundamentally need to both write and execute the enclave. Some of it will be written only from already executable pages, and some privilege should be needed to execute any enclave page that was not loaded like this.

I'm not sure what the API is. Let's say they do something like this:

fd = open("/dev/sgx/enclave", O_RDONLY);
addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); stuff addr into ioctl args
ioctl(fd, ENCLAVE_CREATE, &ioctlargs);
ioctl(fd, ENCLAVE_ADD_PAGE, &ioctlargs);
ioctl(fd, ENCLAVE_INIT, &ioctlargs);

The important points are that they do not open /dev/sgx/enclave with write access (otherwise they will trigger FILE__WRITE at open time, and later encounter FILE__EXECUTE as well during mmap, thereby requiring both to be allowed to /dev/sgx/enclave), and that they do not request PROT_WRITE to the resulting mapping (otherwise they will trigger FILE__WRITE at mmap time). Then only FILE__READ and FILE__EXECUTE are required to /dev/sgx/enclave in policy.

If they switch to an anon inode, then any mmap PROT_EXEC of the opened file will trigger an EXECMEM check, at least as currently implemented, as we have no useful backing inode information.

#116 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 67 lines · Stephen Smalley
Quoted 51 lines · Andy Lutomirski
Quoted 51 lines · Stephen Smalley
Quoted 48 lines · Stephen Smalley
Quoted 46 lines · Sean Christopherson
Quoted 27 lines · Stephen Smalley
Quoted 5 lines · Cedric

I thought EXECMOD applied to files (and memory mappings backed by them) but I was probably wrong. It sounds like EXECMOD applies to the whole process so would allow all pages within a process's address space to be modified then executed, regardless the backing files. Am I correct this time?

No, you were correct the first time I think; EXECMOD is used to control whether a process can make executable a private file mapping that has previously been modified (e.g. text relocation); it is a special case to support text relocations without having to allow full EXECMEM (i.e. execute arbitrary memory).

SELinux checks relevant to W^X include:

- EXECMEM: mmap/mprotect PROT_EXEC an anonymous mapping (regardless of
PROT_WRITE, since we know the content has to have been written at some point) or a private file mapping that is also PROT_WRITE.
- EXECMOD: mprotect PROT_EXEC a private file mapping that has been previously modified, typically for text relocations,
- FILE__WRITE: mmap/mprotect PROT_WRITE a shared file mapping,
- FILE__EXECUTE: mmap/mprotect PROT_EXEC a file mapping.

(ignoring EXECSTACK and EXECHEAP here since they aren't really relevant to this discussion)

Quoted 7 lines

So if you want to ensure W^X, then you wouldn't allow EXECMEM for the process, EXECMOD by the process to any file, and the combination of both FILE__WRITE and FILE__EXECUTE by the process to any file.

If the /dev/sgx/enclave mappings are MAP_SHARED and you aren't using an anonymous inode, then I would expect that only the FILE__WRITE and FILE__EXECUTE checks are relevant.

Yep, I was just typing this up in a different thread:

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode. Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs to RWX.  Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 5 lines
Quoted 3 lines
Quoted 1 line

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified.  The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

Also, just to be clear, there is nothing inherently better about checking EXECMEM instead of checking both FILE__WRITE and FILE__EXECUTE to the /dev/sgx/enclave inode, so I wouldn't switch to using anon inodes for that reason.  Using anon inodes also unfortunately disables SELinux inode-based checking since we no longer have any useful inode information, so you'd lose out on SELinux ioctl whitelisting on those enclave inodes if that matters.

How can that work?  Unless the API changes fairly radically, users fundamentally need to both write and execute the enclave.  Some of it will be written only from already executable pages, and some privilege should be needed to execute any enclave page that was not loaded like this.

I'm not sure what the API is. Let's say they do something like this:

fd = open("/dev/sgx/enclave", O_RDONLY);
addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); stuff addr into ioctl args
ioctl(fd, ENCLAVE_CREATE, &ioctlargs);
ioctl(fd, ENCLAVE_ADD_PAGE, &ioctlargs);
ioctl(fd, ENCLAVE_INIT, &ioctlargs);

Quoted 3 lines

The important points are that they do not open /dev/sgx/enclave with write access (otherwise they will trigger FILE__WRITE at open time, and later encounter FILE__EXECUTE as well during mmap, thereby requiring both to be allowed to /dev/sgx/enclave), and that they do not request PROT_WRITE to the resulting mapping (otherwise they will trigger FILE__WRITE at mmap time).  Then only FILE__READ and FILE__EXECUTE are required to /dev/sgx/enclave in policy.

If they switch to an anon inode, then any mmap PROT_EXEC of the opened file will trigger an EXECMEM check, at least as currently implemented, as we have no useful backing inode information.

FWIW, looking at the selftest for SGX in the patch series, they open /dev/sgx/enclave O_RDWR (probably not necessary?) and mmap the open file RWX. If that is necessary then I'd rather it show up as FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave instead of EXECMEM, so that we can allow the process the ability to perform that mmap without allowing it to make other mappings WX. So staying with the single /dev/sgx/enclave inode is better in that regard.

#117 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Stephen Smalley
Quoted 7 lines · Stephen Smalley
Quoted 5 lines · Andy Lutomirski

How can that work? Unless the API changes fairly radically, users fundamentally need to both write and execute the enclave. Some of it will be written only from already executable pages, and some privilege should be needed to execute any enclave page that was not loaded like this.

Quoted 8 lines

I'm not sure what the API is. Let's say they do something like this:

fd = open("/dev/sgx/enclave", O_RDONLY);
addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); stuff addr into ioctl args
ioctl(fd, ENCLAVE_CREATE, &ioctlargs);
ioctl(fd, ENCLAVE_ADD_PAGE, &ioctlargs);
ioctl(fd, ENCLAVE_INIT, &ioctlargs);

That's rougly the flow, except that that all enclaves need to have RW and X EPC pages.

Quoted 11 lines

The important points are that they do not open /dev/sgx/enclave with write access (otherwise they will trigger FILE__WRITE at open time, and later encounter FILE__EXECUTE as well during mmap, thereby requiring both to be allowed to /dev/sgx/enclave), and that they do not request PROT_WRITE to the resulting mapping (otherwise they will trigger FILE__WRITE at mmap time). Then only FILE__READ and FILE__EXECUTE are required to /dev/sgx/enclave in policy.

If they switch to an anon inode, then any mmap PROT_EXEC of the opened file will trigger an EXECMEM check, at least as currently implemented, as we have no useful backing inode information.

Yep, and that's by design in the overall proposal. The trick is that ENCLAVE_ADD takes a source VMA and copies the contents *and* the permissions from the source VMA. The source VMA points at regular memory that was mapped and populated using existing mechanisms for loading DSOs.

E.g. at a high level:

source_fd = open("/home/sean/path/to/my/enclave", O_RDONLY); for_each_chunk {
<hand waving - mmap()/mprotect() the enclave file into regular memory>
}

enclave_fd = open("/dev/sgx/enclave", O_RDWR); /* allocs anon inode */ enclave_addr = mmap(NULL, size, PROT_READ, MAP_SHARED, enclave_fd, 0);

ioctl(enclave_fd, ENCLAVE_CREATE, {enclave_addr}); for_each_chunk {
struct sgx_enclave_add ioctlargs = {
.offset = chunk.offset,
.source = chunk.addr,
.size = chunk.size,
.type = chunk.type, /* SGX specific metadata */
}
ioctl(fd, ENCLAVE_ADD, &ioctlargs); /* modifies enclave's VMAs */
}
ioctl(fd, ENCLAVE_INIT, ...);

Userspace never explicitly requests PROT_EXEC on enclave_fd, but SGX also ensures userspace isn't bypassing LSM policies by virtue of copying the permissions for EPC VMAs from regular VMAs that have already gone through LSM checks.

#118 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 60 lines · Sean Christopherson
Quoted 7 lines · Stephen Smalley
Quoted 5 lines · Andy Lutomirski

How can that work? Unless the API changes fairly radically, users fundamentally need to both write and execute the enclave. Some of it will be written only from already executable pages, and some privilege should be needed to execute any enclave page that was not loaded like this.

Quoted 8 lines

I'm not sure what the API is. Let's say they do something like this:

fd = open("/dev/sgx/enclave", O_RDONLY);
addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); stuff addr into ioctl args
ioctl(fd, ENCLAVE_CREATE, &ioctlargs);
ioctl(fd, ENCLAVE_ADD_PAGE, &ioctlargs);
ioctl(fd, ENCLAVE_INIT, &ioctlargs);

That's rougly the flow, except that that all enclaves need to have RW and X EPC pages.

Quoted 11 lines

The important points are that they do not open /dev/sgx/enclave with write access (otherwise they will trigger FILE__WRITE at open time, and later encounter FILE__EXECUTE as well during mmap, thereby requiring both to be allowed to /dev/sgx/enclave), and that they do not request PROT_WRITE to the resulting mapping (otherwise they will trigger FILE__WRITE at mmap time). Then only FILE__READ and FILE__EXECUTE are required to /dev/sgx/enclave in policy.

If they switch to an anon inode, then any mmap PROT_EXEC of the opened file will trigger an EXECMEM check, at least as currently implemented, as we have no useful backing inode information.

Yep, and that's by design in the overall proposal. The trick is that ENCLAVE_ADD takes a source VMA and copies the contents *and* the permissions from the source VMA. The source VMA points at regular memory that was mapped and populated using existing mechanisms for loading DSOs.

E.g. at a high level:

source_fd = open("/home/sean/path/to/my/enclave", O_RDONLY); for_each_chunk {
<hand waving - mmap()/mprotect() the enclave file into regular memory>
}

enclave_fd = open("/dev/sgx/enclave", O_RDWR); /* allocs anon inode */ enclave_addr = mmap(NULL, size, PROT_READ, MAP_SHARED, enclave_fd, 0);

ioctl(enclave_fd, ENCLAVE_CREATE, {enclave_addr}); for_each_chunk {
struct sgx_enclave_add ioctlargs = {
.offset = chunk.offset,
.source = chunk.addr,
.size = chunk.size,
.type = chunk.type, /* SGX specific metadata */
}
ioctl(fd, ENCLAVE_ADD, &ioctlargs); /* modifies enclave's VMAs */
}
ioctl(fd, ENCLAVE_INIT, ...);

Quoted 4 lines

Userspace never explicitly requests PROT_EXEC on enclave_fd, but SGX also ensures userspace isn't bypassing LSM policies by virtue of copying the permissions for EPC VMAs from regular VMAs that have already gone through LSM checks.

Is O_RDWR required for /dev/sgx/enclave or would O_RDONLY suffice? Do you do anything other than ioctl() calls on it?

What's the advantage of allocating an anon inode in the above? At present anon inodes are exempted from inode-based checking, thereby losing the ability to perform SELinux ioctl whitelisting, unlike the file-backed /dev/sgx/enclave inode.

How would SELinux (or other security modules) restrict the authorized enclaves that can be loaded via this interface? Would the sgx driver invoke a new LSM hook with the regular/source VMAs as parameters and allow the security module to reject the ENCLAVE_ADD operation? That could be just based on the vm_file (e.g. whitelist what enclave files are permitted in general) or it could be based on both the process and the vm_file (e.g. only allow specific enclaves to be loaded into specific processes).

#119 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 60 lines · Stephen Smalley
Quoted 49 lines · Sean Christopherson
Quoted 8 lines · Stephen Smalley
Quoted 6 lines · Andy Lutomirski

How can that work? Unless the API changes fairly radically, users fundamentally need to both write and execute the enclave. Some of it will be written only from already executable pages, and some privilege should be needed to execute any enclave page that was not loaded like this.

Quoted 8 lines

I'm not sure what the API is. Let's say they do something like this:

fd = open("/dev/sgx/enclave", O_RDONLY);
addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); stuff addr into ioctl args
ioctl(fd, ENCLAVE_CREATE, &ioctlargs);
ioctl(fd, ENCLAVE_ADD_PAGE, &ioctlargs);
ioctl(fd, ENCLAVE_INIT, &ioctlargs);

That's rougly the flow, except that that all enclaves need to have RW and X EPC pages.

Quoted 11 lines

The important points are that they do not open /dev/sgx/enclave with write access (otherwise they will trigger FILE__WRITE at open time, and later encounter FILE__EXECUTE as well during mmap, thereby requiring both to be allowed to /dev/sgx/enclave), and that they do not request PROT_WRITE to the resulting mapping (otherwise they will trigger FILE__WRITE at mmap time). Then only FILE__READ and FILE__EXECUTE are required to /dev/sgx/enclave in policy.

If they switch to an anon inode, then any mmap PROT_EXEC of the opened file will trigger an EXECMEM check, at least as currently implemented, as we have no useful backing inode information.

Yep, and that's by design in the overall proposal. The trick is that ENCLAVE_ADD takes a source VMA and copies the contents *and* the permissions from the source VMA. The source VMA points at regular memory that was mapped and populated using existing mechanisms for loading DSOs. E.g. at a high level:
source_fd = open("/home/sean/path/to/my/enclave", O_RDONLY); for_each_chunk {
<hand waving - mmap()/mprotect() the enclave file into regular memory>
}
enclave_fd = open("/dev/sgx/enclave", O_RDWR); /* allocs anon inode */ enclave_addr = mmap(NULL, size, PROT_READ, MAP_SHARED, enclave_fd, 0); ioctl(enclave_fd, ENCLAVE_CREATE, {enclave_addr});
for_each_chunk {
struct sgx_enclave_add ioctlargs = {
.offset = chunk.offset,
.source = chunk.addr,
.size = chunk.size,
.type = chunk.type, /* SGX specific metadata */

Quoted 8 lines

}
ioctl(fd, ENCLAVE_ADD, &ioctlargs); /* modifies enclave's VMAs */
}
ioctl(fd, ENCLAVE_INIT, ...);
Userspace never explicitly requests PROT_EXEC on enclave_fd, but SGX also ensures userspace isn't bypassing LSM policies by virtue of copying the permissions for EPC VMAs from regular VMAs that have already gone through LSM checks.

Quoted 5 lines

Is O_RDWR required for /dev/sgx/enclave or would O_RDONLY suffice? Do you do anything other than ioctl() calls on it?

What's the advantage of allocating an anon inode in the above? At present anon inodes are exempted from inode-based checking, thereby losing the ability to perform SELinux ioctl whitelisting, unlike the file-backed /dev/sgx/enclave inode.

How would SELinux (or other security modules) restrict the authorized enclaves that can be loaded via this interface? Would the sgx driver invoke a new LSM hook with the regular/source VMAs as parameters and allow the security module to reject the ENCLAVE_ADD operation? That could be just based on the vm_file (e.g. whitelist what enclave files are permitted in general) or it could be based on both the process and the vm_file (e.g. only allow specific enclaves to be loaded into specific processes).

This is the idea behind the .sigstruct file. The driver could call a new hook to approve or reject the .sigstruct. The sigstruct contains a hash of the whole enclave and a signature by the author.

#120 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 60 lines · Andy Lutomirski
Quoted 60 lines · Stephen Smalley
Quoted 57 lines · Sean Christopherson
Quoted 8 lines · Stephen Smalley
Quoted 6 lines · Andy Lutomirski

How can that work? Unless the API changes fairly radically, users fundamentally need to both write and execute the enclave. Some of it will be written only from already executable pages, and some privilege should be needed to execute any enclave page that was not loaded like this.

Quoted 8 lines

I'm not sure what the API is. Let's say they do something like this:

fd = open("/dev/sgx/enclave", O_RDONLY);
addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); stuff addr into ioctl args
ioctl(fd, ENCLAVE_CREATE, &ioctlargs);
ioctl(fd, ENCLAVE_ADD_PAGE, &ioctlargs);
ioctl(fd, ENCLAVE_INIT, &ioctlargs);

That's rougly the flow, except that that all enclaves need to have RW and X EPC pages.

Quoted 11 lines

The important points are that they do not open /dev/sgx/enclave with write access (otherwise they will trigger FILE__WRITE at open time, and later encounter FILE__EXECUTE as well during mmap, thereby requiring both to be allowed to /dev/sgx/enclave), and that they do not request PROT_WRITE to the resulting mapping (otherwise they will trigger FILE__WRITE at mmap time). Then only FILE__READ and FILE__EXECUTE are required to /dev/sgx/enclave in policy.

If they switch to an anon inode, then any mmap PROT_EXEC of the opened file will trigger an EXECMEM check, at least as currently implemented, as we have no useful backing inode information.

Yep, and that's by design in the overall proposal. The trick is that ENCLAVE_ADD takes a source VMA and copies the contents *and* the permissions from the source VMA. The source VMA points at regular memory that was mapped and populated using existing mechanisms for loading DSOs. E.g. at a high level:
source_fd = open("/home/sean/path/to/my/enclave", O_RDONLY); for_each_chunk {
<hand waving - mmap()/mprotect() the enclave file into regular memory>
}
enclave_fd = open("/dev/sgx/enclave", O_RDWR); /* allocs anon inode */ enclave_addr = mmap(NULL, size, PROT_READ, MAP_SHARED, enclave_fd, 0); ioctl(enclave_fd, ENCLAVE_CREATE, {enclave_addr});
for_each_chunk {
struct sgx_enclave_add ioctlargs = {
.offset = chunk.offset,
.source = chunk.addr,
.size = chunk.size,
.type = chunk.type, /* SGX specific metadata */
}
ioctl(fd, ENCLAVE_ADD, &ioctlargs); /* modifies enclave's VMAs */
}
ioctl(fd, ENCLAVE_INIT, ...);
Userspace never explicitly requests PROT_EXEC on enclave_fd, but SGX also ensures userspace isn't bypassing LSM policies by virtue of copying the permissions for EPC VMAs from regular VMAs that have already gone through LSM checks.

Quoted 7 lines
Quoted 5 lines

Is O_RDWR required for /dev/sgx/enclave or would O_RDONLY suffice? Do you do anything other than ioctl() calls on it?

What's the advantage of allocating an anon inode in the above? At present anon inodes are exempted from inode-based checking, thereby losing the ability to perform SELinux ioctl whitelisting, unlike the file-backed /dev/sgx/enclave inode.

How would SELinux (or other security modules) restrict the authorized enclaves that can be loaded via this interface? Would the sgx driver invoke a new LSM hook with the regular/source VMAs as parameters and allow the security module to reject the ENCLAVE_ADD operation? That could be just based on the vm_file (e.g. whitelist what enclave files are permitted in general) or it could be based on both the process and the vm_file (e.g. only allow specific enclaves to be loaded into specific processes).

This is the idea behind the .sigstruct file. The driver could call a new hook to approve or reject the .sigstruct. The sigstruct contains a hash of the whole enclave and a signature by the author.

Ok, so same idea but moved to ENCLAVE_INIT and passing the vma or file for the sigstruct instead of the enclave.

#121 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Stephen Smalley
Quoted 30 lines · Stephen Smalley
Quoted 29 lines · Sean Christopherson

On Fri, May 17, 2019 at 02:05:39PM -0400, Stephen Smalley wrote:
Yep, and that's by design in the overall proposal. The trick is that ENCLAVE_ADD takes a source VMA and copies the contents *and* the permissions from the source VMA. The source VMA points at regular memory that was mapped and populated using existing mechanisms for loading DSOs.

E.g. at a high level:

source_fd = open("/home/sean/path/to/my/enclave", O_RDONLY); for_each_chunk {
<hand waving - mmap()/mprotect() the enclave file into regular memory>
}

enclave_fd = open("/dev/sgx/enclave", O_RDWR); /* allocs anon inode */ enclave_addr = mmap(NULL, size, PROT_READ, MAP_SHARED, enclave_fd, 0);

ioctl(enclave_fd, ENCLAVE_CREATE, {enclave_addr}); for_each_chunk {
struct sgx_enclave_add ioctlargs = {
.offset = chunk.offset,
.source = chunk.addr,
.size = chunk.size,
.type = chunk.type, /* SGX specific metadata */
}
ioctl(fd, ENCLAVE_ADD, &ioctlargs); /* modifies enclave's VMAs */
}
ioctl(fd, ENCLAVE_INIT, ...);

Quoted 7 lines
Quoted 4 lines

Userspace never explicitly requests PROT_EXEC on enclave_fd, but SGX also ensures userspace isn't bypassing LSM policies by virtue of copying the permissions for EPC VMAs from regular VMAs that have already gone through LSM checks.

Is O_RDWR required for /dev/sgx/enclave or would O_RDONLY suffice? Do you do anything other than ioctl() calls on it?

Hmm, in the current implementation, yes, O_RDWR is required. An enclave and its associated EPC memory are represented and referenced by its fd, which is backed by /dev/sgx/enclave. An enclave is not just code, e.g. also has a heap, stack, variables, etc..., which need to be mapped accordingly. In the current implementation, userspace directly does mprotect() or mmap() on EPC VMAs, and so setting PROT_WRITE for the heap and whatnot requires opening /dev/sgx/enclave with O_RDWR.

I *think* /dev/sgx/enclave could be opened O_RDONLY if ENCLAVE_ADD stuffed the EPC VMA permissions, assuming the use case doesn't require changing permissions after the enclave has been created.

The other reason userspace would need to open /dev/sgx/enclave O_RDWR would be to debug an enclave, e.g. pwrite() works on the enclave fd due to SGX restrictions on modifying EPC memory from outside the enclave. But that's an obvious case where FILE__WRITE should be required.

Quoted 4 lines

What's the advantage of allocating an anon inode in the above? At present anon inodes are exempted from inode-based checking, thereby losing the ability to perform SELinux ioctl whitelisting, unlike the file-backed /dev/sgx/enclave inode.

Purely to trigger the EXECMEM check on any PROT_EXEC mapping. However, the motiviation for that was due to my bad assumption that FILE__WRITE and FILE__EXECUTE are global and not per process. If we can do as you suggest and allow creation of enclaves with O_RDONLY, then keeping a file-backed inode is definitely better as it means most processes only need FILE__READ and FILE__* in general has actual meaning.

Thanks a bunch for your help!

#122 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Stephen Smalley
Quoted 13 lines · Stephen Smalley
Quoted 12 lines · Stephen Smalley
Quoted 10 lines · Sean Christopherson

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode.
Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs
to RWX.  Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 8 lines
Quoted 8 lines

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified.  The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

The idea is that by providing an SGX ioctl() to propagate VMA permissions from a source VMA, EXECMEM wouldn't be required to make an EPC page executable. E.g. userspace establishes an enclave in non-EPC memory from an unmodified file (with FILE__EXECUTE perms), and the uses the SGX ioctl() to copy the contents and permissions into EPC memory.

Quoted 6 lines

Also, just to be clear, there is nothing inherently better about checking EXECMEM instead of checking both FILE__WRITE and FILE__EXECUTE to the /dev/sgx/enclave inode, so I wouldn't switch to using anon inodes for that reason. Using anon inodes also unfortunately disables SELinux inode-based checking since we no longer have any useful inode information, so you'd lose out on SELinux ioctl whitelisting on those enclave inodes if that matters.

The problem is that all enclaves are associated with a single inode, i.e. /dev/sgx/enclave. /dev/sgx/enclave is a char device whose purpose is to provide ioctls() and to allow mmap()'ing EPC memory. In no way is it associated with the content that actually gets loaded into EPC memory.

The actual file that contains the enclave's contents (assuming the enclave came from a file) is a separate regular file that the SGX subsystem never sees.

AIUI, having FILE__WRITE and FILE__EXECUTE on /dev/sgx/enclave would allow *any* enclave/process to map EPC as RWX. Moving to anon inodes and thus PROCESS__EXECMEM achieves per-process granularity.

#123 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 45 lines · Sean Christopherson
Quoted 15 lines · Stephen Smalley
Quoted 13 lines · Stephen Smalley
Quoted 11 lines · Sean Christopherson

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode.
Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs
to RWX. Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 8 lines
Quoted 8 lines

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified. The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

The idea is that by providing an SGX ioctl() to propagate VMA permissions from a source VMA, EXECMEM wouldn't be required to make an EPC page executable. E.g. userspace establishes an enclave in non-EPC memory from an unmodified file (with FILE__EXECUTE perms), and the uses the SGX ioctl() to copy the contents and permissions into EPC memory.

Quoted 6 lines

Also, just to be clear, there is nothing inherently better about checking EXECMEM instead of checking both FILE__WRITE and FILE__EXECUTE to the /dev/sgx/enclave inode, so I wouldn't switch to using anon inodes for that reason. Using anon inodes also unfortunately disables SELinux inode-based checking since we no longer have any useful inode information, so you'd lose out on SELinux ioctl whitelisting on those enclave inodes if that matters.

The problem is that all enclaves are associated with a single inode, i.e. /dev/sgx/enclave. /dev/sgx/enclave is a char device whose purpose is to provide ioctls() and to allow mmap()'ing EPC memory. In no way is it associated with the content that actually gets loaded into EPC memory.

Quoted 7 lines

The actual file that contains the enclave's contents (assuming the enclave came from a file) is a separate regular file that the SGX subsystem never sees.

AIUI, having FILE__WRITE and FILE__EXECUTE on /dev/sgx/enclave would allow *any* enclave/process to map EPC as RWX. Moving to anon inodes and thus PROCESS__EXECMEM achieves per-process granularity.

How does anon_inode make any difference? Anon_inode is not the same thing as anon_vma.

#124 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 9 lines · Andy Lutomirski
Quoted 6 lines · Sean Christopherson

AIUI, having FILE__WRITE and FILE__EXECUTE on /dev/sgx/enclave would allow *any* enclave/process to map EPC as RWX. Moving to anon inodes and thus PROCESS__EXECMEM achieves per-process granularity.

How does anon_inode make any difference? Anon_inode is not the same thing as anon_vma.

In this snippet, IS_PRIVATE() is true for anon inodes, false for /dev/sgx/enclave. Because EPC memory is always shared, SELinux will never check PROCESS__EXECMEM for mprotect() on/dev/sgx/enclave.

static int file_map_prot_check(struct file *file, unsigned long prot, int shared)

{
        const struct cred *cred = current_cred();
        u32 sid = cred_sid(cred);
        int rc = 0;

        if (default_noexec &&
            (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
                                   (!shared && (prot & PROT_WRITE)))) {
                /*
                 * We are making executable an anonymous mapping or a
                 * private file mapping that will also be writable.
                 * This has an additional check.
                 */
                rc = avc_has_perm(&selinux_state,
                                  sid, sid, SECCLASS_PROCESS,
                                  PROCESS__EXECMEM, NULL);
                if (rc)
                        goto error;
        }

	...
}
#125 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 4 lines · Sean Christopherson

In this snippet, IS_PRIVATE() is true for anon inodes, false for /dev/sgx/enclave. Because EPC memory is always shared, SELinux will never check PROCESS__EXECMEM for mprotect() on/dev/sgx/enclave.

Why _does_ the memory have to be shared? Shared mmap() is fundamentally less secure than private mmap, since by definition it means "oh, somebody else has access to it too and might modify it under us".

Why does the SGX logic care about things like that? Normal executables are just private mappings of an underlying file, I'm not sure why the SGX interface has to have that shared thing, and why the interface has to have a device node in the first place when you have system calls for setup anyway.

So why don't the system calls just work on perfectly normal anonymous mmap's? Why a device node, and why must it be shared to begin with?

Linus

#126 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 12 lines · Linus Torvalds
Quoted 4 lines · Sean Christopherson

In this snippet, IS_PRIVATE() is true for anon inodes, false for /dev/sgx/enclave. Because EPC memory is always shared, SELinux will never check PROCESS__EXECMEM for mprotect() on/dev/sgx/enclave.

Why _does_ the memory have to be shared? Shared mmap() is fundamentally less secure than private mmap, since by definition it means "oh, somebody else has access to it too and might modify it under us".

Quoted 8 lines

Why does the SGX logic care about things like that? Normal executables are just private mappings of an underlying file, I'm not sure why the SGX interface has to have that shared thing, and why the interface has to have a device node in the first place when you have system calls for setup anyway.

So why don't the system calls just work on perfectly normal anonymous mmap's? Why a device node, and why must it be shared to begin with?

I agree that conceptually EPC is private memory, but because EPC is managed as a separate memory pool, SGX tags it VM_PFNMAP and manually inserts PFNs, i.e. EPC effectively it gets classified as IO memory.

And vmf_insert_pfn_prot() doesn't like writable private IO mappings:

   BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
#127 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 8 lines · Sean Christopherson

I agree that conceptually EPC is private memory, but because EPC is managed as a separate memory pool, SGX tags it VM_PFNMAP and manually inserts PFNs, i.e. EPC effectively it gets classified as IO memory.

And vmf_insert_pfn_prot() doesn't like writable private IO mappings:

   BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));

Hmm. I haven't looked into why you want to do your own page insertion and not just "use existing pages", but I'm sure there's some reason.

It looks like the "shared vs private" inode part is a red herring, though. You might as well give each opener of the sgx node its own inode - and you probably should. Then you can keep track of the pages that have been added in the inode->i_mapping, and you could avoid the whole PFN thing entirely. I still am not a huge fan of the device node in the first place, but I guess it's just one more place where a system admin can then give (or deny) access to a kernel feature from users. I guess the kvm people do the same thing, for not necessarily any better reasons.

With the PFNMAP model I guess the SGX memory ends up being unswappable
- at least done the obvious way.

Again, the way I'd expect it to be done is as a shmem inode - that would I think be a better model. But I think that's a largely internal design decision, and the device node could just do that eventually (and the mmap could just map the populated shmem information into memory, no PFNMAP needed - the inode and the mapping could be "read-only" as far as the _user_ is concerned, but the i_mapping then gets populated by the ioctl's).

I have not actually looked at any of the SGX patches, so maybe you're already doing something like that (although the PFNMAP comment makes me think not), and quite possibly there's some fundamental reason why you can't just use the shmem approach.

So my high-level reaction here may be just the rantings of somebody who just isn't familiar with what you do. My "why not shmem and regular mmap" questions come from a 30000ft view without knowing any of the details.

Linus

#128 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 7 lines · Linus Torvalds
Quoted 5 lines · Sean Christopherson

I agree that conceptually EPC is private memory, but because EPC is managed as a separate memory pool, SGX tags it VM_PFNMAP and manually inserts PFNs, i.e. EPC effectively it gets classified as IO memory.

Quoted 6 lines
Quoted 3 lines

And vmf_insert_pfn_prot() doesn't like writable private IO mappings:

   BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));

Hmm. I haven't looked into why you want to do your own page insertion and not just "use existing pages", but I'm sure there's some reason.

Outside of the SGX subsystem, the kernel is unaware of EPC memory, e.g. BIOS enumerates it as reserved memory in the e820 tables, or not at all.

On current hardware, EPC is backed by system memory, but it's protected by a range registers (and other stuff) and can't be accessed directly except when the CPU is in "enclave mode", i.e. executing an enclave in CPL3. To execute an enclave it must first be built, and because EPC memory can't be written outside of enclave mode, the only way to build the enclave is via dedicated CPL0 ISA, e.g. ENCLS[EADD].

Quoted 10 lines

It looks like the "shared vs private" inode part is a red herring, though. You might as well give each opener of the sgx node its own inode - and you probably should. Then you can keep track of the pages that have been added in the inode->i_mapping, and you could avoid the whole PFN thing entirely. I still am not a huge fan of the device node in the first place, but I guess it's just one more place where a system admin can then give (or deny) access to a kernel feature from users. I guess the kvm people do the same thing, for not necessarily any better reasons.

Quoted 2 lines

With the PFNMAP model I guess the SGX memory ends up being unswappable
- at least done the obvious way.

EPC memory is swappable in it's own terms, e.g. pages can be swapped from EPC to system RAM and vice versa, but again moving pages in and out of the EPC can only be done through dedicated CPL0 ISA. And there are additional TLB flushing requirements, evicted pages need to be refcounted against the enclave, evicted pages need an anchor in the EPC to ensure freshness, etc...

Long story short, we decided to manage EPC in the SGX subsystem as a separate memory pool rather than modify the kernel's MMU to teach it how to deal with EPC.

Quoted 19 lines

Again, the way I'd expect it to be done is as a shmem inode - that would I think be a better model. But I think that's a largely internal design decision, and the device node could just do that eventually (and the mmap could just map the populated shmem information into memory, no PFNMAP needed - the inode and the mapping could be "read-only" as far as the _user_ is concerned, but the i_mapping then gets populated by the ioctl's).

I have not actually looked at any of the SGX patches, so maybe you're already doing something like that (although the PFNMAP comment makes me think not), and quite possibly there's some fundamental reason why you can't just use the shmem approach.

So my high-level reaction here may be just the rantings of somebody who just isn't familiar with what you do. My "why not shmem and regular mmap" questions come from a 30000ft view without knowing any of the details.

Linus

#129 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Sean Christopherson
Quoted 26 lines · Sean Christopherson
Quoted 14 lines · Linus Torvalds
Quoted 4 lines · Sean Christopherson

In this snippet, IS_PRIVATE() is true for anon inodes, false for /dev/sgx/enclave. Because EPC memory is always shared, SELinux will never check PROCESS__EXECMEM for mprotect() on/dev/sgx/enclave.

Why _does_ the memory have to be shared? Shared mmap() is fundamentally less secure than private mmap, since by definition it means "oh, somebody else has access to it too and might modify it under us".

Quoted 8 lines

Why does the SGX logic care about things like that? Normal executables are just private mappings of an underlying file, I'm not sure why the SGX interface has to have that shared thing, and why the interface has to have a device node in the first place when you have system calls for setup anyway.

So why don't the system calls just work on perfectly normal anonymous mmap's? Why a device node, and why must it be shared to begin with?

Quoted 7 lines

I agree that conceptually EPC is private memory, but because EPC is managed as a separate memory pool, SGX tags it VM_PFNMAP and manually inserts PFNs, i.e. EPC effectively it gets classified as IO memory.

And vmf_insert_pfn_prot() doesn't like writable private IO mappings:

  BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));

I don’t see how it could be anonymous even in principle. The kernel can’t *read* the memory — how could we possibly CoW it? And we can’t share an RO backing pages between two different enclaves because the CPU won’t let us — each EPC page belongs to a particular enclave. And fork()ing an enclave is right out.

So I agree that MAP_ANONYMOUS would be nice conceptually, but I don’t see how it would work.

#130 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Sean Christopherson
Quoted 41 lines · Sean Christopherson
Quoted 13 lines · Stephen Smalley
Quoted 12 lines · Stephen Smalley
Quoted 10 lines · Sean Christopherson

I think we may want to change the SGX API to alloc an anon inode for each enclave instead of hanging every enclave off of the /dev/sgx/enclave inode.
Because /dev/sgx/enclave is NOT private, SELinux's file_map_prot_check() will only require FILE__WRITE and FILE__EXECUTE to mprotect() enclave VMAs
to RWX.  Backing each enclave with an anon inode will make SELinux treat EPC memory like anonymous mappings, which is what we want (I think), e.g. making *any* EPC page executable will require PROCESS__EXECMEM (SGX is 64-bit only at this point, so SELinux will always have default_noexec).

Quoted 8 lines
Quoted 8 lines

I don't think we want to require EXECMEM (or equivalently both FILE__WRITE and FILE__EXECUTE to /dev/sgx/enclave) for making any EPC page executable, only if the page is also writable or previously modified.  The intent is to prevent arbitrary code execution without EXECMEM (or FILE__WRITE|FILE__EXECUTE), while still allowing enclaves to be created without EXECMEM as long as the EPC page mapping is only ever mapped RX and its initial contents came from an unmodified file mapping that was PROT_EXEC (and hence already checked via FILE__EXECUTE).

The idea is that by providing an SGX ioctl() to propagate VMA permissions from a source VMA, EXECMEM wouldn't be required to make an EPC page executable. E.g. userspace establishes an enclave in non-EPC memory from an unmodified file (with FILE__EXECUTE perms), and the uses the SGX ioctl() to copy the contents and permissions into EPC memory.

Quoted 6 lines

Also, just to be clear, there is nothing inherently better about checking EXECMEM instead of checking both FILE__WRITE and FILE__EXECUTE to the /dev/sgx/enclave inode, so I wouldn't switch to using anon inodes for that reason. Using anon inodes also unfortunately disables SELinux inode-based checking since we no longer have any useful inode information, so you'd lose out on SELinux ioctl whitelisting on those enclave inodes if that matters.

The problem is that all enclaves are associated with a single inode, i.e. /dev/sgx/enclave. /dev/sgx/enclave is a char device whose purpose is to provide ioctls() and to allow mmap()'ing EPC memory. In no way is it associated with the content that actually gets loaded into EPC memory.

Quoted 8 lines

The actual file that contains the enclave's contents (assuming the enclave came from a file) is a separate regular file that the SGX subsystem never sees.

AIUI, having FILE__WRITE and FILE__EXECUTE on /dev/sgx/enclave would allow *any* enclave/process to map EPC as RWX. Moving to anon inodes and thus PROCESS__EXECMEM achieves per-process granularity.

No, FILE__WRITE and FILE__EXECUTE are a check between a process and a file, so you can ensure that only whitelisted processes are allowed both to /dev/sgx/enclave.

#131 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 9 lines · Stephen Smalley
Quoted 4 lines · Sean Christopherson

AIUI, having FILE__WRITE and FILE__EXECUTE on /dev/sgx/enclave would allow *any* enclave/process to map EPC as RWX. Moving to anon inodes and thus PROCESS__EXECMEM achieves per-process granularity.

No, FILE__WRITE and FILE__EXECUTE are a check between a process and a file, so you can ensure that only whitelisted processes are allowed both to /dev/sgx/enclave.

Ah, so each process has its own FILE__* permissions for a specific set of files?

Does that allow differentiating between a process making an EPC page RWX and a process making two separate EPC pages RW and RX?

#132 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 7 lines · Sean Christopherson
Quoted 6 lines · Stephen Smalley
Quoted 4 lines · Sean Christopherson

AIUI, having FILE__WRITE and FILE__EXECUTE on /dev/sgx/enclave would allow *any* enclave/process to map EPC as RWX. Moving to anon inodes and thus PROCESS__EXECMEM achieves per-process granularity.

Quoted 6 lines
Quoted 3 lines

No, FILE__WRITE and FILE__EXECUTE are a check between a process and a file, so you can ensure that only whitelisted processes are allowed both to /dev/sgx/enclave.

Ah, so each process has its own FILE__* permissions for a specific set of files?

That's correct.

Quoted 2 lines

Does that allow differentiating between a process making an EPC page RWX and a process making two separate EPC pages RW and RX?

Not if they are backed by the same inode, nor if they are all backed by anon inodes, at least not as currently implemented.

maintainer
#133 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Andy Lutomirski
Quoted 7 lines · Andy Lutomirski
Quoted 3 lines · James Morris

You could try user.sigstruct, which does not require any privs.

I don't think I understand your proposal. What file would this attribute be on? What would consume it?

It would be on the enclave file, so you keep the sigstruct bound to it, rather than needing a separate file to manage. It would simplify any LSM policy check.

It would be consumed by (I guess) the SGX_INIT_THE_ENCLAVE ioctl in your example, instead of having a 2nd fd.

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

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 12 lines · James Morris
Quoted 10 lines · Andy Lutomirski
Quoted 5 lines · James Morris

You could try user.sigstruct, which does not require any privs.

I don't think I understand your proposal. What file would this attribute be on? What would consume it?

Quoted 8 lines

It would be on the enclave file, so you keep the sigstruct bound to it, rather than needing a separate file to manage. It would simplify any LSM policy check.

It would be consumed by (I guess) the SGX_INIT_THE_ENCLAVE ioctl in your example, instead of having a 2nd fd.

Okay, I think I see what you’re suggesting. I don’t think it works well, though, since loading the data from the enclave file will almost always be done in multiple chunks, and it’s not clear when the kernel should look for the xattr or what to do if the xattr changes part way through.

#135 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to James Morris

On Thu, May 16, 2019 at 05:24:33PM +1000, James Morris wrote:

Good morning, I hope everyone had a pleasant weekend.

James, I believe the last time our paths crossed was at the Linux Security Summit in Seattle, I trust you have been well since then.

Quoted 10 lines · Andy Lutomirski
Quoted 8 lines · James Morris
Quoted 3 lines

You could try user.sigstruct, which does not require any privs.

I don't think I understand your proposal. What file would this attribute be on? What would consume it?

Quoted 6 lines

It would be on the enclave file, so you keep the sigstruct bound to it, rather than needing a separate file to manage. It would simplify any LSM policy check.

It would be consumed by (I guess) the SGX_INIT_THE_ENCLAVE ioctl in your example, instead of having a 2nd fd.

I've watched this discussion regarding LSM, sigstructs and file descriptors with some fascination, since all of this infrastructure already exists and should be well understood by anyone who has been active in SGX runtime development. There would thus seem to be a disconnect between SGX driver developers and the consumers of the services of the driver.

The existing enclave format, codified by the silo within Intel that is responsible for the existing SDK/PSW, implements a notes section stored inside a standard ELF shared library image. The notes section contains a significant amount of metadata that is used to direct the instantiation of what will be the initialized enclave image. Said metadata includes a copy of the sigstruct that was generated when the enclave was signed, which is the event that triggers metadata generation.

All of this means that any enclave that gets loaded effectively triggers both LSM and IMA checks.

James, if you remember, the paper that we presented in Seattle described the initial implementation of an extension to the Linux IMA infrastructure that tracks whether or not processes can be 'trusted'. That work has gone on to include running the trust modeling and disciplining engine inside of a namespace specific SGX enclave. We would be happy to make available execution trajectory logs that clearly document IMA and LSM checks being conducted on enclaves.

There is a strong probability that we will be maintaining and supporting a modified version of whatever driver that goes upstream. In support of this we are putting together a white paper discussing security architecture concerns inherent in an SGX driver. With the intent of avoiding LKML verbosity we will post a URL to the paper when it is available if there is interest.

The issue of EDMM has already come up, suffice it to say that EDMM makes LSM inspection of enclave content, while desirable, largely irrelevant from a security perspective.

Quoted 1 line

James Morris

Best wishes for a productive week.

Dr. Greg

As always,

Dr. G.W. Wettstein, Ph.D.   Enjellic Systems Development, LLC.
4206 N. 19th Ave.           Specializing in information infra-structure
Fargo, ND  58102            development.
PH: 701-281-1686            EMAIL: [email protected]

------------------------------------------------------------------------------
"If you plugged up your nose and mouth right before you sneezed, would
the sneeze go out your ears or would your head explode? Either way I'm afraid to try."
-- Nick Kean

#136 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Andy Lutomirski
Quoted 8 lines · Andy Lutomirski

2) Just like any other DSO, there are potential issues with how enclaves deal with writable vs executable memory. This takes two forms. First, a task should probably require EXECMEM, EXECMOD, or similar permission to run an enclave that can modify its own text. Second, it would be nice if a task that did *not* have EXECMEM, EXECMOD, or similar could still run the enclave if it had EXECUTE permission on the file containing the enclave.

Quoted 6 lines

Currently, this all works because DSOs are run by mmapping the file to create multiple VMAs, some of which are executable, non-writable, and non-CoWed, and some of which are writable but not executable. With SGX, there's only really one inode per enclave (the anon_inode that comes form /dev/sgx/enclave), and it can only be sensibly mapped MAP_SHARED.

I was wrong when I said /dev/sgx/enclave creates and returns an anon inode. I was thinking of the KVM model for creating VMs. SGX creates an enclave when /dev/sgx/enclave is opened and associates the enclave with the newly opened /dev/sgx/enclave fd.

Regardless, the fundamental problem remains, mmap() of EPC works on a single inode.

#137 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 16 lines · Sean Christopherson
Quoted 8 lines · Andy Lutomirski

2) Just like any other DSO, there are potential issues with how enclaves deal with writable vs executable memory. This takes two forms. First, a task should probably require EXECMEM, EXECMOD, or similar permission to run an enclave that can modify its own text. Second, it would be nice if a task that did *not* have EXECMEM, EXECMOD, or similar could still run the enclave if it had EXECUTE permission on the file containing the enclave.

Quoted 6 lines

Currently, this all works because DSOs are run by mmapping the file to create multiple VMAs, some of which are executable, non-writable, and non-CoWed, and some of which are writable but not executable. With SGX, there's only really one inode per enclave (the anon_inode that comes form /dev/sgx/enclave), and it can only be sensibly mapped MAP_SHARED.

Quoted 7 lines

I was wrong when I said /dev/sgx/enclave creates and returns an anon inode. I was thinking of the KVM model for creating VMs. SGX creates an enclave when /dev/sgx/enclave is opened and associates the enclave with the newly opened /dev/sgx/enclave fd.

Regardless, the fundamental problem remains, mmap() of EPC works on a single inode.

If I read code in file_map_prot_check() correctly, only when you request W+X at the same time that EXECMEM would be required for MAP_SHARED, right? If so, I believe SGX enclaves would never need that.

#138 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Andy Lutomirski
Quoted 17 lines · Andy Lutomirski

Hi, LSM and SELinux people-

We're trying to figure out how SGX fits in with LSMs. For background, an SGX library is functionally a bit like a DSO, except that it's nominally resistant to attack from outside and the process of loading it is complicated. To load an enclave, a program can open /dev/sgx/enclave, do some ioctls to load the code and data segments into the enclave, call a special ioctl to "initialize" the enclave, and then call into the enclave (using special CPU instructions).

One nastiness is that there is not actually a universally agreed upon, documented file format for enclaves. Windows has an undocumented format, and there are probably a few others out there. No one really wants to teach the kernel to parse enclave files.

There are two issues with how this interacts with LSMs:

Quoted 10 lines

1) LSMs might want to be able to whitelist, blacklist, or otherwise restrict what enclaves can run at all. The current proposal that everyone seems to dislike the least is to have a .sigstruct file on disk that contains a hash and signature of the enclave in a CPU-defined format. To initialize an enclave, a program will pass an fd to this file, and a new LSM hook can be called to allow or disallow the operation. In a SELinux context, the idea is that policy could require the .sigstruct file to be labeled with a type like sgx_sigstruct_t, and only enclaves that have a matching .sigstruct with such a label could run.

Similarly if we could take data for the enclave from fd and enforce it with sgx_enclave_t label.

Quoted 9 lines

Here's a very vague proposal that's kind of like what I've been thinking over the past few days. The SGX inode could track, for each page, a "safe-to-execute" bit. When you first open /dev/sgx/enclave, you get a blank enclave and all pages are safe-to-execute. When you do the ioctl to load context (which could be code, data, or anything else), the kernel will check whether the *source* VMA is executable and, if not, mark the page of the enclave being loaded as unsafe. Once the enclave is initialized, the driver will clear the safe-to-execute bit for any page that is successfully mapped writably.

With the fd based model for source I'd mark SECINFO.W pages as unsafe to execute and then check unsafe bit before applying lets say EMODT or EMODPR.

There is a problem here though. Usually the enclave itself is just a loader that then loads the application from outside source and creates the executable pages from the content.

A great example of this is Graphene that bootstraps unmodified Linux applications to an enclave:

https://github.com/oscarlab/graphene

/Jarkko

maintainer
#139 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 31 lines · Jarkko Sakkinen
Quoted 19 lines · Andy Lutomirski

Hi, LSM and SELinux people-

We're trying to figure out how SGX fits in with LSMs. For background, an SGX library is functionally a bit like a DSO, except that it's nominally resistant to attack from outside and the process of loading it is complicated. To load an enclave, a program can open /dev/sgx/enclave, do some ioctls to load the code and data segments into the enclave, call a special ioctl to "initialize" the enclave, and then call into the enclave (using special CPU instructions).

One nastiness is that there is not actually a universally agreed upon, documented file format for enclaves. Windows has an undocumented format, and there are probably a few others out there. No one really wants to teach the kernel to parse enclave files.

There are two issues with how this interacts with LSMs:

Quoted 10 lines

1) LSMs might want to be able to whitelist, blacklist, or otherwise restrict what enclaves can run at all. The current proposal that everyone seems to dislike the least is to have a .sigstruct file on disk that contains a hash and signature of the enclave in a CPU-defined format. To initialize an enclave, a program will pass an fd to this file, and a new LSM hook can be called to allow or disallow the operation. In a SELinux context, the idea is that policy could require the .sigstruct file to be labeled with a type like sgx_sigstruct_t, and only enclaves that have a matching .sigstruct with such a label could run.

Quoted 2 lines

Similarly if we could take data for the enclave from fd and enforce it with sgx_enclave_t label.

That certainly *could* be done, and I guess the decision could be left to the LSMs, but I'm not convinced this adds value. What security use case does this cover that isn't already covered by requiring EXECUTE (e.g. lib_t) on the enclave file and some new SIGSTRUCT right on the .sigstruct?

Quoted 15 lines
Quoted 10 lines

Here's a very vague proposal that's kind of like what I've been thinking over the past few days. The SGX inode could track, for each page, a "safe-to-execute" bit. When you first open /dev/sgx/enclave, you get a blank enclave and all pages are safe-to-execute. When you do the ioctl to load context (which could be code, data, or anything else), the kernel will check whether the *source* VMA is executable and, if not, mark the page of the enclave being loaded as unsafe. Once the enclave is initialized, the driver will clear the safe-to-execute bit for any page that is successfully mapped writably.

With the fd based model for source I'd mark SECINFO.W pages as unsafe to execute and then check unsafe bit before applying lets say EMODT or EMODPR.

Quoted 9 lines

There is a problem here though. Usually the enclave itself is just a loader that then loads the application from outside source and creates the executable pages from the content.

A great example of this is Graphene that bootstraps unmodified Linux applications to an enclave:

https://github.com/oscarlab/graphene

ISTM you should need EXECMEM or similar to run Graphene, then.

#140 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 5 lines · Andy Lutomirski
Quoted 5 lines · Jarkko Sakkinen

There is a problem here though. Usually the enclave itself is just a loader that then loads the application from outside source and creates the executable pages from the content.

Quoted 7 lines
Quoted 5 lines

A great example of this is Graphene that bootstraps unmodified Linux applications to an enclave:

https://github.com/oscarlab/graphene

ISTM you should need EXECMEM or similar to run Graphene, then.

Agreed, Graphene is effectively running arbitrary enclave code. I'm guessing there is nothing that prevents extending/reworking Graphene to allow generating the enclave ahead of time so as to avoid populating the guts of the enclave at runtime, i.e. it's likely possible to run an unmodified application in an enclave without EXECMEM if that's something Graphene or its users really care about.

#141 lore raw

RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines

There is a problem here though. Usually the enclave itself is just a loader that then loads the application from outside source and creates the executable pages from the content.

A great example of this is Graphene that bootstraps unmodified Linux applications to an enclave:

https://github.com/oscarlab/graphene

Quoted 8 lines
Quoted 1 line

ISTM you should need EXECMEM or similar to run Graphene, then.

Agreed, Graphene is effectively running arbitrary enclave code. I'm guessing there is nothing that prevents extending/reworking Graphene to allow generating the enclave ahead of time so as to avoid populating the guts of the enclave at runtime, i.e. it's likely possible to run an unmodified application in an enclave without EXECMEM if that's something Graphene or its users really care about.

Inefficient use of memory is a problem of running Graphene on SGX1, from at least 2 aspects: 1) heaps/stacks have to be pre-allocated but only a small portion of those pages will be actually used; and 2) dynamic linking is commonly used in *unmodified* applications and all dependent libraries have to be loaded, but only a subset of those pages will actually be used - e.g. most applications use only a small set of functions in libc.so but the whole library still has to be loaded. Hence a practical/efficient solution will require/involve EDMM features available in SGX2. I guess we shall look a bit further into future in order to address this problem properly. And I think it necessary to distinguish enclave virtual ranges from regular ones (probably at VMA level) before we could have a practical solution.

#142 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Sean Christopherson
Quoted 12 lines · Sean Christopherson
Quoted 11 lines · Andy Lutomirski
Quoted 10 lines · Jarkko Sakkinen

There is a problem here though. Usually the enclave itself is just a loader that then loads the application from outside source and creates the executable pages from the content.

A great example of this is Graphene that bootstraps unmodified Linux applications to an enclave:

https://github.com/oscarlab/graphene

Quoted 8 lines
Quoted 1 line

ISTM you should need EXECMEM or similar to run Graphene, then.

Agreed, Graphene is effectively running arbitrary enclave code. I'm guessing there is nothing that prevents extending/reworking Graphene to allow generating the enclave ahead of time so as to avoid populating the guts of the enclave at runtime, i.e. it's likely possible to run an unmodified application in an enclave without EXECMEM if that's something Graphene or its users really care about.

I'd guess that also people adding SGX support to containers want somewhat similar framework to work on so that you can just wrap a container with an enclave.

/Jarkko

#143 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Andy Lutomirski
Quoted 5 lines · Andy Lutomirski

That certainly *could* be done, and I guess the decision could be left to the LSMs, but I'm not convinced this adds value. What security use case does this cover that isn't already covered by requiring EXECUTE (e.g. lib_t) on the enclave file and some new SIGSTRUCT right on the .sigstruct?

I guess you are right as SIGSTRUCT completely shields the memory layout and contents of an enclave.

/Jarkko

#144 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Andy Lutomirski
Quoted 10 lines · Andy Lutomirski

Here's a very vague proposal that's kind of like what I've been thinking over the past few days. The SGX inode could track, for each page, a "safe-to-execute" bit. When you first open /dev/sgx/enclave, you get a blank enclave and all pages are safe-to-execute. When you do the ioctl to load context (which could be code, data, or anything else), the kernel will check whether the *source* VMA is executable and, if not, mark the page of the enclave being loaded as unsafe. Once the enclave is initialized, the driver will clear the safe-to-execute bit for any page that is successfully mapped writably.

Quoted 8 lines

The intent is that a page of the enclave is safe-to-execute if that page was populated from executable memory and not modified since then. LSMs could then enforce a policy that you can map an enclave page RX if the page is safe-to-execute, you can map any page you want for write if there are no executable mappings, and you can only map a page for write and execute simultaneously if you can EXECMOD permission. This should allow an enclave to be loaded by userspace from a file with EXECUTE rights.

I'm still confused as to why you want to track execute permissions on the enclave pages and add SGX-specific LSM hooks. Is there anything that prevents userspace from building the enclave like any other DSO and then copying it into enclave memory? I feel like I'm missing something.

1. Userspace loads enclave into regular memory, e.g. like a normal DSO. All mmap(), mprotect(), etc... calls are subject to all existing LSM policies.

2. Userspace opens /dev/sgx/enclave to instantiate a new enclave.

3. Userspace uses mmap() to allocate virtual memory for its enclave, again subject to all existing LSM policies (sane userspaces map it RO since the permissions eventually get tossed anyways).

4. SGX subsystem refuses to service page faults for enclaves that have not yet been initialized, e.g. signals SIGBUS or SIGSEGV.

5. Userspace invokes SGX ioctl() to copy enclave from regulary VMA to enclave VMA.

6. SGX ioctl() propagates VMA protection-related flags from source VMA to enclave VMA, e.g. invokes mprotect_fixup(). Enclave VMA(s) may be split as part of this process.

7. At all times, mprotect() calls on the enclave VMA are subject to existing LSM policies, i.e. it's not special cased for enclaves.

The SGX ioctl() would need to take mmap_sem for write, but we can mitigate that issue by changing the ioctl() to take a range of memory instead of a single page. That'd also provide "EADD batching" that folks have requested.

maintainer
#145 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 21 lines · Sean Christopherson
Quoted 10 lines · Andy Lutomirski

Here's a very vague proposal that's kind of like what I've been thinking over the past few days. The SGX inode could track, for each page, a "safe-to-execute" bit. When you first open /dev/sgx/enclave, you get a blank enclave and all pages are safe-to-execute. When you do the ioctl to load context (which could be code, data, or anything else), the kernel will check whether the *source* VMA is executable and, if not, mark the page of the enclave being loaded as unsafe. Once the enclave is initialized, the driver will clear the safe-to-execute bit for any page that is successfully mapped writably.

Quoted 8 lines

The intent is that a page of the enclave is safe-to-execute if that page was populated from executable memory and not modified since then. LSMs could then enforce a policy that you can map an enclave page RX if the page is safe-to-execute, you can map any page you want for write if there are no executable mappings, and you can only map a page for write and execute simultaneously if you can EXECMOD permission. This should allow an enclave to be loaded by userspace from a file with EXECUTE rights.

Quoted 4 lines

I'm still confused as to why you want to track execute permissions on the enclave pages and add SGX-specific LSM hooks. Is there anything that prevents userspace from building the enclave like any other DSO and then copying it into enclave memory?

It's entirely possible that I'm the one missing something. But here's why I think this:

Quoted 11 lines

I feel like I'm missing something.

1. Userspace loads enclave into regular memory, e.g. like a normal DSO. All mmap(), mprotect(), etc... calls are subject to all existing LSM policies.

2. Userspace opens /dev/sgx/enclave to instantiate a new enclave.

3. Userspace uses mmap() to allocate virtual memory for its enclave, again subject to all existing LSM policies (sane userspaces map it RO since the permissions eventually get tossed anyways).

Is userspace actually requred to mmap() the enclave prior to EADDing things?

Quoted 10 lines

4. SGX subsystem refuses to service page faults for enclaves that have not yet been initialized, e.g. signals SIGBUS or SIGSEGV.

5. Userspace invokes SGX ioctl() to copy enclave from regulary VMA to enclave VMA.

6. SGX ioctl() propagates VMA protection-related flags from source VMA to enclave VMA, e.g. invokes mprotect_fixup(). Enclave VMA(s) may be split as part of this process.

Does this also call the LSM? If so, what is it expected to do? What happens if there are different regions with different permissions on the same page? SGX has 256-byte granularity right?

Quoted 3 lines

7. At all times, mprotect() calls on the enclave VMA are subject to existing LSM policies, i.e. it's not special cased for enclaves.

I don't think the normal behavior actually works here. An enclave is always MAP_SHARED, so (with SELinux) mprotecting() to X or RX requires EXECUTE and mprotecting() to RWX requires extra permissions. But user code can also mmap() the enclave again. What is supposed to happen in that case?

#146 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 37 lines · Andy Lutomirski
Quoted 21 lines · Sean Christopherson
Quoted 10 lines · Andy Lutomirski

Here's a very vague proposal that's kind of like what I've been thinking over the past few days. The SGX inode could track, for each page, a "safe-to-execute" bit. When you first open /dev/sgx/enclave, you get a blank enclave and all pages are safe-to-execute. When you do the ioctl to load context (which could be code, data, or anything else), the kernel will check whether the *source* VMA is executable and, if not, mark the page of the enclave being loaded as unsafe. Once the enclave is initialized, the driver will clear the safe-to-execute bit for any page that is successfully mapped writably.

Quoted 8 lines

The intent is that a page of the enclave is safe-to-execute if that page was populated from executable memory and not modified since then. LSMs could then enforce a policy that you can map an enclave page RX if the page is safe-to-execute, you can map any page you want for write if there are no executable mappings, and you can only map a page for write and execute simultaneously if you can EXECMOD permission. This should allow an enclave to be loaded by userspace from a file with EXECUTE rights.

Quoted 4 lines

I'm still confused as to why you want to track execute permissions on the enclave pages and add SGX-specific LSM hooks. Is there anything that prevents userspace from building the enclave like any other DSO and then copying it into enclave memory?

It's entirely possible that I'm the one missing something. But here's why I think this:

Quoted 6 lines

I feel like I'm missing something.

1. Userspace loads enclave into regular memory, e.g. like a normal DSO. All mmap(), mprotect(), etc... calls are subject to all existing LSM policies.

Quoted 7 lines
Quoted 5 lines

2. Userspace opens /dev/sgx/enclave to instantiate a new enclave.

3. Userspace uses mmap() to allocate virtual memory for its enclave, again subject to all existing LSM policies (sane userspaces map it RO since the permissions eventually get tossed anyways).

Is userspace actually requred to mmap() the enclave prior to EADDing things?

It was a requirement prior to the API rework in v20, i.e. unless someone was really quick on the draw after the v20 update all existing userspace
implementations mmap() the enclave before ECREATE. Requiring a valid
enclave VMA for EADD shoudn't be too onerous.

Quoted 11 lines
Quoted 9 lines

4. SGX subsystem refuses to service page faults for enclaves that have not yet been initialized, e.g. signals SIGBUS or SIGSEGV.

5. Userspace invokes SGX ioctl() to copy enclave from regulary VMA to enclave VMA.

6. SGX ioctl() propagates VMA protection-related flags from source VMA to enclave VMA, e.g. invokes mprotect_fixup(). Enclave VMA(s) may be split as part of this process.

Does this also call the LSM? If so, what is it expected to do?

Nope. My reasoning behind skipping LSM checks is that the LSMs have already ok'd the source VMAs, similar to how dup_mmap() doesn't redo LSM checks.

Quoted 2 lines

What happens if there are different regions with different permissions on the same page? SGX has 256-byte granularity right?

No, EPC pages have 4k granularity.

The EPC is divided into EPC pages. An EPC page is 4KB in size and always aligned on a 4KB boundary

EEXTEND is the only aspect of SGX that works on 256-byte chunks, and that goofiness is primarily to keep the latency of EEXTEND low enough so that the instruction doesn't have to be interruptible, a la EINIT.

Quoted 7 lines
Quoted 3 lines

7. At all times, mprotect() calls on the enclave VMA are subject to existing LSM policies, i.e. it's not special cased for enclaves.

I don't think the normal behavior actually works here. An enclave is always MAP_SHARED, so (with SELinux) mprotecting() to X or RX requires EXECUTE and mprotecting() to RWX requires extra permissions.

Requiring extra permissions is good though, right? My thinking is to make the EADD "VMA copy" the happy/easy path, while using mprotect() to convert EPC memory to executable would require PROCESS__EXECMEM (assuming we back enclaves with anon inodes instead of /dev/sgx/enclave).

Quoted 2 lines

But user code can also mmap() the enclave again. What is supposed to happen in that case?

Hmm, it can't effectively re-mmap() the enclave as executable since entering the enclave requires using the correct virtual address range, i.e. EENTER would fail. It could, I think, do munmap()->mmap() to change the permissions. We could handle that case fairly easily by invoking security_file_mprotect() in SGX's mmap() hook if any pages have been added to the enclave, i.e. treat mmap() like mprotect().

#147 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 4 lines · Sean Christopherson

It was a requirement prior to the API rework in v20, i.e. unless someone was really quick on the draw after the v20 update all existing userspace
implementations mmap() the enclave before ECREATE. Requiring a valid
enclave VMA for EADD shoudn't be too onerous.

Still underlining: it is not required.

/Jarkko

#148 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Andy Lutomirski
Quoted 1 line · Andy Lutomirski

Is userspace actually requred to mmap() the enclave prior to EADDing things?

Nope, not since v20. Here is what I wrote about API to the kernel documentation:

"The enclave life-cycle starts by opening /dev/sgx/enclave. After this there is already a data structure inside kernel tracking the enclave that is initially uncreated. After this a set of ioctl's can be used to create, populate and initialize the enclave.

You can close (if you want) the fd after you've mmap()'d. As long as the file is open the enclave stays alive so you might want to do that after you don't need it anymore. Even munmap() won't destruct the enclave if the file is open. Neither will closing the fd as long as you have mmap() done over the fd (even if it does not across the range defined in SECS)."

Enclave can be created and initialized without doing a single mmap() call.

/Jarkko

#149 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 18 lines · Jarkko Sakkinen
Quoted 1 line · Andy Lutomirski

Is userspace actually requred to mmap() the enclave prior to EADDing things?

Nope, not since v20. Here is what I wrote about API to the kernel documentation:

"The enclave life-cycle starts by opening /dev/sgx/enclave. After this there is already a data structure inside kernel tracking the enclave that is initially uncreated. After this a set of ioctl's can be used to create, populate and initialize the enclave.

You can close (if you want) the fd after you've mmap()'d. As long as the file is open the enclave stays alive so you might want to do that after you don't need it anymore. Even munmap() won't destruct the enclave if the file is open. Neither will closing the fd as long as you have mmap() done over the fd (even if it does not across the range defined in SECS)."

Quoted 2 lines

Enclave can be created and initialized without doing a single mmap() call.

We could even disallow mmap() before EINIT done. The way enclave management internally works right now is quite robust and completely detached from requiring process address space for anything.

/Jarkko

#150 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 1 line · Jarkko Sakkinen

We could even disallow mmap() before EINIT done.

This would be extremely annoying in software because now you have to save the all the page permissions somewhere between EADD and mprotect.

--
Jethro Beekman | Fortanix

#151 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 4 lines · Jethro Beekman
Quoted 1 line · Jarkko Sakkinen

We could even disallow mmap() before EINIT done.

This would be extremely annoying in software because now you have to save the all the page permissions somewhere between EADD and mprotect.

Actually you don't have to use mprotect anymore that much.

You can just do multiple mmap's even with v20 after EINIT, one for each region (albeit it does not enforce above).

/Jarkko

#152 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Jarkko Sakkinen
Quoted 19 lines · Jarkko Sakkinen
Quoted 18 lines · Jarkko Sakkinen
Quoted 1 line · Andy Lutomirski

Is userspace actually requred to mmap() the enclave prior to EADDing things?

Nope, not since v20. Here is what I wrote about API to the kernel documentation:

"The enclave life-cycle starts by opening /dev/sgx/enclave. After this there is already a data structure inside kernel tracking the enclave that is initially uncreated. After this a set of ioctl's can be used to create, populate and initialize the enclave.

You can close (if you want) the fd after you've mmap()'d. As long as the file is open the enclave stays alive so you might want to do that after you don't need it anymore. Even munmap() won't destruct the enclave if the file is open. Neither will closing the fd as long as you have mmap() done over the fd (even if it does not across the range defined in SECS)."

Quoted 6 lines
Quoted 2 lines

Enclave can be created and initialized without doing a single mmap() call.

We could even disallow mmap() before EINIT done. The way enclave management internally works right now is quite robust and completely detached from requiring process address space for anything.

Except that mmap() is more or less required to guarantee that ELRANGE established by ECREATE is available. And we want to disallow mmap() as soon as the first EADD is done so that userspace can't remap the enclave's VMAs via munmap()->mmap() and gain execute permissions to pages that were EADD'd as NX.

Actually, conceptually it's probably more intuitive to disallow mmap() at ECREATE, i.e. the act of creating an enclave pins the associated virtual address range until the enclave is destroyed.

#153 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 5 lines · Sean Christopherson

Except that mmap() is more or less required to guarantee that ELRANGE established by ECREATE is available. And we want to disallow mmap() as soon as the first EADD is done so that userspace can't remap the enclave's VMAs via munmap()->mmap() and gain execute permissions to pages that were EADD'd as NX.

We don't want to guarantee such thing and it is not guaranteed. It does not fit at all to the multi process work done. Enclaves are detached from any particular process addresse spaces. It is responsibility of process to open windows to them.

That would be completely against work that we've done lately.

Quoted 3 lines

Actually, conceptually it's probably more intuitive to disallow mmap() at ECREATE, i.e. the act of creating an enclave pins the associated virtual address range until the enclave is destroyed.

/Jarkko

#154 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 7 lines · Jarkko Sakkinen
Quoted 5 lines · Sean Christopherson

Except that mmap() is more or less required to guarantee that ELRANGE established by ECREATE is available. And we want to disallow mmap() as soon as the first EADD is done so that userspace can't remap the enclave's VMAs via munmap()->mmap() and gain execute permissions to pages that were EADD'd as NX.

Quoted 6 lines

We don't want to guarantee such thing and it is not guaranteed. It does not fit at all to the multi process work done. Enclaves are detached from any particular process addresse spaces. It is responsibility of process to open windows to them.

That would be completely against work that we've done lately.

Example use case: you have a process that just constructs an enclave and sends it to another process or processes for use. The constructor process could have basically anything on that range. This was the key goal of the fd based enclave work.

/Jarkko

#155 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 13 lines · Jarkko Sakkinen
Quoted 12 lines · Jarkko Sakkinen
Quoted 5 lines · Sean Christopherson

Except that mmap() is more or less required to guarantee that ELRANGE established by ECREATE is available. And we want to disallow mmap() as soon as the first EADD is done so that userspace can't remap the enclave's VMAs via munmap()->mmap() and gain execute permissions to pages that were EADD'd as NX.

We don't want to guarantee such thing and it is not guaranteed. It does not fit at all to the multi process work done. Enclaves are detached from any particular process addresse spaces. It is responsibility of process to open windows to them.

Quoted 6 lines
Quoted 1 line

That would be completely against work that we've done lately.

Example use case: you have a process that just constructs an enclave and sends it to another process or processes for use. The constructor process could have basically anything on that range. This was the key goal of the fd based enclave work.

What exactly happens in the constructor versus the recipient processes? Which process performs each of the necessary open(), mmap(), and ioctl() calls for setting up the enclave? Can you provide a high level overview of the sequence of userspace calls by the constructor and by the recipient similar to what Sean showed earlier for just a single process?

#156 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 21 lines · Stephen Smalley
Quoted 13 lines · Jarkko Sakkinen
Quoted 12 lines · Jarkko Sakkinen
Quoted 5 lines · Sean Christopherson

Except that mmap() is more or less required to guarantee that ELRANGE established by ECREATE is available. And we want to disallow mmap() as soon as the first EADD is done so that userspace can't remap the enclave's VMAs via munmap()->mmap() and gain execute permissions to pages that were EADD'd as NX.

We don't want to guarantee such thing and it is not guaranteed. It does not fit at all to the multi process work done. Enclaves are detached from any particular process addresse spaces. It is responsibility of process to open windows to them.

Quoted 6 lines
Quoted 1 line

That would be completely against work that we've done lately.

Example use case: you have a process that just constructs an enclave and sends it to another process or processes for use. The constructor process could have basically anything on that range. This was the key goal of the fd based enclave work.

Quoted 5 lines

What exactly happens in the constructor versus the recipient processes? Which process performs each of the necessary open(), mmap(), and ioctl() calls for setting up the enclave? Can you provide a high level overview of the sequence of userspace calls by the constructor and by the recipient similar to what Sean showed earlier for just a single process?

Hmm, what we had talked about was allowing the SGX ioctls to work without an associated VMA, with the end goal of letting userspace restrict access
to /dev/sgx/enclave. Very roughly...

Enclave Owner:

  connect(builder, ...);
  send(builder, "/home/sean/path/to/my/enclave");

  recv(builder, &enclave_fd);

  for_each_chunk {
          mmap(enclave_addr + offset, size, ..., MAP_SHARED, enclave_fd, 0);
  }

Enclave Builder:

  recv(sock, &enclave_path);

  source_fd = open(enclave_path, O_RDONLY);
  for_each_chunk {
          <hand waving - mmap()/mprotect() the enclave file into regular memory>
  }

  enclave_fd = open("/dev/sgx/enclave", O_RDWR);

  ioctl(enclave_fd, ENCLAVE_CREATE, ...);
  for_each_chunk {
      struct sgx_enclave_add ioctlargs = {
          .offset = chunk.offset,
          .source = chunk.addr,
          .size   = chunk.size,
          .type   = chunk.type, /* SGX specific metadata */
      }
      ioctl(fd, ENCLAVE_ADD, &ioctlargs); /* modifies enclave's VMAs */
  }
  ioctl(enclave_fd, ENCLAVE_INIT, ...);

  write(sock, enclave_fd);

But the above flow is flawed because there'a catch-22: ENCLAVE_ECREATE takes the virtual address of the enclave, but in the above flow that's not established until "mmap(..., enclave_fd)". And because an enclave's virtual range needs to be naturally aligned (hardware requirements), the enclave owner would need to do something like:

  source_fd = open("/home/sean/path/to/my/enclave", O_RDONLY);
  size = <parse size from source_fd>
  
  enclave_range = mmap(NULL, size*2, PROT_READ, ???, NULL, 0);
  enclave_addr = (enclave_range + (size - 1)) & ~(size - 1);

  connect(builder, ...);
  send(builder, {"/home/sean/path/to/my/enclave", enclave_addr});

  recv(builder, &enclave_fd);

  munmap(enclave_range);

  for_each_chunk {
      addr = mmap(enclave_addr + c.offset, c.size, ..., MAP_SHARED, enclave_fd, 0);
      if (addr != enclave_addr + c.offset)
           exit(1);
  } 

And that straight up doesn't work with the v20 driver because mmap() with the enclave_fd will run through sgx_get_unmapped_area(), which also does the natural alignment adjustments (the idea being that mmap() is mapping the entire enclave). E.g. mmap() will map the wrong address if the offset of a chunk is less than its size due to the driver adjusting the address.

Eliminating sgx_get_unmapped_area() means userspace is once again on the hook for naturally aligning the enclave, which is less than desirable.

Looking back at the original API discussions around a builder process[1], we never fleshed out the end-to-end flow. While having a builder process *sounds* reasonable, in practice it adds a lot of complexity without providing much in the way of added security. E.g. in addition to the above mmap() issues, since the order of EADDs affects the enclave measurement, the enclave owner would need to communicate the exact steps to build the enclave, or the builder would need a priori knowledge of the enclave format.

Userspace can still restrict access to /dev/sgx/enclave, e.g. by having a daemon that requires additional credentials to obtain a new enclave_fd. So AFAICT, the only benefit to having a dedicated builder is that it can do its own whitelisting of enclaves, but since we're trending towards supporting whitelisting enclaves in the kernel, e.g. via sigstruct, whitelisting in userspace purely in userspace also provides marginal value.

TL;DR: Requiring VMA backing to build an enclave seems reasonable and sane.

[1] https://lkml.kernel.org/r/CALCETrX+KisMCbptrnPSO79-YF4E3nR1XHt+a7hCs1GXsxAbtw@mail.gmail.com

maintainer
#157 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 96 lines · Sean Christopherson
Quoted 21 lines · Stephen Smalley
Quoted 13 lines · Jarkko Sakkinen
Quoted 12 lines · Jarkko Sakkinen
Quoted 5 lines · Sean Christopherson

Except that mmap() is more or less required to guarantee that ELRANGE established by ECREATE is available. And we want to disallow mmap() as soon as the first EADD is done so that userspace can't remap the enclave's VMAs via munmap()->mmap() and gain execute permissions to pages that were EADD'd as NX.

We don't want to guarantee such thing and it is not guaranteed. It does not fit at all to the multi process work done. Enclaves are detached from any particular process addresse spaces. It is responsibility of process to open windows to them.

Quoted 6 lines
Quoted 1 line

That would be completely against work that we've done lately.

Example use case: you have a process that just constructs an enclave and sends it to another process or processes for use. The constructor process could have basically anything on that range. This was the key goal of the fd based enclave work.

Quoted 5 lines

What exactly happens in the constructor versus the recipient processes? Which process performs each of the necessary open(), mmap(), and ioctl() calls for setting up the enclave? Can you provide a high level overview of the sequence of userspace calls by the constructor and by the recipient similar to what Sean showed earlier for just a single process?

Hmm, what we had talked about was allowing the SGX ioctls to work without an associated VMA, with the end goal of letting userspace restrict access
to /dev/sgx/enclave. Very roughly...

Enclave Owner:

  connect(builder, ...);
  send(builder, "/home/sean/path/to/my/enclave");

  recv(builder, &enclave_fd);

  for_each_chunk {
          mmap(enclave_addr + offset, size, ..., MAP_SHARED, enclave_fd, 0);
  }

Enclave Builder:

  recv(sock, &enclave_path);

  source_fd = open(enclave_path, O_RDONLY);
  for_each_chunk {
          <hand waving - mmap()/mprotect() the enclave file into regular memory>
  }

  enclave_fd = open("/dev/sgx/enclave", O_RDWR);

  ioctl(enclave_fd, ENCLAVE_CREATE, ...);
  for_each_chunk {
      struct sgx_enclave_add ioctlargs = {
          .offset = chunk.offset,
          .source = chunk.addr,
          .size   = chunk.size,
          .type   = chunk.type, /* SGX specific metadata */
      }
      ioctl(fd, ENCLAVE_ADD, &ioctlargs); /* modifies enclave's VMAs */
  }
  ioctl(enclave_fd, ENCLAVE_INIT, ...);

  write(sock, enclave_fd);

But the above flow is flawed because there'a catch-22: ENCLAVE_ECREATE takes the virtual address of the enclave, but in the above flow that's not established until "mmap(..., enclave_fd)". And because an enclave's virtual range needs to be naturally aligned (hardware requirements), the enclave owner would need to do something like:

  source_fd = open("/home/sean/path/to/my/enclave", O_RDONLY);
  size = <parse size from source_fd>

  enclave_range = mmap(NULL, size*2, PROT_READ, ???, NULL, 0);
  enclave_addr = (enclave_range + (size - 1)) & ~(size - 1);

  connect(builder, ...);
  send(builder, {"/home/sean/path/to/my/enclave", enclave_addr});

  recv(builder, &enclave_fd);

  munmap(enclave_range);

  for_each_chunk {
      addr = mmap(enclave_addr + c.offset, c.size, ..., MAP_SHARED, enclave_fd, 0);
      if (addr != enclave_addr + c.offset)
           exit(1);
  }
Quoted 5 lines

And that straight up doesn't work with the v20 driver because mmap() with the enclave_fd will run through sgx_get_unmapped_area(), which also does the natural alignment adjustments (the idea being that mmap() is mapping the entire enclave). E.g. mmap() will map the wrong address if the offset of a chunk is less than its size due to the driver adjusting the address.

That presumably needs to change.

Are we entirely missing an API to allocate a naturally aligned VA range? That's kind of annoying.

Quoted 13 lines

Eliminating sgx_get_unmapped_area() means userspace is once again on the hook for naturally aligning the enclave, which is less than desirable.

Looking back at the original API discussions around a builder process[1], we never fleshed out the end-to-end flow. While having a builder process *sounds* reasonable, in practice it adds a lot of complexity without providing much in the way of added security. E.g. in addition to the above mmap() issues, since the order of EADDs affects the enclave measurement, the enclave owner would need to communicate the exact steps to build the enclave, or the builder would need a priori knowledge of the enclave format.

Quoted 8 lines

Userspace can still restrict access to /dev/sgx/enclave, e.g. by having a daemon that requires additional credentials to obtain a new enclave_fd. So AFAICT, the only benefit to having a dedicated builder is that it can do its own whitelisting of enclaves, but since we're trending towards supporting whitelisting enclaves in the kernel, e.g. via sigstruct, whitelisting in userspace purely in userspace also provides marginal value.

TL;DR: Requiring VMA backing to build an enclave seems reasonable and sane.

This isn't necessarily a problem, but we pretty much have to use mprotect() then.

Maybe the semantics could just be that mmap() on the SGX device gives natural alignment, but that there is no actual constraint enforced by the driver as to whether mmap() happens before or after ECREATE. After all, it's *ugly* for user code to reserve its address range with an awkward giant mmap(), there's nothing fundamentally wrong with it.

As far as I know from this whole discussion, we still haven't come up with any credible way to avoid tracking, per enclave page, whether that page came from unmodified PROT_EXEC memory.

#158 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 10 lines · Andy Lutomirski
Quoted 6 lines · Sean Christopherson

And that straight up doesn't work with the v20 driver because mmap() with the enclave_fd will run through sgx_get_unmapped_area(), which also does the natural alignment adjustments (the idea being that mmap() is mapping the entire enclave). E.g. mmap() will map the wrong address if the offset of a chunk is less than its size due to the driver adjusting the address.

That presumably needs to change.

If we want to allow mmap() on a subset of the enclave, yes. I assume it's a simple matter of respecting MAP_FIXED.

Quoted 2 lines

Are we entirely missing an API to allocate a naturally aligned VA range? That's kind of annoying.

Yes?

Quoted 19 lines
Quoted 19 lines

Eliminating sgx_get_unmapped_area() means userspace is once again on the hook for naturally aligning the enclave, which is less than desirable.

Looking back at the original API discussions around a builder process[1], we never fleshed out the end-to-end flow. While having a builder process *sounds* reasonable, in practice it adds a lot of complexity without providing much in the way of added security. E.g. in addition to the above mmap() issues, since the order of EADDs affects the enclave measurement, the enclave owner would need to communicate the exact steps to build the enclave, or the builder would need a priori knowledge of the enclave format.

Userspace can still restrict access to /dev/sgx/enclave, e.g. by having a daemon that requires additional credentials to obtain a new enclave_fd. So AFAICT, the only benefit to having a dedicated builder is that it can do its own whitelisting of enclaves, but since we're trending towards supporting whitelisting enclaves in the kernel, e.g. via sigstruct, whitelisting in userspace purely in userspace also provides marginal value.

Quoted 4 lines
Quoted 1 line

TL;DR: Requiring VMA backing to build an enclave seems reasonable and sane.

This isn't necessarily a problem, but we pretty much have to use mprotect() then.

You lost me there. Who needs to mprotect() what?

Quoted 9 lines

Maybe the semantics could just be that mmap() on the SGX device gives natural alignment, but that there is no actual constraint enforced by the driver as to whether mmap() happens before or after ECREATE. After all, it's *ugly* for user code to reserve its address range with an awkward giant mmap(), there's nothing fundamentally wrong with it.

As far as I know from this whole discussion, we still haven't come up with any credible way to avoid tracking, per enclave page, whether that page came from unmodified PROT_EXEC memory.

Disallowing mmap() after ECREATE is credible, but apparently not palatable. :-)

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

Tracking permissions per enclave page isn't difficult, it's the new SGX specific LSM hooks and mprotect() interactions that I want to avoid.

Jumping back to mmap(), AIUI the fundamental issue is that we want to allow building/running an enclave without FILE__WRITE and FILE__EXECUTE, otherwise FILE__WRITE and FILE__EXECUTE become meaningless. Assuming I'm not off in the weeds, that means we really just need to special case mmap() on enclaves so it can map enclave memory using the verified page permissions so as not to run afoul of LSM checks. All other behaviors, e.g. mprotect(), can reuse the existing LSM checks for shared mappings.

So, what if we snapshot the permissions for each enclave page at EADD, and then special case mmap() to propagate flags from the snapshot to the VMA? More or less the same idea as doing mprotect_fixup() using the source VMA during EADD. We could define the EADD semantics to match this as well, e.g. only propagate the flags from the source VMA to the enclave VMA if the EADD range is fully mapped with PROT_NONE. This would allow the enclave builder concept, albeit with funky semantics, and wouldn't require new LSM hooks.

E.g. something like this:

static inline void sgx_mmap_update_prot_flags(struct vm_area_struct *vma,
struct sgx_encl *encl)

{
	struct radix_tree_iter iter;
	struct sgx_encl_page *entry;
	unsigned long addr;
	vm_flags_t flags;
	void **slot;

	/*
	 * SGX special: if userspace is requesting PROT_NONE and pages have
	 * been added to the enclave, then propagate the flags snapshot from
	 * the enclave to the VMA.  Do this if and only if all overlapped
	 * pages are defined and have identical permissions.  Stuffing the
	 * VMA on PROT_NONE allows userspace to map EPC pages without being
	 * incorrectly rejected by LSMs due to insufficient permissions (the
	 * snapshottted flags have alaredy been vetted).
	 */
	if (vma->vm_flags & (VM_READ|VM_WRITE|VM_EXEC))
		return;

	flags = 0;

	for (addr = vma->vm_start; addr < vma->vm_end; addr += PAGE_SIZE) {
		entry = radix_tree_lookup(&encl->page_tree, addr >> PAGE_SHIFT);

		if (!entry && flags)
			return;
		if (!flags && entry) {
			if (addr == vma->vm_start) {
				flags = entry->vm_flags;
				continue;
			}
			return;
		}
		if (entry && flags && entry->vm_flags != flags)
			return;

	}
	vma->vm_flags |= flags;
}
#159 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 6 lines · Sean Christopherson

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

I'm lost with the constraints we want to set.

We can still support fork() if we take a step back from v20 and require the mmap(). Given the recent comments, I'd guess that is the best compromise i.e. multiple processes can still share an enclave within the limitations of ancestor hierarchy. Is this the constraint we agree now upon? Some emails are a bit contradicting in this sense.

Quoted 11 lines

Tracking permissions per enclave page isn't difficult, it's the new SGX specific LSM hooks and mprotect() interactions that I want to avoid.

Jumping back to mmap(), AIUI the fundamental issue is that we want to allow building/running an enclave without FILE__WRITE and FILE__EXECUTE, otherwise FILE__WRITE and FILE__EXECUTE become meaningless. Assuming I'm not off in the weeds, that means we really just need to special case mmap() on enclaves so it can map enclave memory using the verified page permissions so as not to run afoul of LSM checks. All other behaviors, e.g. mprotect(), can reuse the existing LSM checks for shared mappings.

Quoted 8 lines

So, what if we snapshot the permissions for each enclave page at EADD, and then special case mmap() to propagate flags from the snapshot to the VMA? More or less the same idea as doing mprotect_fixup() using the source VMA during EADD. We could define the EADD semantics to match this as well, e.g. only propagate the flags from the source VMA to the enclave VMA if the EADD range is fully mapped with PROT_NONE. This would allow the enclave builder concept, albeit with funky semantics, and wouldn't require new LSM hooks.

Dropped off here completely. What if the mmap() is done before any of the EADD operations?

Quoted 36 lines

E.g. something like this:

static inline void sgx_mmap_update_prot_flags(struct vm_area_struct *vma,
struct sgx_encl *encl)

{
	struct radix_tree_iter iter;
	struct sgx_encl_page *entry;
	unsigned long addr;
	vm_flags_t flags;
	void **slot;

	/*
	 * SGX special: if userspace is requesting PROT_NONE and pages have
	 * been added to the enclave, then propagate the flags snapshot from
	 * the enclave to the VMA.  Do this if and only if all overlapped
	 * pages are defined and have identical permissions.  Stuffing the
	 * VMA on PROT_NONE allows userspace to map EPC pages without being
	 * incorrectly rejected by LSMs due to insufficient permissions (the
	 * snapshottted flags have alaredy been vetted).
	 */
	if (vma->vm_flags & (VM_READ|VM_WRITE|VM_EXEC))
		return;

	flags = 0;

	for (addr = vma->vm_start; addr < vma->vm_end; addr += PAGE_SIZE) {
		entry = radix_tree_lookup(&encl->page_tree, addr >> PAGE_SHIFT);

		if (!entry && flags)
			return;
		if (!flags && entry) {
			if (addr == vma->vm_start) {
				flags = entry->vm_flags;
				continue;
			}
Quoted 8 lines
			return;
		}
		if (entry && flags && entry->vm_flags != flags)
			return;

	}
	vma->vm_flags |= flags;
}

This looks flakky and error prone. You'd better have some "shadow VMAs" and check that you have such matching size of the VMA you try to mmap() and check flags from that.

Who would call this function anyhow and when?

Would be better to first agree on constraints. I have zero idea within which kind of enviroment this snippet would live e.g.

- mmap() (before, after?)
- multi process constraint (only fork or full on versatility)

/Jarkko

#160 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 9 lines · Jarkko Sakkinen
Quoted 6 lines · Sean Christopherson

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

I'm lost with the constraints we want to set.

As is today, SELinux policies would require enclave loaders to have FILE__WRITE and FILE__EXECUTE permissions on /dev/sgx/enclave. Presumably other LSMs have similar requirements. Requiring all processes to have FILE__{WRITE,EXECUTE} permissions means the permissions don't add much value, e.g. they can't be used to distinguish between an enclave that is being loaded from an unmodified file and an enclave that is being generated on the fly, e.g. Graphene.

Looking back at Andy's mail, he was talking about requiring FILE__EXECUTE to run an enclave, so perhaps it's only FILE__WRITE that we're trying to special case.

Quoted 26 lines

We can still support fork() if we take a step back from v20 and require the mmap(). Given the recent comments, I'd guess that is the best compromise i.e. multiple processes can still share an enclave within the limitations of ancestor hierarchy. Is this the constraint we agree now upon? Some emails are a bit contradicting in this sense.

Quoted 11 lines

Tracking permissions per enclave page isn't difficult, it's the new SGX specific LSM hooks and mprotect() interactions that I want to avoid.

Jumping back to mmap(), AIUI the fundamental issue is that we want to allow building/running an enclave without FILE__WRITE and FILE__EXECUTE, otherwise FILE__WRITE and FILE__EXECUTE become meaningless. Assuming I'm not off in the weeds, that means we really just need to special case mmap() on enclaves so it can map enclave memory using the verified page permissions so as not to run afoul of LSM checks. All other behaviors, e.g. mprotect(), can reuse the existing LSM checks for shared mappings.

Quoted 8 lines

So, what if we snapshot the permissions for each enclave page at EADD, and then special case mmap() to propagate flags from the snapshot to the VMA? More or less the same idea as doing mprotect_fixup() using the source VMA during EADD. We could define the EADD semantics to match this as well, e.g. only propagate the flags from the source VMA to the enclave VMA if the EADD range is fully mapped with PROT_NONE. This would allow the enclave builder concept, albeit with funky semantics, and wouldn't require new LSM hooks.

Quoted 2 lines

Dropped off here completely. What if the mmap() is done before any of the EADD operations?

Three options I can think of, in descending order of magic required:

1. Do nothing. Userspace would essentially be required to mmap() the enclave after EINIT, which is ugly but not breaking since userspace could mmap() the enclave with a placeholder VMA prior to building the enclave, and then a series of mmap() to establish its "real" mapping.

2. Propagate the permissions from EADD to the VMAs of the current mm if the entire EADD range is mapped and the mapping is PROT_NONE.

3. Propagate the permissions from EADD to the VMAs of all mm structs that have mapped some piece of the enclave, following the matching rules from #2.

Quoted 48 lines
Quoted 35 lines

E.g. something like this:

static inline void sgx_mmap_update_prot_flags(struct vm_area_struct *vma,
struct sgx_encl *encl)

{
	struct radix_tree_iter iter;
	struct sgx_encl_page *entry;
	unsigned long addr;
	vm_flags_t flags;
	void **slot;

	/*
	 * SGX special: if userspace is requesting PROT_NONE and pages have
	 * been added to the enclave, then propagate the flags snapshot from
	 * the enclave to the VMA.  Do this if and only if all overlapped
	 * pages are defined and have identical permissions.  Stuffing the
	 * VMA on PROT_NONE allows userspace to map EPC pages without being
	 * incorrectly rejected by LSMs due to insufficient permissions (the
	 * snapshottted flags have alaredy been vetted).
	 */
	if (vma->vm_flags & (VM_READ|VM_WRITE|VM_EXEC))
		return;

	flags = 0;

	for (addr = vma->vm_start; addr < vma->vm_end; addr += PAGE_SIZE) {
		entry = radix_tree_lookup(&encl->page_tree, addr >> PAGE_SHIFT);

		if (!entry && flags)
			return;
		if (!flags && entry) {
			if (addr == vma->vm_start) {
				flags = entry->vm_flags;
				continue;
			}
Quoted 8 lines
			return;
		}
		if (entry && flags && entry->vm_flags != flags)
			return;

	}
	vma->vm_flags |= flags;
}

This looks flakky and error prone. You'd better have some "shadow VMAs" and check that you have such matching size of the VMA you try to mmap() and check flags from that.

Quoted 7 lines

Who would call this function anyhow and when?

Would be better to first agree on constraints. I have zero idea within which kind of enviroment this snippet would live e.g.

- mmap() (before, after?)
- multi process constraint (only fork or full on versatility)

This would be called from sgx_mmap(), i.e. mmap(). Sorry that wasn't at all clear. The idea is to inherit the protections from the enclave pages if mmap() was passed PROT_NONE, but do so in a paranoid way.

I don't think multi-process contraints would be required. This would allow an individual process to inherit the pre-verified protections. Other process(es) could map the enclave page with different protections, but doing so would require the appropriate FILE__* permissions for the other process(es).

maintainer
#161 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 20 lines · Sean Christopherson
Quoted 9 lines · Jarkko Sakkinen
Quoted 6 lines · Sean Christopherson

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

I'm lost with the constraints we want to set.

As is today, SELinux policies would require enclave loaders to have FILE__WRITE and FILE__EXECUTE permissions on /dev/sgx/enclave. Presumably other LSMs have similar requirements. Requiring all processes to have FILE__{WRITE,EXECUTE} permissions means the permissions don't add much value, e.g. they can't be used to distinguish between an enclave that is being loaded from an unmodified file and an enclave that is being generated on the fly, e.g. Graphene.

Quoted 4 lines

Looking back at Andy's mail, he was talking about requiring FILE__EXECUTE to run an enclave, so perhaps it's only FILE__WRITE that we're trying to special case.

I thought about this some more, and I have a new proposal that helps address the ELRANGE alignment issue and the permission issue at the cost of some extra verbosity. Maybe you all can poke holes in it :) The basic idea is to make everything more explicit from a user's perspective. Here's how it works:

Opening /dev/sgx/enclave gives an enclave_fd that, by design, doesn't give EXECUTE or WRITE. mmap() on the enclave_fd only works if you pass PROT_NONE and gives the correct alignment. The resulting VMA cannot be mprotected or mremapped. It can't be mmapped at all until after ECREATE because the alignment isn't known before that.

Associated with the enclave are a bunch (up to 7) "enclave segment inodes". These are anon_inodes that are created automagically. An enclave segment is a group of pages, not necessary contiguous, with an upper bound on the memory permissions. Each enclave page belongs to a segment. When you do EADD, you tell the driver what segment you're adding to. [0] This means that EADD gets an extra argument that is a permission mask for the page -- in addition to the initial SECINFO, you also pass to EADD something to the effect of "I promise never to map this with permissions greater than RX".

Then we just need some way to mmap a region from an enclave segment. This could be done by having a way to get an fd for an enclave segment or it could be done by having a new ioctl SGX_IOC_MAP_SEGMENT. User code would use this operation to replace, MAP_FIXED-style, ranges from the big PROT_NONE mapping with the relevant pages from the enclave segment. The resulting vma would only have VM_MAYWRITE if the segment is W, only have VM_MAYEXEC if the segment is X, and only have VM_MAYREAD if the segment is R. Depending on implementation details, the VMAs might need to restrict mremap() to avoid mapping pages that aren't part of the segment in question.

It's plausible that this whole thing works without the magic segment inodes under the hood, but figuring that out would need a careful look at how all the core mm bits and LSM bits work together.

To get all the LSM stuff to work, SELinux will need some way to automatically assign an appropriate label to the segment inodes. I assume that such a mechanism already exists and gets used for things like sockets, but I haven't actually confirmed this.

[0] There needs to be some vaguely intelligent semantics if you EADD the *same* address more than once. A simple solution would be to disallow it if the segments don't match.

#162 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 33 lines · Andy Lutomirski
Quoted 20 lines · Sean Christopherson
Quoted 9 lines · Jarkko Sakkinen
Quoted 6 lines · Sean Christopherson

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

I'm lost with the constraints we want to set.

As is today, SELinux policies would require enclave loaders to have FILE__WRITE and FILE__EXECUTE permissions on /dev/sgx/enclave. Presumably other LSMs have similar requirements. Requiring all processes to have FILE__{WRITE,EXECUTE} permissions means the permissions don't add much value, e.g. they can't be used to distinguish between an enclave that is being loaded from an unmodified file and an enclave that is being generated on the fly, e.g. Graphene.

Quoted 4 lines

Looking back at Andy's mail, he was talking about requiring FILE__EXECUTE to run an enclave, so perhaps it's only FILE__WRITE that we're trying to special case.

I thought about this some more, and I have a new proposal that helps address the ELRANGE alignment issue and the permission issue at the cost of some extra verbosity. Maybe you all can poke holes in it :) The basic idea is to make everything more explicit from a user's perspective. Here's how it works:

Quoted 4 lines

Opening /dev/sgx/enclave gives an enclave_fd that, by design, doesn't give EXECUTE or WRITE. mmap() on the enclave_fd only works if you pass PROT_NONE and gives the correct alignment. The resulting VMA cannot be mprotected or mremapped. It can't be mmapped at all until

I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?

Quoted 1 line

after ECREATE because the alignment isn't known before that.

I don't follow. The alignment is known because userspace knows the size of its enclave. The initial unknown is the address, but that becomes known once the initial mmap() completes.

Quoted 1 line

Associated with the enclave are a bunch (up to 7) "enclave segment

I assume 7 = R, W, X, RW, RX, WX and RWX?

Quoted 9 lines

inodes". These are anon_inodes that are created automagically. An enclave segment is a group of pages, not necessary contiguous, with an upper bound on the memory permissions. Each enclave page belongs to a segment. When you do EADD, you tell the driver what segment you're adding to. [0] This means that EADD gets an extra argument that is a permission mask for the page -- in addition to the initial SECINFO, you also pass to EADD something to the effect of "I promise never to map this with permissions greater than RX".

Quoted 10 lines

Then we just need some way to mmap a region from an enclave segment. This could be done by having a way to get an fd for an enclave segment or it could be done by having a new ioctl SGX_IOC_MAP_SEGMENT. User code would use this operation to replace, MAP_FIXED-style, ranges from the big PROT_NONE mapping with the relevant pages from the enclave segment. The resulting vma would only have VM_MAYWRITE if the segment is W, only have VM_MAYEXEC if the segment is X, and only have VM_MAYREAD if the segment is R. Depending on implementation details, the VMAs might need to restrict mremap() to avoid mapping pages that aren't part of the segment in question.

If my above assumptions regarding VM_MAY* and the "7 segments" are correct, IIUC you're proposing that an LSM could have policies for each of the anon inodes, e.g. grant/deny RWX vs. RW vs RX. Am I in the ballpark?

Quoted 8 lines

It's plausible that this whole thing works without the magic segment inodes under the hood, but figuring that out would need a careful look at how all the core mm bits and LSM bits work together.

To get all the LSM stuff to work, SELinux will need some way to automatically assign an appropriate label to the segment inodes. I assume that such a mechanism already exists and gets used for things like sockets, but I haven't actually confirmed this.

I (obviously) don't fully understand your proposal, but I don't think we want to hook inodes, e.g. AppArmor doesn't implement inode_permission() but does implement file_mprotect() and mmap_file(), which feel like the natural hooks for this sort of thing. I also think it's overkill, e.g. AppArmor doesn't have a concept of EXECMOD, EXECMEM, EXECHEAP, etc.., so I don't think we need to go beyond detecting W+X scenarios.

Starting with your original idea of tracking "safe to execute" and Cedric's of propagating the permissions from the source VMA, but tweaked with your new idea of clearing VM_MAY* and a custom MAP_FIXED/mprotect().

Add SGX_IOC_MPROTECT (or SGX_IOC_MAP_REGION?) that works as follows:

1. Track VM_MAY{READ,WRITE,EXEC} flags for each enclave page.
2. SGX_IOC_ADD_REGION, i.e. EADD, initializes the VM_MAY* flags for each enclave page based on the source VMA.
3. sgx_mmap() only works with PROT_NONE, skips alignment stuff if MAP_FIXED, and clears VM_MAY{READ,WRITE,EXEC}.
4. mprotect() on /dev/sgx/enclave doesn't work because the VMA doesn't have any VM_MAY{READ,WRITE,EXEC} capabilities.
5. Deny mremap() post-ECREATE as the address and size of the enclave are fixed at ECREATE (in hardware).
6. SGX_IOC_MPROTECT works like normal mprotect(), except the VM_MAY* flags are pulled from the enclave pages, and its call to security_file_mprotect() is VM_READ|VM_EXEC by default. The LSM call sets VM_WRITE iff the enclave page has both VM_MAYWRITE and VM_MAYEXEC. The idea here is to require READ and EXECUTE to run an enclave, and only require WRITE on /dev/sgx/enclave when the enclave can execute modified memory.

To support SGX2 down the road, which will want to convert a page to executable on the fly, we could add:

7. SGX_IOC_EXTEND_PERMISSIONS enables userspace to extend the VM_MAY* flags for an enclave page, e.g. to make a page executable. SGX_IOC_MPROTECT is still required to actually map the page. Notably, adding a RW page to the enclave, e.g. to grow its heap, doesn't require WRITE, whereas adding a RWX page, e.g. for dynamic loading, would require WRITE. This can only extend! E.g. userspace can't circumvent the WRITE requirement by clearing VM_MAYWRITE.

Note, FILE__WRITE on /dev/sgx/enclave is essentially equivalent to FILE__EXECMOD. Using FILE__WRITE in this way means there are no changes to SELinux (triggering FILE__EXECMOD would be awkward), and AppArmor also picks up extra protections for enclaves.

Quoted 3 lines

[0] There needs to be some vaguely intelligent semantics if you EADD the *same* address more than once. A simple solution would be to disallow it if the segments don't match.

I don't see any reason to allow duplicate EADD as it serves no purpose, e.g. doing so changes the enclave's measurement and that's it.

maintainer
#163 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 40 lines · Sean Christopherson
Quoted 33 lines · Andy Lutomirski
Quoted 20 lines · Sean Christopherson
Quoted 9 lines · Jarkko Sakkinen
Quoted 6 lines · Sean Christopherson

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

I'm lost with the constraints we want to set.

As is today, SELinux policies would require enclave loaders to have FILE__WRITE and FILE__EXECUTE permissions on /dev/sgx/enclave. Presumably other LSMs have similar requirements. Requiring all processes to have FILE__{WRITE,EXECUTE} permissions means the permissions don't add much value, e.g. they can't be used to distinguish between an enclave that is being loaded from an unmodified file and an enclave that is being generated on the fly, e.g. Graphene.

Quoted 4 lines

Looking back at Andy's mail, he was talking about requiring FILE__EXECUTE to run an enclave, so perhaps it's only FILE__WRITE that we're trying to special case.

I thought about this some more, and I have a new proposal that helps address the ELRANGE alignment issue and the permission issue at the cost of some extra verbosity. Maybe you all can poke holes in it :) The basic idea is to make everything more explicit from a user's perspective. Here's how it works:

Quoted 4 lines

Opening /dev/sgx/enclave gives an enclave_fd that, by design, doesn't give EXECUTE or WRITE. mmap() on the enclave_fd only works if you pass PROT_NONE and gives the correct alignment. The resulting VMA cannot be mprotected or mremapped. It can't be mmapped at all until

Quoted 7 lines

I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?

Quoted 1 line

after ECREATE because the alignment isn't known before that.

I don't follow. The alignment is known because userspace knows the size of its enclave. The initial unknown is the address, but that becomes known once the initial mmap() completes.

[...]

I think I made the mistake of getting too carried away with implementation details rather than just getting to the point. And I misremembered the ECREATE flow -- oops. Let me try again. First, here are some problems with some earlier proposals (mine, yours Cedric's):

- Having the EADD operation always work but have different effects
depending on the source memory permissions is, at the very least, confusing.

- If we want to encourage user programs to be well-behaved, we want
to make it easy to map the RX parts of an enclave RX, the RW parts RW, the RO parts R, etc. But this interacts poorly with the sgx_mmap() alignment magic, as you've pointed out.

- We don't want to couple LSMs with SGX too tightly.

So here's how a nice interface might work:

int enclave_fd = open("/dev/sgx/enclave", O_RDWR);

/* enclave_fd points to a totally blank enclave. Before ECREATE, we need to decide on an address. */

void *addr = mmap(NULL, size, PROT_NONE, MAP_SHARED, enclave_fd, 0);

/* we have an address! */

ioctl(enclave_fd, ECREATE, ...);

/* now add some data to the enclave. We want the RWX addition to fail
immediately unless we have the relevant LSM pemission. Similarly, we
want the RX addition to fail immediately unless the source VMA is appropriate. */

ioctl(enclave_fd, EADD, rx_source_1, MAXPERM=RX, ...); [the ... includes SECINFO, which the kernel doesn't really care about] ioctl(enclave_fd, EADD, ro_source_1, MAXPERM=RX ...); ioctl(enclave_fd, EADD, rw_source_1, MAXPERM=RW ...); ioctl(enclave_fd, EADD, rwx_source_1, MAXPERM=RWX ...);

ioctl(enclave_fd, EINIT, ...); /* presumably pass sigstruct_fd here, too. */

/* at this point, all is well except that the enclave is mapped PROT_NONE. There are a couple ways I can imagine to fix this. */

We could use mmap:

mmap(baseaddr+offset, len, PROT_READ, MAP_SHARED | MAP_FIXED, enclave_fd, 0); /* only succeeds if MAXPERM & R == R */

But this has some annoying implications with regard to sgx_get_unmapped_area(). We could use an ioctl:

ioctl(enclave_fd, SGX_IOC_MPROTECT, offset, len, PROT_READ);

which has the potentially nice property that we can completely bypass the LSM hooks, because the LSM has *already* vetted everything when the EADD calls were allowed. Or we could maybe even just use mprotect() itself:

mprotect(baseaddr + offset, len, PROT_READ);

Or, for the really evil option, we could use a bit of magic in .fault and do nothing here. Instead we'd make the initial mapping PROT_READ|PROT_WRITE|PROT_EXEC and have .fault actually instantiate the PTEs with the intersection of the VMA permissions and MAXPERM. I don't think I like this alternative, since it feels more magical than needed and it will be harder to debug. I like the fact that /proc/self/maps shows the actual permissions in all the other variants.

All of the rest of the crud in my earlier email was just implementation details. The point I was trying to make was that I think it's possible to implement this without making too much of a mess internally. I think I favor the mprotect() approach since it makes the behavior fairly obvious.

I don't think any of this needs to change for SGX2. We'd have an ioctl() that does EAUG and specifies MAXPERM. Trying to mprotect() a page that hasn't been added yet with any permission other than PROT_NONE would fail. I suppose we might end up needing a way to let the EAUG operation *change* MAXPERM, and this operation would have to do some more LSM checks and walk all the existing mappings to make sure they're consistent with the new MAXPERM.

As an aside, I wonder if Linus et all would be okay with a new MAP_FULLY_ALIGNED mmap() flag that allocated memory aligned to the requested size. Then we could get rid of yet another bit of magic.

--Andy

#164 lore raw

RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Hi Andy,

Quoted 58 lines

From: Andy Lutomirski [mailto:[email protected]]
Sent: Thursday, May 23, 2019 6:18 PM

Quoted 17 lines · Sean Christopherson
Quoted 15 lines · Andy Lutomirski
Quoted 13 lines · Sean Christopherson
Quoted 10 lines · Jarkko Sakkinen
Quoted 7 lines · Sean Christopherson

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to
mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

I'm lost with the constraints we want to set.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

As is today, SELinux policies would require enclave loaders to
have FILE__WRITE and FILE__EXECUTE permissions on
/dev/sgx/enclave. Presumably other LSMs have similar
requirements. Requiring all processes to have
FILE__{WRITE,EXECUTE} permissions means the permissions don't add much value, e.g. they can't be used to distinguish between an enclave that is being loaded from an unmodified file and an enclave that is being

generated on the fly, e.g. Graphene.

Quoted 25 lines
Quoted 12 lines
Quoted 5 lines

Looking back at Andy's mail, he was talking about requiring FILE__EXECUTE to run an enclave, so perhaps it's only FILE__WRITE that we're trying to special case.

I thought about this some more, and I have a new proposal that helps address the ELRANGE alignment issue and the permission issue at the cost of some extra verbosity. Maybe you all can poke holes in it :) The basic idea is to make everything more explicit from a user's perspective. Here's how it works:

Quoted 5 lines

Opening /dev/sgx/enclave gives an enclave_fd that, by design, doesn't give EXECUTE or WRITE. mmap() on the enclave_fd only works if you pass PROT_NONE and gives the correct alignment. The resulting VMA cannot be mprotected or mremapped. It can't be mmapped at all until

I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?

Quoted 1 line

after ECREATE because the alignment isn't known before that.

I don't follow. The alignment is known because userspace knows the size of its enclave. The initial unknown is the address, but that becomes known once the initial mmap() completes.

[...]

Quoted 7 lines

I think I made the mistake of getting too carried away with implementation details rather than just getting to the point. And I misremembered the ECREATE flow -- oops. Let me try again. First, here are some problems with some earlier proposals (mine, yours Cedric's):

- Having the EADD operation always work but have different effects depending on the
source memory permissions is, at the very least, confusing.

Inheriting permissions from source pages IMHO is the easiest way to validate the EPC permissions without any changes to LSM. And the argument about its security is also easy to make.

I understand that it may take some effort to document it properly but otherwise don't see any practical issues with it.

Quoted 20 lines

- If we want to encourage user programs to be well-behaved, we want to make it easy to
map the RX parts of an enclave RX, the RW parts RW, the RO parts R, etc. But this interacts poorly with the sgx_mmap() alignment magic, as you've pointed out.

- We don't want to couple LSMs with SGX too tightly.

So here's how a nice interface might work:

int enclave_fd = open("/dev/sgx/enclave", O_RDWR);

/* enclave_fd points to a totally blank enclave. Before ECREATE, we need to decide on an address. */

void *addr = mmap(NULL, size, PROT_NONE, MAP_SHARED, enclave_fd, 0);

/* we have an address! */

ioctl(enclave_fd, ECREATE, ...);

Quoted 8 lines

/* now add some data to the enclave. We want the RWX addition to fail
immediately unless we have the relevant LSM pemission. Similarly, we
want the RX addition to fail immediately unless the source VMA is appropriate. */

ioctl(enclave_fd, EADD, rx_source_1, MAXPERM=RX, ...); [the ... includes SECINFO, which the kernel doesn't really care about] ioctl(enclave_fd, EADD, ro_source_1, MAXPERM=RX ...); ioctl(enclave_fd, EADD, rw_source_1, MAXPERM=RW ...); ioctl(enclave_fd, EADD, rwx_source_1, MAXPERM=RWX ...);

If MAXPERM is taken from ioctl parameters, the real question here is how to validate MAXPERM. Guess we shouldn't allow arbitrary MAXPERM to be specified by user code, and the only logical source I can think of is from the source pages (or from the enclave source file, but memory mapping is preferred because it offers more flexibility).

Quoted 6 lines

ioctl(enclave_fd, EINIT, ...); /* presumably pass sigstruct_fd here, too. */

/* at this point, all is well except that the enclave is mapped PROT_NONE. There are a couple ways I can imagine to fix this. */

Quoted 7 lines

We could use mmap:

mmap(baseaddr+offset, len, PROT_READ, MAP_SHARED | MAP_FIXED, enclave_fd, 0); /* only succeeds if MAXPERM & R == R */

But this has some annoying implications with regard to sgx_get_unmapped_area(). We could use an ioctl:

There's an easy fix. Just let sgx_get_unmapped_area() do the natural alignment only if MAP_FIXED is *not* set, otherwise, honor both address and len.

But mmap() is subject to LSM check (probably against /dev/sgx/enclave?). How to do mmap(RX) if FILE__EXECUTE is *not* granted for /dev/sgx/enclave, even if MAXPERM=RX?

Quoted 9 lines

ioctl(enclave_fd, SGX_IOC_MPROTECT, offset, len, PROT_READ);

which has the potentially nice property that we can completely bypass the LSM hooks, because the LSM has *already* vetted everything when the EADD calls were allowed. Or we could maybe even just use
mprotect() itself:

mprotect(baseaddr + offset, len, PROT_READ);

How to bypass LSM hooks in this mprotect()?

Quoted 7 lines

Or, for the really evil option, we could use a bit of magic in .fault and do nothing here. Instead we'd make the initial mapping PROT_READ|PROT_WRITE|PROT_EXEC and have .fault actually instantiate the PTEs with the intersection of the VMA permissions and MAXPERM. I don't think I like this alternative, since it feels more magical than needed and it will be harder to debug. I like the fact that /proc/self/maps shows the actual permissions in all the other variants.

Agreed.

Quoted 7 lines

All of the rest of the crud in my earlier email was just implementation details. The point I was trying to make was that I think it's possible to implement this without making too much of a mess internally. I think I favor the mprotect() approach since it makes the behavior fairly obvious.

Quoted 6 lines

I don't think any of this needs to change for SGX2. We'd have an
ioctl() that does EAUG and specifies MAXPERM. Trying to mprotect() a page that hasn't been added yet with any permission other than PROT_NONE would fail. I suppose we might end up needing a way to let the EAUG operation *change* MAXPERM, and this operation would have to do some more LSM checks and walk all the existing mappings to make sure they're consistent with the new MAXPERM.

EAUG ioctl could be a solution, but isn't optimal at least. What we've done is #PF based. Specifically, an SGX2 enclave will have its heap mapped as RW, but without any pages populated before EINIT. Then when the enclave needs a new page in its heap, it issues EACCEPT, which will cause a #PF and the driver will respond by EAUG a new EPC page. And then the enclave will be resumed and the faulted EACCEPT will be retried (and succeed).

Quoted 6 lines

As an aside, I wonder if Linus et all would be okay with a new MAP_FULLY_ALIGNED mmap() flag that allocated memory aligned to the requested size. Then we could get rid of yet another bit of magic.

--Andy

I've also got a chance to think more about it lately.

When we talk about EPC page permissions with SGX2 in mind, I think we should distinguish between initial permissions and runtime permissions. Initial permissions refer to the page permissions set at EADD. They are technically set by "untrusted" code so should go by policies similar to those applicable to regular shared objects. Runtime permissions refer to the permissions granted by EMODPE, EAUG and EACCEPTCOPY. They are resulted from inherent behavior of the enclave, which in theory is determined by the enclave's measurements (MRENCLAVE and/or MRSIGNER).

And we have 2 distinct files to work with - the enclave file and /dev/sgx/enclave. And I consider the enclave file a logical source for initial permissions while /dev/sgx/enclave is a means to control runtime permissions. Then we can have a simpler approach like the pseudo code below.

/**
* Summary:
* - The enclave file resembles a shared object that contains RO/RX/RW segments
* - FILE__* are assigned to /dev/sgx/enclave, to determine acceptable permissions to mmap()/mprotect(), valid combinations are

 *   + FILE__READ - Allow SGX1 enclaves only
 *   + FILE__READ|FILE__WRITE - Allow SGX2 enclaves to expand data segments (e.g. heaps, stacks, etc.)
 *   + FILE__READ|FILE__WRITE|FILE__EXECUTE - Allow SGX2 enclaves to expend both data and code segments. This is necessary to support dynamically linked enclaves (e.g. Graphene)
 *   + FILE__READ|FILE__EXECUTE - Allow RW->RX changes for SGX1 enclaves - necessary to support dynamically linked enclaves (e.g. Graphene) on SGX1. EXECMEM is also required for this to work
 *   + <None> - Disallow the calling process to launch any enclaves

*/

/* Step 1: mmap() the enclave file according to the segment attributes (similar to what dlopen() would do for regular shared objects) */ int image_fd = open("/path/to/enclave/file", O_RDONLY);

foreach phdr in loadable segments /* phdr->p_type == PT_LOAD */ {
    /* <segment permission> below is subject to LSM checks */
    loadable_segments[i] = mmap(NULL, phdr->p_memsz, MAP_PRIATE, <segment permission>, image_fd, phdr->p_offset);
}

/* Step 2: Create enclave */
int enclave_fd = open("/dev/sgx/enclave", O_RDONLY /* or O_RDWR for SGX2 enclaves */);
void *enclave_base = mmap(NULL, <enclave size>, MAP_SHARED, PROT_READ, enclave_fd, 0); /* Only FILE__READ is required here */ ioctl(enclave_fd, IOC_ECREATE, ...);

/* Step 3: EADD and map initial EPC pages */
foreach s in loadable_segments {
/* IOC_EADD_AND_MAP_SEGMENT will make sure s->perm is a subset of VMA permissions of the source pages, and use that as *both* EPCM and VMA permissions).
* Given enclave_fd may have FILE__READ only, LSM has to be bypassed so the "mmap" part has to be done inside the driver.
* Initial EPC pages will be mapped only once, so no inode is needed to remember the initial permissions. mmap/mprotect afterwards are subject to FILE__* on /dev/sgx/enclave
* The key point here is: permissions of source pages govern initial permissions of EADD'ed pages, regardless FILE__* on /dev/sgx/enclave
*/
ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, s->base, s->size, s->perm...);
}
/* EADD other enclave components, e.g. TCS, stacks, heaps, etc. */
ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, tcs, 0x1000, RW | PT_TCS...);
ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, <zero page>, <stack size>, RW...);
...

/* Step 4 (SGX2 only): Reserve ranges for additional heaps, stacks, etc. */
/* FILE__WRITE required to allow expansion of data segments at runtime */
/* Key point here is: permissions, if needed to change at runtime, are subject to FILL__* on /dev/sgx/enclave */ mprotect(<heap address>, <heap size>, PROT_READ | PROT_WRITE);

/* Step 5: EINIT */
ioctl(IOC_EINIT, <sigstruct>...);

/* Step 6 (SGX2 only): Set RX for dynamically loaded code pages (e.g. Graphene, encrypted enclaves, etc.) as needed, at runtime */ /* FILE__EXECUTE required */
mprotect(<RX address>, <RX size>, PROT_READ | PROT_EXEC);

-Cedric

#165 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 172 lines · Cedric

Hi Andy,

Quoted 58 lines

From: Andy Lutomirski [mailto:[email protected]]
Sent: Thursday, May 23, 2019 6:18 PM

Quoted 17 lines · Sean Christopherson
Quoted 15 lines · Andy Lutomirski
Quoted 13 lines · Sean Christopherson
Quoted 10 lines · Jarkko Sakkinen
Quoted 7 lines · Sean Christopherson

But actually, there's no need to disallow mmap() after ECREATE since the LSM checks also apply to mmap(), e.g. FILE__EXECUTE would be needed to
mmap() any enclave pages PROT_EXEC. I guess my past self thought mmap() bypassed LSM checks? The real problem is that mmap()'ng an existing enclave would require FILE__WRITE and FILE__EXECUTE, which puts us back at square one.

I'm lost with the constraints we want to set.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

As is today, SELinux policies would require enclave loaders to
have FILE__WRITE and FILE__EXECUTE permissions on
/dev/sgx/enclave. Presumably other LSMs have similar
requirements. Requiring all processes to have
FILE__{WRITE,EXECUTE} permissions means the permissions don't add much value, e.g. they can't be used to distinguish between an enclave that is being loaded from an unmodified file and an enclave that is being

generated on the fly, e.g. Graphene.

Quoted 25 lines
Quoted 12 lines
Quoted 5 lines

Looking back at Andy's mail, he was talking about requiring FILE__EXECUTE to run an enclave, so perhaps it's only FILE__WRITE that we're trying to special case.

I thought about this some more, and I have a new proposal that helps address the ELRANGE alignment issue and the permission issue at the cost of some extra verbosity. Maybe you all can poke holes in it :) The basic idea is to make everything more explicit from a user's perspective. Here's how it works:

Quoted 5 lines

Opening /dev/sgx/enclave gives an enclave_fd that, by design, doesn't give EXECUTE or WRITE. mmap() on the enclave_fd only works if you pass PROT_NONE and gives the correct alignment. The resulting VMA cannot be mprotected or mremapped. It can't be mmapped at all until

I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?

Quoted 1 line

after ECREATE because the alignment isn't known before that.

I don't follow. The alignment is known because userspace knows the size of its enclave. The initial unknown is the address, but that becomes known once the initial mmap() completes.

[...]

Quoted 7 lines

I think I made the mistake of getting too carried away with implementation details rather than just getting to the point. And I misremembered the ECREATE flow -- oops. Let me try again. First, here are some problems with some earlier proposals (mine, yours Cedric's):

- Having the EADD operation always work but have different effects depending on the
source memory permissions is, at the very least, confusing.

Inheriting permissions from source pages IMHO is the easiest way to validate the EPC permissions without any changes to LSM. And the argument about its security is also easy to make.

I understand that it may take some effort to document it properly but otherwise don't see any practical issues with it.

Quoted 20 lines

- If we want to encourage user programs to be well-behaved, we want to make it easy to
map the RX parts of an enclave RX, the RW parts RW, the RO parts R, etc. But this interacts poorly with the sgx_mmap() alignment magic, as you've pointed out.

- We don't want to couple LSMs with SGX too tightly.

So here's how a nice interface might work:

int enclave_fd = open("/dev/sgx/enclave", O_RDWR);

/* enclave_fd points to a totally blank enclave. Before ECREATE, we need to decide on an address. */

void *addr = mmap(NULL, size, PROT_NONE, MAP_SHARED, enclave_fd, 0);

/* we have an address! */

ioctl(enclave_fd, ECREATE, ...);

Quoted 8 lines

/* now add some data to the enclave. We want the RWX addition to fail
immediately unless we have the relevant LSM pemission. Similarly, we
want the RX addition to fail immediately unless the source VMA is appropriate. */

ioctl(enclave_fd, EADD, rx_source_1, MAXPERM=RX, ...); [the ... includes SECINFO, which the kernel doesn't really care about] ioctl(enclave_fd, EADD, ro_source_1, MAXPERM=RX ...); ioctl(enclave_fd, EADD, rw_source_1, MAXPERM=RW ...); ioctl(enclave_fd, EADD, rwx_source_1, MAXPERM=RWX ...);

If MAXPERM is taken from ioctl parameters, the real question here is how to validate MAXPERM. Guess we shouldn't allow arbitrary MAXPERM to be specified by user code, and the only logical source I can think of is from the source pages (or from the enclave source file, but memory mapping is preferred because it offers more flexibility).

Quoted 6 lines

ioctl(enclave_fd, EINIT, ...); /* presumably pass sigstruct_fd here, too. */

/* at this point, all is well except that the enclave is mapped PROT_NONE. There are a couple ways I can imagine to fix this. */

Quoted 7 lines

We could use mmap:

mmap(baseaddr+offset, len, PROT_READ, MAP_SHARED | MAP_FIXED, enclave_fd, 0); /* only succeeds if MAXPERM & R == R */

But this has some annoying implications with regard to sgx_get_unmapped_area(). We could use an ioctl:

There's an easy fix. Just let sgx_get_unmapped_area() do the natural alignment only if MAP_FIXED is *not* set, otherwise, honor both address and len.

But mmap() is subject to LSM check (probably against /dev/sgx/enclave?). How to do mmap(RX) if FILE__EXECUTE is *not* granted for /dev/sgx/enclave, even if MAXPERM=RX?

Quoted 9 lines

ioctl(enclave_fd, SGX_IOC_MPROTECT, offset, len, PROT_READ);

which has the potentially nice property that we can completely bypass the LSM hooks, because the LSM has *already* vetted everything when the EADD calls were allowed. Or we could maybe even just use
mprotect() itself:

mprotect(baseaddr + offset, len, PROT_READ);

How to bypass LSM hooks in this mprotect()?

Quoted 7 lines

Or, for the really evil option, we could use a bit of magic in .fault and do nothing here. Instead we'd make the initial mapping PROT_READ|PROT_WRITE|PROT_EXEC and have .fault actually instantiate the PTEs with the intersection of the VMA permissions and MAXPERM. I don't think I like this alternative, since it feels more magical than needed and it will be harder to debug. I like the fact that /proc/self/maps shows the actual permissions in all the other variants.

Agreed.

Quoted 7 lines

All of the rest of the crud in my earlier email was just implementation details. The point I was trying to make was that I think it's possible to implement this without making too much of a mess internally. I think I favor the mprotect() approach since it makes the behavior fairly obvious.

Quoted 6 lines

I don't think any of this needs to change for SGX2. We'd have an
ioctl() that does EAUG and specifies MAXPERM. Trying to mprotect() a page that hasn't been added yet with any permission other than PROT_NONE would fail. I suppose we might end up needing a way to let the EAUG operation *change* MAXPERM, and this operation would have to do some more LSM checks and walk all the existing mappings to make sure they're consistent with the new MAXPERM.

EAUG ioctl could be a solution, but isn't optimal at least. What we've done is #PF based. Specifically, an SGX2 enclave will have its heap mapped as RW, but without any pages populated before EINIT. Then when the enclave needs a new page in its heap, it issues EACCEPT, which will cause a #PF and the driver will respond by EAUG a new EPC page. And then the enclave will be resumed and the faulted EACCEPT will be retried (and succeed).

Quoted 6 lines

As an aside, I wonder if Linus et all would be okay with a new MAP_FULLY_ALIGNED mmap() flag that allocated memory aligned to the requested size. Then we could get rid of yet another bit of magic.

--Andy

I've also got a chance to think more about it lately.

When we talk about EPC page permissions with SGX2 in mind, I think we should distinguish between initial permissions and runtime permissions. Initial permissions refer to the page permissions set at EADD. They are technically set by "untrusted" code so should go by policies similar to those applicable to regular shared objects. Runtime permissions refer to the permissions granted by EMODPE, EAUG and EACCEPTCOPY. They are resulted from inherent behavior of the enclave, which in theory is determined by the enclave's measurements (MRENCLAVE and/or MRSIGNER).

And we have 2 distinct files to work with - the enclave file and /dev/sgx/enclave. And I consider the enclave file a logical source for initial permissions while /dev/sgx/enclave is a means to control runtime permissions. Then we can have a simpler approach like the pseudo code below.

Quoted 8 lines

/**
* Summary:
* - The enclave file resembles a shared object that contains RO/RX/RW segments
* - FILE__* are assigned to /dev/sgx/enclave, to determine acceptable permissions to mmap()/mprotect(), valid combinations are

  *   + FILE__READ - Allow SGX1 enclaves only
  *   + FILE__READ|FILE__WRITE - Allow SGX2 enclaves to expand data segments (e.g. heaps, stacks, etc.)
  *   + FILE__READ|FILE__WRITE|FILE__EXECUTE - Allow SGX2 enclaves to expend both data and code segments. This is necessary to support dynamically linked enclaves (e.g. Graphene)
  *   + FILE__READ|FILE__EXECUTE - Allow RW->RX changes for SGX1 enclaves - necessary to support dynamically linked enclaves (e.g. Graphene) on SGX1. EXECMEM is also required for this to work

I think EXECMOD would fit better than EXECMEM for this case; the former is applied for RW->RX changes for private file mappings while the latter is applied for WX private file mappings.

Quoted 5 lines

* + <None> - Disallow the calling process to launch any enclaves
*/

/* Step 1: mmap() the enclave file according to the segment attributes (similar to what dlopen() would do for regular shared objects) */ int image_fd = open("/path/to/enclave/file", O_RDONLY);

FILE__READ checked to enclave file upon open().

Quoted 3 lines
foreach phdr in loadable segments /* phdr->p_type == PT_LOAD */ {
     /* <segment permission> below is subject to LSM checks */
     loadable_segments[i] = mmap(NULL, phdr->p_memsz, MAP_PRIATE, <segment permission>, image_fd, phdr->p_offset);

FILE__READ revalidated and FILE__EXECUTE checked to enclave file upon mmap() for PROT_READ and PROT_EXEC respectively. FILE__WRITE not checked even for PROT_WRITE mappings since it is a private file mapping and writes do not reach the file. EXECMEM checked if any segment permission has both W and X simultaneously. EXECMOD checked on any subsequent mprotect() RW->RX changes (if modified).

Quoted 4 lines

}

/* Step 2: Create enclave */
int enclave_fd = open("/dev/sgx/enclave", O_RDONLY /* or O_RDWR for SGX2 enclaves */);

FILE__READ checked (SGX1) or both FILE__READ and FILE__WRITE checked (SGX2) to /dev/sgx/enclave upon open(). Assuming that we are returning an open file referencing the /dev/sgx/enclave inode and not an anon inode, else we lose all subsequent FILE__* checking on mmap/mprotect and trigger EXECMEM on any mmap/mprotect PROT_EXEC.

Quoted 1 line

void *enclave_base = mmap(NULL, <enclave size>, MAP_SHARED, PROT_READ, enclave_fd, 0); /* Only FILE__READ is required here */

FILE__READ revalidated to /dev/sgx/enclave upon mmap().

Quoted 16 lines

ioctl(enclave_fd, IOC_ECREATE, ...);

/* Step 3: EADD and map initial EPC pages */
foreach s in loadable_segments {
/* IOC_EADD_AND_MAP_SEGMENT will make sure s->perm is a subset of VMA permissions of the source pages, and use that as *both* EPCM and VMA permissions).
* Given enclave_fd may have FILE__READ only, LSM has to be bypassed so the "mmap" part has to be done inside the driver.
* Initial EPC pages will be mapped only once, so no inode is needed to remember the initial permissions. mmap/mprotect afterwards are subject to FILE__* on /dev/sgx/enclave
* The key point here is: permissions of source pages govern initial permissions of EADD'ed pages, regardless FILE__* on /dev/sgx/enclave
*/
ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, s->base, s->size, s->perm...);
}
/* EADD other enclave components, e.g. TCS, stacks, heaps, etc. */
ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, tcs, 0x1000, RW | PT_TCS...);
ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, <zero page>, <stack size>, RW...);
...

Quoted 4 lines

/* Step 4 (SGX2 only): Reserve ranges for additional heaps, stacks, etc. */
/* FILE__WRITE required to allow expansion of data segments at runtime */
/* Key point here is: permissions, if needed to change at runtime, are subject to FILL__* on /dev/sgx/enclave */ mprotect(<heap address>, <heap size>, PROT_READ | PROT_WRITE);

FILE__READ and FILE__WRITE revalidated to /dev/sgx/enclave upon mprotect().

Quoted 7 lines

/* Step 5: EINIT */
ioctl(IOC_EINIT, <sigstruct>...);

/* Step 6 (SGX2 only): Set RX for dynamically loaded code pages (e.g. Graphene, encrypted enclaves, etc.) as needed, at runtime */ /* FILE__EXECUTE required */
mprotect(<RX address>, <RX size>, PROT_READ | PROT_EXEC);

FILE__READ revalidated and FILE__EXECUTE checked to /dev/sgx/enclave upon mprotect(). Cumulative set of checks at this point is FILE__READ|FILE__WRITE|FILE__EXECUTE.

What would the step be for a SGX1 RW->RX change? How would that trigger EXECMOD? Do we really need to distinguish it from the SGX2 dynamically loaded code case?

Quoted 3 lines

-Cedric

#166 lore raw

RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Hi Stephen,

Quoted 37 lines · Cedric
Quoted 2 lines

When we talk about EPC page permissions with SGX2 in mind, I think we

should distinguish between initial permissions and runtime permissions. Initial permissions refer to the page permissions set at EADD. They are technically set by "untrusted" code so should go by policies similar to those applicable to regular shared objects. Runtime permissions refer to the permissions granted by EMODPE, EAUG and EACCEPTCOPY. They are resulted from inherent behavior of the enclave, which in theory is determined by the enclave's measurements (MRENCLAVE and/or MRSIGNER).

Quoted 2 lines

And we have 2 distinct files to work with - the enclave file and

/dev/sgx/enclave. And I consider the enclave file a logical source for initial permissions while /dev/sgx/enclave is a means to control runtime permissions. Then we can have a simpler approach like the pseudo code below.

Quoted 4 lines

/**
* Summary:
* - The enclave file resembles a shared object that contains

RO/RX/RW segments

Quoted 1 line

* - FILE__* are assigned to /dev/sgx/enclave, to determine

acceptable permissions to mmap()/mprotect(), valid combinations are

Quoted 2 lines

* + FILE__READ - Allow SGX1 enclaves only
* + FILE__READ|FILE__WRITE - Allow SGX2 enclaves to expand data

segments (e.g. heaps, stacks, etc.)

Quoted 1 line

* + FILE__READ|FILE__WRITE|FILE__EXECUTE - Allow SGX2 enclaves to

expend both data and code segments. This is necessary to support dynamically linked enclaves (e.g. Graphene)

Quoted 1 line

* + FILE__READ|FILE__EXECUTE - Allow RW->RX changes for SGX1

enclaves - necessary to support dynamically linked enclaves (e.g. Graphene) on SGX1. EXECMEM is also required for this to work

I think EXECMOD would fit better than EXECMEM for this case; the former is applied for RW->RX changes for private file mappings while the latter is applied for WX private file mappings.

Quoted 8 lines
Quoted 6 lines

* + <None> - Disallow the calling process to launch any enclaves
*/

/* Step 1: mmap() the enclave file according to the segment attributes (similar to what dlopen() would do for regular shared objects) */ int image_fd = open("/path/to/enclave/file", O_RDONLY);

FILE__READ checked to enclave file upon open().

Yes. We'd like to have the enclave file pass LSM/IMA checks and let EPC pages "inherit" the permissions from it as "initial" permissions.

Quoted 6 lines
Quoted 5 lines
foreach phdr in loadable segments /* phdr->p_type == PT_LOAD */ {
     /* <segment permission> below is subject to LSM checks */
     loadable_segments[i] = mmap(NULL, phdr->p_memsz, MAP_PRIATE,

<segment permission>, image_fd, phdr->p_offset);

Quoted 6 lines

FILE__READ revalidated and FILE__EXECUTE checked to enclave file upon mmap() for PROT_READ and PROT_EXEC respectively. FILE__WRITE not checked even for PROT_WRITE mappings since it is a private file mapping and writes do not reach the file. EXECMEM checked if any segment permission has both W and X simultaneously. EXECMOD checked on any subsequent mprotect() RW->RX changes (if modified).

Yes. The intention here is to make sure all X pages come directly from file (unless EXECMEM or EXECMOD is granted). And because the driver will grant X only if the source page also has X, we can assert that all executable EPC pages are loaded from a file that has passed LSM/IMA checks.

Quoted 7 lines
Quoted 6 lines

}

/* Step 2: Create enclave */
int enclave_fd = open("/dev/sgx/enclave", O_RDONLY /* or O_RDWR for SGX2 enclaves */);

Quoted 5 lines

FILE__READ checked (SGX1) or both FILE__READ and FILE__WRITE checked (SGX2) to /dev/sgx/enclave upon open(). Assuming that we are returning an open file referencing the /dev/sgx/enclave inode and not an anon inode, else we lose all subsequent FILE__* checking on mmap/mprotect and trigger EXECMEM on any mmap/mprotect PROT_EXEC.

Yes, the returned fd will be referencing /dev/sgx/enclave. The intention here is to limit EPC "runtime" permissions by the permissions granted to /dev/sgx/enclave, in order to allow user/administrator to specify what kinds of enclaves a given process can launch. Per your earlier comments, FILE__EXECMOD is probably also needed to support dynamically linked enclaves (that require RW->RX changes).

Quoted 5 lines
Quoted 3 lines

void *enclave_base = mmap(NULL, <enclave size>, MAP_SHARED, PROT_READ, enclave_fd, 0); /* Only FILE__READ is required here */

FILE__READ revalidated to /dev/sgx/enclave upon mmap().

Yes. This mmap() is to set "default" permissions for regions that do *not* have EPC pages populated. It is significant only for SGX2, to specify what action to take by the SGX driver upon #PF with those regions. For example, a R attempt (usually triggered by EACCEPT) within a RW region will cause SGX driver to EAUG a page at the fault address.

Quoted 32 lines
Quoted 6 lines

ioctl(enclave_fd, IOC_ECREATE, ...);

/* Step 3: EADD and map initial EPC pages */ foreach s in

loadable_segments {
     /* IOC_EADD_AND_MAP_SEGMENT will make sure s->perm is a subset of

VMA permissions of the source pages, and use that as *both* EPCM and VMA permissions).

Quoted 1 line

* Given enclave_fd may have FILE__READ only, LSM has to be

bypassed so the "mmap" part has to be done inside the driver.

Quoted 1 line

* Initial EPC pages will be mapped only once, so no inode is

needed to remember the initial permissions. mmap/mprotect afterwards are subject to FILE__* on /dev/sgx/enclave

Quoted 1 line

* The key point here is: permissions of source pages govern

initial permissions of EADD'ed pages, regardless FILE__* on /dev/sgx/enclave

Quoted 8 lines
      */
     ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, s->base, s->size,

s->perm...); }
/* EADD other enclave components, e.g. TCS, stacks, heaps, etc. */ ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, tcs, 0x1000, RW | PT_TCS...); ioctl(enclave_fd, IOC_EADD_AND_MAP_SEGMENT, <zero page>, <stack size>, RW...); ...

Quoted 7 lines

/* Step 4 (SGX2 only): Reserve ranges for additional heaps, stacks, etc. */
/* FILE__WRITE required to allow expansion of data segments at runtime */
/* Key point here is: permissions, if needed to change at runtime, are subject to FILL__* on /dev/sgx/enclave */ mprotect(<heap address>, <heap size>, PROT_READ | PROT_WRITE);

Quoted 2 lines

FILE__READ and FILE__WRITE revalidated to /dev/sgx/enclave upon mprotect().

Yes. The intention here is to limit "runtime" permissions by accesses granted to the calling process to /dev/sgx/enclave. The "initial" permissions are set by ioctl to bypass LSM, because they are derived/determined by the enclave file.

Alternatively, the driver can remember "initial" permissions for each EPC page at IOC_EADD, to be committed at IOC_EINIT. Then this new IOC_EADD_AND_MAP will not be needed.

Quoted 10 lines
Quoted 9 lines

/* Step 5: EINIT */
ioctl(IOC_EINIT, <sigstruct>...);

/* Step 6 (SGX2 only): Set RX for dynamically loaded code pages (e.g. Graphene, encrypted enclaves, etc.) as needed, at runtime */ /* FILE__EXECUTE required */
mprotect(<RX address>, <RX size>, PROT_READ | PROT_EXEC);

Quoted 7 lines

FILE__READ revalidated and FILE__EXECUTE checked to /dev/sgx/enclave upon mprotect(). Cumulative set of checks at this point is FILE__READ|FILE__WRITE|FILE__EXECUTE.

What would the step be for a SGX1 RW->RX change? How would that trigger EXECMOD? Do we really need to distinguish it from the SGX2 dynamically loaded code case?

Per your earlier comments, FILE__EXECMOD is also needed I think to allow RW->RX changes.

FILE__WRITE controls EAUG. I'm not judging its necessity, but just saying they are both valid combinations. To minimize impact to LSM, I don't want to special-case /dev/sgx/enclave. And the current semantics of FILE__* distinguish those two naturally.

BTW, there are usages, such as encrypted enclaves (https://github.com/intel/linux-sgx-pcl), requiring RW->RX but not EAUG. Graphene could also run on SGX1, provided that pages needed by shared objects are all pre-allocated before EINIT. All those could run without FILE__WRITE.

Quoted 4 lines
Quoted 4 lines

-Cedric

#167 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Stephen Smalley
Quoted 26 lines · Stephen Smalley
Quoted 8 lines · Cedric

/**
* Summary:
* - The enclave file resembles a shared object that contains RO/RX/RW segments
* - FILE__* are assigned to /dev/sgx/enclave, to determine acceptable permissions to mmap()/mprotect(), valid combinations are

 *   + FILE__READ - Allow SGX1 enclaves only
 *   + FILE__READ|FILE__WRITE - Allow SGX2 enclaves to expand data segments (e.g. heaps, stacks, etc.)
 *   + FILE__READ|FILE__WRITE|FILE__EXECUTE - Allow SGX2 enclaves to expend both data and code segments. This is necessary to support dynamically linked enclaves (e.g. Graphene)
 *   + FILE__READ|FILE__EXECUTE - Allow RW->RX changes for SGX1 enclaves - necessary to support dynamically linked enclaves (e.g. Graphene) on SGX1. EXECMEM is also required for this to work

I think EXECMOD would fit better than EXECMEM for this case; the former is applied for RW->RX changes for private file mappings while the latter is applied for WX private file mappings.

Quoted 5 lines

* + <None> - Disallow the calling process to launch any enclaves
*/

/* Step 1: mmap() the enclave file according to the segment attributes (similar to what dlopen() would do for regular shared objects) */ int image_fd = open("/path/to/enclave/file", O_RDONLY);

FILE__READ checked to enclave file upon open().

Quoted 3 lines
foreach phdr in loadable segments /* phdr->p_type == PT_LOAD */ {
    /* <segment permission> below is subject to LSM checks */
    loadable_segments[i] = mmap(NULL, phdr->p_memsz, MAP_PRIATE, <segment permission>, image_fd, phdr->p_offset);
Quoted 6 lines

FILE__READ revalidated and FILE__EXECUTE checked to enclave file upon mmap() for PROT_READ and PROT_EXEC respectively. FILE__WRITE not checked even for PROT_WRITE mappings since it is a private file mapping and writes do not reach the file. EXECMEM checked if any segment permission has both W and X simultaneously. EXECMOD checked on any subsequent mprotect() RW->RX changes (if modified).

Hmm, I've been thinking more about pulling permissions from the source page. Conceptually I'm not sure we need to meet the same requirements as non-enclave DSOs while the enclave is being built, i.e. do we really need to force userspace to fully map the enclave in normal memory?

Consider the Graphene scenario where it's building an enclave on the fly. Pulling permissions from the source VMAs means Graphene has to map the code pages of the enclave with X. This means Graphene will need EXEDMOD (or EXECMEM if Graphene isn't careful). In a non-SGX scenario this makes perfect sense since there is no way to verify the end result of RW->RX.

But for SGX, assuming enclaves are whitelisted by their sigstruct (checked at EINIT) and because page permissions affect sigstruct.MRENCLAVE, it *is* possible to verify the resulting RX contents. E.g. for the purposes of LSMs, can't we use the .sigstruct file as a proxy for the enclave and require FILE__EXECUTE on the .sigstruct inode to map/run the enclave?

Stephen, is my logic sound?

If so...

- Require FILE__READ+FILE__EXECUTE on .sigstruct to mmap() the enclave.

- Prevent userspace from mapping the enclave with permissions beyond the original permissions of the enclave. This can be done by populating VM_MAY{READ,WRITE,EXEC} from the SECINFO (same basic concept as Andy's proposals). E.g. pre-EINIT, mmap() and mprotect() can only succeed with PROT_NONE.

- Require FILE__{READ,WRITE,EXECUTE} on /dev/sgx/enclave for simplicity, or provide an alternate SGX_IOC_MPROTECT if we want to sidestep the FILE__WRITE requirement.

No changes are required to LSMs, SGX1 has a single LSM touchpoint in its mmap(), and I *think* the only required userspace change is to mmap() PROT_NONE when allocating the enclave's virtual address range.

As for Graphene, it doesn't need extra permissions to run its enclaves, it just needs a way to install .sigstruct, which is a generic permissions problem and not SGX specific.

For SGX2 maybe:

- No additional requirements to map an EAUG'd page as RW page. Not aligned with standard MAP_SHARED behavior, but we really don't want to require FILE__WRITE, and thus allow writes to .sigstruct.

- Require FILE__EXECMOD on the .sigstruct to map previously writable page as executable (which indirectly includes all EAUG'd pages). Wiring this up will be a little funky, but we again we don't want to require FILE__WRITE on .sigstruct.

#168 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 49 lines · Sean Christopherson
Quoted 28 lines · Stephen Smalley
Quoted 9 lines · Cedric

/**
* Summary:
* - The enclave file resembles a shared object that contains RO/RX/RW segments
* - FILE__* are assigned to /dev/sgx/enclave, to determine acceptable permissions to mmap()/mprotect(), valid combinations are

*   + FILE__READ - Allow SGX1 enclaves only
*   + FILE__READ|FILE__WRITE - Allow SGX2 enclaves to expand data segments (e.g. heaps, stacks, etc.)
*   + FILE__READ|FILE__WRITE|FILE__EXECUTE - Allow SGX2 enclaves to expend both data and code segments. This is necessary to support dynamically linked enclaves (e.g. Graphene)
*   + FILE__READ|FILE__EXECUTE - Allow RW->RX changes for SGX1 enclaves - necessary to support dynamically linked enclaves (e.g. Graphene) on SGX1. EXECMEM is also required for this to work

I think EXECMOD would fit better than EXECMEM for this case; the former is applied for RW->RX changes for private file mappings while the latter is applied for WX private file mappings.

Quoted 5 lines

* + <None> - Disallow the calling process to launch any enclaves
*/

/* Step 1: mmap() the enclave file according to the segment attributes (similar to what dlopen() would do for regular shared objects) */ int image_fd = open("/path/to/enclave/file", O_RDONLY);

FILE__READ checked to enclave file upon open().

Quoted 3 lines
foreach phdr in loadable segments /* phdr->p_type == PT_LOAD */ {
   /* <segment permission> below is subject to LSM checks */
   loadable_segments[i] = mmap(NULL, phdr->p_memsz, MAP_PRIATE, <segment permission>, image_fd, phdr->p_offset);
Quoted 6 lines

FILE__READ revalidated and FILE__EXECUTE checked to enclave file upon mmap() for PROT_READ and PROT_EXEC respectively. FILE__WRITE not checked even for PROT_WRITE mappings since it is a private file mapping and writes do not reach the file. EXECMEM checked if any segment permission has both W and X simultaneously. EXECMOD checked on any subsequent mprotect() RW->RX changes (if modified).

Hmm, I've been thinking more about pulling permissions from the source page. Conceptually I'm not sure we need to meet the same requirements as non-enclave DSOs while the enclave is being built, i.e. do we really need to force userspace to fully map the enclave in normal memory?

Consider the Graphene scenario where it's building an enclave on the fly. Pulling permissions from the source VMAs means Graphene has to map the code pages of the enclave with X. This means Graphene will need EXEDMOD (or EXECMEM if Graphene isn't careful). In a non-SGX scenario this makes perfect sense since there is no way to verify the end result of RW->RX.

Quoted 5 lines

But for SGX, assuming enclaves are whitelisted by their sigstruct (checked at EINIT) and because page permissions affect sigstruct.MRENCLAVE, it *is* possible to verify the resulting RX contents. E.g. for the purposes of LSMs, can't we use the .sigstruct file as a proxy for the enclave and require FILE__EXECUTE on the .sigstruct inode to map/run the enclave?

I think it’s sound for some but not all use cases. I would imagine that a lot of users won’t restrict sigstruct at all — the “use this as a sigstruct” permission will be granted to everything and maybe even to memfd. But even users like that might want to force their enclaves to be hardened such that writable pages are never executable, in which case Graphene may need an exception to run.

But maybe I’m nuts.

#169 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

Quoted 20 lines · Andy Lutomirski
Quoted 14 lines · Sean Christopherson

Hmm, I've been thinking more about pulling permissions from the source page. Conceptually I'm not sure we need to meet the same requirements as non-enclave DSOs while the enclave is being built, i.e. do we really need to force userspace to fully map the enclave in normal memory?

Consider the Graphene scenario where it's building an enclave on the fly. Pulling permissions from the source VMAs means Graphene has to map the code pages of the enclave with X. This means Graphene will need EXEDMOD (or EXECMEM if Graphene isn't careful). In a non-SGX scenario this makes perfect sense since there is no way to verify the end result of RW->RX.

Quoted 5 lines

But for SGX, assuming enclaves are whitelisted by their sigstruct (checked at EINIT) and because page permissions affect sigstruct.MRENCLAVE, it *is* possible to verify the resulting RX contents. E.g. for the purposes of LSMs, can't we use the .sigstruct file as a proxy for the enclave and require FILE__EXECUTE on the .sigstruct inode to map/run the enclave?

Quoted 6 lines

I think it’s sound for some but not all use cases. I would imagine that a lot of users won’t restrict sigstruct at all — the “use this as a sigstruct” permission will be granted to everything and maybe even to memfd. But even users like that might want to force their enclaves to be hardened such that writable pages are never executable, in which case Graphene may need an exception to run.

Heh, I belatedly had the same thought. See my follow-up about EXECMEM.

Quoted 1 line

But maybe I’m nuts.

#170 lore raw

Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)

In reply to Sean Christopherson
Quoted 30 lines · Sean Christopherson

Hmm, I've been thinking more about pulling permissions from the source page. Conceptually I'm not sure we need to meet the same requirements as non-enclave DSOs while the enclave is being built, i.e. do we really need to force userspace to fully map the enclave in normal memory?

Consider the Graphene scenario where it's building an enclave on the fly. Pulling permissions from the source VMAs means Graphene has to map the code pages of the enclave with X. This means Graphene will need EXEDMOD (or EXECMEM if Graphene isn't careful). In a non-SGX scenario this makes perfect sense since there is no way to verify the end result of RW->RX.

But for SGX, assuming enclaves are whitelisted by their sigstruct (checked at EINIT) and because page permissions affect sigstruct.MRENCLAVE, it *is* possible to verify the resulting RX contents. E.g. for the purposes of LSMs, can't we use the .sigstruct file as a proxy for the enclave and require FILE__EXECUTE on the .sigstruct inode to map/run the enclave?

Stephen, is my logic sound?

If so...

- Require FILE__READ+FILE__EXECUTE on .sigstruct to mmap() the enclave.

- Prevent userspace from mapping the enclave with permissions beyond the original permissions of the enclave. This can be done by populating VM_MAY{READ,WRITE,EXEC} from the SECINFO (same basic concept as Andy's proposals). E.g. pre-EINIT, mmap() and mprotect() can only succeed with PROT_NONE.

Quoted 3 lines

- Require FILE__{READ,WRITE,EXECUTE} on /dev/sgx/enclave for simplicity, or provide an alternate SGX_IOC_MPROTECT if we want to sidestep the FILE__WRITE requirement.

One more thought. EADD (and the equivalent SGX2 flow) could do security_mmap_file() with a NULL file on the SECINFO permissions, which would trigger PROCESS_EXECMEM if an enclave attempts to map a page RWX.

Quoted 20 lines

No changes are required to LSMs, SGX1 has a single LSM touchpoint in its mmap(), and I *think* the only required userspace change is to mmap() PROT_NONE when allocating the enclave's virtual address range.

As for Graphene, it doesn't need extra permissions to run its enclaves, it just needs a way to install .sigstruct, which is a generic permissions problem and not SGX specific.

For SGX2 maybe:

- No additional requirements to map an EAUG'd page as RW page. Not aligned with standard MAP_SHARED behavior, but we really don't want to require FILE__WRITE, and thus allow writes to .sigstruct.

- Require FILE__EXECMOD on the .sigstruct to map previously writable page as executable (which indirectly includes all EAUG'd pages). Wiring this up will be a little funky, but we again we don't want to require FILE__WRITE on .sigstruct.