linux-sgx.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v20 00/28] Intel SGX1 support
@ 2019-04-17 10:39 Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 01/28] x86/cpufeatures: Add Intel-defined SGX feature bit Jarkko Sakkinen
                   ` (33 more replies)
  0 siblings, 34 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #1: Type: text/plain; charset=y, Size: 22862 bytes --]

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

-- 
2.19.1


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

* [PATCH v20 01/28] x86/cpufeatures: Add Intel-defined SGX feature bit
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 02/28] x86/cpufeatures: Add SGX sub-features (as Linux-defined bits) Jarkko Sakkinen
                   ` (32 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes, Kai Huang,
	Jarkko Sakkinen

From: Kai Huang <kai.huang@linux.intel.com>

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

Signed-off-by: Kai Huang <kai.huang@linux.intel.com>
Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Reviewed-by: Borislav Petkov <bp@suse.de>
---
 arch/x86/include/asm/cpufeatures.h       | 1 +
 arch/x86/include/asm/disabled-features.h | 8 +++++++-
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/arch/x86/include/asm/cpufeatures.h b/arch/x86/include/asm/cpufeatures.h
index 981ff9479648..a16325db4cff 100644
--- a/arch/x86/include/asm/cpufeatures.h
+++ b/arch/x86/include/asm/cpufeatures.h
@@ -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 */
diff --git a/arch/x86/include/asm/disabled-features.h b/arch/x86/include/asm/disabled-features.h
index a5ea841cc6d2..74de07d0f390 100644
--- a/arch/x86/include/asm/disabled-features.h
+++ b/arch/x86/include/asm/disabled-features.h
@@ -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
-- 
2.19.1


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

* [PATCH v20 02/28] x86/cpufeatures: Add SGX sub-features (as Linux-defined bits)
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 01/28] x86/cpufeatures: Add Intel-defined SGX feature bit Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 03/28] x86/msr: Add IA32_FEATURE_CONTROL.SGX_ENABLE definition Jarkko Sakkinen
                   ` (31 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

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.

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 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(-)

diff --git a/arch/x86/include/asm/cpufeatures.h b/arch/x86/include/asm/cpufeatures.h
index a16325db4cff..313c58c04b51 100644
--- a/arch/x86/include/asm/cpufeatures.h
+++ b/arch/x86/include/asm/cpufeatures.h
@@ -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 */
diff --git a/arch/x86/include/asm/disabled-features.h b/arch/x86/include/asm/disabled-features.h
index 74de07d0f390..926f9dc4d75a 100644
--- a/arch/x86/include/asm/disabled-features.h
+++ b/arch/x86/include/asm/disabled-features.h
@@ -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
diff --git a/arch/x86/kernel/cpu/scattered.c b/arch/x86/kernel/cpu/scattered.c
index 94aa1c72ca98..9a5f6cf947b9 100644
--- a/arch/x86/kernel/cpu/scattered.c
+++ b/arch/x86/kernel/cpu/scattered.c
@@ -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 },
diff --git a/tools/arch/x86/include/asm/cpufeatures.h b/tools/arch/x86/include/asm/cpufeatures.h
index 981ff9479648..748180a4a1f5 100644
--- a/tools/arch/x86/include/asm/cpufeatures.h
+++ b/tools/arch/x86/include/asm/cpufeatures.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 03/28] x86/msr: Add IA32_FEATURE_CONTROL.SGX_ENABLE definition
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 01/28] x86/cpufeatures: Add Intel-defined SGX feature bit Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 02/28] x86/cpufeatures: Add SGX sub-features (as Linux-defined bits) Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 04/28] x86/cpufeatures: Add Intel-defined SGX_LC feature bit Jarkko Sakkinen
                   ` (30 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

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.

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/include/asm/msr-index.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/arch/x86/include/asm/msr-index.h b/arch/x86/include/asm/msr-index.h
index ca5bc0eacb95..6efaa8026c64 100644
--- a/arch/x86/include/asm/msr-index.h
+++ b/arch/x86/include/asm/msr-index.h
@@ -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
-- 
2.19.1


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

* [PATCH v20 04/28] x86/cpufeatures: Add Intel-defined SGX_LC feature bit
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (2 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 03/28] x86/msr: Add IA32_FEATURE_CONTROL.SGX_ENABLE definition Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 05/28] x86/msr: Add SGX Launch Control MSR definitions Jarkko Sakkinen
                   ` (29 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes, Kai Huang,
	Jarkko Sakkinen

From: Kai Huang <kai.huang@linux.intel.com>

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.

Signed-off-by: Kai Huang <kai.huang@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/include/asm/cpufeatures.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/arch/x86/include/asm/cpufeatures.h b/arch/x86/include/asm/cpufeatures.h
index 313c58c04b51..c5080842ecad 100644
--- a/arch/x86/include/asm/cpufeatures.h
+++ b/arch/x86/include/asm/cpufeatures.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 05/28] x86/msr: Add SGX Launch Control MSR definitions
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (3 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 04/28] x86/cpufeatures: Add Intel-defined SGX_LC feature bit Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 06/28] x86/mm: x86/sgx: Add new 'PF_SGX' page fault error code bit Jarkko Sakkinen
                   ` (28 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

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.

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Haim Cohen <haim.cohen@intel.com>
Signed-off-by: Haim Cohen <haim.cohen@intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/include/asm/msr-index.h | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/arch/x86/include/asm/msr-index.h b/arch/x86/include/asm/msr-index.h
index 6efaa8026c64..a4a22441d000 100644
--- a/arch/x86/include/asm/msr-index.h
+++ b/arch/x86/include/asm/msr-index.h
@@ -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
 
-- 
2.19.1


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

* [PATCH v20 06/28] x86/mm: x86/sgx: Add new 'PF_SGX' page fault error code bit
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (4 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 05/28] x86/msr: Add SGX Launch Control MSR definitions Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 07/28] x86/mm: x86/sgx: Signal SIGSEGV for userspace #PFs w/ PF_SGX Jarkko Sakkinen
                   ` (27 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Dave Hansen, Jarkko Sakkinen

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

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.

Cc: Dave Hansen <dave.hansen@linux.intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/include/asm/traps.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/arch/x86/include/asm/traps.h b/arch/x86/include/asm/traps.h
index 7d6f3f3fad78..c3e02912e9c7 100644
--- a/arch/x86/include/asm/traps.h
+++ b/arch/x86/include/asm/traps.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 07/28] x86/mm: x86/sgx: Signal SIGSEGV for userspace #PFs w/ PF_SGX
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (5 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 06/28] x86/mm: x86/sgx: Add new 'PF_SGX' page fault error code bit Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 08/28] x86/cpu/intel: Detect SGX support and update caps appropriately Jarkko Sakkinen
                   ` (26 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Andy Lutomirski, Dave Hansen, Jarkko Sakkinen

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

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.

Cc: Andy Lutomirski <luto@amacapital.net>
Cc: Dave Hansen <dave.hansen@linux.intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/mm/fault.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/arch/x86/mm/fault.c b/arch/x86/mm/fault.c
index 667f1da36208..78e2807fbede 100644
--- a/arch/x86/mm/fault.c
+++ b/arch/x86/mm/fault.c
@@ -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
-- 
2.19.1


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

* [PATCH v20 08/28] x86/cpu/intel: Detect SGX support and update caps appropriately
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (6 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 07/28] x86/mm: x86/sgx: Signal SIGSEGV for userspace #PFs w/ PF_SGX Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 09/28] x86/sgx: Add ENCLS architectural error codes Jarkko Sakkinen
                   ` (25 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

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.

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/kernel/cpu/intel.c | 39 +++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)

diff --git a/arch/x86/kernel/cpu/intel.c b/arch/x86/kernel/cpu/intel.c
index fc3c07fe7df5..702497f34a96 100644
--- a/arch/x86/kernel/cpu/intel.c
+++ b/arch/x86/kernel/cpu/intel.c
@@ -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);
-- 
2.19.1


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

* [PATCH v20 09/28] x86/sgx: Add ENCLS architectural error codes
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (7 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 08/28] x86/cpu/intel: Detect SGX support and update caps appropriately Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-22 21:35   ` Sean Christopherson
  2019-04-17 10:39 ` [PATCH v20 10/28] x86/sgx: Add SGX1 and SGX2 architectural data structures Jarkko Sakkinen
                   ` (24 subsequent siblings)
  33 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 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

diff --git a/arch/x86/include/uapi/asm/sgx_errno.h b/arch/x86/include/uapi/asm/sgx_errno.h
new file mode 100644
index 000000000000..48b87aed58d7
--- /dev/null
+++ b/arch/x86/include/uapi/asm/sgx_errno.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 10/28] x86/sgx: Add SGX1 and SGX2 architectural data structures
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (8 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 09/28] x86/sgx: Add ENCLS architectural error codes Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 11/28] x86/sgx: Add wrappers for ENCLS leaf functions Jarkko Sakkinen
                   ` (23 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 arch/x86/kernel/cpu/sgx/arch.h | 424 +++++++++++++++++++++++++++++++++
 1 file changed, 424 insertions(+)
 create mode 100644 arch/x86/kernel/cpu/sgx/arch.h

diff --git a/arch/x86/kernel/cpu/sgx/arch.h b/arch/x86/kernel/cpu/sgx/arch.h
new file mode 100644
index 000000000000..39f731580ea8
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/arch.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 11/28] x86/sgx: Add wrappers for ENCLS leaf functions
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (9 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 10/28] x86/sgx: Add SGX1 and SGX2 architectural data structures Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 12/28] x86/sgx: Enumerate and track EPC sections Jarkko Sakkinen
                   ` (22 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 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

diff --git a/arch/x86/kernel/cpu/sgx/Makefile b/arch/x86/kernel/cpu/sgx/Makefile
new file mode 100644
index 000000000000..4432d935894e
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/Makefile
@@ -0,0 +1 @@
+obj-y += encls.o
diff --git a/arch/x86/kernel/cpu/sgx/encls.c b/arch/x86/kernel/cpu/sgx/encls.c
new file mode 100644
index 000000000000..5045f1365e07
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/encls.c
@@ -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;
+}
diff --git a/arch/x86/kernel/cpu/sgx/encls.h b/arch/x86/kernel/cpu/sgx/encls.h
new file mode 100644
index 000000000000..aea3b9d09936
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/encls.h
@@ -0,0 +1,244 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+#ifndef _X86_ENCLS_H
+#define _X86_ENCLS_H
+
+#include <linux/bitops.h>
+#include <linux/err.h>
+#include <linux/io.h>
+#include <linux/rwsem.h>
+#include <linux/types.h>
+#include <asm/asm.h>
+#include "arch.h"
+
+/**
+ * ENCLS_FAULT_FLAG - flag signifying an ENCLS return code is a trapnr
+ *
+ * ENCLS has its own (positive value) error codes and also generates
+ * ENCLS specific #GP and #PF faults.  And the ENCLS values get munged
+ * with system error codes as everything percolates back up the stack.
+ * Unfortunately (for us), we need to precisely identify each unique
+ * error code, e.g. the action taken if EWB fails varies based on the
+ * type of fault and on the exact SGX error code, i.e. we can't simply
+ * convert all faults to -EFAULT.
+ *
+ * To make all three error types coexist, we set bit 30 to identify an
+ * ENCLS fault.  Bit 31 (technically bits N:31) is used to differentiate
+ * between positive (faults and SGX error codes) and negative (system
+ * error codes) values.
+ */
+#define ENCLS_FAULT_FLAG 0x40000000
+
+/**
+ * Retrieve the encoded trapnr from the specified return code.
+ */
+#define ENCLS_TRAPNR(r) ((r) & ~ENCLS_FAULT_FLAG)
+
+/* Issue a WARN() about an ENCLS leaf. */
+#define ENCLS_WARN(r, name) {						\
+	do {								\
+		int _r = (r);						\
+		WARN(_r, "sgx: %s returned %d (0x%x)\n", (name), _r,	\
+		     _r);						\
+	} while (0);							\
+}
+
+/**
+ * encls_faulted() - Check if ENCLS leaf function faulted
+ * @ret:	the return value of an ENCLS leaf function call
+ *
+ * Return: true if the fault flag is set
+ */
+static inline bool encls_faulted(int ret)
+{
+	return (ret & ENCLS_FAULT_FLAG) != 0;
+}
+
+/**
+ * encls_returned_code() - Check if an ENCLS leaf function returned a code
+ * @ret:	the return value of an ENCLS leaf function call
+ *
+ * Check if an ENCLS leaf function returned an error or information code.
+ *
+ * Return: true if there was a fault other than an EPCM conflict
+ */
+static inline bool encls_returned_code(int ret)
+{
+	return !encls_faulted(ret) && ret;
+}
+
+bool encls_failed(int ret);
+
+/**
+ * __encls_ret_N - encode an ENCLS leaf that returns an error code in EAX
+ * @rax:	leaf number
+ * @inputs:	asm inputs for the leaf
+ *
+ * Emit assembly for an ENCLS leaf that returns an error code, e.g. EREMOVE.
+ * And because SGX isn't complex enough as it is, leafs that return an error
+ * code also modify flags.
+ *
+ * Return:
+ *	0 on success,
+ *	SGX error code on failure
+ */
+#define __encls_ret_N(rax, inputs...)				\
+	({							\
+	int ret;						\
+	asm volatile(						\
+	"1: .byte 0x0f, 0x01, 0xcf;\n\t"			\
+	"2:\n"							\
+	".section .fixup,\"ax\"\n"				\
+	"3: orl $"__stringify(ENCLS_FAULT_FLAG)",%%eax\n"	\
+	"   jmp 2b\n"						\
+	".previous\n"						\
+	_ASM_EXTABLE_FAULT(1b, 3b)				\
+	: "=a"(ret)						\
+	: "a"(rax), inputs					\
+	: "memory", "cc");					\
+	ret;							\
+	})
+
+#define __encls_ret_1(rax, rcx)		\
+	({				\
+	__encls_ret_N(rax, "c"(rcx));	\
+	})
+
+#define __encls_ret_2(rax, rbx, rcx)		\
+	({					\
+	__encls_ret_N(rax, "b"(rbx), "c"(rcx));	\
+	})
+
+#define __encls_ret_3(rax, rbx, rcx, rdx)			\
+	({							\
+	__encls_ret_N(rax, "b"(rbx), "c"(rcx), "d"(rdx));	\
+	})
+
+/**
+ * __encls_N - encode an ENCLS leaf that doesn't return an error code
+ * @rax:	leaf number
+ * @rbx_out:	optional output variable
+ * @inputs:	asm inputs for the leaf
+ *
+ * Emit assembly for an ENCLS leaf that does not return an error code,
+ * e.g. ECREATE.  Leaves without error codes either succeed or fault.
+ * @rbx_out is an optional parameter for use by EDGBRD, which returns
+ * the the requested value in RBX.
+ *
+ * Return:
+ *   0 on success,
+ *   trapnr with ENCLS_FAULT_FLAG set on fault
+ */
+#define __encls_N(rax, rbx_out, inputs...)			\
+	({							\
+	int ret;						\
+	asm volatile(						\
+	"1: .byte 0x0f, 0x01, 0xcf;\n\t"			\
+	"   xor %%eax,%%eax;\n"					\
+	"2:\n"							\
+	".section .fixup,\"ax\"\n"				\
+	"3: orl $"__stringify(ENCLS_FAULT_FLAG)",%%eax\n"	\
+	"   jmp 2b\n"						\
+	".previous\n"						\
+	_ASM_EXTABLE_FAULT(1b, 3b)				\
+	: "=a"(ret), "=b"(rbx_out)				\
+	: "a"(rax), inputs					\
+	: "memory");						\
+	ret;							\
+	})
+
+#define __encls_2(rax, rbx, rcx)				\
+	({							\
+	unsigned long ign_rbx_out;				\
+	__encls_N(rax, ign_rbx_out, "b"(rbx), "c"(rcx));	\
+	})
+
+#define __encls_1_1(rax, data, rcx)			\
+	({						\
+	unsigned long rbx_out;				\
+	int ret = __encls_N(rax, rbx_out, "c"(rcx));	\
+	if (!ret)					\
+		data = rbx_out;				\
+	ret;						\
+	})
+
+static inline int __ecreate(struct sgx_pageinfo *pginfo, void *secs)
+{
+	return __encls_2(SGX_ECREATE, pginfo, secs);
+}
+
+static inline int __eextend(void *secs, void *addr)
+{
+	return __encls_2(SGX_EEXTEND, secs, addr);
+}
+
+static inline int __eadd(struct sgx_pageinfo *pginfo, void *addr)
+{
+	return __encls_2(SGX_EADD, pginfo, addr);
+}
+
+static inline int __einit(void *sigstruct, struct sgx_einittoken *einittoken,
+			  void *secs)
+{
+	return __encls_ret_3(SGX_EINIT, sigstruct, secs, einittoken);
+}
+
+static inline int __eremove(void *addr)
+{
+	return __encls_ret_1(SGX_EREMOVE, addr);
+}
+
+static inline int __edbgwr(void *addr, unsigned long *data)
+{
+	return __encls_2(SGX_EDGBWR, *data, addr);
+}
+
+static inline int __edbgrd(void *addr, unsigned long *data)
+{
+	return __encls_1_1(SGX_EDGBRD, *data, addr);
+}
+
+static inline int __etrack(void *addr)
+{
+	return __encls_ret_1(SGX_ETRACK, addr);
+}
+
+static inline int __eldu(struct sgx_pageinfo *pginfo, void *addr,
+			 void *va)
+{
+	return __encls_ret_3(SGX_ELDU, pginfo, addr, va);
+}
+
+static inline int __eblock(void *addr)
+{
+	return __encls_ret_1(SGX_EBLOCK, addr);
+}
+
+static inline int __epa(void *addr)
+{
+	unsigned long rbx = SGX_PAGE_TYPE_VA;
+
+	return __encls_2(SGX_EPA, rbx, addr);
+}
+
+static inline int __ewb(struct sgx_pageinfo *pginfo, void *addr,
+			void *va)
+{
+	return __encls_ret_3(SGX_EWB, pginfo, addr, va);
+}
+
+static inline int __eaug(struct sgx_pageinfo *pginfo, void *addr)
+{
+	return __encls_2(SGX_EAUG, pginfo, addr);
+}
+
+static inline int __emodpr(struct sgx_secinfo *secinfo, void *addr)
+{
+	return __encls_ret_2(SGX_EMODPR, secinfo, addr);
+}
+
+static inline int __emodt(struct sgx_secinfo *secinfo, void *addr)
+{
+	return __encls_ret_2(SGX_EMODT, secinfo, addr);
+}
+
+#endif /* _X86_ENCLS_H */
-- 
2.19.1


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

* [PATCH v20 12/28] x86/sgx: Enumerate and track EPC sections
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (10 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 11/28] x86/sgx: Add wrappers for ENCLS leaf functions Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 13/28] x86/sgx: Add functions to allocate and free EPC pages Jarkko Sakkinen
                   ` (21 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

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.

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Co-developed-by: Suresh Siddha <suresh.b.siddha@intel.com>
Signed-off-by: Suresh Siddha <suresh.b.siddha@intel.com>
Co-developed-by: Serge Ayoun <serge.ayoun@intel.com>
Signed-off-by: Serge Ayoun <serge.ayoun@intel.com>
---
 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

diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 5ad92419be19..5d90a20621cb 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -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
diff --git a/arch/x86/kernel/cpu/Makefile b/arch/x86/kernel/cpu/Makefile
index cfd24f9f7614..d1163c0fd5d6 100644
--- a/arch/x86/kernel/cpu/Makefile
+++ b/arch/x86/kernel/cpu/Makefile
@@ -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
 
diff --git a/arch/x86/kernel/cpu/sgx/Makefile b/arch/x86/kernel/cpu/sgx/Makefile
index 4432d935894e..fa930e292110 100644
--- a/arch/x86/kernel/cpu/sgx/Makefile
+++ b/arch/x86/kernel/cpu/sgx/Makefile
@@ -1 +1 @@
-obj-y += encls.o
+obj-y += encls.o main.o reclaim.o
diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
new file mode 100644
index 000000000000..e2317f6e4374
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-17 Intel Corporation.
+
+#include <linux/freezer.h>
+#include <linux/highmem.h>
+#include <linux/kthread.h>
+#include <linux/pagemap.h>
+#include <linux/ratelimit.h>
+#include <linux/sched/signal.h>
+#include <linux/slab.h>
+#include "arch.h"
+#include "sgx.h"
+
+struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
+EXPORT_SYMBOL_GPL(sgx_epc_sections);
+
+int sgx_nr_epc_sections;
+
+static __init void sgx_free_epc_section(struct sgx_epc_section *section)
+{
+	struct sgx_epc_page *page;
+
+	while (!list_empty(&section->page_list)) {
+		page = list_first_entry(&section->page_list,
+					struct sgx_epc_page, list);
+		list_del(&page->list);
+		kfree(page);
+	}
+
+	while (!list_empty(&section->unsanitized_page_list)) {
+		page = list_first_entry(&section->unsanitized_page_list,
+					struct sgx_epc_page, list);
+		list_del(&page->list);
+		kfree(page);
+	}
+
+	memunmap(section->va);
+}
+
+static __init int sgx_init_epc_section(u64 addr, u64 size, unsigned long index,
+				       struct sgx_epc_section *section)
+{
+	unsigned long nr_pages = size >> PAGE_SHIFT;
+	struct sgx_epc_page *page;
+	unsigned long i;
+
+	section->va = memremap(addr, size, MEMREMAP_WB);
+	if (!section->va)
+		return -ENOMEM;
+
+	section->pa = addr;
+	spin_lock_init(&section->lock);
+	INIT_LIST_HEAD(&section->page_list);
+	INIT_LIST_HEAD(&section->unsanitized_page_list);
+
+	for (i = 0; i < nr_pages; i++) {
+		page = kzalloc(sizeof(*page), GFP_KERNEL);
+		if (!page)
+			goto out;
+		page->desc = (addr + (i << PAGE_SHIFT)) | index;
+		list_add_tail(&page->list, &section->unsanitized_page_list);
+		section->free_cnt++;
+	}
+
+	return 0;
+out:
+	sgx_free_epc_section(section);
+	return -ENOMEM;
+}
+
+static __init void sgx_page_cache_teardown(void)
+{
+	int i;
+
+	for (i = 0; i < sgx_nr_epc_sections; i++)
+		sgx_free_epc_section(&sgx_epc_sections[i]);
+}
+
+/**
+ * A section metric is concatenated in a way that @low bits 12-31 define the
+ * bits 12-31 of the metric and @high bits 0-19 define the bits 32-51 of the
+ * metric.
+ */
+static inline u64 sgx_calc_section_metric(u64 low, u64 high)
+{
+	return (low & GENMASK_ULL(31, 12)) +
+	       ((high & GENMASK_ULL(19, 0)) << 32);
+}
+
+static __init int sgx_page_cache_init(void)
+{
+	u32 eax, ebx, ecx, edx, type;
+	u64 pa, size;
+	int ret;
+	int i;
+
+	BUILD_BUG_ON(SGX_MAX_EPC_SECTIONS > (SGX_EPC_SECTION_MASK + 1));
+
+	for (i = 0; i < (SGX_MAX_EPC_SECTIONS + 1); i++) {
+		cpuid_count(SGX_CPUID, i + SGX_CPUID_FIRST_VARIABLE_SUB_LEAF,
+			    &eax, &ebx, &ecx, &edx);
+
+		type = eax & SGX_CPUID_SUB_LEAF_TYPE_MASK;
+		if (type == SGX_CPUID_SUB_LEAF_INVALID)
+			break;
+		if (type != SGX_CPUID_SUB_LEAF_EPC_SECTION) {
+			pr_err_once("sgx: Unknown sub-leaf type: %u\n", type);
+			return -ENODEV;
+		}
+		if (i == SGX_MAX_EPC_SECTIONS) {
+			pr_warn("sgx: More than "
+				__stringify(SGX_MAX_EPC_SECTIONS)
+				" EPC sections\n");
+			break;
+		}
+
+		pa = sgx_calc_section_metric(eax, ebx);
+		size = sgx_calc_section_metric(ecx, edx);
+		pr_info("sgx: EPC section 0x%llx-0x%llx\n", pa, pa + size - 1);
+
+		ret = sgx_init_epc_section(pa, size, i, &sgx_epc_sections[i]);
+		if (ret) {
+			sgx_page_cache_teardown();
+			return ret;
+		}
+
+		sgx_nr_epc_sections++;
+	}
+
+	if (!sgx_nr_epc_sections) {
+		pr_err("sgx: There are zero EPC sections.\n");
+		return -ENODEV;
+	}
+
+	return 0;
+}
+
+static __init int sgx_init(void)
+{
+	int ret;
+
+	if (!boot_cpu_has(X86_FEATURE_SGX))
+		return false;
+
+	ret = sgx_page_cache_init();
+	if (ret)
+		return ret;
+
+	ret = sgx_page_reclaimer_init();
+	if (ret) {
+		sgx_page_cache_teardown();
+		return ret;
+	}
+
+	return 0;
+}
+
+arch_initcall(sgx_init);
diff --git a/arch/x86/kernel/cpu/sgx/reclaim.c b/arch/x86/kernel/cpu/sgx/reclaim.c
new file mode 100644
index 000000000000..042769f03be9
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/reclaim.c
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-19 Intel Corporation.
+
+#include <linux/freezer.h>
+#include <linux/highmem.h>
+#include <linux/kthread.h>
+#include <linux/pagemap.h>
+#include <linux/ratelimit.h>
+#include <linux/slab.h>
+#include <linux/sched/mm.h>
+#include <linux/sched/signal.h>
+#include "encls.h"
+#include "sgx.h"
+
+static struct task_struct *ksgxswapd_tsk;
+
+static void sgx_sanitize_section(struct sgx_epc_section *section)
+{
+	struct sgx_epc_page *page, *tmp;
+	LIST_HEAD(secs_list);
+	int ret;
+
+	while (!list_empty(&section->unsanitized_page_list)) {
+		if (kthread_should_stop())
+			return;
+
+		spin_lock(&section->lock);
+
+		page = list_first_entry(&section->unsanitized_page_list,
+					struct sgx_epc_page, list);
+
+		ret = __eremove(sgx_epc_addr(page));
+		if (!ret)
+			list_move(&page->list, &section->page_list);
+		else
+			list_move_tail(&page->list, &secs_list);
+
+		spin_unlock(&section->lock);
+
+		cond_resched();
+	}
+
+	list_for_each_entry_safe(page, tmp, &secs_list, list) {
+		if (kthread_should_stop())
+			return;
+
+		ret = __eremove(sgx_epc_addr(page));
+		if (!WARN_ON_ONCE(ret)) {
+			spin_lock(&section->lock);
+			list_move(&page->list, &section->page_list);
+			spin_unlock(&section->lock);
+		} else {
+			list_del(&page->list);
+			kfree(page);
+		}
+
+		cond_resched();
+	}
+}
+
+static int ksgxswapd(void *p)
+{
+	int i;
+
+	set_freezable();
+
+	for (i = 0; i < sgx_nr_epc_sections; i++)
+		sgx_sanitize_section(&sgx_epc_sections[i]);
+
+	return 0;
+}
+
+int sgx_page_reclaimer_init(void)
+{
+	struct task_struct *tsk;
+
+	tsk = kthread_run(ksgxswapd, NULL, "ksgxswapd");
+	if (IS_ERR(tsk))
+		return PTR_ERR(tsk);
+
+	ksgxswapd_tsk = tsk;
+
+	return 0;
+}
diff --git a/arch/x86/kernel/cpu/sgx/sgx.h b/arch/x86/kernel/cpu/sgx/sgx.h
new file mode 100644
index 000000000000..3009ec816339
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/sgx.h
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+#ifndef _X86_SGX_H
+#define _X86_SGX_H
+
+#include <linux/bitops.h>
+#include <linux/err.h>
+#include <linux/io.h>
+#include <linux/rwsem.h>
+#include <linux/types.h>
+#include <asm/asm.h>
+#include <uapi/asm/sgx_errno.h>
+
+struct sgx_epc_page {
+	unsigned long desc;
+	struct list_head list;
+};
+
+/**
+ * struct sgx_epc_section
+ *
+ * The firmware can define multiple chunks of EPC to the different areas of the
+ * physical memory e.g. for memory areas of the each node. This structure is
+ * used to store EPC pages for one EPC section and virtual memory area where
+ * the pages have been mapped.
+ */
+struct sgx_epc_section {
+	unsigned long pa;
+	void *va;
+	struct list_head page_list;
+	struct list_head unsanitized_page_list;
+	unsigned long free_cnt;
+	spinlock_t lock;
+};
+
+#define SGX_MAX_EPC_SECTIONS	8
+
+extern struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
+
+/**
+ * enum sgx_epc_page_desc - bits and masks for an EPC page's descriptor
+ * %SGX_EPC_SECTION_MASK:	SGX allows to have multiple EPC sections in the
+ *				physical memory. The existing and near-future
+ *				hardware defines at most eight sections, hence
+ *				three bits to hold a section.
+ */
+enum sgx_epc_page_desc {
+	SGX_EPC_SECTION_MASK			= GENMASK_ULL(3, 0),
+	/* bits 12-63 are reserved for the physical page address of the page */
+};
+
+static inline struct sgx_epc_section *sgx_epc_section(struct sgx_epc_page *page)
+{
+	return &sgx_epc_sections[page->desc & SGX_EPC_SECTION_MASK];
+}
+
+static inline void *sgx_epc_addr(struct sgx_epc_page *page)
+{
+	struct sgx_epc_section *section = sgx_epc_section(page);
+
+	return section->va + (page->desc & PAGE_MASK) - section->pa;
+}
+
+extern int sgx_nr_epc_sections;
+
+int sgx_page_reclaimer_init(void);
+
+#endif /* _X86_SGX_H */
-- 
2.19.1


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

* [PATCH v20 13/28] x86/sgx: Add functions to allocate and free EPC pages
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (11 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 12/28] x86/sgx: Enumerate and track EPC sections Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 14/28] x86/sgx: Add sgx_einit() for initializing enclaves Jarkko Sakkinen
                   ` (20 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 arch/x86/kernel/cpu/sgx/main.c | 90 ++++++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h  |  4 ++
 2 files changed, 94 insertions(+)

diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
index e2317f6e4374..6b4727df72ca 100644
--- a/arch/x86/kernel/cpu/sgx/main.c
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -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;
diff --git a/arch/x86/kernel/cpu/sgx/sgx.h b/arch/x86/kernel/cpu/sgx/sgx.h
index 3009ec816339..210510a28ce0 100644
--- a/arch/x86/kernel/cpu/sgx/sgx.h
+++ b/arch/x86/kernel/cpu/sgx/sgx.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 14/28] x86/sgx: Add sgx_einit() for initializing enclaves
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (12 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 13/28] x86/sgx: Add functions to allocate and free EPC pages Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver Jarkko Sakkinen
                   ` (19 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

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.

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/kernel/cpu/sgx/main.c | 51 ++++++++++++++++++++++++++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h  |  2 ++
 2 files changed, 53 insertions(+)

diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
index 6b4727df72ca..d3ed742e90fe 100644
--- a/arch/x86/kernel/cpu/sgx/main.c
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -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;
diff --git a/arch/x86/kernel/cpu/sgx/sgx.h b/arch/x86/kernel/cpu/sgx/sgx.h
index 210510a28ce0..41d4130c33a2 100644
--- a/arch/x86/kernel/cpu/sgx/sgx.h
+++ b/arch/x86/kernel/cpu/sgx/sgx.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (13 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 14/28] x86/sgx: Add sgx_einit() for initializing enclaves Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-22 21:58   ` Sean Christopherson
  2019-04-17 10:39 ` [PATCH v20 16/28] x86/sgx: Add provisioning Jarkko Sakkinen
                   ` (18 subsequent siblings)
  33 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Serge Ayoun <serge.ayoun@intel.com>
Signed-off-by: Serge Ayoun <serge.ayoun@intel.com>
Co-developed-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
Signed-off-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
Co-developed-by: Suresh Siddha <suresh.b.siddha@intel.com>
Signed-off-by: Suresh Siddha <suresh.b.siddha@intel.com>
---
 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

diff --git a/Documentation/ioctl/ioctl-number.txt b/Documentation/ioctl/ioctl-number.txt
index c9558146ac58..ef2694221cd0 100644
--- a/Documentation/ioctl/ioctl-number.txt
+++ b/Documentation/ioctl/ioctl-number.txt
@@ -312,6 +312,7 @@ Code  Seq#(hex)	Include File		Comments
 					<mailto:tlewis@mindspring.com>
 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
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 5d90a20621cb..adea370b331f 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -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
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
new file mode 100644
index 000000000000..7bf627ac4958
--- /dev/null
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -0,0 +1,57 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/*
+ * Copyright(c) 2016-18 Intel Corporation.
+ */
+#ifndef _UAPI_ASM_X86_SGX_H
+#define _UAPI_ASM_X86_SGX_H
+
+#include <linux/types.h>
+#include <linux/ioctl.h>
+
+#define SGX_MAGIC 0xA4
+
+#define SGX_IOC_ENCLAVE_CREATE \
+	_IOW(SGX_MAGIC, 0x00, struct sgx_enclave_create)
+#define SGX_IOC_ENCLAVE_ADD_PAGE \
+	_IOW(SGX_MAGIC, 0x01, struct sgx_enclave_add_page)
+#define SGX_IOC_ENCLAVE_INIT \
+	_IOW(SGX_MAGIC, 0x02, struct sgx_enclave_init)
+
+/* IOCTL return values */
+#define SGX_POWER_LOST_ENCLAVE		0x40000000
+
+/**
+ * struct sgx_enclave_create - parameter structure for the
+ *                             %SGX_IOC_ENCLAVE_CREATE ioctl
+ * @src:	address for the SECS page data
+ */
+struct sgx_enclave_create  {
+	__u64	src;
+};
+
+/**
+ * struct sgx_enclave_add_page - parameter structure for the
+ *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
+ * @addr:	address within the ELRANGE
+ * @src:	address for the page data
+ * @secinfo:	address for the SECINFO data
+ * @mrmask:	bitmask for the measured 256 byte chunks
+ */
+struct sgx_enclave_add_page {
+	__u64	addr;
+	__u64	src;
+	__u64	secinfo;
+	__u16	mrmask;
+} __attribute__((__packed__));
+
+
+/**
+ * struct sgx_enclave_init - parameter structure for the
+ *                           %SGX_IOC_ENCLAVE_INIT ioctl
+ * @sigstruct:	address for the SIGSTRUCT data
+ */
+struct sgx_enclave_init {
+	__u64	sigstruct;
+};
+
+#endif /* _UAPI_ASM_X86_SGX_H */
diff --git a/arch/x86/kernel/cpu/sgx/Makefile b/arch/x86/kernel/cpu/sgx/Makefile
index fa930e292110..e5d1e862969c 100644
--- a/arch/x86/kernel/cpu/sgx/Makefile
+++ b/arch/x86/kernel/cpu/sgx/Makefile
@@ -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/
diff --git a/arch/x86/kernel/cpu/sgx/driver/Makefile b/arch/x86/kernel/cpu/sgx/driver/Makefile
new file mode 100644
index 000000000000..01ebbbb06a47
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/driver/Makefile
@@ -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
diff --git a/arch/x86/kernel/cpu/sgx/driver/driver.h b/arch/x86/kernel/cpu/sgx/driver/driver.h
new file mode 100644
index 000000000000..507712eb0a68
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/driver/driver.h
@@ -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__ */
diff --git a/arch/x86/kernel/cpu/sgx/driver/ioctl.c b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
new file mode 100644
index 000000000000..f88226518b21
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
@@ -0,0 +1,750 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-19 Intel Corporation.
+
+#include <asm/mman.h>
+#include <linux/delay.h>
+#include <linux/file.h>
+#include <linux/hashtable.h>
+#include <linux/highmem.h>
+#include <linux/ratelimit.h>
+#include <linux/sched/signal.h>
+#include <linux/shmem_fs.h>
+#include <linux/slab.h>
+#include <linux/suspend.h>
+#include "driver.h"
+
+struct sgx_add_page_req {
+	struct sgx_encl *encl;
+	struct sgx_encl_page *encl_page;
+	struct sgx_secinfo secinfo;
+	unsigned long mrmask;
+	struct list_head list;
+};
+
+static bool sgx_process_add_page_req(struct sgx_add_page_req *req,
+				     struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *encl_page = req->encl_page;
+	struct sgx_encl *encl = req->encl;
+	unsigned long page_index = sgx_encl_get_index(encl, encl_page);
+	struct sgx_secinfo secinfo;
+	struct sgx_pageinfo pginfo;
+	struct page *backing;
+	unsigned long addr;
+	int ret;
+	int i;
+
+	if (encl->flags & (SGX_ENCL_SUSPEND | SGX_ENCL_DEAD))
+		return false;
+
+	addr = SGX_ENCL_PAGE_ADDR(encl_page);
+
+	backing = sgx_encl_get_backing_page(encl, page_index);
+	if (IS_ERR(backing))
+		return false;
+
+	/*
+	 * The SECINFO field must be 64-byte aligned, copy it to a local
+	 * variable that is guaranteed to be aligned as req->secinfo may
+	 * or may not be 64-byte aligned, e.g. req may have been allocated
+	 * via kzalloc which is not aware of __aligned attributes.
+	 */
+	memcpy(&secinfo, &req->secinfo, sizeof(secinfo));
+
+	pginfo.secs = (unsigned long)sgx_epc_addr(encl->secs.epc_page);
+	pginfo.addr = addr;
+	pginfo.metadata = (unsigned long)&secinfo;
+	pginfo.contents = (unsigned long)kmap_atomic(backing);
+	ret = __eadd(&pginfo, sgx_epc_addr(epc_page));
+	kunmap_atomic((void *)(unsigned long)pginfo.contents);
+
+	put_page(backing);
+
+	if (ret) {
+		if (encls_failed(ret))
+			ENCLS_WARN(ret, "EADD");
+		return false;
+	}
+
+	for_each_set_bit(i, &req->mrmask, 16) {
+		ret = __eextend(sgx_epc_addr(encl->secs.epc_page),
+				sgx_epc_addr(epc_page) + (i * 0x100));
+		if (ret) {
+			if (encls_failed(ret))
+				ENCLS_WARN(ret, "EEXTEND");
+			return false;
+		}
+	}
+
+	encl_page->encl = encl;
+	encl_page->epc_page = epc_page;
+	encl->secs_child_cnt++;
+
+	return true;
+}
+
+static void sgx_add_page_worker(struct work_struct *work)
+{
+	struct sgx_add_page_req *req;
+	bool skip_rest = false;
+	bool is_empty = false;
+	struct sgx_encl *encl;
+	struct sgx_epc_page *epc_page;
+
+	encl = container_of(work, struct sgx_encl, work);
+
+	do {
+		schedule();
+
+		mutex_lock(&encl->lock);
+		if (encl->flags & SGX_ENCL_DEAD)
+			skip_rest = true;
+
+		req = list_first_entry(&encl->add_page_reqs,
+				       struct sgx_add_page_req, list);
+		list_del(&req->list);
+		is_empty = list_empty(&encl->add_page_reqs);
+		mutex_unlock(&encl->lock);
+
+		if (skip_rest)
+			goto next;
+
+		epc_page = sgx_alloc_page();
+
+		mutex_lock(&encl->lock);
+
+		if (IS_ERR(epc_page)) {
+			sgx_encl_destroy(encl);
+			skip_rest = true;
+		} else if (!sgx_process_add_page_req(req, epc_page)) {
+			sgx_free_page(epc_page);
+			sgx_encl_destroy(encl);
+			skip_rest = true;
+		}
+
+		mutex_unlock(&encl->lock);
+
+next:
+		kfree(req);
+	} while (!kref_put(&encl->refcount, sgx_encl_release) && !is_empty);
+}
+
+static u32 sgx_calc_ssaframesize(u32 miscselect, u64 xfrm)
+{
+	u32 size_max = PAGE_SIZE;
+	u32 size;
+	int i;
+
+	for (i = 2; i < 64; i++) {
+		if (!((1 << i) & xfrm))
+			continue;
+
+		size = SGX_SSA_GPRS_SIZE + sgx_xsave_size_tbl[i];
+		if (miscselect & SGX_MISC_EXINFO)
+			size += SGX_SSA_MISC_EXINFO_SIZE;
+
+		if (size > size_max)
+			size_max = size;
+	}
+
+	return PFN_UP(size_max);
+}
+
+static int sgx_validate_secs(const struct sgx_secs *secs,
+			     unsigned long ssaframesize)
+{
+	if (secs->size < (2 * PAGE_SIZE) || !is_power_of_2(secs->size))
+		return -EINVAL;
+
+	if (secs->base & (secs->size - 1))
+		return -EINVAL;
+
+	if (secs->miscselect & sgx_misc_reserved_mask ||
+	    secs->attributes & sgx_attributes_reserved_mask ||
+	    secs->xfrm & sgx_xfrm_reserved_mask)
+		return -EINVAL;
+
+	if (secs->attributes & SGX_ATTR_MODE64BIT) {
+		if (secs->size > sgx_encl_size_max_64)
+			return -EINVAL;
+	} else if (secs->size > sgx_encl_size_max_32)
+		return -EINVAL;
+
+	if (!(secs->xfrm & XFEATURE_MASK_FP) ||
+	    !(secs->xfrm & XFEATURE_MASK_SSE) ||
+	    (((secs->xfrm >> XFEATURE_BNDREGS) & 1) !=
+	     ((secs->xfrm >> XFEATURE_BNDCSR) & 1)))
+		return -EINVAL;
+
+	if (!secs->ssa_frame_size || ssaframesize > secs->ssa_frame_size)
+		return -EINVAL;
+
+	if (memchr_inv(secs->reserved1, 0, SGX_SECS_RESERVED1_SIZE) ||
+	    memchr_inv(secs->reserved2, 0, SGX_SECS_RESERVED2_SIZE) ||
+	    memchr_inv(secs->reserved3, 0, SGX_SECS_RESERVED3_SIZE) ||
+	    memchr_inv(secs->reserved4, 0, SGX_SECS_RESERVED4_SIZE))
+		return -EINVAL;
+
+	return 0;
+}
+
+static struct sgx_encl_page *sgx_encl_page_alloc(struct sgx_encl *encl,
+						 unsigned long addr)
+{
+	struct sgx_encl_page *encl_page;
+	int ret;
+
+	if (radix_tree_lookup(&encl->page_tree, PFN_DOWN(addr)))
+		return ERR_PTR(-EEXIST);
+	encl_page = kzalloc(sizeof(*encl_page), GFP_KERNEL);
+	if (!encl_page)
+		return ERR_PTR(-ENOMEM);
+	encl_page->desc = addr;
+	encl_page->encl = encl;
+	ret = radix_tree_insert(&encl->page_tree, PFN_DOWN(encl_page->desc),
+				encl_page);
+	if (ret) {
+		kfree(encl_page);
+		return ERR_PTR(ret);
+	}
+	return encl_page;
+}
+
+static int sgx_encl_pm_notifier(struct notifier_block *nb,
+				unsigned long action, void *data)
+{
+	struct sgx_encl *encl = container_of(nb, struct sgx_encl, pm_notifier);
+
+	if (action != PM_SUSPEND_PREPARE && action != PM_HIBERNATION_PREPARE)
+		return NOTIFY_DONE;
+
+	mutex_lock(&encl->lock);
+	sgx_encl_destroy(encl);
+	encl->flags |= SGX_ENCL_SUSPEND;
+	mutex_unlock(&encl->lock);
+	flush_work(&encl->work);
+	return NOTIFY_DONE;
+}
+
+static int sgx_encl_create(struct sgx_encl *encl, struct sgx_secs *secs)
+{
+	unsigned long encl_size = secs->size + PAGE_SIZE;
+	struct sgx_epc_page *secs_epc;
+	struct sgx_encl_mm *encl_mm;
+	unsigned long ssaframesize;
+	struct sgx_pageinfo pginfo;
+	struct sgx_secinfo secinfo;
+	struct file *backing;
+	long ret;
+
+	mutex_lock(&encl->lock);
+
+	if (encl->flags & SGX_ENCL_CREATED) {
+		ret = -EFAULT;
+		goto err_out;
+	}
+
+	ssaframesize = sgx_calc_ssaframesize(secs->miscselect, secs->xfrm);
+	if (sgx_validate_secs(secs, ssaframesize)) {
+		ret = -EINVAL;
+		goto err_out;
+	}
+
+	backing = shmem_file_setup("SGX backing", encl_size + (encl_size >> 5),
+				   VM_NORESERVE);
+	if (IS_ERR(backing)) {
+		ret = PTR_ERR(backing);
+		goto err_out;
+	}
+
+	encl->backing = backing;
+
+	INIT_WORK(&encl->work, sgx_add_page_worker);
+
+	encl_mm = sgx_encl_mm_add(encl, current->mm);
+	if (IS_ERR(encl_mm)) {
+		ret = PTR_ERR(encl_mm);
+		goto err_out;
+	}
+
+	secs_epc = sgx_alloc_page();
+	if (IS_ERR(secs_epc)) {
+		ret = PTR_ERR(secs_epc);
+		goto err_out;
+	}
+
+	encl->secs.epc_page = secs_epc;
+
+	pginfo.addr = 0;
+	pginfo.contents = (unsigned long)secs;
+	pginfo.metadata = (unsigned long)&secinfo;
+	pginfo.secs = 0;
+	memset(&secinfo, 0, sizeof(secinfo));
+
+	ret = __ecreate((void *)&pginfo, sgx_epc_addr(secs_epc));
+	if (ret) {
+		pr_debug("ECREATE returned %ld\n", ret);
+		goto err_out;
+	}
+
+	if (secs->attributes & SGX_ATTR_DEBUG)
+		encl->flags |= SGX_ENCL_DEBUG;
+
+	encl->pm_notifier.notifier_call = &sgx_encl_pm_notifier;
+	ret = register_pm_notifier(&encl->pm_notifier);
+	if (ret) {
+		encl->pm_notifier.notifier_call = NULL;
+		goto err_out;
+	}
+
+	encl->secs.encl = encl;
+	encl->secs_attributes = secs->attributes;
+	encl->allowed_attributes = SGX_ATTR_ALLOWED_MASK;
+	encl->base = secs->base;
+	encl->size = secs->size;
+	encl->ssaframesize = secs->ssa_frame_size;
+	encl->flags |= SGX_ENCL_CREATED;
+
+	mutex_unlock(&encl->lock);
+	return 0;
+
+err_out:
+	if (encl->secs.epc_page) {
+		sgx_free_page(encl->secs.epc_page);
+		encl->secs.epc_page = NULL;
+	}
+
+	if (encl->backing) {
+		fput(encl->backing);
+		encl->backing = NULL;
+	}
+
+	if (!list_empty(&encl->mm_list)) {
+		encl_mm = list_first_entry(&encl->mm_list, struct sgx_encl_mm,
+					   list);
+		list_del(&encl_mm->list);
+		kfree(encl_mm);
+	}
+
+	mutex_unlock(&encl->lock);
+	return ret;
+}
+
+/**
+ * sgx_ioc_enclave_create - handler for %SGX_IOC_ENCLAVE_CREATE
+ * @filep:	open file to /dev/sgx
+ * @cmd:	the command value
+ * @arg:	pointer to an &sgx_enclave_create instance
+ *
+ * Allocate kernel data structures for a new enclave and execute ECREATE after
+ * verifying the correctness of the provided SECS.
+ *
+ * Note, enforcement of restricted and disallowed attributes is deferred until
+ * sgx_ioc_enclave_init(), only the architectural correctness of the SECS is
+ * checked by sgx_ioc_enclave_create().
+ *
+ * Return:
+ *   0 on success,
+ *   -errno otherwise
+ */
+static long sgx_ioc_enclave_create(struct file *filep, unsigned int cmd,
+				   unsigned long arg)
+{
+	struct sgx_enclave_create *createp = (struct sgx_enclave_create *)arg;
+	struct sgx_encl *encl = filep->private_data;
+	struct page *secs_page;
+	struct sgx_secs *secs;
+	int ret;
+
+	secs_page = alloc_page(GFP_HIGHUSER);
+	if (!secs_page)
+		return -ENOMEM;
+
+	secs = kmap(secs_page);
+	if (copy_from_user(secs, (void __user *)createp->src, sizeof(*secs))) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+
+	ret = sgx_encl_create(encl, secs);
+
+out:
+	kunmap(secs_page);
+	__free_page(secs_page);
+	return ret;
+}
+
+static int sgx_validate_secinfo(struct sgx_secinfo *secinfo)
+{
+	u64 page_type = secinfo->flags & SGX_SECINFO_PAGE_TYPE_MASK;
+	u64 perm = secinfo->flags & SGX_SECINFO_PERMISSION_MASK;
+	int i;
+
+	if ((secinfo->flags & SGX_SECINFO_RESERVED_MASK) ||
+	    ((perm & SGX_SECINFO_W) && !(perm & SGX_SECINFO_R)) ||
+	    (page_type != SGX_SECINFO_TCS && page_type != SGX_SECINFO_TRIM &&
+	     page_type != SGX_SECINFO_REG))
+		return -EINVAL;
+
+	for (i = 0; i < SGX_SECINFO_RESERVED_SIZE; i++)
+		if (secinfo->reserved[i])
+			return -EINVAL;
+
+	return 0;
+}
+
+static bool sgx_validate_offset(struct sgx_encl *encl, unsigned long offset)
+{
+	if (offset & (PAGE_SIZE - 1))
+		return false;
+
+	if (offset >= encl->size)
+		return false;
+
+	return true;
+}
+
+static int sgx_validate_tcs(struct sgx_encl *encl, struct sgx_tcs *tcs)
+{
+	int i;
+
+	if (tcs->flags & SGX_TCS_RESERVED_MASK)
+		return -EINVAL;
+
+	if (tcs->flags & SGX_TCS_DBGOPTIN)
+		return -EINVAL;
+
+	if (!sgx_validate_offset(encl, tcs->ssa_offset))
+		return -EINVAL;
+
+	if (!sgx_validate_offset(encl, tcs->fs_offset))
+		return -EINVAL;
+
+	if (!sgx_validate_offset(encl, tcs->gs_offset))
+		return -EINVAL;
+
+	if ((tcs->fs_limit & 0xFFF) != 0xFFF)
+		return -EINVAL;
+
+	if ((tcs->gs_limit & 0xFFF) != 0xFFF)
+		return -EINVAL;
+
+	for (i = 0; i < SGX_TCS_RESERVED_SIZE; i++)
+		if (tcs->reserved[i])
+			return -EINVAL;
+
+	return 0;
+}
+
+static int __sgx_encl_add_page(struct sgx_encl *encl,
+			       struct sgx_encl_page *encl_page,
+			       void *data,
+			       struct sgx_secinfo *secinfo,
+			       unsigned int mrmask)
+{
+	unsigned long page_index = sgx_encl_get_index(encl, encl_page);
+	u64 page_type = secinfo->flags & SGX_SECINFO_PAGE_TYPE_MASK;
+	struct sgx_add_page_req *req = NULL;
+	struct page *backing;
+	void *backing_ptr;
+	int empty;
+
+	req = kzalloc(sizeof(*req), GFP_KERNEL);
+	if (!req)
+		return -ENOMEM;
+
+	backing = sgx_encl_get_backing_page(encl, page_index);
+	if (IS_ERR(backing)) {
+		kfree(req);
+		return PTR_ERR(backing);
+	}
+
+	backing_ptr = kmap(backing);
+	memcpy(backing_ptr, data, PAGE_SIZE);
+	kunmap(backing);
+	if (page_type == SGX_SECINFO_TCS)
+		encl_page->desc |= SGX_ENCL_PAGE_TCS;
+	memcpy(&req->secinfo, secinfo, sizeof(*secinfo));
+	req->encl = encl;
+	req->encl_page = encl_page;
+	req->mrmask = mrmask;
+	empty = list_empty(&encl->add_page_reqs);
+	kref_get(&encl->refcount);
+	list_add_tail(&req->list, &encl->add_page_reqs);
+	if (empty)
+		queue_work(sgx_encl_wq, &encl->work);
+	set_page_dirty(backing);
+	put_page(backing);
+	return 0;
+}
+
+static int sgx_encl_add_page(struct sgx_encl *encl, unsigned long addr,
+			     void *data, struct sgx_secinfo *secinfo,
+			     unsigned int mrmask)
+{
+	u64 page_type = secinfo->flags & SGX_SECINFO_PAGE_TYPE_MASK;
+	struct sgx_encl_page *encl_page;
+	int ret;
+
+	if (sgx_validate_secinfo(secinfo))
+		return -EINVAL;
+	if (page_type == SGX_SECINFO_TCS) {
+		ret = sgx_validate_tcs(encl, data);
+		if (ret)
+			return ret;
+	}
+
+	mutex_lock(&encl->lock);
+
+	if (!(encl->flags & SGX_ENCL_CREATED) ||
+	    (encl->flags & (SGX_ENCL_INITIALIZED | SGX_ENCL_DEAD))) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+	encl_page = sgx_encl_page_alloc(encl, addr);
+	if (IS_ERR(encl_page)) {
+		ret = PTR_ERR(encl_page);
+		goto out;
+	}
+
+	ret = __sgx_encl_add_page(encl, encl_page, data, secinfo, mrmask);
+	if (ret) {
+		radix_tree_delete(&encl_page->encl->page_tree,
+				  PFN_DOWN(encl_page->desc));
+		kfree(encl_page);
+	}
+
+out:
+	mutex_unlock(&encl->lock);
+	return ret;
+}
+
+/**
+ * sgx_ioc_enclave_add_page - handler for %SGX_IOC_ENCLAVE_ADD_PAGE
+ *
+ * @filep:	open file to /dev/sgx
+ * @cmd:	the command value
+ * @arg:	pointer to an &sgx_enclave_add_page instance
+ *
+ * Add a page to an uninitialized enclave (EADD), and optionally extend the
+ * enclave's measurement with the contents of the page (EEXTEND).  EADD and
+ * EEXTEND are done asynchronously via worker threads.  A successful
+ * sgx_ioc_enclave_add_page() only indicates the page has been added to the
+ * work queue, it does not guarantee adding the page to the enclave will
+ * succeed.
+ *
+ * Return:
+ *   0 on success,
+ *   -errno otherwise
+ */
+static long sgx_ioc_enclave_add_page(struct file *filep, unsigned int cmd,
+				     unsigned long arg)
+{
+	struct sgx_enclave_add_page *addp = (void *)arg;
+	struct sgx_encl *encl = filep->private_data;
+	struct sgx_secinfo secinfo;
+	struct page *data_page;
+	void *data;
+	int ret;
+
+	if (copy_from_user(&secinfo, (void __user *)addp->secinfo,
+			   sizeof(secinfo)))
+		return -EFAULT;
+
+	data_page = alloc_page(GFP_HIGHUSER);
+	if (!data_page)
+		return -ENOMEM;
+
+	data = kmap(data_page);
+
+	if (copy_from_user((void *)data, (void __user *)addp->src, PAGE_SIZE)) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+	ret = sgx_encl_add_page(encl, addp->addr, data, &secinfo, addp->mrmask);
+	if (ret)
+		goto out;
+
+out:
+	kunmap(data_page);
+	__free_page(data_page);
+	return ret;
+}
+
+static int __sgx_get_key_hash(struct crypto_shash *tfm, const void *modulus,
+			      void *hash)
+{
+	SHASH_DESC_ON_STACK(shash, tfm);
+
+	shash->tfm = tfm;
+	shash->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
+
+	return crypto_shash_digest(shash, modulus, SGX_MODULUS_SIZE, hash);
+}
+
+static int sgx_get_key_hash(const void *modulus, void *hash)
+{
+	struct crypto_shash *tfm;
+	int ret;
+
+	tfm = crypto_alloc_shash("sha256", 0, CRYPTO_ALG_ASYNC);
+	if (IS_ERR(tfm))
+		return PTR_ERR(tfm);
+
+	ret = __sgx_get_key_hash(tfm, modulus, hash);
+
+	crypto_free_shash(tfm);
+	return ret;
+}
+
+static int sgx_encl_init(struct sgx_encl *encl, struct sgx_sigstruct *sigstruct,
+			 struct sgx_einittoken *token)
+{
+	u64 mrsigner[4];
+	int ret;
+	int i;
+	int j;
+
+	/* Check that the required attributes have been authorized. */
+	if (encl->secs_attributes & ~encl->allowed_attributes)
+		return -EINVAL;
+
+	ret = sgx_get_key_hash(sigstruct->modulus, mrsigner);
+	if (ret)
+		return ret;
+
+	flush_work(&encl->work);
+
+	mutex_lock(&encl->lock);
+
+	if (!(encl->flags & SGX_ENCL_CREATED) ||
+	    (encl->flags & (SGX_ENCL_INITIALIZED | SGX_ENCL_DEAD))) {
+		ret = -EFAULT;
+		goto err_out;
+	}
+
+	for (i = 0; i < SGX_EINIT_SLEEP_COUNT; i++) {
+		for (j = 0; j < SGX_EINIT_SPIN_COUNT; j++) {
+			ret = sgx_einit(sigstruct, token, encl->secs.epc_page,
+					mrsigner);
+			if (ret == SGX_UNMASKED_EVENT)
+				continue;
+			else
+				break;
+		}
+
+		if (ret != SGX_UNMASKED_EVENT)
+			break;
+
+		msleep_interruptible(SGX_EINIT_SLEEP_TIME);
+
+		if (signal_pending(current)) {
+			ret = -ERESTARTSYS;
+			goto err_out;
+		}
+	}
+
+	if (encls_faulted(ret)) {
+		if (encls_failed(ret))
+			ENCLS_WARN(ret, "EINIT");
+
+		sgx_encl_destroy(encl);
+		ret = -EFAULT;
+	} else if (encls_returned_code(ret)) {
+		pr_debug("EINIT returned %d\n", ret);
+	} else {
+		encl->flags |= SGX_ENCL_INITIALIZED;
+	}
+
+err_out:
+	mutex_unlock(&encl->lock);
+	return ret;
+}
+
+/**
+ * sgx_ioc_enclave_init - handler for %SGX_IOC_ENCLAVE_INIT
+ *
+ * @filep:	open file to /dev/sgx
+ * @cmd:	the command value
+ * @arg:	pointer to an &sgx_enclave_init instance
+ *
+ * Flush any outstanding enqueued EADD operations and perform EINIT.  The
+ * Launch Enclave Public Key Hash MSRs are rewritten as necessary to match
+ * the enclave's MRSIGNER, which is caculated from the provided sigstruct.
+ *
+ * Return:
+ *   0 on success,
+ *   SGX error code on EINIT failure,
+ *   -errno otherwise
+ */
+static long sgx_ioc_enclave_init(struct file *filep, unsigned int cmd,
+				 unsigned long arg)
+{
+	struct sgx_enclave_init *initp = (struct sgx_enclave_init *)arg;
+	struct sgx_encl *encl = filep->private_data;
+	struct sgx_einittoken *einittoken;
+	struct sgx_sigstruct *sigstruct;
+	struct page *initp_page;
+	int ret;
+
+	initp_page = alloc_page(GFP_HIGHUSER);
+	if (!initp_page)
+		return -ENOMEM;
+
+	sigstruct = kmap(initp_page);
+	einittoken = (struct sgx_einittoken *)
+		((unsigned long)sigstruct + PAGE_SIZE / 2);
+	memset(einittoken, 0, sizeof(*einittoken));
+
+	if (copy_from_user(sigstruct, (void __user *)initp->sigstruct,
+			   sizeof(*sigstruct))) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+
+	ret = sgx_encl_init(encl, sigstruct, einittoken);
+
+out:
+	kunmap(initp_page);
+	__free_page(initp_page);
+	return ret;
+}
+
+typedef long (*sgx_ioc_t)(struct file *filep, unsigned int cmd,
+			  unsigned long arg);
+
+long sgx_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
+{
+	char data[256];
+	sgx_ioc_t handler = NULL;
+	long ret;
+
+	switch (cmd) {
+	case SGX_IOC_ENCLAVE_CREATE:
+		handler = sgx_ioc_enclave_create;
+		break;
+	case SGX_IOC_ENCLAVE_ADD_PAGE:
+		handler = sgx_ioc_enclave_add_page;
+		break;
+	case SGX_IOC_ENCLAVE_INIT:
+		handler = sgx_ioc_enclave_init;
+		break;
+	default:
+		return -ENOIOCTLCMD;
+	}
+
+	if (copy_from_user(data, (void __user *)arg, _IOC_SIZE(cmd)))
+		return -EFAULT;
+
+	ret = handler(filep, cmd, (unsigned long)((void *)data));
+	if (!ret && (cmd & IOC_OUT)) {
+		if (copy_to_user((void __user *)arg, data, _IOC_SIZE(cmd)))
+			return -EFAULT;
+	}
+
+	return ret;
+}
diff --git a/arch/x86/kernel/cpu/sgx/driver/main.c b/arch/x86/kernel/cpu/sgx/driver/main.c
new file mode 100644
index 000000000000..d371add399cd
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/driver/main.c
@@ -0,0 +1,358 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-18 Intel Corporation.
+
+#include <linux/acpi.h>
+#include <linux/cdev.h>
+#include <linux/mman.h>
+#include <linux/platform_device.h>
+#include <linux/security.h>
+#include <linux/suspend.h>
+#include <asm/traps.h>
+#include "driver.h"
+
+MODULE_DESCRIPTION("Intel SGX Enclave Driver");
+MODULE_AUTHOR("Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>");
+MODULE_LICENSE("Dual BSD/GPL");
+
+struct workqueue_struct *sgx_encl_wq;
+u64 sgx_encl_size_max_32;
+u64 sgx_encl_size_max_64;
+u32 sgx_misc_reserved_mask;
+u64 sgx_attributes_reserved_mask;
+u64 sgx_xfrm_reserved_mask = ~0x3;
+u32 sgx_xsave_size_tbl[64];
+
+static int sgx_open(struct inode *inode, struct file *file)
+{
+	struct sgx_encl *encl;
+
+	encl = kzalloc(sizeof(*encl), GFP_KERNEL);
+	if (!encl)
+		return -ENOMEM;
+
+	kref_init(&encl->refcount);
+	INIT_LIST_HEAD(&encl->add_page_reqs);
+	INIT_RADIX_TREE(&encl->page_tree, GFP_KERNEL);
+	mutex_init(&encl->lock);
+	INIT_LIST_HEAD(&encl->mm_list);
+	spin_lock_init(&encl->mm_lock);
+
+	file->private_data = encl;
+
+	return 0;
+}
+
+static int sgx_release(struct inode *inode, struct file *file)
+{
+	struct sgx_encl *encl = file->private_data;
+
+	kref_put(&encl->refcount, sgx_encl_release);
+
+	return 0;
+}
+
+#ifdef CONFIG_COMPAT
+static long sgx_compat_ioctl(struct file *filep, unsigned int cmd,
+			      unsigned long arg)
+{
+	return sgx_ioctl(filep, cmd, arg);
+}
+#endif
+
+static int sgx_mmap(struct file *file, struct vm_area_struct *vma)
+{
+	struct sgx_encl *encl = file->private_data;
+
+	vma->vm_ops = &sgx_vm_ops;
+	vma->vm_flags |= VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP | VM_IO;
+	vma->vm_private_data = encl;
+
+	kref_get(&encl->refcount);
+
+	return 0;
+}
+
+static unsigned long sgx_get_unmapped_area(struct file *file,
+					   unsigned long addr,
+					   unsigned long len,
+					   unsigned long pgoff,
+					   unsigned long flags)
+{
+	if (len < 2 * PAGE_SIZE || len & (len - 1) || flags & MAP_PRIVATE)
+		return -EINVAL;
+
+	addr = current->mm->get_unmapped_area(file, addr, 2 * len, pgoff,
+					      flags);
+	if (IS_ERR_VALUE(addr))
+		return addr;
+
+	addr = (addr + (len - 1)) & ~(len - 1);
+
+	return addr;
+}
+
+static const struct file_operations sgx_encl_fops = {
+	.owner			= THIS_MODULE,
+	.open			= sgx_open,
+	.release		= sgx_release,
+	.unlocked_ioctl		= sgx_ioctl,
+#ifdef CONFIG_COMPAT
+	.compat_ioctl		= sgx_compat_ioctl,
+#endif
+	.mmap			= sgx_mmap,
+	.get_unmapped_area	= sgx_get_unmapped_area,
+};
+
+static const struct file_operations sgx_provision_fops = {
+	.owner			= THIS_MODULE,
+};
+
+static struct bus_type sgx_bus_type = {
+	.name	= "sgx",
+};
+
+struct sgx_dev_ctx {
+	struct device encl_dev;
+	struct cdev encl_cdev;
+	struct device provision_dev;
+	struct cdev provision_cdev;
+	struct kref refcount;
+};
+
+static dev_t sgx_devt;
+
+static void sgx_dev_ctx_free(struct kref *ref)
+{
+	struct sgx_dev_ctx *ctx = container_of(ref, struct sgx_dev_ctx,
+					       refcount);
+
+	kfree(ctx);
+}
+
+static void sgx_dev_release(struct device *dev)
+{
+	struct sgx_dev_ctx *ctx = container_of(dev, struct sgx_dev_ctx,
+					       encl_dev);
+
+	kref_put(&ctx->refcount, sgx_dev_ctx_free);
+}
+
+static int sgx_dev_populate(const char *name, struct device *dev,
+			    struct cdev *cdev, struct device *parent,
+			    const struct file_operations *fops,
+			    int minor)
+{
+	int ret;
+
+	device_initialize(dev);
+
+	dev->bus = &sgx_bus_type;
+	dev->parent = parent;
+	dev->devt = MKDEV(MAJOR(sgx_devt), minor);
+	dev->release = sgx_dev_release;
+
+	ret = dev_set_name(dev, name);
+	if (ret) {
+		put_device(dev);
+		return ret;
+	}
+
+	cdev_init(cdev, fops);
+	cdev->owner = THIS_MODULE;
+	return 0;
+}
+
+static struct sgx_dev_ctx *sgx_dev_ctx_alloc(struct device *parent)
+{
+	struct sgx_dev_ctx *ctx;
+	int ret;
+
+	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return ERR_PTR(-ENOMEM);
+
+	kref_init(&ctx->refcount);
+	kref_get(&ctx->refcount);
+
+	ret = sgx_dev_populate("sgx/enclave", &ctx->encl_dev, &ctx->encl_cdev,
+			       parent, &sgx_encl_fops, 0);
+	if (ret)
+		return ERR_PTR(ret);
+
+	ret = sgx_dev_populate("sgx/provision", &ctx->provision_dev,
+			       &ctx->provision_cdev, parent,
+			       &sgx_provision_fops, 1);
+	if (ret) {
+		put_device(&ctx->encl_dev);
+		return ERR_PTR(ret);
+	}
+
+	dev_set_drvdata(parent, ctx);
+
+	return ctx;
+}
+
+static struct sgx_dev_ctx *sgxm_dev_ctx_alloc(struct device *parent)
+{
+	struct sgx_dev_ctx *ctx;
+	int rc;
+
+	ctx = sgx_dev_ctx_alloc(parent);
+	if (IS_ERR(ctx))
+		return ctx;
+
+	rc = devm_add_action_or_reset(parent, (void (*)(void *))put_device,
+				      &ctx->encl_dev);
+	if (rc)
+		return ERR_PTR(rc);
+
+	rc = devm_add_action_or_reset(parent, (void (*)(void *))put_device,
+				      &ctx->provision_dev);
+	if (rc)
+		return ERR_PTR(rc);
+
+	return ctx;
+}
+
+static int sgx_dev_init(struct device *parent)
+{
+	struct sgx_dev_ctx *sgx_dev;
+	unsigned int eax;
+	unsigned int ebx;
+	unsigned int ecx;
+	unsigned int edx;
+	u64 attr_mask;
+	u64 xfrm_mask;
+	int ret;
+	int i;
+
+	cpuid_count(SGX_CPUID, 0, &eax, &ebx, &ecx, &edx);
+	sgx_misc_reserved_mask = ~ebx | SGX_MISC_RESERVED_MASK;
+	sgx_encl_size_max_64 = 1ULL << ((edx >> 8) & 0xFF);
+	sgx_encl_size_max_32 = 1ULL << (edx & 0xFF);
+
+	cpuid_count(SGX_CPUID, 1, &eax, &ebx, &ecx, &edx);
+
+	attr_mask = (((u64)ebx) << 32) + (u64)eax;
+	sgx_attributes_reserved_mask = ~attr_mask | SGX_ATTR_RESERVED_MASK;
+
+	if (boot_cpu_has(X86_FEATURE_OSXSAVE)) {
+		xfrm_mask = (((u64)edx) << 32) + (u64)ecx;
+
+		for (i = 2; i < 64; i++) {
+			cpuid_count(0x0D, i, &eax, &ebx, &ecx, &edx);
+			if ((1 << i) & xfrm_mask)
+				sgx_xsave_size_tbl[i] = eax + ebx;
+		}
+
+		sgx_xfrm_reserved_mask = ~xfrm_mask;
+	}
+
+	sgx_dev = sgxm_dev_ctx_alloc(parent);
+	if (IS_ERR(sgx_dev))
+		return PTR_ERR(sgx_dev);
+
+	sgx_encl_wq = alloc_workqueue("sgx-encl-wq",
+				      WQ_UNBOUND | WQ_FREEZABLE, 1);
+	if (!sgx_encl_wq)
+		return -ENOMEM;
+
+	ret = cdev_device_add(&sgx_dev->encl_cdev, &sgx_dev->encl_dev);
+	if (ret)
+		goto err_encl_dev_add;
+
+	return 0;
+
+err_encl_dev_add:
+	destroy_workqueue(sgx_encl_wq);
+
+	return ret;
+}
+
+static int sgx_drv_probe(struct platform_device *pdev)
+{
+	if (!sgx_enabled) {
+		pr_info("sgx: SGX is not enabled in the core\n");
+		return -ENODEV;
+	}
+
+	if (!boot_cpu_has(X86_FEATURE_SGX_LC)) {
+		pr_info("sgx: The public key MSRs are not writable\n");
+		return -ENODEV;
+	}
+
+	return sgx_dev_init(&pdev->dev);
+}
+
+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);
+	destroy_workqueue(sgx_encl_wq);
+
+	return 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,
+	.driver = {
+		.name			= "sgx",
+		.acpi_match_table	= ACPI_PTR(sgx_device_ids),
+	},
+};
+
+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);
diff --git a/arch/x86/kernel/cpu/sgx/encl.c b/arch/x86/kernel/cpu/sgx/encl.c
new file mode 100644
index 000000000000..cc3bd4a4d82b
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/encl.c
@@ -0,0 +1,349 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-18 Intel Corporation.
+
+#include <linux/mm.h>
+#include <linux/shmem_fs.h>
+#include <linux/suspend.h>
+#include <linux/sched/mm.h>
+#include "arch.h"
+#include "encl.h"
+#include "sgx.h"
+
+static struct sgx_encl_page *sgx_encl_load_page(struct sgx_encl *encl,
+						unsigned long addr)
+{
+	struct sgx_encl_page *entry;
+
+	/* If process was forked, VMA is still there but vm_private_data is set
+	 * to NULL.
+	 */
+	if (!encl)
+		return ERR_PTR(-EFAULT);
+
+	if ((encl->flags & SGX_ENCL_DEAD) ||
+	    !(encl->flags & SGX_ENCL_INITIALIZED))
+		return ERR_PTR(-EFAULT);
+
+	entry = radix_tree_lookup(&encl->page_tree, addr >> PAGE_SHIFT);
+	if (!entry)
+		return ERR_PTR(-EFAULT);
+
+	/* Page is already resident in the EPC. */
+	if (entry->epc_page)
+		return entry;
+
+	return ERR_PTR(-EFAULT);
+}
+
+struct sgx_encl_mm *sgx_encl_mm_add(struct sgx_encl *encl,
+				    struct mm_struct *mm)
+{
+	struct sgx_encl_mm *encl_mm;
+
+	encl_mm = kzalloc(sizeof(*encl_mm), GFP_KERNEL);
+	if (!encl_mm)
+		return ERR_PTR(-ENOMEM);
+
+	encl_mm->encl = encl;
+	encl_mm->mm = mm;
+	kref_init(&encl_mm->refcount);
+
+	spin_lock(&encl->mm_lock);
+	list_add(&encl_mm->list, &encl->mm_list);
+	spin_unlock(&encl->mm_lock);
+
+	return encl_mm;
+}
+EXPORT_SYMBOL_GPL(sgx_encl_mm_add);
+
+void sgx_encl_mm_release(struct kref *ref)
+{
+	struct sgx_encl_mm *encl_mm =
+		container_of(ref, struct sgx_encl_mm, refcount);
+
+	spin_lock(&encl_mm->encl->mm_lock);
+	list_del(&encl_mm->list);
+	spin_unlock(&encl_mm->encl->mm_lock);
+
+	kfree(encl_mm);
+}
+
+static struct sgx_encl_mm *sgx_encl_get_mm(struct sgx_encl *encl,
+					   struct mm_struct *mm)
+{
+	struct sgx_encl_mm *encl_mm = NULL;
+	struct sgx_encl_mm *prev_mm = NULL;
+	int iter;
+
+	while (true) {
+		encl_mm = sgx_encl_next_mm(encl, prev_mm, &iter);
+		if (prev_mm)
+			kref_put(&prev_mm->refcount, sgx_encl_mm_release);
+		prev_mm = encl_mm;
+
+		if (iter == SGX_ENCL_MM_ITER_DONE)
+			break;
+
+		if (iter == SGX_ENCL_MM_ITER_RESTART)
+			continue;
+
+		if (mm == encl_mm->mm)
+			return encl_mm;
+	}
+
+	return NULL;
+}
+
+static void sgx_vma_open(struct vm_area_struct *vma)
+{
+	struct sgx_encl *encl = vma->vm_private_data;
+	struct sgx_encl_mm *encl_mm;
+
+	if (!encl)
+		return;
+
+	if (encl->flags & SGX_ENCL_DEAD)
+		goto error;
+
+	encl_mm = sgx_encl_get_mm(encl, vma->vm_mm);
+	if (!encl_mm) {
+		encl_mm = sgx_encl_mm_add(encl, vma->vm_mm);
+		if (IS_ERR(encl_mm))
+			goto error;
+	}
+
+	kref_get(&encl->refcount);
+	return;
+
+error:
+	vma->vm_private_data = NULL;
+}
+
+static void sgx_vma_close(struct vm_area_struct *vma)
+{
+	struct sgx_encl *encl = vma->vm_private_data;
+	struct sgx_encl_mm *encl_mm;
+
+	if (!encl)
+		return;
+
+	encl_mm = sgx_encl_get_mm(encl, vma->vm_mm);
+	if (encl_mm) {
+		kref_put(&encl_mm->refcount, sgx_encl_mm_release);
+
+		/* Release kref for the VMA. */
+		kref_put(&encl_mm->refcount, sgx_encl_mm_release);
+	}
+
+	kref_put(&encl->refcount, sgx_encl_release);
+}
+
+static unsigned int sgx_vma_fault(struct vm_fault *vmf)
+{
+	unsigned long addr = (unsigned long)vmf->address;
+	struct vm_area_struct *vma = vmf->vma;
+	struct sgx_encl *encl = vma->vm_private_data;
+	struct sgx_encl_page *entry;
+	int ret = VM_FAULT_NOPAGE;
+	unsigned long pfn;
+
+	if (!encl)
+		return VM_FAULT_SIGBUS;
+
+	mutex_lock(&encl->lock);
+
+	entry = sgx_encl_load_page(encl, addr);
+	if (IS_ERR(entry)) {
+		if (unlikely(PTR_ERR(entry) != -EBUSY))
+			ret = VM_FAULT_SIGBUS;
+
+		goto out;
+	}
+
+	if (!follow_pfn(vma, addr, &pfn))
+		goto out;
+
+	ret = vmf_insert_pfn(vma, addr, PFN_DOWN(entry->epc_page->desc));
+	if (ret != VM_FAULT_NOPAGE) {
+		ret = VM_FAULT_SIGBUS;
+		goto out;
+	}
+
+out:
+	mutex_unlock(&encl->lock);
+	return ret;
+}
+
+const struct vm_operations_struct sgx_vm_ops = {
+	.close = sgx_vma_close,
+	.open = sgx_vma_open,
+	.fault = sgx_vma_fault,
+};
+EXPORT_SYMBOL_GPL(sgx_vm_ops);
+
+/**
+ * sgx_encl_find - find an enclave
+ * @mm:		mm struct of the current process
+ * @addr:	address in the ELRANGE
+ * @vma:	the resulting VMA
+ *
+ * Find an enclave identified by the given address. Give back a VMA that is
+ * part of the enclave and located in that address. The VMA is given back if it
+ * is a proper enclave VMA even if an &sgx_encl instance does not exist yet
+ * (enclave creation has not been performed).
+ *
+ * Return:
+ *   0 on success,
+ *   -EINVAL if an enclave was not found,
+ *   -ENOENT if the enclave has not been created yet
+ */
+int sgx_encl_find(struct mm_struct *mm, unsigned long addr,
+		  struct vm_area_struct **vma)
+{
+	struct vm_area_struct *result;
+	struct sgx_encl *encl;
+
+	result = find_vma(mm, addr);
+	if (!result || result->vm_ops != &sgx_vm_ops || addr < result->vm_start)
+		return -EINVAL;
+
+	encl = result->vm_private_data;
+	*vma = result;
+
+	return encl ? 0 : -ENOENT;
+}
+EXPORT_SYMBOL_GPL(sgx_encl_find);
+
+/**
+ * sgx_encl_destroy() - destroy enclave resources
+ * @encl:	an &sgx_encl instance
+ */
+void sgx_encl_destroy(struct sgx_encl *encl)
+{
+	struct sgx_encl_page *entry;
+	struct radix_tree_iter iter;
+	void **slot;
+
+	encl->flags |= SGX_ENCL_DEAD;
+
+	radix_tree_for_each_slot(slot, &encl->page_tree, &iter, 0) {
+		entry = *slot;
+		if (entry->epc_page) {
+			if (!__sgx_free_page(entry->epc_page)) {
+				encl->secs_child_cnt--;
+				entry->epc_page = NULL;
+
+			}
+
+			radix_tree_delete(&entry->encl->page_tree,
+					  PFN_DOWN(entry->desc));
+		}
+	}
+
+	if (!encl->secs_child_cnt && encl->secs.epc_page) {
+		sgx_free_page(encl->secs.epc_page);
+		encl->secs.epc_page = NULL;
+	}
+}
+EXPORT_SYMBOL_GPL(sgx_encl_destroy);
+
+/**
+ * sgx_encl_release - Destroy an enclave instance
+ * @kref:	address of a kref inside &sgx_encl
+ *
+ * Used together with kref_put(). Frees all the resources associated with the
+ * enclave and the instance itself.
+ */
+void sgx_encl_release(struct kref *ref)
+{
+	struct sgx_encl *encl = container_of(ref, struct sgx_encl, refcount);
+	struct sgx_encl_mm *encl_mm;
+
+	if (encl->pm_notifier.notifier_call)
+		unregister_pm_notifier(&encl->pm_notifier);
+
+	sgx_encl_destroy(encl);
+
+	if (encl->backing)
+		fput(encl->backing);
+
+	WARN(!list_empty(&encl->mm_list), "sgx: mm_list non-empty");
+
+	kfree(encl);
+}
+EXPORT_SYMBOL_GPL(sgx_encl_release);
+
+/**
+ * sgx_encl_get_index() - Convert a page descriptor to a page index
+ * @encl:	an enclave
+ * @page:	an enclave page
+ *
+ * Given an enclave page descriptor, convert it to a page index used to access
+ * backing storage. The backing page for SECS is located after the enclave
+ * pages.
+ */
+pgoff_t sgx_encl_get_index(struct sgx_encl *encl, struct sgx_encl_page *page)
+{
+	if (!PFN_DOWN(page->desc))
+		return PFN_DOWN(encl->size);
+
+	return PFN_DOWN(page->desc - encl->base);
+}
+EXPORT_SYMBOL_GPL(sgx_encl_get_index);
+
+/**
+ * sgx_encl_encl_get_backing_page() - Pin the backing page
+ * @encl:	an enclave
+ * @index:	page index
+ *
+ * Return: the pinned backing page
+ */
+struct page *sgx_encl_get_backing_page(struct sgx_encl *encl, pgoff_t index)
+{
+	struct inode *inode = encl->backing->f_path.dentry->d_inode;
+	struct address_space *mapping = inode->i_mapping;
+	gfp_t gfpmask = mapping_gfp_mask(mapping);
+
+	return shmem_read_mapping_page_gfp(mapping, index, gfpmask);
+}
+EXPORT_SYMBOL_GPL(sgx_encl_get_backing_page);
+
+/**
+ * sgx_encl_next_mm() - Iterate to the next mm
+ * @encl:	an enclave
+ * @mm:		an mm list entry
+ * @iter:	iterator status
+ *
+ * Return: the enclave mm or NULL
+ */
+struct sgx_encl_mm *sgx_encl_next_mm(struct sgx_encl *encl,
+				     struct sgx_encl_mm *encl_mm, int *iter)
+{
+	struct list_head *entry;
+
+	WARN(!encl, "%s: encl is NULL", __func__);
+	WARN(!iter, "%s: iter is NULL", __func__);
+
+	spin_lock(&encl->mm_lock);
+
+	entry = encl_mm ? encl_mm->list.next : encl->mm_list.next;
+	WARN(!entry, "%s: entry is NULL", __func__);
+
+	if (entry == &encl->mm_list) {
+		spin_unlock(&encl->mm_lock);
+		*iter = SGX_ENCL_MM_ITER_DONE;
+		return NULL;
+	}
+
+	encl_mm = list_entry(entry, struct sgx_encl_mm, list);
+
+	if (!kref_get_unless_zero(&encl_mm->refcount)) {
+		spin_unlock(&encl->mm_lock);
+		*iter = SGX_ENCL_MM_ITER_RESTART;
+		return NULL;
+	}
+
+	spin_unlock(&encl->mm_lock);
+	*iter = SGX_ENCL_MM_ITER_NEXT;
+	return encl_mm;
+}
diff --git a/arch/x86/kernel/cpu/sgx/encl.h b/arch/x86/kernel/cpu/sgx/encl.h
new file mode 100644
index 000000000000..1f96991839ad
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/encl.h
@@ -0,0 +1,98 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/**
+ * Copyright(c) 2016-19 Intel Corporation.
+ */
+#ifndef _X86_ENCL_H
+#define _X86_ENCL_H
+
+#include <linux/cpumask.h>
+#include <linux/kref.h>
+#include <linux/list.h>
+#include <linux/mm_types.h>
+#include <linux/mutex.h>
+#include <linux/notifier.h>
+#include <linux/radix-tree.h>
+#include <linux/workqueue.h>
+
+/**
+ * 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_ADDR_MASK:		Holds the virtual address of the page.
+ *
+ * The page address for SECS is zero and is used by the subsystem to recognize
+ * the SECS page.
+ */
+enum sgx_encl_page_desc {
+	SGX_ENCL_PAGE_TCS		= BIT(0),
+	/* Bits 11:3 are available when the page is not swapped. */
+	SGX_ENCL_PAGE_ADDR_MASK		= PAGE_MASK,
+};
+
+#define SGX_ENCL_PAGE_ADDR(encl_page) \
+	((encl_page)->desc & SGX_ENCL_PAGE_ADDR_MASK)
+#define SGX_ENCL_PAGE_VA_OFFSET(encl_page) \
+	((encl_page)->desc & SGX_ENCL_PAGE_VA_OFFSET_MASK)
+
+struct sgx_encl_page {
+	unsigned long desc;
+	struct sgx_epc_page *epc_page;
+	struct sgx_encl *encl;
+};
+
+enum sgx_encl_flags {
+	SGX_ENCL_CREATED	= BIT(0),
+	SGX_ENCL_INITIALIZED	= BIT(1),
+	SGX_ENCL_DEBUG		= BIT(2),
+	SGX_ENCL_SUSPEND	= BIT(3),
+	SGX_ENCL_DEAD		= BIT(4),
+};
+
+struct sgx_encl_mm {
+	struct sgx_encl *encl;
+	struct mm_struct *mm;
+	struct kref refcount;
+	struct list_head list;
+};
+
+struct sgx_encl {
+	unsigned int flags;
+	u64 secs_attributes;
+	u64 allowed_attributes;
+	unsigned int page_cnt;
+	unsigned int secs_child_cnt;
+	struct mutex lock;
+	struct list_head mm_list;
+	spinlock_t mm_lock;
+	struct file *backing;
+	struct kref refcount;
+	unsigned long base;
+	unsigned long size;
+	unsigned long ssaframesize;
+	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;
+};
+
+extern const struct vm_operations_struct sgx_vm_ops;
+
+enum sgx_encl_mm_iter {
+	SGX_ENCL_MM_ITER_DONE		= 0,
+	SGX_ENCL_MM_ITER_NEXT		= 1,
+	SGX_ENCL_MM_ITER_RESTART	= 2,
+};
+
+int sgx_encl_find(struct mm_struct *mm, unsigned long addr,
+		  struct vm_area_struct **vma);
+void sgx_encl_destroy(struct sgx_encl *encl);
+void sgx_encl_release(struct kref *ref);
+pgoff_t sgx_encl_get_index(struct sgx_encl *encl, struct sgx_encl_page *page);
+struct page *sgx_encl_get_backing_page(struct sgx_encl *encl, pgoff_t index);
+struct sgx_encl_mm *sgx_encl_next_mm(struct sgx_encl *encl,
+				     struct sgx_encl_mm *encl_mm, int *iter);
+struct sgx_encl_mm *sgx_encl_mm_add(struct sgx_encl *encl,
+				    struct mm_struct *mm);
+void sgx_encl_mm_release(struct kref *ref);
+
+#endif /* _X86_ENCL_H */
diff --git a/arch/x86/kernel/cpu/sgx/encls.c b/arch/x86/kernel/cpu/sgx/encls.c
index 5045f1365e07..698cc526bfbf 100644
--- a/arch/x86/kernel/cpu/sgx/encls.c
+++ b/arch/x86/kernel/cpu/sgx/encls.c
@@ -19,3 +19,4 @@ bool encls_failed(int ret)
 
 	return encls_faulted(ret) && ENCLS_TRAPNR(ret) != epcm_trapnr;
 }
+EXPORT_SYMBOL_GPL(encls_failed);
diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
index d3ed742e90fe..d911a1038712 100644
--- a/arch/x86/kernel/cpu/sgx/main.c
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -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;
 }
 
diff --git a/arch/x86/kernel/cpu/sgx/sgx.h b/arch/x86/kernel/cpu/sgx/sgx.h
index 41d4130c33a2..62a574ed230a 100644
--- a/arch/x86/kernel/cpu/sgx/sgx.h
+++ b/arch/x86/kernel/cpu/sgx/sgx.h
@@ -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
-- 
2.19.1


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

* [PATCH v20 16/28] x86/sgx: Add provisioning
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (14 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-19  3:06   ` Huang, Kai
  2019-04-24  1:34   ` Jethro Beekman
  2019-04-17 10:39 ` [PATCH v20 17/28] x86/sgx: Add swapping code to the core and SGX driver Jarkko Sakkinen
                   ` (17 subsequent siblings)
  33 siblings, 2 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen, James Morris, Serge E . Hallyn,
	linux-security-module

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #1: Type: text/plain; charset=y, Size: 6250 bytes --]

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);

Cc: James Morris <jmorris@namei.org>
Cc: Serge E. Hallyn <serge@hallyn.com>
Cc: linux-security-module@vger.kernel.org
Suggested-by: Andy Lutomirski <luto@kernel.org>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 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(-)

diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 7bf627ac4958..3b80acde8671 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -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 */
diff --git a/arch/x86/kernel/cpu/sgx/driver/driver.h b/arch/x86/kernel/cpu/sgx/driver/driver.h
index 507712eb0a68..153b4a48aa6f 100644
--- a/arch/x86/kernel/cpu/sgx/driver/driver.h
+++ b/arch/x86/kernel/cpu/sgx/driver/driver.h
@@ -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);
 
diff --git a/arch/x86/kernel/cpu/sgx/driver/ioctl.c b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
index f88226518b21..65c9fb7b2a95 100644
--- a/arch/x86/kernel/cpu/sgx/driver/ioctl.c
+++ b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
@@ -714,6 +714,54 @@ static long sgx_ioc_enclave_init(struct file *filep, unsigned int cmd,
 	return ret;
 }
 
+/**
+ * sgx_ioc_enclave_set_attribute - handler for %SGX_IOC_ENCLAVE_SET_ATTRIBUTE
+ * @filep:	open file to /dev/sgx
+ * @cmd:	the command value
+ * @arg:	pointer to a struct sgx_enclave_set_attribute instance
+ *
+ * Mark the enclave as being allowed to access a restricted attribute bit.
+ * The requested attribute is specified via the attribute_fd field in the
+ * provided struct sgx_enclave_set_attribute.  The attribute_fd must be a
+ * handle to an SGX attribute file, e.g. “/dev/sgx/provision".
+ *
+ * Failure to explicitly request access to a restricted attribute will cause
+ * sgx_ioc_enclave_init() to fail.  Currently, the only restricted attribute
+ * is access to the PROVISION_KEY.
+ *
+ * Note, access to the EINITTOKEN_KEY is disallowed entirely.
+ *
+ * Return: 0 on success, -errno otherwise
+ */
+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 file *attribute_file;
+	struct sgx_encl *encl;
+	int ret;
+
+	attribute_file = fget(params->attribute_fd);
+	if (!attribute_file->f_op)
+		return -EINVAL;
+
+	if (attribute_file->f_op != &sgx_provision_fops) {
+		ret = -EINVAL;
+		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);
+	return ret;
+}
+
 typedef long (*sgx_ioc_t)(struct file *filep, unsigned int cmd,
 			  unsigned long arg);
 
@@ -733,6 +781,9 @@ long sgx_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
 	case SGX_IOC_ENCLAVE_INIT:
 		handler = sgx_ioc_enclave_init;
 		break;
+	case SGX_IOC_ENCLAVE_SET_ATTRIBUTE:
+		handler = sgx_ioc_enclave_set_attribute;
+		break;
 	default:
 		return -ENOIOCTLCMD;
 	}
diff --git a/arch/x86/kernel/cpu/sgx/driver/main.c b/arch/x86/kernel/cpu/sgx/driver/main.c
index d371add399cd..8b79c4a60037 100644
--- a/arch/x86/kernel/cpu/sgx/driver/main.c
+++ b/arch/x86/kernel/cpu/sgx/driver/main.c
@@ -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;
-- 
2.19.1


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

* [PATCH v20 17/28] x86/sgx: Add swapping code to the core and SGX driver
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (15 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 16/28] x86/sgx: Add provisioning Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 18/28] x86/sgx: ptrace() support for the " Jarkko Sakkinen
                   ` (16 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Cc: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Serge Ayoun <serge.ayoun@intel.com>
Signed-off-by: Serge Ayoun <serge.ayoun@intel.com>
Co-developed-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
Signed-off-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
---
 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(-)

diff --git a/arch/x86/kernel/cpu/sgx/driver/ioctl.c b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
index 65c9fb7b2a95..3a01c3dd579d 100644
--- a/arch/x86/kernel/cpu/sgx/driver/ioctl.c
+++ b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
@@ -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);
diff --git a/arch/x86/kernel/cpu/sgx/driver/main.c b/arch/x86/kernel/cpu/sgx/driver/main.c
index 8b79c4a60037..afe844aa81d6 100644
--- a/arch/x86/kernel/cpu/sgx/driver/main.c
+++ b/arch/x86/kernel/cpu/sgx/driver/main.c
@@ -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);
diff --git a/arch/x86/kernel/cpu/sgx/encl.c b/arch/x86/kernel/cpu/sgx/encl.c
index cc3bd4a4d82b..16e8524687c1 100644
--- a/arch/x86/kernel/cpu/sgx/encl.c
+++ b/arch/x86/kernel/cpu/sgx/encl.c
@@ -7,11 +7,91 @@
 #include <linux/sched/mm.h>
 #include "arch.h"
 #include "encl.h"
+#include "encls.h"
 #include "sgx.h"
 
+static int __sgx_encl_eldu(struct sgx_encl_page *encl_page,
+			   struct sgx_epc_page *epc_page)
+{
+	unsigned long addr = SGX_ENCL_PAGE_ADDR(encl_page);
+	unsigned long va_offset = SGX_ENCL_PAGE_VA_OFFSET(encl_page);
+	struct sgx_encl *encl = encl_page->encl;
+	pgoff_t page_index = sgx_encl_get_index(encl, encl_page);
+	pgoff_t pcmd_index = sgx_pcmd_index(encl, page_index);
+	unsigned long pcmd_offset = sgx_pcmd_offset(page_index);
+	struct sgx_pageinfo pginfo;
+	struct page *backing;
+	struct page *pcmd;
+	int ret;
+
+	backing = sgx_encl_get_backing_page(encl, page_index);
+	if (IS_ERR(backing)) {
+		ret = PTR_ERR(backing);
+		goto err_backing;
+	}
+
+	pcmd = sgx_encl_get_backing_page(encl, pcmd_index);
+	if (IS_ERR(pcmd)) {
+		ret = PTR_ERR(pcmd);
+		goto err_pcmd;
+	}
+
+	pginfo.addr = addr;
+	pginfo.contents = (unsigned long)kmap_atomic(backing);
+	pginfo.metadata = (unsigned long)kmap_atomic(pcmd) + pcmd_offset;
+	pginfo.secs = addr ? (unsigned long)sgx_epc_addr(encl->secs.epc_page) :
+		      0;
+
+	ret = __eldu(&pginfo, sgx_epc_addr(epc_page),
+		     sgx_epc_addr(encl_page->va_page->epc_page) + va_offset);
+	if (ret) {
+		if (encls_failed(ret) || encls_returned_code(ret))
+			ENCLS_WARN(ret, "ELDU");
+
+		ret = -EFAULT;
+	}
+
+	kunmap_atomic((void *)(unsigned long)(pginfo.metadata - pcmd_offset));
+	kunmap_atomic((void *)(unsigned long)pginfo.contents);
+
+	put_page(pcmd);
+
+err_pcmd:
+	put_page(backing);
+
+err_backing:
+	return ret;
+}
+
+static struct sgx_epc_page *sgx_encl_eldu(struct sgx_encl_page *encl_page)
+{
+	unsigned long va_offset = SGX_ENCL_PAGE_VA_OFFSET(encl_page);
+	struct sgx_encl *encl = encl_page->encl;
+	struct sgx_epc_page *epc_page;
+	int ret;
+
+	epc_page = sgx_alloc_page(encl_page, false);
+	if (IS_ERR(epc_page))
+		return epc_page;
+
+	ret = __sgx_encl_eldu(encl_page, epc_page);
+	if (ret) {
+		sgx_free_page(epc_page);
+		return ERR_PTR(ret);
+	}
+
+	sgx_free_va_slot(encl_page->va_page, va_offset);
+	list_move(&encl_page->va_page->list, &encl->va_pages);
+	encl_page->desc &= ~SGX_ENCL_PAGE_VA_OFFSET_MASK;
+	encl_page->epc_page = epc_page;
+
+	return epc_page;
+}
+
 static struct sgx_encl_page *sgx_encl_load_page(struct sgx_encl *encl,
 						unsigned long addr)
 {
+	struct sgx_epc_page *epc_page;
 	struct sgx_encl_page *entry;
 
 	/* If process was forked, VMA is still there but vm_private_data is set
@@ -29,10 +109,27 @@ static struct sgx_encl_page *sgx_encl_load_page(struct sgx_encl *encl,
 		return ERR_PTR(-EFAULT);
 
 	/* Page is already resident in the EPC. */
-	if (entry->epc_page)
+	if (entry->epc_page) {
+		if (entry->desc & SGX_ENCL_PAGE_RECLAIMED)
+			return ERR_PTR(-EBUSY);
+
 		return entry;
+	}
+
+	if (!(encl->secs.epc_page)) {
+		epc_page = sgx_encl_eldu(&encl->secs);
+		if (IS_ERR(epc_page))
+			return ERR_CAST(epc_page);
+	}
+
+	epc_page = entry->epc_page ? entry->epc_page : sgx_encl_eldu(entry);
+	if (IS_ERR(epc_page))
+		return ERR_CAST(epc_page);
 
-	return ERR_PTR(-EFAULT);
+	encl->secs_child_cnt++;
+	sgx_mark_page_reclaimable(entry->epc_page);
+
+	return entry;
 }
 
 struct sgx_encl_mm *sgx_encl_mm_add(struct sgx_encl *encl,
@@ -169,6 +266,8 @@ static unsigned int sgx_vma_fault(struct vm_fault *vmf)
 		goto out;
 	}
 
+	sgx_encl_test_and_clear_young(vma->vm_mm, entry);
+
 out:
 	mutex_unlock(&encl->lock);
 	return ret;
@@ -220,6 +319,7 @@ EXPORT_SYMBOL_GPL(sgx_encl_find);
  */
 void sgx_encl_destroy(struct sgx_encl *encl)
 {
+	struct sgx_va_page *va_page;
 	struct sgx_encl_page *entry;
 	struct radix_tree_iter iter;
 	void **slot;
@@ -244,6 +344,15 @@ void sgx_encl_destroy(struct sgx_encl *encl)
 		sgx_free_page(encl->secs.epc_page);
 		encl->secs.epc_page = NULL;
 	}
+
+
+	while (!list_empty(&encl->va_pages)) {
+		va_page = list_first_entry(&encl->va_pages, struct sgx_va_page,
+					   list);
+		list_del(&va_page->list);
+		sgx_free_page(va_page->epc_page);
+		kfree(va_page);
+	}
 }
 EXPORT_SYMBOL_GPL(sgx_encl_destroy);
 
@@ -347,3 +456,157 @@ struct sgx_encl_mm *sgx_encl_next_mm(struct sgx_encl *encl,
 	*iter = SGX_ENCL_MM_ITER_NEXT;
 	return encl_mm;
 }
+
+static int sgx_encl_test_and_clear_young_cb(pte_t *ptep, pgtable_t token,
+					    unsigned long addr, void *data)
+{
+	pte_t pte;
+	int ret;
+
+	ret = pte_young(*ptep);
+	if (ret) {
+		pte = pte_mkold(*ptep);
+		set_pte_at((struct mm_struct *)data, addr, ptep, pte);
+	}
+
+	return ret;
+}
+
+/**
+ * sgx_encl_test_and_clear_young() - Test and reset the accessed bit
+ * @mm:		mm_struct that is checked
+ * @page:	enclave page to be tested for recent access
+ *
+ * Checks the Access (A) bit from the PTE corresponding to the enclave page and
+ * clears it.
+ *
+ * Return: 1 if the page has been recently accessed and 0 if not.
+ */
+int sgx_encl_test_and_clear_young(struct mm_struct *mm,
+				  struct sgx_encl_page *page)
+{
+	unsigned long addr = SGX_ENCL_PAGE_ADDR(page);
+	struct sgx_encl *encl = page->encl;
+	struct vm_area_struct *vma;
+	int ret;
+
+	ret = sgx_encl_find(mm, addr, &vma);
+	if (ret)
+		return 0;
+
+	if (encl != vma->vm_private_data)
+		return 0;
+
+	ret = apply_to_page_range(vma->vm_mm, addr, PAGE_SIZE,
+				  sgx_encl_test_and_clear_young_cb, vma->vm_mm);
+	if (ret < 0)
+		return 0;
+
+	return ret;
+}
+
+/**
+ * sgx_encl_reserve_page() - Reserve an enclave page
+ * @encl:	an enclave
+ * @addr:	a page address
+ *
+ * Load an enclave page and lock the enclave so that the page can be used by
+ * EDBG* and EMOD*.
+ *
+ * Return:
+ *   an enclave page on success
+ *   -EFAULT	if the load fails
+ */
+struct sgx_encl_page *sgx_encl_reserve_page(struct sgx_encl *encl,
+					    unsigned long addr)
+{
+	struct sgx_encl_page *entry;
+
+	for ( ; ; ) {
+		mutex_lock(&encl->lock);
+
+		entry = sgx_encl_load_page(encl, addr);
+		if (PTR_ERR(entry) != -EBUSY)
+			break;
+
+		mutex_unlock(&encl->lock);
+	}
+
+	if (IS_ERR(entry))
+		mutex_unlock(&encl->lock);
+
+	return entry;
+}
+EXPORT_SYMBOL(sgx_encl_reserve_page);
+
+/**
+ * sgx_alloc_page - allocate a VA page
+ *
+ * Allocates an &sgx_epc_page instance and converts it to a VA page.
+ *
+ * Return:
+ *   a &struct sgx_va_page instance,
+ *   -errno otherwise
+ */
+struct sgx_epc_page *sgx_alloc_va_page(void)
+{
+	struct sgx_epc_page *epc_page;
+	int ret;
+
+	epc_page = sgx_alloc_page(NULL, true);
+	if (IS_ERR(epc_page))
+		return ERR_CAST(epc_page);
+
+	ret = __epa(sgx_epc_addr(epc_page));
+	if (ret) {
+		WARN_ONCE(1, "sgx: EPA returned %d (0x%x)", ret, ret);
+		sgx_free_page(epc_page);
+		return ERR_PTR(-EFAULT);
+	}
+
+	return epc_page;
+}
+EXPORT_SYMBOL_GPL(sgx_alloc_va_page);
+
+/**
+ * sgx_alloc_va_slot - allocate a VA slot
+ * @va_page:	a &struct sgx_va_page instance
+ *
+ * Allocates a slot from a &struct sgx_va_page instance.
+ *
+ * Return: offset of the slot inside the VA page
+ */
+unsigned int sgx_alloc_va_slot(struct sgx_va_page *va_page)
+{
+	int slot = find_first_zero_bit(va_page->slots, SGX_VA_SLOT_COUNT);
+
+	if (slot < SGX_VA_SLOT_COUNT)
+		set_bit(slot, va_page->slots);
+
+	return slot << 3;
+}
+
+/**
+ * sgx_free_va_slot - free a VA slot
+ * @va_page:	a &struct sgx_va_page instance
+ * @offset:	offset of the slot inside the VA page
+ *
+ * Frees a slot from a &struct sgx_va_page instance.
+ */
+void sgx_free_va_slot(struct sgx_va_page *va_page, unsigned int offset)
+{
+	clear_bit(offset >> 3, va_page->slots);
+}
+
+/**
+ * sgx_va_page_full - is the VA page full?
+ * @va_page:	a &struct sgx_va_page instance
+ *
+ * Return: true if all slots have been taken
+ */
+bool sgx_va_page_full(struct sgx_va_page *va_page)
+{
+	int slot = find_first_zero_bit(va_page->slots, SGX_VA_SLOT_COUNT);
+
+	return slot == SGX_VA_SLOT_COUNT;
+}
diff --git a/arch/x86/kernel/cpu/sgx/encl.h b/arch/x86/kernel/cpu/sgx/encl.h
index 1f96991839ad..c557f0374d74 100644
--- a/arch/x86/kernel/cpu/sgx/encl.h
+++ b/arch/x86/kernel/cpu/sgx/encl.h
@@ -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 */
diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
index d911a1038712..07adb35c260b 100644
--- a/arch/x86/kernel/cpu/sgx/main.c
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -22,7 +22,7 @@ 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(
+static struct sgx_epc_page *sgx_section_try_take_page(
 	struct sgx_epc_section *section)
 {
 	struct sgx_epc_page *page;
@@ -30,23 +30,14 @@ static struct sgx_epc_page *sgx_section_get_page(
 	if (!section->free_cnt)
 		return NULL;
 
-	page = list_first_entry(&section->page_list,
-				struct sgx_epc_page, list);
+	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)
+static struct sgx_epc_page *sgx_try_alloc_page(void *owner)
 {
 	struct sgx_epc_section *section;
 	struct sgx_epc_page *page;
@@ -55,14 +46,61 @@ struct sgx_epc_page *sgx_alloc_page(void)
 	for (i = 0; i < sgx_nr_epc_sections; i++) {
 		section = &sgx_epc_sections[i];
 		spin_lock(&section->lock);
-		page = sgx_section_get_page(section);
+		page = sgx_section_try_take_page(section);
 		spin_unlock(&section->lock);
 
-		if (page)
+		if (page) {
+			page->owner = owner;
 			return page;
+		}
 	}
 
-	return ERR_PTR(-ENOMEM);
+	return NULL;
+}
+
+/**
+ * sgx_alloc_page - Allocate an EPC page
+ * @owner:	the owner of the EPC page
+ * @reclaim:	reclaim pages if necessary
+ *
+ * Try to grab a page from the free EPC page list. If there is a free page
+ * available, it is returned to the caller. The @reclaim parameter hints
+ * the EPC memory manager to swap pages when required.
+ *
+ * Return:
+ *   a pointer to a &struct sgx_epc_page instance,
+ *   -errno on error
+ */
+struct sgx_epc_page *sgx_alloc_page(void *owner, bool reclaim)
+{
+	struct sgx_epc_page *entry;
+
+	for ( ; ; ) {
+		entry = sgx_try_alloc_page(owner);
+		if (entry)
+			break;
+
+		if (list_empty(&sgx_active_page_list))
+			return ERR_PTR(-ENOMEM);
+
+		if (!reclaim) {
+			entry = ERR_PTR(-EBUSY);
+			break;
+		}
+
+		if (signal_pending(current)) {
+			entry = ERR_PTR(-ERESTARTSYS);
+			break;
+		}
+
+		sgx_reclaim_pages();
+		schedule();
+	}
+
+	if (sgx_calc_free_cnt() < SGX_NR_LOW_PAGES)
+		wake_up(&ksgxswapd_waitq);
+
+	return entry;
 }
 EXPORT_SYMBOL_GPL(sgx_alloc_page);
 
@@ -70,10 +108,12 @@ 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.
+ * EREMOVE an EPC page and insert it back to the list of free pages.  If the
+ * page is reclaimable, delete it from the active page list.
  *
  * Return:
  *   0 on success
+ *   -EBUSY if the page cannot be removed from the active list
  *   SGX error code if EREMOVE fails
  */
 int __sgx_free_page(struct sgx_epc_page *page)
@@ -81,6 +121,23 @@ int __sgx_free_page(struct sgx_epc_page *page)
 	struct sgx_epc_section *section = sgx_epc_section(page);
 	int ret;
 
+	/*
+	 * Remove the page from the active list if necessary.  If the page
+	 * is actively being reclaimed, i.e. RECLAIMABLE is set but the
+	 * page isn't on the active list, return -EBUSY as we can't free
+	 * the page at this time since it is "owned" by the reclaimer.
+	 */
+	spin_lock(&sgx_active_page_list_lock);
+	if (page->desc & SGX_EPC_PAGE_RECLAIMABLE) {
+		if (list_empty(&page->list)) {
+			spin_unlock(&sgx_active_page_list_lock);
+			return -EBUSY;
+		}
+		list_del(&page->list);
+		page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
+	}
+	spin_unlock(&sgx_active_page_list_lock);
+
 	ret = __eremove(sgx_epc_addr(page));
 	if (ret)
 		return ret;
@@ -107,6 +164,7 @@ void sgx_free_page(struct sgx_epc_page *page)
 	int ret;
 
 	ret = __sgx_free_page(page);
+	WARN(ret < 0, "sgx: cannot free page, reclaim in-progress");
 	WARN(ret > 0, "sgx: EREMOVE returned %d (0x%x)", ret, ret);
 }
 EXPORT_SYMBOL_GPL(sgx_free_page);
diff --git a/arch/x86/kernel/cpu/sgx/reclaim.c b/arch/x86/kernel/cpu/sgx/reclaim.c
index 042769f03be9..219d31495838 100644
--- a/arch/x86/kernel/cpu/sgx/reclaim.c
+++ b/arch/x86/kernel/cpu/sgx/reclaim.c
@@ -9,9 +9,13 @@
 #include <linux/slab.h>
 #include <linux/sched/mm.h>
 #include <linux/sched/signal.h>
-#include "encls.h"
+#include "driver/driver.h"
 #include "sgx.h"
 
+LIST_HEAD(sgx_active_page_list);
+DEFINE_SPINLOCK(sgx_active_page_list_lock);
+DECLARE_WAIT_QUEUE_HEAD(ksgxswapd_waitq);
+
 static struct task_struct *ksgxswapd_tsk;
 
 static void sgx_sanitize_section(struct sgx_epc_section *section)
@@ -58,6 +62,12 @@ static void sgx_sanitize_section(struct sgx_epc_section *section)
 	}
 }
 
+static inline bool sgx_should_reclaim(void)
+{
+	return sgx_calc_free_cnt() < SGX_NR_HIGH_PAGES &&
+	       !list_empty(&sgx_active_page_list);
+}
+
 static int ksgxswapd(void *p)
 {
 	int i;
@@ -67,6 +77,19 @@ static int ksgxswapd(void *p)
 	for (i = 0; i < sgx_nr_epc_sections; i++)
 		sgx_sanitize_section(&sgx_epc_sections[i]);
 
+	while (!kthread_should_stop()) {
+		if (try_to_freeze())
+			continue;
+
+		wait_event_freezable(ksgxswapd_waitq, kthread_should_stop() ||
+						      sgx_should_reclaim());
+
+		if (sgx_should_reclaim())
+			sgx_reclaim_pages();
+
+		cond_resched();
+	}
+
 	return 0;
 }
 
@@ -82,3 +105,378 @@ int sgx_page_reclaimer_init(void)
 
 	return 0;
 }
+
+/**
+ * sgx_mark_page_reclaimable() - Mark a page as reclaimable
+ * @page:	EPC page
+ *
+ * Mark a page as reclaimable and add it to the active page list. Pages
+ * are automatically removed from the active list when freed.
+ */
+void sgx_mark_page_reclaimable(struct sgx_epc_page *page)
+{
+	spin_lock(&sgx_active_page_list_lock);
+	page->desc |= SGX_EPC_PAGE_RECLAIMABLE;
+	list_add_tail(&page->list, &sgx_active_page_list);
+	spin_unlock(&sgx_active_page_list_lock);
+}
+EXPORT_SYMBOL_GPL(sgx_mark_page_reclaimable);
+
+bool sgx_reclaimer_get(struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *encl_page = epc_page->owner;
+	struct sgx_encl *encl = encl_page->encl;
+
+	return kref_get_unless_zero(&encl->refcount) != 0;
+}
+
+void sgx_reclaimer_put(struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *encl_page = epc_page->owner;
+	struct sgx_encl *encl = encl_page->encl;
+
+	kref_put(&encl->refcount, sgx_encl_release);
+}
+
+static bool sgx_reclaimer_evict(struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *page = epc_page->owner;
+	struct sgx_encl *encl = page->encl;
+	struct sgx_encl_mm *encl_mm = NULL;
+	struct sgx_encl_mm *prev_mm = NULL;
+	bool ret = true;
+	int iter;
+
+	while (true) {
+		encl_mm = sgx_encl_next_mm(encl, prev_mm, &iter);
+		if (prev_mm)
+			kref_put(&prev_mm->refcount, sgx_encl_mm_release);
+		prev_mm = encl_mm;
+
+		if (iter == SGX_ENCL_MM_ITER_DONE)
+			break;
+
+		if (iter == SGX_ENCL_MM_ITER_RESTART)
+			continue;
+
+		if (!mmget_not_zero(encl_mm->mm))
+			continue;
+
+		down_read(&encl_mm->mm->mmap_sem);
+		ret = !sgx_encl_test_and_clear_young(encl_mm->mm, page);
+		up_read(&encl_mm->mm->mmap_sem);
+
+		mmput(encl_mm->mm);
+
+		if (!ret || (encl->flags & SGX_ENCL_DEAD)) {
+			kref_put(&encl_mm->refcount, sgx_encl_mm_release);
+			break;
+		}
+	}
+
+	/*
+	 * Do not reclaim this page if it has been recently accessed by any
+	 * mm_struct *and* if the enclave is still alive.  No need to take
+	 * the enclave's lock, worst case scenario reclaiming pages from a
+	 * dead enclave is delayed slightly.  A live enclave with a recently
+	 * accessed page is more common and avoiding lock contention in that
+	 * case is a boon to performance.
+	 */
+	if (!ret && !(encl->flags & SGX_ENCL_DEAD))
+		return false;
+
+	mutex_lock(&encl->lock);
+	page->desc |= SGX_ENCL_PAGE_RECLAIMED;
+	mutex_unlock(&encl->lock);
+
+	return true;
+}
+
+static void sgx_reclaimer_block(struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *page = epc_page->owner;
+	unsigned long addr = SGX_ENCL_PAGE_ADDR(page);
+	struct sgx_encl *encl = page->encl;
+	struct sgx_encl_mm *encl_mm = NULL;
+	struct sgx_encl_mm *prev_mm = NULL;
+	struct vm_area_struct *vma;
+	int iter;
+	int ret;
+
+	while (true) {
+		encl_mm = sgx_encl_next_mm(encl, prev_mm, &iter);
+		if (prev_mm)
+			kref_put(&prev_mm->refcount, sgx_encl_mm_release);
+		prev_mm = encl_mm;
+
+		if (iter == SGX_ENCL_MM_ITER_DONE)
+			break;
+
+		if (iter == SGX_ENCL_MM_ITER_RESTART)
+			continue;
+
+		if (!mmget_not_zero(encl_mm->mm))
+			continue;
+
+		down_read(&encl_mm->mm->mmap_sem);
+
+		ret = sgx_encl_find(encl_mm->mm, addr, &vma);
+		if (!ret && encl == vma->vm_private_data)
+			zap_vma_ptes(vma, addr, PAGE_SIZE);
+
+		up_read(&encl_mm->mm->mmap_sem);
+
+		mmput(encl_mm->mm);
+	}
+
+	mutex_lock(&encl->lock);
+
+	if (!(encl->flags & SGX_ENCL_DEAD)) {
+		ret = __eblock(sgx_epc_addr(epc_page));
+		if (encls_failed(ret))
+			ENCLS_WARN(ret, "EBLOCK");
+	}
+
+	mutex_unlock(&encl->lock);
+}
+
+static int __sgx_encl_ewb(struct sgx_encl *encl, struct sgx_epc_page *epc_page,
+			  struct sgx_va_page *va_page, unsigned int va_offset)
+{
+	struct sgx_encl_page *encl_page = epc_page->owner;
+	pgoff_t page_index = sgx_encl_get_index(encl, encl_page);
+	pgoff_t pcmd_index = sgx_pcmd_index(encl, page_index);
+	unsigned long pcmd_offset = sgx_pcmd_offset(page_index);
+	struct sgx_pageinfo pginfo;
+	struct page *backing;
+	struct page *pcmd;
+	int ret;
+
+	backing = sgx_encl_get_backing_page(encl, page_index);
+	if (IS_ERR(backing)) {
+		ret = PTR_ERR(backing);
+		goto err_backing;
+	}
+
+	pcmd = sgx_encl_get_backing_page(encl, pcmd_index);
+	if (IS_ERR(pcmd)) {
+		ret = PTR_ERR(pcmd);
+		goto err_pcmd;
+	}
+
+	pginfo.addr = 0;
+	pginfo.contents = (unsigned long)kmap_atomic(backing);
+	pginfo.metadata = (unsigned long)kmap_atomic(pcmd) + pcmd_offset;
+	pginfo.secs = 0;
+	ret = __ewb(&pginfo, sgx_epc_addr(epc_page),
+		    sgx_epc_addr(va_page->epc_page) + va_offset);
+	kunmap_atomic((void *)(unsigned long)(pginfo.metadata - pcmd_offset));
+	kunmap_atomic((void *)(unsigned long)pginfo.contents);
+
+	set_page_dirty(pcmd);
+	put_page(pcmd);
+	set_page_dirty(backing);
+
+err_pcmd:
+	put_page(backing);
+
+err_backing:
+	return ret;
+}
+
+static void sgx_ipi_cb(void *info)
+{
+}
+
+static const cpumask_t *sgx_encl_ewb_cpumask(struct sgx_encl *encl)
+{
+	cpumask_t *cpumask = &encl->cpumask;
+	struct sgx_encl_mm *encl_mm = NULL;
+	struct sgx_encl_mm *prev_mm = NULL;
+	int iter;
+
+	cpumask_clear(cpumask);
+
+	while (true) {
+		encl_mm = sgx_encl_next_mm(encl, prev_mm, &iter);
+		if (prev_mm)
+			kref_put(&prev_mm->refcount, sgx_encl_mm_release);
+		prev_mm = encl_mm;
+
+		if (iter == SGX_ENCL_MM_ITER_DONE)
+			break;
+
+		if (iter == SGX_ENCL_MM_ITER_RESTART)
+			continue;
+
+		if (!mmget_not_zero(encl_mm->mm))
+			continue;
+
+		cpumask_or(cpumask, cpumask, mm_cpumask(encl_mm->mm));
+
+		mmput(encl_mm->mm);
+	}
+
+	return cpumask;
+}
+
+static void sgx_encl_ewb(struct sgx_epc_page *epc_page, bool do_free)
+{
+	struct sgx_encl_page *encl_page = epc_page->owner;
+	struct sgx_encl *encl = encl_page->encl;
+	struct sgx_va_page *va_page;
+	unsigned int va_offset;
+	int ret;
+
+	encl_page->desc &= ~SGX_ENCL_PAGE_RECLAIMED;
+
+	if (!(encl->flags & SGX_ENCL_DEAD)) {
+		va_page = list_first_entry(&encl->va_pages, struct sgx_va_page,
+					   list);
+		va_offset = sgx_alloc_va_slot(va_page);
+		if (sgx_va_page_full(va_page))
+			list_move_tail(&va_page->list, &encl->va_pages);
+
+		ret = __sgx_encl_ewb(encl, epc_page, va_page, va_offset);
+		if (ret == SGX_NOT_TRACKED) {
+			ret = __etrack(sgx_epc_addr(encl->secs.epc_page));
+			if (ret) {
+				if (encls_failed(ret) ||
+				    encls_returned_code(ret))
+					ENCLS_WARN(ret, "ETRACK");
+			}
+
+			ret = __sgx_encl_ewb(encl, epc_page, va_page,
+					     va_offset);
+			if (ret == SGX_NOT_TRACKED) {
+				/*
+				 * Slow path, send IPIs to kick cpus out of the
+				 * enclave.  Note, it's imperative that the cpu
+				 * mask is generated *after* ETRACK, else we'll
+				 * miss cpus that entered the enclave between
+				 * generating the mask and incrementing epoch.
+				 */
+				on_each_cpu_mask(sgx_encl_ewb_cpumask(encl),
+						 sgx_ipi_cb, NULL, 1);
+				ret = __sgx_encl_ewb(encl, epc_page, va_page,
+						     va_offset);
+			}
+		}
+
+		if (ret)
+			if (encls_failed(ret) || encls_returned_code(ret))
+				ENCLS_WARN(ret, "EWB");
+
+		encl_page->desc |= va_offset;
+		encl_page->va_page = va_page;
+	} else if (!do_free) {
+		ret = __eremove(sgx_epc_addr(epc_page));
+		WARN(ret, "EREMOVE returned %d\n", ret);
+	}
+
+	if (do_free)
+		sgx_free_page(epc_page);
+
+	encl_page->epc_page = NULL;
+}
+
+static void sgx_reclaimer_write(struct sgx_epc_page *epc_page)
+{
+	struct sgx_encl_page *encl_page = epc_page->owner;
+	struct sgx_encl *encl = encl_page->encl;
+
+	mutex_lock(&encl->lock);
+
+	sgx_encl_ewb(epc_page, false);
+	encl->secs_child_cnt--;
+	if (!encl->secs_child_cnt &&
+	    (encl->flags & (SGX_ENCL_DEAD | SGX_ENCL_INITIALIZED))) {
+		sgx_encl_ewb(encl->secs.epc_page, true);
+	}
+
+	mutex_unlock(&encl->lock);
+}
+
+/**
+ * sgx_reclaim_pages() - Reclaim EPC pages from the consumers
+ * Takes a fixed chunk of pages from the global list of consumed EPC pages and
+ * tries to swap them. Only the pages that are either being freed by the
+ * consumer or actively used are skipped.
+ */
+void sgx_reclaim_pages(void)
+{
+	struct sgx_epc_page *chunk[SGX_NR_TO_SCAN + 1];
+	struct sgx_epc_page *epc_page;
+	struct sgx_epc_section *section;
+	int i, j;
+
+	spin_lock(&sgx_active_page_list_lock);
+	for (i = 0, j = 0; i < SGX_NR_TO_SCAN; i++) {
+		if (list_empty(&sgx_active_page_list))
+			break;
+
+		epc_page = list_first_entry(&sgx_active_page_list,
+					    struct sgx_epc_page, list);
+		list_del_init(&epc_page->list);
+
+		if (sgx_reclaimer_get(epc_page))
+			chunk[j++] = epc_page;
+		else
+			/* The owner is freeing the page. No need to add the
+			 * page back to the list of reclaimable pages.
+			 */
+			epc_page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
+	}
+	spin_unlock(&sgx_active_page_list_lock);
+
+	for (i = 0; i < j; i++) {
+		epc_page = chunk[i];
+		if (sgx_reclaimer_evict(epc_page))
+			continue;
+
+		sgx_reclaimer_put(epc_page);
+
+		spin_lock(&sgx_active_page_list_lock);
+		list_add_tail(&epc_page->list, &sgx_active_page_list);
+		spin_unlock(&sgx_active_page_list_lock);
+
+		chunk[i] = NULL;
+	}
+
+	for (i = 0; i < j; i++) {
+		epc_page = chunk[i];
+		if (epc_page)
+			sgx_reclaimer_block(epc_page);
+	}
+
+	for (i = 0; i < j; i++) {
+		epc_page = chunk[i];
+		if (epc_page) {
+			sgx_reclaimer_write(epc_page);
+			sgx_reclaimer_put(epc_page);
+			epc_page->desc &= ~SGX_EPC_PAGE_RECLAIMABLE;
+
+			section = sgx_epc_section(epc_page);
+
+			spin_lock(&section->lock);
+			list_add_tail(&epc_page->list,
+				      &section->page_list);
+			section->free_cnt++;
+			spin_unlock(&section->lock);
+		}
+	}
+}
+
+unsigned long sgx_calc_free_cnt(void)
+{
+	struct sgx_epc_section *section;
+	unsigned long free_cnt = 0;
+	int i;
+
+	for (i = 0; i < sgx_nr_epc_sections; i++) {
+		section = &sgx_epc_sections[i];
+		free_cnt += section->free_cnt;
+	}
+
+	return free_cnt;
+}
diff --git a/arch/x86/kernel/cpu/sgx/sgx.h b/arch/x86/kernel/cpu/sgx/sgx.h
index 62a574ed230a..8a1dff1e5e8a 100644
--- a/arch/x86/kernel/cpu/sgx/sgx.h
+++ b/arch/x86/kernel/cpu/sgx/sgx.h
@@ -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,
-- 
2.19.1


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

* [PATCH v20 18/28] x86/sgx: ptrace() support for the SGX driver
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (16 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 17/28] x86/sgx: Add swapping code to the core and SGX driver Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 19/28] x86/vdso: Add support for exception fixup in vDSO functions Jarkko Sakkinen
                   ` (15 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 arch/x86/kernel/cpu/sgx/encl.c | 97 ++++++++++++++++++++++++++++++++++
 1 file changed, 97 insertions(+)

diff --git a/arch/x86/kernel/cpu/sgx/encl.c b/arch/x86/kernel/cpu/sgx/encl.c
index 16e8524687c1..7216bdf07bd0 100644
--- a/arch/x86/kernel/cpu/sgx/encl.c
+++ b/arch/x86/kernel/cpu/sgx/encl.c
@@ -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);
 
-- 
2.19.1


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

* [PATCH v20 19/28] x86/vdso: Add support for exception fixup in vDSO functions
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (17 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 18/28] x86/sgx: ptrace() support for the " Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 20/28] x86/fault: Add helper function to sanitize error code Jarkko Sakkinen
                   ` (14 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Andy Lutomirski, Jarkko Sakkinen, Dave Hansen

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

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.

Suggested-by: Andy Lutomirski <luto@amacapital.net>
Cc: Andy Lutomirski <luto@amacapital.net>
Cc: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Cc: Dave Hansen <dave.hansen@linux.intel.com>
Cc: Josh Triplett <josh@joshtriplett.org>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 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

diff --git a/arch/x86/entry/vdso/Makefile b/arch/x86/entry/vdso/Makefile
index 5bfe2243a08f..34bcf87d358c 100644
--- a/arch/x86/entry/vdso/Makefile
+++ b/arch/x86/entry/vdso/Makefile
@@ -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)
 
diff --git a/arch/x86/entry/vdso/extable.c b/arch/x86/entry/vdso/extable.c
new file mode 100644
index 000000000000..49284d560d36
--- /dev/null
+++ b/arch/x86/entry/vdso/extable.c
@@ -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;
+}
diff --git a/arch/x86/entry/vdso/extable.h b/arch/x86/entry/vdso/extable.h
new file mode 100644
index 000000000000..aafdac396948
--- /dev/null
+++ b/arch/x86/entry/vdso/extable.h
@@ -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 */
+
diff --git a/arch/x86/entry/vdso/vdso-layout.lds.S b/arch/x86/entry/vdso/vdso-layout.lds.S
index 93c6dc7812d0..8ef849064501 100644
--- a/arch/x86/entry/vdso/vdso-layout.lds.S
+++ b/arch/x86/entry/vdso/vdso-layout.lds.S
@@ -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.*)
diff --git a/arch/x86/entry/vdso/vdso2c.h b/arch/x86/entry/vdso/vdso2c.h
index fa847a620f40..eca2f808bec3 100644
--- a/arch/x86/entry/vdso/vdso2c.h
+++ b/arch/x86/entry/vdso/vdso2c.h
@@ -5,6 +5,41 @@
  * are built for 32-bit userspace.
  */
 
+static void BITSFUNC(copy)(FILE *outfile, const unsigned char *data, size_t len)
+{
+	size_t i;
+
+	for (i = 0; i < len; i++) {
+		if (i % 10 == 0)
+			fprintf(outfile, "\n\t");
+		fprintf(outfile, "0x%02X, ", (int)(data)[i]);
+	}
+}
+
+
+/*
+ * Extract a section from the input data into a standalone blob.  Used to
+ * capture kernel-only data that needs to persist indefinitely, e.g. the
+ * exception fixup tables, but only in the kernel, i.e. the section can
+ * be stripped from the final vDSO image.
+ */
+static void BITSFUNC(extract)(const unsigned char *data, size_t data_len,
+			      FILE *outfile, ELF(Shdr) *sec, const char *name)
+{
+	unsigned long offset;
+	size_t len;
+
+	offset = (unsigned long)GET_LE(&sec->sh_offset);
+	len = (size_t)GET_LE(&sec->sh_size);
+
+	if (offset + len > data_len)
+		fail("section to extract overruns input data");
+
+	fprintf(outfile, "static const unsigned char %s[%lu] = {", name, len);
+	BITSFUNC(copy)(outfile, data + offset, len);
+	fprintf(outfile, "\n};\n\n");
+}
+
 static void BITSFUNC(go)(void *raw_addr, size_t raw_len,
 			 void *stripped_addr, size_t stripped_len,
 			 FILE *outfile, const char *name)
@@ -14,9 +49,8 @@ static void BITSFUNC(go)(void *raw_addr, size_t raw_len,
 	unsigned long mapping_size;
 	ELF(Ehdr) *hdr = (ELF(Ehdr) *)raw_addr;
 	int i;
-	unsigned long j;
 	ELF(Shdr) *symtab_hdr = NULL, *strtab_hdr, *secstrings_hdr,
-		*alt_sec = NULL;
+		*alt_sec = NULL, *extable_sec = NULL;
 	ELF(Dyn) *dyn = 0, *dyn_end = 0;
 	const char *secstrings;
 	INT_BITS syms[NSYMS] = {};
@@ -78,6 +112,8 @@ static void BITSFUNC(go)(void *raw_addr, size_t raw_len,
 		if (!strcmp(secstrings + GET_LE(&sh->sh_name),
 			    ".altinstructions"))
 			alt_sec = sh;
+		if (!strcmp(secstrings + GET_LE(&sh->sh_name), "__ex_table"))
+			extable_sec = sh;
 	}
 
 	if (!symtab_hdr)
@@ -149,13 +185,11 @@ static void BITSFUNC(go)(void *raw_addr, size_t raw_len,
 	fprintf(outfile,
 		"static unsigned char raw_data[%lu] __ro_after_init __aligned(PAGE_SIZE) = {",
 		mapping_size);
-	for (j = 0; j < stripped_len; j++) {
-		if (j % 10 == 0)
-			fprintf(outfile, "\n\t");
-		fprintf(outfile, "0x%02X, ",
-			(int)((unsigned char *)stripped_addr)[j]);
-	}
+	BITSFUNC(copy)(outfile, stripped_addr, stripped_len);
 	fprintf(outfile, "\n};\n\n");
+	if (extable_sec)
+		BITSFUNC(extract)(raw_addr, raw_len, outfile,
+				  extable_sec, "extable");
 
 	fprintf(outfile, "const struct vdso_image %s = {\n", name);
 	fprintf(outfile, "\t.data = raw_data,\n");
@@ -166,6 +200,14 @@ static void BITSFUNC(go)(void *raw_addr, size_t raw_len,
 		fprintf(outfile, "\t.alt_len = %lu,\n",
 			(unsigned long)GET_LE(&alt_sec->sh_size));
 	}
+	if (extable_sec) {
+		fprintf(outfile, "\t.extable_base = %lu,\n",
+			(unsigned long)GET_LE(&extable_sec->sh_offset));
+		fprintf(outfile, "\t.extable_len = %lu,\n",
+			(unsigned long)GET_LE(&extable_sec->sh_size));
+		fprintf(outfile, "\t.extable = extable,\n");
+	}
+
 	for (i = 0; i < NSYMS; i++) {
 		if (required_syms[i].export && syms[i])
 			fprintf(outfile, "\t.sym_%s = %" PRIi64 ",\n",
diff --git a/arch/x86/include/asm/vdso.h b/arch/x86/include/asm/vdso.h
index 27566e57e87d..1c8a6a8f7b59 100644
--- a/arch/x86/include/asm/vdso.h
+++ b/arch/x86/include/asm/vdso.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 20/28] x86/fault: Add helper function to sanitize error code
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (18 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 19/28] x86/vdso: Add support for exception fixup in vDSO functions Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 21/28] x86/fault: Attempt to fixup unhandled #PF in vDSO before signaling Jarkko Sakkinen
                   ` (13 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes

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

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

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 arch/x86/mm/fault.c | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/arch/x86/mm/fault.c b/arch/x86/mm/fault.c
index 78e2807fbede..5babd515f616 100644
--- a/arch/x86/mm/fault.c
+++ b/arch/x86/mm/fault.c
@@ -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
-- 
2.19.1


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

* [PATCH v20 21/28] x86/fault: Attempt to fixup unhandled #PF in vDSO before signaling
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (19 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 20/28] x86/fault: Add helper function to sanitize error code Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions " Jarkko Sakkinen
                   ` (12 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Andy Lutomirski, Jarkko Sakkinen, Dave Hansen

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

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.

Suggested-by: Andy Lutomirski <luto@amacapital.net>
Cc: Andy Lutomirski <luto@amacapital.net>
Cc: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Cc: Dave Hansen <dave.hansen@linux.intel.com>
Cc: Josh Triplett <josh@joshtriplett.org>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 arch/x86/mm/fault.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/arch/x86/mm/fault.c b/arch/x86/mm/fault.c
index 5babd515f616..13be0c67379e 100644
--- a/arch/x86/mm/fault.c
+++ b/arch/x86/mm/fault.c
@@ -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
-- 
2.19.1


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

* [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (20 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 21/28] x86/fault: Attempt to fixup unhandled #PF in vDSO before signaling Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-06-25 15:43   ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 23/28] x86/vdso: Add __vdso_sgx_enter_enclave() to wrap SGX enclave transitions Jarkko Sakkinen
                   ` (11 subsequent siblings)
  33 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Andy Lutomirski, Jarkko Sakkinen, Dave Hansen

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

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.

Suggested-by: Andy Lutomirski <luto@amacapital.net>
Cc: Andy Lutomirski <luto@amacapital.net>
Cc: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Cc: Dave Hansen <dave.hansen@linux.intel.com>
Cc: Josh Triplett <josh@joshtriplett.org>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 arch/x86/kernel/traps.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/arch/x86/kernel/traps.c b/arch/x86/kernel/traps.c
index d26f9e9c3d83..02eda456c119 100644
--- a/arch/x86/kernel/traps.c
+++ b/arch/x86/kernel/traps.c
@@ -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);
 }
-- 
2.19.1


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

* [PATCH v20 23/28] x86/vdso: Add __vdso_sgx_enter_enclave() to wrap SGX enclave transitions
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (21 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions " Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 24/28] selftests/x86: Add a selftest for SGX Jarkko Sakkinen
                   ` (10 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Andy Lutomirski, Jarkko Sakkinen, Dave Hansen, Haitao Huang,
	Jethro Beekman, Dr . Greg Wettstein

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

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

Suggested-by: Andy Lutomirski <luto@amacapital.net>
Cc: Andy Lutomirski <luto@amacapital.net>
Cc: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Cc: Dave Hansen <dave.hansen@linux.intel.com>
Cc: Josh Triplett <josh@joshtriplett.org>
Cc: Haitao Huang <haitao.huang@linux.intel.com>
Cc: Jethro Beekman <jethro@fortanix.com>
Cc: Dr. Greg Wettstein <greg@enjellic.com>
Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 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

diff --git a/arch/x86/entry/vdso/Makefile b/arch/x86/entry/vdso/Makefile
index 34bcf87d358c..fb5b9960b192 100644
--- a/arch/x86/entry/vdso/Makefile
+++ b/arch/x86/entry/vdso/Makefile
@@ -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.
diff --git a/arch/x86/entry/vdso/vdso.lds.S b/arch/x86/entry/vdso/vdso.lds.S
index d3a2dce4cfa9..50952a995a6c 100644
--- a/arch/x86/entry/vdso/vdso.lds.S
+++ b/arch/x86/entry/vdso/vdso.lds.S
@@ -25,6 +25,7 @@ VERSION {
 		__vdso_getcpu;
 		time;
 		__vdso_time;
+		__vdso_sgx_enter_enclave;
 	local: *;
 	};
 }
diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
new file mode 100644
index 000000000000..fe0bf6671d6d
--- /dev/null
+++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
@@ -0,0 +1,101 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#include <linux/linkage.h>
+#include <asm/export.h>
+#include <asm/errno.h>
+
+#include "extable.h"
+
+#define EX_LEAF		0*8
+#define EX_TRAPNR	0*8+4
+#define EX_ERROR_CODE	0*8+6
+#define EX_ADDRESS	1*8
+
+.code64
+.section .text, "ax"
+
+#ifdef SGX_KERNEL_DOC
+/**
+ * __vdso_sgx_enter_enclave() - Enter an SGX enclave
+ *
+ * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
+ * @tcs:	**IN \%rbx** - TCS, must be non-NULL
+ * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
+ *
+ * Return:
+ *  **OUT \%eax** -
+ *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
+ *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
+ *
+ * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
+ * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
+ * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
+ * the return value passed via ``%eax``.  All registers except ``%rsp`` must
+ * be treated as volatile from the caller's perspective, including but not
+ * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
+ * being run **must** preserve the untrusted ``%rsp`` and stack.
+ */
+__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
+			 struct sgx_enclave_exception *ex_info)
+{
+	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
+		return -EINVAL;
+
+	if (!tcs)
+		return -EINVAL;
+
+	try {
+		ENCLU[leaf];
+	} catch (exception) {
+		if (e)
+			*e = exception;
+		return -EFAULT;
+	}
+
+	return 0;
+}
+#endif
+ENTRY(__vdso_sgx_enter_enclave)
+	/* EENTER <= leaf <= ERESUME */
+	cmp	$0x2, %eax
+	jb	bad_input
+
+	cmp	$0x3, %eax
+	ja	bad_input
+
+	/* TCS must be non-NULL */
+	test	%rbx, %rbx
+	je	bad_input
+
+	/* Save @exception_info */
+	push	%rcx
+
+	/* Load AEP for ENCLU */
+	lea	1f(%rip),  %rcx
+1:	enclu
+
+	add	$0x8, %rsp
+	xor	%eax, %eax
+	ret
+
+bad_input:
+	mov     $(-EINVAL), %rax
+	ret
+
+.pushsection .fixup, "ax"
+	/* Re-load @exception_info and fill it (if it's non-NULL) */
+2:	pop	%rcx
+	test    %rcx, %rcx
+	je      3f
+
+	mov	%eax, EX_LEAF(%rcx)
+	mov	%di,  EX_TRAPNR(%rcx)
+	mov	%si,  EX_ERROR_CODE(%rcx)
+	mov	%rdx, EX_ADDRESS(%rcx)
+3:	mov	$(-EFAULT), %rax
+	ret
+.popsection
+
+_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
+
+ENDPROC(__vdso_sgx_enter_enclave)
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 3b80acde8671..9ed690a38c70 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -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 */
-- 
2.19.1


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

* [PATCH v20 24/28] selftests/x86: Add a selftest for SGX
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (22 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 23/28] x86/vdso: Add __vdso_sgx_enter_enclave() to wrap SGX enclave transitions Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 25/28] x86/sgx: Update MAINTAINERS Jarkko Sakkinen
                   ` (9 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	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.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 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

diff --git a/tools/testing/selftests/x86/Makefile b/tools/testing/selftests/x86/Makefile
index 186520198de7..4fc9a42f56ea 100644
--- a/tools/testing/selftests/x86/Makefile
+++ b/tools/testing/selftests/x86/Makefile
@@ -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
diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
new file mode 100644
index 000000000000..1fd6f2708e81
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -0,0 +1,48 @@
+top_srcdir = ../../../../..
+
+include ../../lib.mk
+
+HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
+ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
+	       -fno-stack-protector -mrdrnd $(INCLUDES)
+
+TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
+all_64: $(TEST_CUSTOM_PROGS)
+
+$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
+		      $(OUTPUT)/encl_piggy.o
+	$(CC) $(HOST_CFLAGS) -o $@ $^
+
+$(OUTPUT)/main.o: main.c
+	$(CC) $(HOST_CFLAGS) -c $< -o $@
+
+$(OUTPUT)/sgx_call.o: sgx_call.S
+	$(CC) $(HOST_CFLAGS) -c $< -o $@
+
+$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
+
+$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
+	objcopy --remove-section=.got.plt -O binary $< $@
+
+$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
+	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
+
+$(OUTPUT)/encl.o: encl.c
+	$(CC) $(ENCL_CFLAGS) -c $< -o $@
+
+$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
+	$(CC) $(ENCL_CFLAGS) -c $< -o $@
+
+$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
+	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+
+$(OUTPUT)/sgxsign: sgxsign.c
+	$(CC) -o $@ $< -lcrypto
+
+EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
+	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
+	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
+	       $(OUTPUT)/sgxsign
+
+.PHONY: clean
diff --git a/tools/testing/selftests/x86/sgx/defines.h b/tools/testing/selftests/x86/sgx/defines.h
new file mode 100644
index 000000000000..3ff73a9d9b93
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/defines.h
@@ -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 */
diff --git a/tools/testing/selftests/x86/sgx/encl.c b/tools/testing/selftests/x86/sgx/encl.c
new file mode 100644
index 000000000000..ede915399742
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/encl.c
@@ -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);
+}
diff --git a/tools/testing/selftests/x86/sgx/encl.lds b/tools/testing/selftests/x86/sgx/encl.lds
new file mode 100644
index 000000000000..2ee01ac3ec79
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/encl.lds
@@ -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")
diff --git a/tools/testing/selftests/x86/sgx/encl_bootstrap.S b/tools/testing/selftests/x86/sgx/encl_bootstrap.S
new file mode 100644
index 000000000000..d07f970ccdf9
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/encl_bootstrap.S
@@ -0,0 +1,94 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) */
+/*
+ * Copyright(c) 2016-18 Intel Corporation.
+ */
+
+	.macro ENCLU
+	.byte 0x0f, 0x01, 0xd7
+	.endm
+
+	.section ".tcs", "a"
+	.balign	4096
+
+	.fill	1, 8, 0			# STATE (set by CPU)
+	.fill	1, 8, 0			# FLAGS
+	.quad	encl_ssa		# OSSA
+	.fill	1, 4, 0			# CSSA (set by CPU)
+	.fill	1, 4, 1			# NSSA
+	.quad	encl_entry		# OENTRY
+	.fill	1, 8, 0			# AEP (set by EENTER and ERESUME)
+	.fill	1, 8, 0			# OFSBASE
+	.fill	1, 8, 0			# OGSBASE
+	.fill	1, 4, 0xFFFFFFFF 	# FSLIMIT
+	.fill	1, 4, 0xFFFFFFFF	# GSLIMIT
+	.fill	4024, 1, 0		# Reserved
+
+	.text
+
+encl_entry:
+	# RBX contains the base address for TCS, which is also the first address
+	# inside the enclave. By adding the value of le_stack_end to it, we get
+	# the absolute address for the stack.
+	lea	(encl_stack)(%rbx), %rax
+	xchg	%rsp, %rax
+	push	%rax
+
+	push	%rcx # push the address after EENTER
+	push	%rbx # push the enclave base address
+
+	call	encl_body
+
+	pop	%rbx # pop the enclave base address
+
+	# Restore XSAVE registers to a synthetic state.
+	mov     $0xFFFFFFFF, %rax
+	mov     $0xFFFFFFFF, %rdx
+	lea	(xsave_area)(%rbx), %rdi
+	fxrstor	(%rdi)
+
+	# Clear GPRs.
+	xor     %rcx, %rcx
+	xor     %rdx, %rdx
+	xor     %rdi, %rdi
+	xor     %rsi, %rsi
+	xor     %r8, %r8
+	xor     %r9, %r9
+	xor     %r10, %r10
+	xor     %r11, %r11
+	xor     %r12, %r12
+	xor     %r13, %r13
+	xor     %r14, %r14
+	xor     %r15, %r15
+
+	# Reset status flags.
+	add     %rdx, %rdx # OF = SF = AF = CF = 0; ZF = PF = 1
+
+	# Prepare EEXIT target by popping the address of the instruction after
+	# EENTER to RBX.
+	pop	%rbx
+
+	# Restore the caller stack.
+	pop	%rax
+	mov	%rax, %rsp
+
+	# EEXIT
+	mov	$4, %rax
+	enclu
+
+	.section ".data", "aw"
+
+encl_ssa:
+	.space 4096
+
+xsave_area:
+	.fill	1, 4, 0x037F		# FCW
+	.fill	5, 4, 0
+	.fill	1, 4, 0x1F80		# MXCSR
+	.fill	1, 4, 0xFFFF		# MXCSR_MASK
+	.fill	123, 4, 0
+	.fill	1, 4, 0x80000000	# XCOMP_BV[63] = 1, compaction mode
+	.fill	12, 4, 0
+
+	.balign 4096
+	.space 8192
+encl_stack:
diff --git a/tools/testing/selftests/x86/sgx/encl_piggy.S b/tools/testing/selftests/x86/sgx/encl_piggy.S
new file mode 100644
index 000000000000..542001658afb
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/encl_piggy.S
@@ -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
diff --git a/tools/testing/selftests/x86/sgx/encl_piggy.h b/tools/testing/selftests/x86/sgx/encl_piggy.h
new file mode 100644
index 000000000000..ee8224f8cc8d
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/encl_piggy.h
@@ -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 */
diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
new file mode 100644
index 000000000000..e2265f841fb0
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/main.c
@@ -0,0 +1,279 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-18 Intel Corporation.
+
+#include <elf.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include "encl_piggy.h"
+#include "defines.h"
+#include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
+#include "../../../../../arch/x86/include/uapi/asm/sgx.h"
+
+static const uint64_t MAGIC = 0x1122334455667788ULL;
+
+struct vdso_symtab {
+	Elf64_Sym *elf_symtab;
+	const char *elf_symstrtab;
+	Elf64_Word *elf_hashtab;
+};
+
+static void *vdso_get_base_addr(char *envp[])
+{
+	Elf64_auxv_t *auxv;
+	int i;
+
+	for (i = 0; envp[i]; i++);
+	auxv = (Elf64_auxv_t *)&envp[i + 1];
+
+	for (i = 0; auxv[i].a_type != AT_NULL; i++) {
+		if (auxv[i].a_type == AT_SYSINFO_EHDR)
+			return (void *)auxv[i].a_un.a_val;
+	}
+
+	return NULL;
+}
+
+static Elf64_Dyn *vdso_get_dyntab(void *addr)
+{
+	Elf64_Ehdr *ehdr = addr;
+	Elf64_Phdr *phdrtab = addr + ehdr->e_phoff;
+	int i;
+
+	for (i = 0; i < ehdr->e_phnum; i++)
+		if (phdrtab[i].p_type == PT_DYNAMIC)
+			return addr + phdrtab[i].p_offset;
+
+	return NULL;
+}
+
+static void *vdso_get_dyn(void *addr, Elf64_Dyn *dyntab, Elf64_Sxword tag)
+{
+	int i;
+
+	for (i = 0; dyntab[i].d_tag != DT_NULL; i++)
+		if (dyntab[i].d_tag == tag)
+			return addr + dyntab[i].d_un.d_ptr;
+
+	return NULL;
+}
+
+static bool vdso_get_symtab(void *addr, struct vdso_symtab *symtab)
+{
+	Elf64_Dyn *dyntab = vdso_get_dyntab(addr);
+
+	symtab->elf_symtab = vdso_get_dyn(addr, dyntab, DT_SYMTAB);
+	if (!symtab->elf_symtab)
+		return false;
+
+	symtab->elf_symstrtab = vdso_get_dyn(addr, dyntab, DT_STRTAB);
+	if (!symtab->elf_symstrtab)
+		return false;
+
+	symtab->elf_hashtab = vdso_get_dyn(addr, dyntab, DT_HASH);
+	if (!symtab->elf_hashtab)
+		return false;
+
+	return true;
+}
+
+static unsigned long elf_sym_hash(const char *name)
+{
+	unsigned long h = 0, high;
+
+	while (*name) {
+		h = (h << 4) + *name++;
+		high = h & 0xf0000000;
+
+		if (high)
+			h ^= high >> 24;
+
+		h &= ~high;
+	}
+
+	return h;
+}
+
+static Elf64_Sym *vdso_symtab_get(struct vdso_symtab *symtab, const char *name)
+{
+	Elf64_Word bucketnum = symtab->elf_hashtab[0];
+	Elf64_Word *buckettab = &symtab->elf_hashtab[2];
+	Elf64_Word *chaintab = &symtab->elf_hashtab[2 + bucketnum];
+	Elf64_Sym *sym;
+	Elf64_Word i;
+
+	for (i = buckettab[elf_sym_hash(name) % bucketnum]; i != STN_UNDEF;
+	     i = chaintab[i]) {
+		sym = &symtab->elf_symtab[i];
+		if (!strcmp(name, &symtab->elf_symstrtab[sym->st_name]))
+			return sym;
+	}
+
+	return NULL;
+}
+
+static bool encl_create(int dev_fd, unsigned long bin_size,
+			struct sgx_secs *secs)
+{
+	struct sgx_enclave_create ioc;
+	void *base;
+	int rc;
+
+	memset(secs, 0, sizeof(*secs));
+	secs->ssa_frame_size = 1;
+	secs->attributes = SGX_ATTR_MODE64BIT;
+	secs->xfrm = 3;
+
+	for (secs->size = 4096; secs->size < bin_size; )
+		secs->size <<= 1;
+
+	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
+		    MAP_SHARED, dev_fd, 0);
+	if (base == MAP_FAILED) {
+		perror("mmap");
+		return false;
+	}
+
+	secs->base = (uint64_t)base;
+
+	ioc.src = (unsigned long)secs;
+	rc = ioctl(dev_fd, SGX_IOC_ENCLAVE_CREATE, &ioc);
+	if (rc) {
+		fprintf(stderr, "ECREATE failed rc=%d.\n", rc);
+		munmap(base, secs->size);
+		return false;
+	}
+
+	return true;
+}
+
+static bool encl_add_page(int dev_fd, unsigned long addr, void *data,
+			  uint64_t flags)
+{
+	struct sgx_enclave_add_page ioc;
+	struct sgx_secinfo secinfo;
+	int rc;
+
+	memset(&secinfo, 0, sizeof(secinfo));
+	secinfo.flags = flags;
+
+	ioc.secinfo = (unsigned long)&secinfo;
+	ioc.mrmask = 0xFFFF;
+	ioc.addr = addr;
+	ioc.src = (uint64_t)data;
+
+	rc = ioctl(dev_fd, SGX_IOC_ENCLAVE_ADD_PAGE, &ioc);
+	if (rc) {
+		fprintf(stderr, "EADD failed rc=%d.\n", rc);
+		return false;
+	}
+
+	return true;
+}
+
+static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
+{
+	struct sgx_enclave_init ioc;
+	uint64_t offset;
+	uint64_t flags;
+	int dev_fd;
+	int rc;
+
+	dev_fd = open("/dev/sgx/enclave", O_RDWR);
+	if (dev_fd < 0) {
+		fprintf(stderr, "Unable to open /dev/sgx\n");
+		return false;
+	}
+
+	if (!encl_create(dev_fd, bin_size, secs))
+		goto out_dev_fd;
+
+	for (offset = 0; offset < bin_size; offset += 0x1000) {
+		if (!offset)
+			flags = SGX_SECINFO_TCS;
+		else
+			flags = SGX_SECINFO_REG | SGX_SECINFO_R |
+				SGX_SECINFO_W | SGX_SECINFO_X;
+
+		if (!encl_add_page(dev_fd, secs->base + offset,
+				   encl_bin + offset, flags))
+			goto out_map;
+	}
+
+	ioc.sigstruct = (uint64_t)&encl_ss;
+	rc = ioctl(dev_fd, SGX_IOC_ENCLAVE_INIT, &ioc);
+	if (rc) {
+		printf("EINIT failed rc=%d\n", rc);
+		goto out_map;
+	}
+
+	close(dev_fd);
+	return true;
+out_map:
+	munmap((void *)secs->base, secs->size);
+out_dev_fd:
+	close(dev_fd);
+	return false;
+}
+
+void sgx_call(void *rdi, void *rsi, void *tcs,
+	      struct sgx_enclave_exception *exception,
+	      void *eenter);
+
+int main(int argc, char *argv[], char *envp[])
+{
+	unsigned long bin_size = encl_bin_end - encl_bin;
+	unsigned long ss_size = encl_ss_end - encl_ss;
+	struct sgx_enclave_exception exception;
+	Elf64_Sym *eenter_sym;
+	struct vdso_symtab symtab;
+	struct sgx_secs secs;
+	uint64_t result = 0;
+	void *eenter;
+	void *addr;
+
+	memset(&exception, 0, sizeof(exception));
+
+	addr = vdso_get_base_addr(envp);
+	if (!addr)
+		exit(1);
+
+	if (!vdso_get_symtab(addr, &symtab))
+		exit(1);
+
+	eenter_sym = vdso_symtab_get(&symtab, "__vdso_sgx_enter_enclave");
+	if (!eenter_sym)
+		exit(1);
+	eenter = addr + eenter_sym->st_value;
+
+	printf("Binary size %lu (0x%lx), SIGSTRUCT size %lu\n", bin_size,
+	       bin_size, ss_size);
+	if (ss_size != sizeof(struct sgx_sigstruct)) {
+		fprintf(stderr, "The size of SIGSTRUCT should be %lu\n",
+			sizeof(struct sgx_sigstruct));
+		exit(1);
+	}
+
+	printf("Loading the enclave.\n");
+	if (!encl_load(&secs, bin_size))
+		exit(1);
+
+	printf("Input: 0x%lx\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, (void *)secs.base, &exception,
+		 eenter);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+
+	printf("Output: 0x%lx\n", result);
+	exit(0);
+}
diff --git a/tools/testing/selftests/x86/sgx/sgx_call.S b/tools/testing/selftests/x86/sgx/sgx_call.S
new file mode 100644
index 000000000000..14bd0a044199
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/sgx_call.S
@@ -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
diff --git a/tools/testing/selftests/x86/sgx/sgxsign.c b/tools/testing/selftests/x86/sgx/sgxsign.c
new file mode 100644
index 000000000000..0b89823fc703
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/sgxsign.c
@@ -0,0 +1,508 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) 2016-18 Intel Corporation.
+
+#define _GNU_SOURCE
+#include <getopt.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <openssl/err.h>
+#include <openssl/pem.h>
+#include "defines.h"
+
+struct sgx_sigstruct_payload {
+	struct sgx_sigstruct_header header;
+	struct sgx_sigstruct_body body;
+};
+
+static const char *sign_key_pass;
+
+static bool check_crypto_errors(void)
+{
+	int err;
+	bool had_errors = false;
+	const char *filename;
+	int line;
+	char str[256];
+
+	for ( ; ; ) {
+		if (ERR_peek_error() == 0)
+			break;
+
+		had_errors = true;
+		err = ERR_get_error_line(&filename, &line);
+		ERR_error_string_n(err, str, sizeof(str));
+		fprintf(stderr, "crypto: %s: %s:%d\n", str, filename, line);
+	}
+
+	return had_errors;
+}
+
+static void exit_usage(const char *program)
+{
+	fprintf(stderr,
+		"Usage: %s/sign-le <key> <enclave> <sigstruct>\n", program);
+	exit(1);
+}
+
+static int pem_passwd_cb(char *buf, int size, int rwflag, void *u)
+{
+	if (!sign_key_pass)
+		return -1;
+
+	strncpy(buf, sign_key_pass, size);
+	/* no retry */
+	sign_key_pass = NULL;
+
+	return strlen(buf) >= size ? size - 1 : strlen(buf);
+}
+
+static inline const BIGNUM *get_modulus(RSA *key)
+{
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+	return key->n;
+#else
+	const BIGNUM *n;
+
+	RSA_get0_key(key, &n, NULL, NULL);
+	return n;
+#endif
+}
+
+static RSA *load_sign_key(const char *path)
+{
+	FILE *f;
+	RSA *key;
+
+	f = fopen(path, "rb");
+	if (!f) {
+		fprintf(stderr, "Unable to open %s\n", path);
+		return NULL;
+	}
+	key = RSA_new();
+	if (!PEM_read_RSAPrivateKey(f, &key, pem_passwd_cb, NULL))
+		return NULL;
+	fclose(f);
+
+	if (BN_num_bytes(get_modulus(key)) != SGX_MODULUS_SIZE) {
+		fprintf(stderr, "Invalid key size %d\n",
+			BN_num_bytes(get_modulus(key)));
+		RSA_free(key);
+		return NULL;
+	}
+
+	return key;
+}
+
+static void reverse_bytes(void *data, int length)
+{
+	int i = 0;
+	int j = length - 1;
+	uint8_t temp;
+	uint8_t *ptr = data;
+
+	while (i < j) {
+		temp = ptr[i];
+		ptr[i] = ptr[j];
+		ptr[j] = temp;
+		i++;
+		j--;
+	}
+}
+
+enum mrtags {
+	MRECREATE = 0x0045544145524345,
+	MREADD = 0x0000000044444145,
+	MREEXTEND = 0x00444E4554584545,
+};
+
+static bool mrenclave_update(EVP_MD_CTX *ctx, const void *data)
+{
+	if (!EVP_DigestUpdate(ctx, data, 64)) {
+		fprintf(stderr, "digest update failed\n");
+		return false;
+	}
+
+	return true;
+}
+
+static bool mrenclave_commit(EVP_MD_CTX *ctx, uint8_t *mrenclave)
+{
+	unsigned int size;
+
+	if (!EVP_DigestFinal_ex(ctx, (unsigned char *)mrenclave, &size)) {
+		fprintf(stderr, "digest commit failed\n");
+		return false;
+	}
+
+	if (size != 32) {
+		fprintf(stderr, "invalid digest size = %u\n", size);
+		return false;
+	}
+
+	return true;
+}
+
+struct mrecreate {
+	uint64_t tag;
+	uint32_t ssaframesize;
+	uint64_t size;
+	uint8_t reserved[44];
+} __attribute__((__packed__));
+
+
+static bool mrenclave_ecreate(EVP_MD_CTX *ctx, uint64_t blob_size)
+{
+	struct mrecreate mrecreate;
+	uint64_t encl_size;
+
+	for (encl_size = 0x1000; encl_size < blob_size; )
+		encl_size <<= 1;
+
+	memset(&mrecreate, 0, sizeof(mrecreate));
+	mrecreate.tag = MRECREATE;
+	mrecreate.ssaframesize = 1;
+	mrecreate.size = encl_size;
+
+	if (!EVP_DigestInit_ex(ctx, EVP_sha256(), NULL))
+		return false;
+
+	return mrenclave_update(ctx, &mrecreate);
+}
+
+struct mreadd {
+	uint64_t tag;
+	uint64_t offset;
+	uint64_t flags; /* SECINFO flags */
+	uint8_t reserved[40];
+} __attribute__((__packed__));
+
+static bool mrenclave_eadd(EVP_MD_CTX *ctx, uint64_t offset, uint64_t flags)
+{
+	struct mreadd mreadd;
+
+	memset(&mreadd, 0, sizeof(mreadd));
+	mreadd.tag = MREADD;
+	mreadd.offset = offset;
+	mreadd.flags = flags;
+
+	return mrenclave_update(ctx, &mreadd);
+}
+
+struct mreextend {
+	uint64_t tag;
+	uint64_t offset;
+	uint8_t reserved[48];
+} __attribute__((__packed__));
+
+static bool mrenclave_eextend(EVP_MD_CTX *ctx, uint64_t offset, uint8_t *data)
+{
+	struct mreextend mreextend;
+	int i;
+
+	for (i = 0; i < 0x1000; i += 0x100) {
+		memset(&mreextend, 0, sizeof(mreextend));
+		mreextend.tag = MREEXTEND;
+		mreextend.offset = offset + i;
+
+		if (!mrenclave_update(ctx, &mreextend))
+			return false;
+
+		if (!mrenclave_update(ctx, &data[i + 0x00]))
+			return false;
+
+		if (!mrenclave_update(ctx, &data[i + 0x40]))
+			return false;
+
+		if (!mrenclave_update(ctx, &data[i + 0x80]))
+			return false;
+
+		if (!mrenclave_update(ctx, &data[i + 0xC0]))
+			return false;
+	}
+
+	return true;
+}
+
+/**
+ * measure_encl - measure enclave
+ * @path: path to the enclave
+ * @mrenclave: measurement
+ *
+ * Calculates MRENCLAVE. Assumes that the very first page is a TCS page and
+ * following pages are regular pages. Does not measure the contents of the
+ * enclave as the signing tool is used at the moment only for the launch
+ * enclave, which is pass-through (everything gets a token).
+ */
+static bool measure_encl(const char *path, uint8_t *mrenclave)
+{
+	FILE *file;
+	struct stat sb;
+	EVP_MD_CTX *ctx;
+	uint64_t flags;
+	uint64_t offset;
+	uint8_t data[0x1000];
+	int rc;
+
+	ctx = EVP_MD_CTX_create();
+	if (!ctx)
+		return false;
+
+	file = fopen(path, "rb");
+	if (!file) {
+		perror("fopen");
+		EVP_MD_CTX_destroy(ctx);
+		return false;
+	}
+
+	rc = stat(path, &sb);
+	if (rc) {
+		perror("stat");
+		goto out;
+	}
+
+	if (!sb.st_size || sb.st_size & 0xfff) {
+		fprintf(stderr, "Invalid blob size %lu\n", sb.st_size);
+		goto out;
+	}
+
+	if (!mrenclave_ecreate(ctx, sb.st_size))
+		goto out;
+
+	for (offset = 0; offset < sb.st_size; offset += 0x1000) {
+		if (!offset)
+			flags = SGX_SECINFO_TCS;
+		else
+			flags = SGX_SECINFO_REG | SGX_SECINFO_R |
+				SGX_SECINFO_W | SGX_SECINFO_X;
+
+		if (!mrenclave_eadd(ctx, offset, flags))
+			goto out;
+
+		rc = fread(data, 1, 0x1000, file);
+		if (!rc)
+			break;
+		if (rc < 0x1000)
+			goto out;
+
+		if (!mrenclave_eextend(ctx, offset, data))
+			goto out;
+	}
+
+	if (!mrenclave_commit(ctx, mrenclave))
+		goto out;
+
+	fclose(file);
+	EVP_MD_CTX_destroy(ctx);
+	return true;
+out:
+	fclose(file);
+	EVP_MD_CTX_destroy(ctx);
+	return false;
+}
+
+/**
+ * sign_encl - sign enclave
+ * @sigstruct: pointer to SIGSTRUCT
+ * @key: 3072-bit RSA key
+ * @signature: byte array for the signature
+ *
+ * Calculates EMSA-PKCSv1.5 signature for the given SIGSTRUCT. The result is
+ * stored in big-endian format so that it can be further passed to OpenSSL
+ * libcrypto functions.
+ */
+static bool sign_encl(const struct sgx_sigstruct *sigstruct, RSA *key,
+		      uint8_t *signature)
+{
+	struct sgx_sigstruct_payload payload;
+	unsigned int siglen;
+	uint8_t digest[SHA256_DIGEST_LENGTH];
+	bool ret;
+
+	memcpy(&payload.header, &sigstruct->header, sizeof(sigstruct->header));
+	memcpy(&payload.body, &sigstruct->body, sizeof(sigstruct->body));
+
+	SHA256((unsigned char *)&payload, sizeof(payload), digest);
+
+	ret = RSA_sign(NID_sha256, digest, SHA256_DIGEST_LENGTH, signature,
+		       &siglen, key);
+
+	return ret;
+}
+
+struct q1q2_ctx {
+	BN_CTX *bn_ctx;
+	BIGNUM *m;
+	BIGNUM *s;
+	BIGNUM *q1;
+	BIGNUM *qr;
+	BIGNUM *q2;
+};
+
+static void free_q1q2_ctx(struct q1q2_ctx *ctx)
+{
+	BN_CTX_free(ctx->bn_ctx);
+	BN_free(ctx->m);
+	BN_free(ctx->s);
+	BN_free(ctx->q1);
+	BN_free(ctx->qr);
+	BN_free(ctx->q2);
+}
+
+static bool alloc_q1q2_ctx(const uint8_t *s, const uint8_t *m,
+			   struct q1q2_ctx *ctx)
+{
+	ctx->bn_ctx = BN_CTX_new();
+	ctx->s = BN_bin2bn(s, SGX_MODULUS_SIZE, NULL);
+	ctx->m = BN_bin2bn(m, SGX_MODULUS_SIZE, NULL);
+	ctx->q1 = BN_new();
+	ctx->qr = BN_new();
+	ctx->q2 = BN_new();
+
+	if (!ctx->bn_ctx || !ctx->s || !ctx->m || !ctx->q1 || !ctx->qr ||
+	    !ctx->q2) {
+		free_q1q2_ctx(ctx);
+		return false;
+	}
+
+	return true;
+}
+
+static bool calc_q1q2(const uint8_t *s, const uint8_t *m, uint8_t *q1,
+		      uint8_t *q2)
+{
+	struct q1q2_ctx ctx;
+
+	if (!alloc_q1q2_ctx(s, m, &ctx)) {
+		fprintf(stderr, "Not enough memory for Q1Q2 calculation\n");
+		return false;
+	}
+
+	if (!BN_mul(ctx.q1, ctx.s, ctx.s, ctx.bn_ctx))
+		goto out;
+
+	if (!BN_div(ctx.q1, ctx.qr, ctx.q1, ctx.m, ctx.bn_ctx))
+		goto out;
+
+	if (BN_num_bytes(ctx.q1) > SGX_MODULUS_SIZE) {
+		fprintf(stderr, "Too large Q1 %d bytes\n",
+			BN_num_bytes(ctx.q1));
+		goto out;
+	}
+
+	if (!BN_mul(ctx.q2, ctx.s, ctx.qr, ctx.bn_ctx))
+		goto out;
+
+	if (!BN_div(ctx.q2, NULL, ctx.q2, ctx.m, ctx.bn_ctx))
+		goto out;
+
+	if (BN_num_bytes(ctx.q2) > SGX_MODULUS_SIZE) {
+		fprintf(stderr, "Too large Q2 %d bytes\n",
+			BN_num_bytes(ctx.q2));
+		goto out;
+	}
+
+	BN_bn2bin(ctx.q1, q1);
+	BN_bn2bin(ctx.q2, q2);
+
+	free_q1q2_ctx(&ctx);
+	return true;
+out:
+	free_q1q2_ctx(&ctx);
+	return false;
+}
+
+static bool save_sigstruct(const struct sgx_sigstruct *sigstruct,
+			   const char *path)
+{
+	FILE *f = fopen(path, "wb");
+
+	if (!f) {
+		fprintf(stderr, "Unable to open %s\n", path);
+		return false;
+	}
+
+	fwrite(sigstruct, sizeof(*sigstruct), 1, f);
+	fclose(f);
+	return true;
+}
+
+int main(int argc, char **argv)
+{
+	uint64_t header1[2] = {0x000000E100000006, 0x0000000000010000};
+	uint64_t header2[2] = {0x0000006000000101, 0x0000000100000060};
+	struct sgx_sigstruct ss;
+	const char *program;
+	int opt;
+	RSA *sign_key;
+
+	memset(&ss, 0, sizeof(ss));
+	ss.header.header1[0] = header1[0];
+	ss.header.header1[1] = header1[1];
+	ss.header.header2[0] = header2[0];
+	ss.header.header2[1] = header2[1];
+	ss.exponent = 3;
+
+#ifndef CONFIG_EINITTOKENKEY
+	ss.body.attributes = SGX_ATTR_MODE64BIT;
+#else
+	ss.body.attributes = SGX_ATTR_MODE64BIT | SGX_ATTR_EINITTOKENKEY;
+#endif
+	ss.body.xfrm = 3,
+
+	sign_key_pass = getenv("KBUILD_SGX_SIGN_PIN");
+	program = argv[0];
+
+	do {
+		opt = getopt(argc, argv, "");
+		switch (opt) {
+		case -1:
+			break;
+		default:
+			exit_usage(program);
+		}
+	} while (opt != -1);
+
+	argc -= optind;
+	argv += optind;
+
+	if (argc < 3)
+		exit_usage(program);
+
+	/* sanity check only */
+	if (check_crypto_errors())
+		exit(1);
+
+	sign_key = load_sign_key(argv[0]);
+	if (!sign_key)
+		goto out;
+
+	BN_bn2bin(get_modulus(sign_key), ss.modulus);
+
+	if (!measure_encl(argv[1], ss.body.mrenclave))
+		goto out;
+
+	if (!sign_encl(&ss, sign_key, ss.signature))
+		goto out;
+
+	if (!calc_q1q2(ss.signature, ss.modulus, ss.q1, ss.q2))
+		goto out;
+
+	/* convert to little endian */
+	reverse_bytes(ss.signature, SGX_MODULUS_SIZE);
+	reverse_bytes(ss.modulus, SGX_MODULUS_SIZE);
+	reverse_bytes(ss.q1, SGX_MODULUS_SIZE);
+	reverse_bytes(ss.q2, SGX_MODULUS_SIZE);
+
+	if (!save_sigstruct(&ss, argv[2]))
+		goto out;
+	exit(0);
+out:
+	check_crypto_errors();
+	exit(1);
+}
diff --git a/tools/testing/selftests/x86/sgx/signing_key.pem b/tools/testing/selftests/x86/sgx/signing_key.pem
new file mode 100644
index 000000000000..d76f21f19187
--- /dev/null
+++ b/tools/testing/selftests/x86/sgx/signing_key.pem
@@ -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-----
-- 
2.19.1


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

* [PATCH v20 25/28] x86/sgx: Update MAINTAINERS
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (23 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 24/28] selftests/x86: Add a selftest for SGX Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 26/28] docs: x86/sgx: Add Architecture documentation Jarkko Sakkinen
                   ` (8 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

Add the maintainer information for the SGX subsystem.

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 MAINTAINERS | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 3671fdea5010..eb3b80811653 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -8044,6 +8044,18 @@ L:	linux-gpio@vger.kernel.org
 S:	Maintained
 F:	drivers/gpio/gpio-intel-mid.c
 
+INTEL SGX
+M:	Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
+M:	Sean Christopherson <sean.j.christopherson@intel.com>
+L:	linux-sgx@vger.kernel.org
+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 <georgi.djakov@linaro.org>
 S:	Maintained
-- 
2.19.1


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

* [PATCH v20 26/28] docs: x86/sgx: Add Architecture documentation
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (24 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 25/28] x86/sgx: Update MAINTAINERS Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 27/28] docs: x86/sgx: Document kernel internals Jarkko Sakkinen
                   ` (7 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #1: Type: text/plain; charset=y, Size: 24263 bytes --]

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

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

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 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

diff --git a/Documentation/index.rst b/Documentation/index.rst
index 80a421cb935e..3511400dc092 100644
--- a/Documentation/index.rst
+++ b/Documentation/index.rst
@@ -102,6 +102,7 @@ implementation.
    :maxdepth: 2
 
    sh/index
+   x86/index
 
 Filesystem Documentation
 ------------------------
diff --git a/Documentation/x86/index.rst b/Documentation/x86/index.rst
new file mode 100644
index 000000000000..6f3251c4b7b9
--- /dev/null
+++ b/Documentation/x86/index.rst
@@ -0,0 +1,10 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=================
+x86 Documentation
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   sgx/index
diff --git a/Documentation/x86/sgx/1.Architecture.rst b/Documentation/x86/sgx/1.Architecture.rst
new file mode 100644
index 000000000000..a4de6c610231
--- /dev/null
+++ b/Documentation/x86/sgx/1.Architecture.rst
@@ -0,0 +1,431 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============
+Architecture
+============
+
+Introduction
+============
+
+SGX is a set of instructions and mechanisms that enable ring 3 applications to
+set aside private regions of code and data for the purpose of establishing and
+running enclaves.  An enclave is a secure entity whose private memory can only
+be accessed by code running within the enclave.  Accesses from outside the
+enclave, including software running at a higher privilege level and other
+enclaves, are disallowed by hardware.
+
+SGX also provides for local and remote attestation.  `Attestation`_ allows an
+enclave to attest its identity, that it has not been tampered with, that it is
+running on a genuine platform with Intel SGX enabled, and the security
+properties of the platform on which it is running.
+
+You can determine if your CPU supports SGX by querying ``/proc/cpuinfo``:
+
+	``cat /proc/cpuinfo | grep sgx``
+
+
+Enclave Page Cache
+==================
+
+SGX utilizes an Enclave Page Cache (EPC) to store pages that are associated
+with an enclave.  The EPC is secure storage whose exact physical implementation
+is micro-architecture specific (see `EPC Implemenations`_).  Similar to normal
+system memory, the EPC is managed by privileged software using conventional
+paging mechanisms, e.g. the kernel can grant/deny access to EPC memory by
+manipulating a process' page tables, and can swap pages in/out of the EPC in
+order to oversubscribe the EPC.
+
+Unlikely regular memory, hardware prevents arbitrary insertion, eviction,
+deletion, access, etc... to/from the EPC.  Software must instead use dedicated
+`SGX instructions`_ to operate on the EPC, which enables the processor to
+provide SGX's security guarantees by enforcing various restrictions and
+behaviors, e.g. limits concurrent accesses to EPC pages and ensures proper TLB
+flushing when moving pages in/out of the EPC.
+
+Accesses to EPC pages are allowed if and only if the access is classified as an
+"enclave access".  There are two categories of allowed enclave accesses: direct
+and indirect.  Direct enclave accesses are generated if and only the processor
+is executing in Enclave Mode (see `Enclave execution`_).  Indirect enclave
+accesses are generated by various ENCL{S,U,V} functions, many of which can be
+executed outside of Enclave Mode.
+
+Non-enclave accesses to the EPC result in undefined behavior.  Conversely,
+enclave accesses to non-EPC memory result in a page fault (#PF)[1]_.  Page
+faults due to invalid enclave accesses set the PF_SGX flag (bit 15) in the page
+fault error code[2]_.
+
+Although all EPC implementations will undoubtedly encrypt the EPC itself, all
+all EPC code/data is stored unencrypted in the processor's caches.  I.e. SGX
+relies on the aforementioned mechanisms to protect an enclave's secrets while
+they are resident in the cache.
+
+Note, EPC pages are always 4KB sized and aligned.  Software can map EPC using
+using large pages, but the processor always operates on a 4KB granularity when
+working with EPC pages.
+
+
+SGX instructions
+================
+
+SGX introduces three new instructions, ENCLS, ENCLU and ENCLV, for Supervisor,
+User and Virtualization respectively.  ENCL{S,U,V} are umbrella instructions,
+using a single opcode as the front end to a variety of SGX functions.  The leaf
+function to execute is specified via %eax, with %rbx, %rcx and %rdx optionally
+used for leaf-specific purposes.
+
+Note that supervisor software, i.e. the kernel, creates and manages enclaves,
+but only user-level software can execute/enter an enclave.
+
+ENCLS Leafs
+-----------
+
+ - ECREATE: create an enclave
+ - EADD: add page to an uninitialized enclave
+ - EAUG: add page to an initialized enclave
+ - EEXTEND: extended the measurement of an (uninitialized) enclave
+ - EINIT: verify and initialize enclave
+ - EDBG{RD,WR}: read/write from/to a debug enclave’s memory
+ - EMODPR: restrict an EPC page’s permissions
+ - EMODT: modify an EPC page’s type
+ - EBLOCK: mark a page as blocked in EPCM
+ - ETRACK{C}: activate blocking tracing
+ - EWB: write back page from EPC to regular memory
+ - ELD{B,U}{C}: load page in {un}blocked state from system memory to EPC
+ - EPA: add version array (use to track evicted EPC pages)
+ - EREMOVE: remove a page from EPC
+ - ERDINFO: retrieve info about an EPC page from EPCM
+
+ENCLU Leafs
+-----------
+ - EENTER: enter an enclave
+ - ERESUME: resume execution of an interrupted enclave
+ - EEXIT: exit an enclave
+ - EGETKEY: retrieve a cryptographic key from the processor
+ - EREPORT: generate a cryptographic report describing an enclave
+ - EMODPE: extend an EPC page's permissions
+ - EACCEPT: accept changes to an EPC page
+ - EACCEPTCOPY: copy an existing EPC page to an uninitialized EPC page
+
+ENCLV Leafs
+-----------
+ - E{DEC,INC}VIRTCHILD: {dec,inc}rement SECS virtual refcount
+ - ESETCONTEXT: set SECS’ context pointer
+
+
+EPC page types
+==============
+
+All pages in the EPC have an explicit page type identifying the type of page.
+The type of page affects the page's accessibility, concurrency requirements,
+lifecycle, etc...
+
+SGX Enclave Control Structure (SECS)
+    An enclave is defined and referenced by an SGX Enclave Control Structure.
+    When creating an enclave (via ECREATE), software provides a source SECS for
+    the enclave, which is copied into a target EPC page.  The source SECS
+    contains security and measurement information, as well as attributes and
+    properties of the enclave.  Once the SECS is copied into the EPC, it's used
+    by the processor to store enclave metadata, e.g. the number of EPC pages
+    associated with the enclave, and is no longer directly accessible by
+    software.
+
+Regular (REG)
+    Regular EPC pages contain the code and data of an enclave.  Code and data
+    pages can be added to an uninitialized enclave (prior to EINIT) via EADD.
+    Post EINIT, pages can be added to an enclave via EAUG.  Pages added via
+    EAUG must be explicitly accepted by the enclave via EACCEPT or EACCEPTCOPY.
+
+Thread Control Structure (TCS)
+    Thread Control Structure pages define the entry points to an enclave and
+    track the execution state of an enclave thread.  A TCS can only be used by
+    a single logical CPU at any given time, but otherwise has no attachment to
+    any particular logical CPU.  Like regular pages, TCS pages are added to
+    enclaves via EADD and EINIT.
+
+Version Array (VA)
+   Version Array pages contain 512 slots, each of which can contain a version
+   number for a page evicted from the EPC.  A version number is a unique 8-byte
+   value that is fed into the MAC computation used to verify the contents of an
+   evicted page when reloading said page into the EPC.  VA pages are the only
+   page type not directly associated with an enclave, and are allocated in the
+   EPC via EPA.   Note that VA pages can also be evicted from the EPC, but
+   doing so requires another VA page/slot to hold the version number of the VA
+   page being evicted.
+
+Trim (TRIM)
+   The Trim page type indicates that a page has been trimmed from the enclave’s
+   address space and is no longer accessible to enclave software, i.e. is about
+   to be removed from the enclave (via EREMOVE).  Removing pages from a running
+   enclaves requires the enclave to explicit accept the removal (via EACCEPT).
+   The intermediate Trim type allows software to batch deallocation operations
+   to improve efficiency, e.g. minimize transitions between userspace, enclave
+   and kernel.
+
+
+Enclave Page Cache Map
+======================
+
+The processor tracks EPC pages via the Enclave Page Cache Map (EPCM).  The EPCM
+is a processor-managed structure that enforces access restrictions to EPC pages
+in addition to the software-managed page tables.  The EPCM contains one entry
+per EPC page, and although the details are implementation specific, all
+implementations contain the following architectural information:
+
+ - The status of EPC page with respect to validity and accessibility.
+ - An SECS identifier of the enclave to which the page belongs.
+ - The type of page: regular, SECS, TCS, VA or TRIM
+ - The linear address through which the enclave is allowed to access the page.
+ - The specified read/write/execute permissions on that page.
+
+Access violations, e.g. insufficient permissions or incorrect linear address,
+detected via the EPCM result in a page fault (#PF)[1]_ exception being signaled
+by the processor.  Page faults due to EPCM violations set the PF_SGX flag
+(bit 15) in the page fault error code[2]_.
+
+The EPCM is consulted if and only if walking the software-managed page tables,
+i.e. the kernel's page tables, succeeds.  I.e. the effective permissions for an
+EPC page are a logical AND of the kernel's page tables and the corresponding
+EPCM entry.  This allows the kernel to make its page tables more restrictive
+without triggering an EPCM violation, e.g. it may mark an entry as not-present
+prior to evicting a page from the EPC.
+
+**IMPORTANT** For all intents and purposes the SGX architecture allows the
+processor to invalidate all EPCM entries at will, i.e. requires that software
+be prepared to handle an EPCM fault at any time.  Most processors are expected
+to implement the EPC{M} as a subset of system DRAM that is encrypted with an
+ephemeral key, i.e. a key that is randomly generated at processor reset.  As a
+result of using an ephemeral key, the contents of the EPC{M} are lost when the
+processor is powered down as part of an S3 transition or when a virtual machine
+is live migrated to a new physical system.
+
+
+Enclave initialization
+======================
+
+Because software cannot directly access the EPC except when executing in an
+enclave, an enclave must be built using ENCLS functions (ECREATE and EADD) as
+opposed to simply copying the enclave from the filesystem to memory.  Once an
+enclave is built, it must be initialized (via EINIT) before userspace can enter
+the enclave and begin `Enclave execution`_.
+
+During the enclave build process, two "measurements", i.e. SHA-256 hashes, are
+taken of the enclave: MRENCLAVE and MRSIGNER.  MRENCLAVE measures the enclave's
+contents,  e.g. code/data explicitly added to the measurement (via EEXTEND), as
+well as metadata from the enclave's build process, e.g. pages offsets (relative
+to the enclave's base) and page permissions of all pages added to the enclave
+(via EADD).  MRENCLAVE is initialized by ECREATE and finalized by EINIT.
+MRSIGNER is simply the SHA-256 hash of the public key used to sign the enclave.
+
+EINIT accepts two parameters in addition to the SECS of the target enclave: an
+Enclave Signature Struct (SIGSTRUCT) and an EINIT token (EINITTOKEN).
+SIGSTRUCT is a structure created and signed by the enclave's developer.  Among
+other fields, SIGSTRUCT contains the expected MRENCLAVE of the enclave and the
+MRSIGNER of the enclave.  SIGSTRUCT's MRENCLAVE is used by the processor to
+verify that the enclave was properly built (at runtime), and its SIGSTRUCT is
+copied to the SECS upon successful EINIT.  EINITTOKEN is an optional parameter
+that is consumed as part of `Launch Control`_.
+
+
+Enclave execution
+=================
+
+Enclaves execute in a bespoke sub-mode of ring 3, appropriately named Enclave
+Mode.  Enclave Mode changes behavior in key ways to support SGX's security
+guarantees and to reduce the probability of unintentional disclosure of
+sensitive data.
+
+A notable cornerstone of Enclave Mode is the Enclave Linear Range (ELRANGE).
+An enclave is associated with one, and only one, contiguous linear address
+range, its ELRANGE.  The ELRANGE is specified via the SIZE and BASEADDR fields
+in the SECS (provided to ECREATE).  The processor queries the active enclave's
+ELRANGE to differentiate enclave and non-enclave accesses, i.e. accesses that
+originate in Enclave Mode *and* whose linear address falls within ELRANGE are
+considered (direct) enclave accesses.  Note, the processor also generates
+(indirect) enclave accesses when executing ENCL* instructions, which may occur
+outside of Enclave Mode, e.g. when copying the SECS to its target EPC page
+during ECREATE.
+
+Enclave Mode changes include, but are not limited to:
+
+ - Permits direct software access to EPC pages owned by the enclave
+ - Ensures enclave accesses map to the EPC (EPCM violation, i.e. #PF w/ PF_SGX)
+ - Prevents executing code outside the enclave's ELRANGE (#GP fault)
+ - Changes the behavior of exceptions/events
+ - Causes many instructions to become illegal, i.e. generate an exception
+ - Supresses all instruction breakpoints*
+ - Suppresses data breakpoints within enclave's ELRANGE*
+
+ * For non-debug enclaves.
+
+Transitions to/from Enclave Mode have semantics that are a lovely blend of
+SYSCALL, SYSRET and VM-Exit.  In normal execution, entering and exiting Enclave
+Mode can only be done through EENTER and EEXIT respectively.  EENTER+EEXIT is
+analogous to SYSCALL+SYSRET, e.g. EENTER/SYSCALL load RCX with the next RIP and
+EEXIT/SYSRET load RIP from R{B,C}X, and EENTER can only jump to a predefined
+location controlled by the enclave/kernel.
+
+But when an exception, interrupt, VM-Exit, etc... occurs, enclave transitions
+behave more like VM-Exit and VMRESUME.  To maintain the black box nature of the
+enclave, the processor automatically switches register context when any of the
+aforementioned events occur (the SDM refers to such events as Enclave Exiting
+Events (EEE)).
+
+To handle an EEE, the processor performs an Asynchronous Enclave Exits (AEX).
+Note, although exceptions and traps are synchronous from a processor execution
+perspective, the are asynchronous from the enclave's perspective as the enclave
+is not provided an opportunity to save/fuzz state prior to exiting the enclave.
+On an AEX, the processor exits the enclave to a predefined %rip called the
+Asynchronous Exiting Pointer (AEP).  The AEP is specified at enclave entry (via
+EENTER/ERESUME) and saved into the associated TCS, similar to how a hypervisor
+specifies the VM-Exit target (via VMCS.HOST_RIP at VMLAUNCH/VMRESUME), i.e. the
+the AEP is an exit location controlled by the enclave's untrusted runtime.
+
+On an AEX, the processor fully exits the enclave prior to vectoring the event,
+i.e. from the event handler's perspective the event occurred at the AEP.  Thus,
+IRET/RSM/VMRESUME (from the event handler) returns control to the enclave's
+untrusted runtime, which can take appropriate action, e.g. immediately ERESUME
+the enclave on interrupts, forward expected exceptions to the enclave, restart
+the enclave on fatal exceptions, and so on and so forth.
+
+To preserve the enclave's state across AEX events, the processor automatically
+saves architectural into a State Save Area (SSA).  Because SGX supports nested
+AEX events, e.g. the untrusted runtime can re-EENTER the enclave after an AEX,
+which can in turn trigger an AEX, the TCS holds a pointer to a stack of SSA
+frames (as opposed to a single SSA), an index to the current SSA frame and the
+total number of available frames.  When an AEX occurs, the processor saves the
+architectural state into the TCS's current SSA frame.  The untrusted runtime
+can then pop the last SSA frame (off the TCS's stack) via ERESUME, i.e. restart
+the enclave after the AEX is handled.
+
+
+Launch Control
+==============
+
+SGX provides a set of controls, referred to as Launch Control, that governs the
+initialization of enclaves.  The processor internally stores a SHA-256 hash of
+a 3072-bit RSA public key, i.e. a MRSIGNER, often referred to as the "LE pubkey
+hash".  The LE pubkey hash is used during EINIT to prevent launching an enclave
+without proper authorization.  In order for EINIT to succeed, the enclave's
+MRSIGNER (from SIGSTRUCT) *or* the MRSIGNER of the enclave's EINITTOKEN must
+match the LE pubkey hash.
+
+An EINITTOKEN can only be created by a so called Launch Enclave (LE).  A LE is
+an enclave with SECS.ATTRIBUTES.EINITTOKEN_KEY=1, which grants it access to the
+EINITTOKEN_KEY (retrieved via EGETKEY).  EINITTOKENs provide a ready-built
+mechanism for userspace to bless enclaves without requiring additional kernel
+infrastructure.
+
+Processors that support SGX Launch Control Configuration, enumerated by the
+SGX_LC flag (bit 30 in CPUID 0x7.0x0.ECX), expose the LE pubkey hash as a set
+of four MSRs, aptly named IA32_SGXLEPUBKEYHASH[0-3].  The reset value of the
+MSRs is an internally defined (Intel) key (processors that don't support
+SGX_LC also use an internally defined key, it's just not exposed to software).
+
+While the IA32_SGXLEPUBKEYHASH MSRs are readable on any platform that supports
+SGX_LC, the MSRs are only writable if the IA32_FEATURE_CONTROL is locked with
+bit 17 ("SGX Launch Control Enable" per the SDM, or more accurately "SGX LE
+pubkey hash writable") set to '1'.  Note, the MSRs are also writable prior to
+`SGX activation`_.
+
+Note, while "Launch Control Configuration" is the official feature name used by
+the Intel SDM, other documentation may use the term "Flexible Launch Control",
+or even simply "Launch Control".  Colloquially, the vast majority of usage of
+the term "Launch Control" is synonymous with "Launch Control Configuration".
+
+
+EPC oversubscription
+====================
+
+SGX supports the concept of EPC oversubscription.  Analogous to swapping system
+DRAM to disk, enclave pages can be swapped from the EPC to memory, and later
+reloaded from memory to the EPC.  But because the kernel is untrusted, swapping
+pages in/out of the EPC has specialized requirements:
+
+  - The kernel cannot directly access EPC memory, i.e. cannot copy data to/from
+    the EPC.
+  - The kernel must "prove" to hardware that there are no valid TLB entries for
+    said page prior to eviction (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 and TCS pages, hardware must be
+    able to associate the page with an SECS, i.e. refcount an enclaves pages.
+
+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 TLB 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 (see `EPC page types`_)
+  - EWB:    Write back a page from EPC to memory, e.g. RAM.  Software must
+    supply a VA slot, memory to hold the Paging Crypto Metadata (PCMD) of the
+    page and obviously backing for the evicted page.
+  - ELD*:   Load a page in {un}blocked state from memory to EPC.
+
+Swapped EPC pages are {de,en}crypted on their way in/out of the EPC, e.g. EWB
+encrypts and ELDU decrypts.  The version number (stored in a VA page) and PCMD
+structure associated with an evicted EPC page seal a page (prevent undetected
+modification) and ensure its freshness (prevent rollback to a stale version of
+the page) while the page resides in unprotected storage, e.g. memory or disk.
+
+
+Attestation
+===========
+
+SGX provides mechanisms that allow software to implement what Intel refers to
+as Local Attestation (used by enclaves running on a the same physical platform
+to securely identify one another) and Remote Attestation (a process by which an
+enclave attests itself to a remote entity in order to gain the trust of said
+entity).
+
+The details of Local Attestation and Remote Attestation are far beyond the
+scope of this document.  Please see Intel's Software Developer's Manual and/or
+use your search engine of choice to learn more about SGX's attestation
+capabilities.
+
+
+EPC Implemenations
+==================
+
+PRM with MEE
+--------------
+
+Initial hardware support for SGX implements the EPC by reserving a chunk of
+system DRAM, referred to as Processor Reserved Memory (PRM).   A percentage of
+PRM is consumed by the processor to implement the EPCM, with the remainder of
+PRM being exposed to software as the EPC.  PRM is configured by firmware via
+dedicated PRM Range Registers (PRMRRs).   The PRMRRs are locked  which are locked as part of SGX activation, i.e.
+resizing the PRM, and thus EPC, requires rebooting the system.
+
+An autonomous hardware unit called the Memory Encryption Engine (MEE) protects
+the confidentiality, integrity, and freshness of the PRM, e.g. {de,en}crypts
+data as it is read/written from/to DRAM to provide confidentiality.
+
+
+SGX activation
+==============
+
+Before SGX can be fully enabled, e.g. via FEATURE_CONTROL, the platform must
+undergo explicit SGX activation.  SGX activation is a mechanism by which the
+processor verifies and locks the platform configuration set by pre-boot
+firmware, e.g. to ensure it satisfies SGX's security requirements.  Before
+SGX is activated (and its configuration locked), firmware can modify the
+PRMRRs, e.g. to set the base/size of the PRM and thus EPC, and can also write
+the SGX_LEPUBKEYHASH MSRs.  Notably, the latter allows pre-boot firmware to
+lock the SGX_LEPUBKEYHASH MSRs to a non-Intel value by writing the MSRs and
+locking MSR_IA32_FEATURE_CONTROL without setting the "SGX LE pubkey hash
+writable" flag, i.e. making the SGX_LEPUBKEYHASH MSRs readonly.
+
+
+Footnotes
+=========
+
+.. [1] All processors that do not support the SGX2 ISA take an errata and
+       signal #GP(0) instead of #PF(PF_SGX) when vectoring EPCM violations and
+       faults due to enclave-accesses to non-EPC memory.
+
+.. [2] Note that despite being vectored as a #PF, a #PF with PF_SGX has nothing
+       to do with conventional paging.
+
diff --git a/Documentation/x86/sgx/index.rst b/Documentation/x86/sgx/index.rst
new file mode 100644
index 000000000000..c5dfef62e612
--- /dev/null
+++ b/Documentation/x86/sgx/index.rst
@@ -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
-- 
2.19.1


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

* [PATCH v20 27/28] docs: x86/sgx: Document kernel internals
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (25 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 26/28] docs: x86/sgx: Add Architecture documentation Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-17 10:39 ` [PATCH v20 28/28] docs: x86/sgx: Document the enclave API Jarkko Sakkinen
                   ` (6 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

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

Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
Co-developed-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 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

diff --git a/Documentation/x86/sgx/2.Kernel-internals.rst b/Documentation/x86/sgx/2.Kernel-internals.rst
new file mode 100644
index 000000000000..de359bf605ca
--- /dev/null
+++ b/Documentation/x86/sgx/2.Kernel-internals.rst
@@ -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.
diff --git a/Documentation/x86/sgx/index.rst b/Documentation/x86/sgx/index.rst
index c5dfef62e612..5d660e83d984 100644
--- a/Documentation/x86/sgx/index.rst
+++ b/Documentation/x86/sgx/index.rst
@@ -14,3 +14,4 @@ potentially malicious.
    :maxdepth: 1
 
    1.Architecture
+   2.Kernel-internals
-- 
2.19.1


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

* [PATCH v20 28/28] docs: x86/sgx: Document the enclave API
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (26 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 27/28] docs: x86/sgx: Document kernel internals Jarkko Sakkinen
@ 2019-04-17 10:39 ` Jarkko Sakkinen
  2019-04-18 17:10 ` [PATCH v20 00/28] Intel SGX1 support Dr. Greg
                   ` (5 subsequent siblings)
  33 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-17 10:39 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	Jarkko Sakkinen

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

Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
---
 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

diff --git a/Documentation/x86/sgx/3.API.rst b/Documentation/x86/sgx/3.API.rst
new file mode 100644
index 000000000000..b113aeb05f54
--- /dev/null
+++ b/Documentation/x86/sgx/3.API.rst
@@ -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
diff --git a/Documentation/x86/sgx/index.rst b/Documentation/x86/sgx/index.rst
index 5d660e83d984..de0b78328611 100644
--- a/Documentation/x86/sgx/index.rst
+++ b/Documentation/x86/sgx/index.rst
@@ -15,3 +15,4 @@ potentially malicious.
 
    1.Architecture
    2.Kernel-internals
+   3.API
-- 
2.19.1


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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (27 preceding siblings ...)
  2019-04-17 10:39 ` [PATCH v20 28/28] docs: x86/sgx: Document the enclave API Jarkko Sakkinen
@ 2019-04-18 17:10 ` Dr. Greg
  2019-04-18 17:24   ` Dave Hansen
                     ` (2 more replies)
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
                   ` (4 subsequent siblings)
  33 siblings, 3 replies; 318+ messages in thread
From: Dr. Greg @ 2019-04-18 17:10 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: torvalds, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

[-- Attachment #1: Type: text/plain, Size: 9413 bytes --]

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.

> 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: greg@enjellic.com
------------------------------------------------------------------------------
"I can only provide the information, I can't make you hear it."
                                -- Shelley Bainter

[-- Attachment #2: jarkko-master-SFLC.patch --]
[-- Type: text/plain, Size: 23667 bytes --]

 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(-)

diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 9ed690a38c70..694981e03c65 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -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;
 };
 
 /**
diff --git a/arch/x86/kernel/cpu/sgx/driver/Makefile b/arch/x86/kernel/cpu/sgx/driver/Makefile
index 01ebbbb06a47..ac7702201229 100644
--- a/arch/x86/kernel/cpu/sgx/driver/Makefile
+++ b/arch/x86/kernel/cpu/sgx/driver/Makefile
@@ -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
diff --git a/arch/x86/kernel/cpu/sgx/driver/driver.h b/arch/x86/kernel/cpu/sgx/driver/driver.h
index 153b4a48aa6f..d5994c4aa65d 100644
--- a/arch/x86/kernel/cpu/sgx/driver/driver.h
+++ b/arch/x86/kernel/cpu/sgx/driver/driver.h
@@ -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__ */
diff --git a/arch/x86/kernel/cpu/sgx/driver/ioctl.c b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
index 3a01c3dd579d..0d758f1498f7 100644
--- a/arch/x86/kernel/cpu/sgx/driver/ioctl.c
+++ b/arch/x86/kernel/cpu/sgx/driver/ioctl.c
@@ -639,7 +639,17 @@ static int __sgx_get_key_hash(struct crypto_shash *tfm, const void *modulus,
 	return crypto_shash_digest(shash, modulus, SGX_MODULUS_SIZE, hash);
 }
 
-static int sgx_get_key_hash(const void *modulus, void *hash)
+/**
+* sgx_get_key_hash - Compute the hash of the enclave signer.
+*
+* @modulus:	A pointer to the signature modulus.
+* @hash:	A pointer to the signature buffer.
+*
+* Return:
+*   0 on success,
+*   Cryptographic subsystem error.
+*/
+int sgx_get_key_hash(const void *modulus, void *hash)
 {
 	struct crypto_shash *tfm;
 	int ret;
@@ -655,20 +665,26 @@ static int sgx_get_key_hash(const void *modulus, void *hash)
 }
 
 static int sgx_encl_init(struct sgx_encl *encl, struct sgx_sigstruct *sigstruct,
-			 struct sgx_einittoken *token)
+			 struct sgx_einittoken *token, bool use_lc)
 {
 	u64 mrsigner[4];
 	int ret;
 	int i;
 	int j;
+	uint8_t *(*get_signer)(uint8_t *) = NULL;
 
 	/* Check that the required attributes have been authorized. */
 	if (encl->secs_attributes & ~encl->allowed_attributes)
 		return -EINVAL;
 
-	ret = sgx_get_key_hash(sigstruct->modulus, mrsigner);
-	if (ret)
-		return ret;
+	if (use_lc)
+		get_signer = sgx_get_launch_signer;
+	else {
+		pr_debug("%s: Using modulus signature.\n", __FILE__);
+		ret = sgx_get_key_hash(sigstruct->modulus, mrsigner);
+		if (ret)
+			return ret;
+	}
 
 	flush_work(&encl->work);
 
@@ -683,7 +699,7 @@ static int sgx_encl_init(struct sgx_encl *encl, struct sgx_sigstruct *sigstruct,
 	for (i = 0; i < SGX_EINIT_SLEEP_COUNT; i++) {
 		for (j = 0; j < SGX_EINIT_SPIN_COUNT; j++) {
 			ret = sgx_einit(sigstruct, token, encl->secs.epc_page,
-					mrsigner);
+					mrsigner, get_signer);
 			if (ret == SGX_UNMASKED_EVENT)
 				continue;
 			else
@@ -737,6 +753,7 @@ static int sgx_encl_init(struct sgx_encl *encl, struct sgx_sigstruct *sigstruct,
 static long sgx_ioc_enclave_init(struct file *filep, unsigned int cmd,
 				 unsigned long arg)
 {
+	bool use_sc, use_lc, use_pc;
 	struct sgx_enclave_init *initp = (struct sgx_enclave_init *)arg;
 	struct sgx_encl *encl = filep->private_data;
 	struct sgx_einittoken *einittoken;
@@ -744,6 +761,25 @@ static long sgx_ioc_enclave_init(struct file *filep, unsigned int cmd,
 	struct page *initp_page;
 	int ret;
 
+	use_sc = sgx_signing_control(NULL);
+	pr_debug("%s: Signing control status: %s\n", __FILE__,
+		 use_sc ? "active" : "disabled");
+
+	use_lc = sgx_launch_control(NULL);
+	pr_debug("%s: Launch control status: %s\n", __FILE__,
+		 use_lc ? "active" : "disabled");
+
+	use_pc = sgx_provisioning_control(NULL);
+	pr_debug("%s: Provisioning control status: %s\n", __FILE__,
+		 use_pc ? "active" : "disabled");
+
+	if (!use_sc) {
+		if (initp->einittoken != 0 && !use_lc)
+			return -EINVAL;
+		if (initp->einittoken == 0 && use_lc)
+			return -EINVAL;
+	}
+
 	initp_page = alloc_page(GFP_HIGHUSER);
 	if (!initp_page)
 		return -ENOMEM;
@@ -751,7 +787,16 @@ static long sgx_ioc_enclave_init(struct file *filep, unsigned int cmd,
 	sigstruct = kmap(initp_page);
 	einittoken = (struct sgx_einittoken *)
 		((unsigned long)sigstruct + PAGE_SIZE / 2);
-	memset(einittoken, 0, sizeof(*einittoken));
+	if ( !initp->einittoken )
+		memset(einittoken, 0, sizeof(*einittoken));
+	else {
+		if (copy_from_user(einittoken,
+				   (void __user *)initp->einittoken,
+				   sizeof(*einittoken))) {
+			ret = -EFAULT;
+			goto out;
+		}
+	}
 
 	if (copy_from_user(sigstruct, (void __user *)initp->sigstruct,
 			   sizeof(*sigstruct))) {
@@ -759,8 +804,35 @@ static long sgx_ioc_enclave_init(struct file *filep, unsigned int cmd,
 		goto out;
 	}
 
+	if (!use_lc && (sigstruct->body.attributes & SGX_ATTR_EINITTOKENKEY)) {
+		ret = -EINVAL;
+		goto out;
+	}
+
+	if ((sigstruct->body.attributes & SGX_ATTR_EINITTOKENKEY) &&
+	    sgx_launch_control(sigstruct->modulus))
+		encl->allowed_attributes |= SGX_ATTR_EINITTOKENKEY;
+
+	if (!use_pc)
+		encl->allowed_attributes |= SGX_ATTR_PROVISIONKEY;
+	else {
+		if ((sigstruct->body.attributes & SGX_ATTR_PROVISIONKEY) &&
+		    sgx_provisioning_control(sigstruct->modulus))
+			encl->allowed_attributes |= SGX_ATTR_PROVISIONKEY;
+	}
+
+	if (use_sc) {
+		use_sc = sgx_signing_control(sigstruct->modulus);
+		if (!use_sc && !use_lc) {
+			ret = -EINVAL;
+			goto out;
+		}
+		if (use_sc)
+			use_lc = false;
+	}
+
+	ret = sgx_encl_init(encl, sigstruct, einittoken, use_lc);
 
-	ret = sgx_encl_init(encl, sigstruct, einittoken);
 
 out:
 	kunmap(initp_page);
diff --git a/arch/x86/kernel/cpu/sgx/driver/main.c b/arch/x86/kernel/cpu/sgx/driver/main.c
index afe844aa81d6..503c2a9728ec 100644
--- a/arch/x86/kernel/cpu/sgx/driver/main.c
+++ b/arch/x86/kernel/cpu/sgx/driver/main.c
@@ -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();
 }
diff --git a/arch/x86/kernel/cpu/sgx/driver/policy.c b/arch/x86/kernel/cpu/sgx/driver/policy.c
new file mode 100644
index 000000000000..c72b1604c1fa
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/driver/policy.c
@@ -0,0 +1,584 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) IDfusion, LLC
+
+#define KEY_SIZE 32
+
+#include <linux/types.h>
+#include <linux/seq_file.h>
+#include <linux/atomic.h>
+#include <linux/security.h>
+#include "driver.h"
+
+/* Variables for launch key management. */
+struct list_key {
+	struct list_head list;
+	uint8_t key[KEY_SIZE];
+};
+
+static struct dentry *sgx_fs;
+static struct dentry *launch_keys;
+static atomic_t launch_keys_opencount = ATOMIC_INIT(1);
+static unsigned int launch_keys_count;
+static bool launch_keys_locked;
+static DEFINE_MUTEX(launch_key_list_mutex);
+static LIST_HEAD(launch_key_list);
+
+static struct dentry *provision_keys;
+static atomic_t provision_keys_opencount = ATOMIC_INIT(1);
+static unsigned int provision_keys_count;
+static bool provision_keys_locked;
+static DEFINE_MUTEX(provision_key_list_mutex);
+static LIST_HEAD(provision_key_list);
+
+static struct dentry *signing_keys;
+static atomic_t signing_keys_opencount = ATOMIC_INIT(1);
+static unsigned int signing_keys_count;
+static bool signing_keys_locked;
+static DEFINE_MUTEX(signing_key_list_mutex);
+static LIST_HEAD(signing_key_list);
+
+/**
+ * have_signer - Verify the presence presence of a key signer.
+ *
+ * @signature:	Pointer to signature of signer.
+ *
+ * Return:
+ *   0 Signer signature was not found.
+ *   1 Signer signature was found.
+ */
+static bool have_signer(struct list_head *keylist, struct mutex *lock,
+			uint8_t *signature)
+{
+	bool retn = false;
+	struct list_key *kp;
+
+	mutex_lock(lock);
+	list_for_each_entry(kp, keylist, list) {
+		pr_debug("%s: Checking signer=%*phN, ks=%*phN\n", __func__,
+			 KEY_SIZE, signature, KEY_SIZE, kp->key);
+		if (memcmp(kp->key, signature, KEY_SIZE) == 0) {
+			retn = true;
+			goto done;
+		}
+	}
+
+ done:
+	mutex_unlock(lock);
+	return retn;
+}
+
+/**
+ * sgx_launch_control - Launch Control policy status
+ *
+ * Verifies whether or not launch control is active.
+ *
+ * Return:
+ *   0 No launch control is authorized.
+ *   1 Launch control is permitted.
+ */
+bool sgx_launch_control(uint8_t *modulus)
+{
+	bool retn = false;
+	uint8_t mrsigner[KEY_SIZE];
+
+	if (modulus == NULL) {
+		retn = launch_keys_count > 0;
+		goto done;
+	}
+
+	pr_debug("%s: Verifying launch control modulus.\n", __func__);
+	if (sgx_get_key_hash(modulus, mrsigner))
+		goto done;
+	retn = have_signer(&launch_key_list, &launch_key_list_mutex, mrsigner);
+
+ done:
+	return retn;
+}
+
+/**
+ * sgx_get_launch_signer - Iterate through list of enclave authorizers.
+ *
+ * @signer:	The last returned enclave signer.
+ *
+ * This function iterates through the list of enclave signers from the
+ * last signature.  Calling the function with a NULL signer value
+ * resets the iteration to the beginning of the list.
+ *
+ * Return:
+ *   NULL indicates end of list
+ *   non-NULL the next enclave signature on the list.
+ */
+
+uint8_t * sgx_get_launch_signer(uint8_t *signature)
+{
+	bool seeking = false;
+	uint8_t *retn = NULL;
+	struct list_key *kp;
+
+	if (!signature) {
+		kp = list_first_entry(&launch_key_list, struct list_key, list);
+		return kp->key;
+	}
+
+	kp = list_last_entry(&launch_key_list, struct list_key, list);
+	if ( memcmp(kp->key, signature, sizeof(kp->key)) == 0 )
+		return NULL;
+
+	mutex_lock(&launch_key_list_mutex);
+	list_for_each_entry(kp, &launch_key_list, list) {
+		if (seeking) {
+			retn = kp->key;
+			goto done;
+		}
+		pr_debug("%s: Skipping: %*phN\n", __func__, KEY_SIZE, kp->key);
+		if (memcmp(kp->key, signature, KEY_SIZE) == 0)
+			seeking = true;
+	}
+
+ done:
+	mutex_unlock(&launch_key_list_mutex);
+	return retn;
+}
+
+/**
+ * sgx_provisioning_control - Provisioning control verification.
+ *
+ * This function returns a true value if provision control is active
+ * and the signature of the modulus of the signing key for an enclave
+ * with the PROVISION bit set is on the list of approved keys.
+ *
+ * Return:
+ *   0 No provisioning control is authorized.
+ *   1 Provisioning is authorized for the enclave.
+ */
+bool sgx_provisioning_control(uint8_t *modulus)
+{
+	bool retn = false;
+	uint8_t mrsigner[KEY_SIZE];
+
+	if (modulus == NULL) {
+		retn = provision_keys_count > 0;
+		goto done;
+	}
+
+	pr_debug("Verifying provisioning control signature.\n");
+	if (sgx_get_key_hash(modulus, mrsigner))
+		goto done;
+	retn = have_signer(&provision_key_list, &provision_key_list_mutex,
+			   mrsigner);
+
+ done:
+	return retn;
+}
+
+/**
+ * sgx_signing_control - Signing control verification.
+ *
+ * This function returns a true value if signing control is active
+ * and the signature of the modulus of the signing key for an enclave
+ * is on the list of approved keys.
+ *
+ * Return:
+ *   0 No signing control is authorized.
+ *   1 Signing is authorized for the enclave.
+ */
+bool sgx_signing_control(uint8_t *modulus)
+{
+	bool retn = false;
+	uint8_t mrsigner[KEY_SIZE];
+
+	if (modulus == NULL) {
+		retn = signing_keys_count > 0;
+		goto done;
+	}
+
+	pr_debug("Verifying signing control signature.\n");
+	if (sgx_get_key_hash(modulus, mrsigner))
+		goto done;
+	retn = have_signer(&signing_key_list, &signing_key_list_mutex,
+			   mrsigner);
+
+ done:
+	return retn;
+}
+
+static int process_write_key(const char __user *buf, size_t datalen,
+			     unsigned int *keycnt, struct mutex *lock,
+			     struct list_head *keylist)
+{
+	ssize_t retn;
+
+	char *p, keybufr[KEY_SIZE*2 + 1], key[KEY_SIZE];
+
+	struct list_key *kp;
+
+	if (datalen != sizeof(keybufr)) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	memset(keybufr, '\0', sizeof(keybufr));
+	if (copy_from_user(keybufr, buf, datalen)) {
+		retn = -EFAULT;
+		goto done;
+	}
+
+	p = strchr(keybufr, '\n');
+	if (!p) {
+		retn = -EINVAL;
+		goto done;
+	}
+	*p = '\0';
+	if (hex2bin(key, keybufr, sizeof(key))) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	kp = kzalloc(sizeof(*kp), GFP_KERNEL);
+	if (!kp) {
+		retn = -ENOMEM;
+		goto done;
+	}
+	memcpy(kp->key, key, sizeof(kp->key));
+
+	mutex_lock(lock);
+	list_add_tail(&kp->list, keylist);
+	++*keycnt;
+	mutex_unlock(lock);
+
+	retn = datalen;
+	pr_debug("%s: Added key: %*phN\n", __func__, KEY_SIZE, key);
+
+ done:
+	return retn;
+}
+
+static int process_lock(const char __user *buf, size_t datalen, bool *lockfile)
+{
+	char bufr[5];
+
+	if (datalen != strlen("lock") + 1)
+		return 0;
+
+	memset(bufr, '\0', sizeof(bufr));
+	if (copy_from_user(bufr, buf, datalen-1))
+		return -EFAULT;
+	if ( strcmp(bufr, "lock") != 0 )
+		return 0;
+
+	*lockfile = true;
+	return datalen;
+}
+
+static int process_clear(const char __user *buf, size_t datalen, char *type,
+			 unsigned int *keycnt, struct mutex *lock,
+			 struct list_head *keylist)
+{
+	char bufr[6];
+	struct list_key *kp, *kp_tmp;
+
+	if (datalen != strlen("clear") + 1)
+		return 0;
+
+	memset(bufr, '\0', sizeof(bufr));
+	if (copy_from_user(bufr, buf, datalen-1))
+		return -EFAULT;
+	if ( strcmp(bufr, "clear") != 0 )
+		return 0;
+
+	mutex_lock(lock);
+	list_for_each_entry_safe(kp, kp_tmp, keylist, list) {
+		pr_debug("[%s]: Freeing signature: %*phN\n", __FILE__,
+			 KEY_SIZE, kp->key);
+		list_del(&kp->list);
+		kfree(kp);
+	}
+	*keycnt = 0;
+	mutex_unlock(lock);
+
+	pr_info("Cleared %s signatures.\n", type);
+	return datalen;
+}
+
+static int process_dump(const char __user *buf, size_t datalen, char *type,
+			struct mutex *lock, struct list_head *keylist)
+{
+	char bufr[5];
+	struct list_key *kp;
+
+	if (datalen != strlen("dump") + 1)
+		return 0;
+
+	memset(bufr, '\0', sizeof(bufr));
+	if (copy_from_user(bufr, buf, datalen-1))
+		return -EFAULT;
+	if ( strcmp(bufr, "dump") != 0 )
+		return 0;
+
+	pr_info("SGX %s keys:\n", type);
+	mutex_lock(lock);
+	list_for_each_entry(kp, keylist, list) {
+		pr_info("SGX %s: %*phN\n", type, KEY_SIZE, kp->key);
+	}
+	mutex_unlock(lock);
+
+	return datalen;
+}
+
+static int open_launch_keys(struct inode * inode, struct file * filp)
+{
+	if (!(filp->f_flags & O_WRONLY))
+		return -EACCES;
+	if (atomic_dec_and_test(&launch_keys_opencount))
+		return 0;
+	return -EBUSY;
+}
+
+static ssize_t write_launch_keys(struct file *file, const char __user *buf,
+				 size_t datalen, loff_t *ppos)
+{
+	ssize_t retn;
+
+	if (launch_keys_locked) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	if (*ppos != 0) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	retn = process_lock(buf, datalen, &launch_keys_locked);
+	if (retn != 0)
+		return retn;
+
+	retn = process_clear(buf, datalen, "launch control",
+			     &launch_keys_count, &launch_key_list_mutex,
+			     &launch_key_list);
+	if (retn != 0)
+		return retn;
+
+	retn = process_dump(buf, datalen, "lc", &launch_key_list_mutex,
+			    &launch_key_list);
+	if (retn != 0)
+		return retn;
+
+	retn = process_write_key(buf, datalen, &launch_keys_count,
+				 &launch_key_list_mutex, &launch_key_list);
+
+done:
+	return retn;
+}
+
+static int release_launch_keys(struct inode *inode, struct file *file)
+{
+	atomic_set(&launch_keys_opencount, 1);
+	return 0;
+}
+
+static const struct file_operations launch_keys_ops = {
+	.open = open_launch_keys,
+	.write = write_launch_keys,
+	.release = release_launch_keys,
+	.llseek = generic_file_llseek,
+};
+
+/* Provisioning control. */
+
+static int open_provision_keys(struct inode * inode, struct file * filp)
+{
+	if (!(filp->f_flags & O_WRONLY))
+		return -EACCES;
+	if (atomic_dec_and_test(&provision_keys_opencount))
+		return 0;
+	return -EBUSY;
+}
+
+static ssize_t write_provision_keys(struct file *file, const char __user *buf,
+				    size_t datalen, loff_t *ppos)
+{
+	ssize_t retn;
+
+	if (provision_keys_locked) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	if (*ppos != 0) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	retn = process_lock(buf, datalen, &provision_keys_locked);
+	if (retn != 0)
+		return retn;
+
+	retn = process_clear(buf, datalen, "provisioning control",
+			     &provision_keys_count, &provision_key_list_mutex,
+			     &provision_key_list);
+	if (retn != 0)
+		return retn;
+
+	retn = process_dump(buf, datalen, "pc", &provision_key_list_mutex,
+			    &provision_key_list);
+	if (retn != 0)
+		return retn;
+
+	retn = process_write_key(buf, datalen, &provision_keys_count,
+				 &provision_key_list_mutex,
+				 &provision_key_list);
+done:
+	return retn;
+}
+
+static int release_provision_keys(struct inode *inode, struct file *file)
+{
+	atomic_set(&provision_keys_opencount, 1);
+	return 0;
+}
+
+static const struct file_operations provision_keys_ops = {
+	.open = open_provision_keys,
+	.write = write_provision_keys,
+	.release = release_provision_keys,
+	.llseek = generic_file_llseek,
+};
+
+/*
+ * Signing control.
+ */
+
+static int open_signing_keys(struct inode * inode, struct file * filp)
+{
+	if (!(filp->f_flags & O_WRONLY))
+		return -EACCES;
+	if (atomic_dec_and_test(&signing_keys_opencount))
+		return 0;
+	return -EBUSY;
+}
+
+static ssize_t write_signing_keys(struct file *file, const char __user *buf,
+				  size_t datalen, loff_t *ppos)
+{
+	ssize_t retn;
+
+	if (signing_keys_locked) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	if (*ppos != 0) {
+		retn = -EINVAL;
+		goto done;
+	}
+
+	retn = process_lock(buf, datalen, &signing_keys_locked);
+	if (retn != 0)
+		return retn;
+
+	retn = process_clear(buf, datalen, "signing control",
+			     &signing_keys_count, &signing_key_list_mutex,
+			     &signing_key_list);
+	if (retn != 0)
+		return retn;
+
+	retn = process_dump(buf, datalen, "sc", &signing_key_list_mutex,
+			    &signing_key_list);
+	if (retn != 0)
+		return retn;
+
+	retn = process_write_key(buf, datalen, &signing_keys_count,
+				 &signing_key_list_mutex, &signing_key_list);
+done:
+	return retn;
+}
+
+static int release_signing_keys(struct inode *inode, struct file *file)
+{
+	atomic_set(&signing_keys_opencount, 1);
+	return 0;
+}
+
+static const struct file_operations signing_keys_ops = {
+	.open = open_signing_keys,
+	.write = write_signing_keys,
+	.release = release_signing_keys,
+	.llseek = generic_file_llseek,
+};
+
+int sgx_policy_fs(void)
+{
+	int retn = -1;
+
+	sgx_fs = securityfs_create_dir("sgx", NULL);
+	if(IS_ERR(sgx_fs)) {
+		retn = PTR_ERR(sgx_fs);
+		goto err;
+	}
+
+	launch_keys = securityfs_create_file("launch_keys", S_IWUSR | S_IRUSR,
+					     sgx_fs, NULL, &launch_keys_ops);
+	if (IS_ERR(launch_keys)) {
+		retn = PTR_ERR(launch_keys);
+		goto err;
+	}
+
+	provision_keys = securityfs_create_file("provisioning_keys",
+						S_IWUSR | S_IRUSR,
+						sgx_fs, NULL,
+						&provision_keys_ops);
+	if (IS_ERR(provision_keys)) {
+		retn = PTR_ERR(provision_keys);
+		goto err;
+	}
+
+	signing_keys = securityfs_create_file("signing_keys",
+					      S_IWUSR | S_IRUSR,
+					      sgx_fs, NULL,
+					      &signing_keys_ops);
+	if (IS_ERR(signing_keys)) {
+		retn = PTR_ERR(signing_keys);
+		goto err;
+	}
+
+	return 0;
+
+ err:
+	securityfs_remove(launch_keys);
+	securityfs_remove(provision_keys);
+	securityfs_remove(signing_keys);
+	securityfs_remove(sgx_fs);
+	return retn;
+}
+
+void sgx_policy_fs_remove(void)
+{
+	struct list_key *kp, *kp_tmp;
+
+	mutex_lock(&launch_key_list_mutex);
+	list_for_each_entry_safe(kp, kp_tmp, &launch_key_list, list) {
+		list_del(&kp->list);
+		kfree(kp);
+	}
+	mutex_unlock(&launch_key_list_mutex);
+
+	mutex_lock(&provision_key_list_mutex);
+	list_for_each_entry_safe(kp, kp_tmp, &provision_key_list, list) {
+		list_del(&kp->list);
+		kfree(kp);
+	}
+	mutex_unlock(&provision_key_list_mutex);
+
+	mutex_lock(&signing_key_list_mutex);
+	list_for_each_entry_safe(kp, kp_tmp, &signing_key_list, list) {
+		list_del(&kp->list);
+		kfree(kp);
+	}
+	mutex_unlock(&signing_key_list_mutex);
+
+	securityfs_remove(launch_keys);
+	securityfs_remove(provision_keys);
+	securityfs_remove(signing_keys);
+	securityfs_remove(sgx_fs);
+}
diff --git a/arch/x86/kernel/cpu/sgx/main.c b/arch/x86/kernel/cpu/sgx/main.c
index 07adb35c260b..c5a9df27702c 100644
--- a/arch/x86/kernel/cpu/sgx/main.c
+++ b/arch/x86/kernel/cpu/sgx/main.c
@@ -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));
diff --git a/arch/x86/kernel/cpu/sgx/sgx.h b/arch/x86/kernel/cpu/sgx/sgx.h
index 8a1dff1e5e8a..50fc9ee9d556 100644
--- a/arch/x86/kernel/cpu/sgx/sgx.h
+++ b/arch/x86/kernel/cpu/sgx/sgx.h
@@ -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 */

[-- Attachment #3: jarkko-master-SFLC.patch.asc --]
[-- Type: text/plain, Size: 455 bytes --]

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

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-18 17:10 ` [PATCH v20 00/28] Intel SGX1 support Dr. Greg
@ 2019-04-18 17:24   ` Dave Hansen
  2019-04-19 16:24     ` Dr. Greg
  2019-04-18 18:01   ` Dave Hansen
  2019-04-18 18:07   ` Andy Lutomirski
  2 siblings, 1 reply; 318+ messages in thread
From: Dave Hansen @ 2019-04-18 17:24 UTC (permalink / raw)
  To: Dr. Greg, Jarkko Sakkinen
  Cc: torvalds, linux-kernel, x86, linux-sgx, akpm,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

On 4/18/19 10:10 AM, Dr. Greg wrote:
> 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.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-18 17:10 ` [PATCH v20 00/28] Intel SGX1 support Dr. Greg
  2019-04-18 17:24   ` Dave Hansen
@ 2019-04-18 18:01   ` Dave Hansen
  2019-04-19 14:17     ` Dr. Greg
  2019-04-18 18:07   ` Andy Lutomirski
  2 siblings, 1 reply; 318+ messages in thread
From: Dave Hansen @ 2019-04-18 18:01 UTC (permalink / raw)
  To: Dr. Greg, Jarkko Sakkinen
  Cc: torvalds, linux-kernel, x86, linux-sgx, akpm,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

On 4/18/19 10:10 AM, Dr. Greg wrote:
> 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?

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-18 17:10 ` [PATCH v20 00/28] Intel SGX1 support Dr. Greg
  2019-04-18 17:24   ` Dave Hansen
  2019-04-18 18:01   ` Dave Hansen
@ 2019-04-18 18:07   ` Andy Lutomirski
  2 siblings, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-18 18:07 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Dave Hansen, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Thomas Gleixner, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Andrew Lutomirski, Huang, Kai, David Rientjes

On Thu, Apr 18, 2019 at 10:11 AM Dr. Greg <greg@enjellic.com> wrote:
>
> 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.
>
> > 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.

"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.

>
> 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.]

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

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

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

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

* Re: [PATCH v20 16/28] x86/sgx: Add provisioning
  2019-04-17 10:39 ` [PATCH v20 16/28] x86/sgx: Add provisioning Jarkko Sakkinen
@ 2019-04-19  3:06   ` Huang, Kai
  2019-04-23 14:33     ` Jarkko Sakkinen
  2019-04-24  1:34   ` Jethro Beekman
  1 sibling, 1 reply; 318+ messages in thread
From: Huang, Kai @ 2019-04-19  3:06 UTC (permalink / raw)
  To: jarkko.sakkinen, linux-kernel, linux-sgx, x86
  Cc: Svahn, Kai, nhorman, jmorris, Christopherson, Sean J, josh, tglx,
	Ayoun, Serge, Huang, Haitao, linux-security-module, akpm,
	npmccallum, rientjes, luto, Katz-zamir, Shay, Hansen, Dave, bp,
	serge, andriy.shevchenko

On Wed, 2019-04-17 at 13:39 +0300, Jarkko Sakkinen wrote:
> 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;
> 
Should be params.attribute_fd = prov_fd;

Thanks,
-Kai

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-18 18:01   ` Dave Hansen
@ 2019-04-19 14:17     ` Dr. Greg
  2019-04-19 14:25       ` Dave Hansen
  2019-04-19 15:27       ` Andy Lutomirski
  0 siblings, 2 replies; 318+ messages in thread
From: Dr. Greg @ 2019-04-19 14:17 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Jarkko Sakkinen, torvalds, linux-kernel, x86, linux-sgx, akpm,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

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

Good morning to everyone.

> On 4/18/19 10:10 AM, Dr. Greg wrote:
> > 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?

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: greg@enjellic.com
------------------------------------------------------------------------------
"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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 14:17     ` Dr. Greg
@ 2019-04-19 14:25       ` Dave Hansen
  2019-04-19 15:27       ` Andy Lutomirski
  1 sibling, 0 replies; 318+ messages in thread
From: Dave Hansen @ 2019-04-19 14:25 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Jarkko Sakkinen, torvalds, linux-kernel, x86, linux-sgx, akpm,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

On 4/19/19 7:17 AM, Dr. Greg wrote:
> 3.) The approach we propose addresses these issues while imposing no
> functional limitations on how Linux platform owners can use enclave
> technology.

Let's say v20 gets merged.  Is there any reason your approach can not be
rebased on top of that code, reviewed and merged later?

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 14:17     ` Dr. Greg
  2019-04-19 14:25       ` Dave Hansen
@ 2019-04-19 15:27       ` Andy Lutomirski
  2019-04-19 19:38         ` Jethro Beekman
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-19 15:27 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Dave Hansen, Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Thomas Gleixner, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Andrew Lutomirski, Huang, Kai, David Rientjes

> On Apr 19, 2019, at 7:17 AM, Dr. Greg <greg@enjellic.com> wrote:
>
> 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?

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-18 17:24   ` Dave Hansen
@ 2019-04-19 16:24     ` Dr. Greg
  2019-04-19 16:39       ` Dave Hansen
  0 siblings, 1 reply; 318+ messages in thread
From: Dr. Greg @ 2019-04-19 16:24 UTC (permalink / raw)
  To: Dave Hansen
  Cc: Jarkko Sakkinen, torvalds, linux-kernel, x86, linux-sgx, akpm,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

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

Good morning again.

> On 4/18/19 10:10 AM, Dr. Greg wrote:
> > 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.

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

> 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: greg@enjellic.com
------------------------------------------------------------------------------
"If you get to thinkin' you're a person of some influence, try
 orderin' somebody else's dog around."
                                -- Cowboy Wisdom

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 16:24     ` Dr. Greg
@ 2019-04-19 16:39       ` Dave Hansen
  0 siblings, 0 replies; 318+ messages in thread
From: Dave Hansen @ 2019-04-19 16:39 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Jarkko Sakkinen, torvalds, linux-kernel, x86, linux-sgx, akpm,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

On 4/19/19 9:24 AM, Dr. Greg wrote:
>> 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.

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 15:27       ` Andy Lutomirski
@ 2019-04-19 19:38         ` Jethro Beekman
  2019-04-19 20:39           ` Thomas Gleixner
  0 siblings, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-04-19 19:38 UTC (permalink / raw)
  To: Andy Lutomirski, Dr. Greg
  Cc: Dave Hansen, Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Thomas Gleixner, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On 2019-04-19 08:27, Andy Lutomirski wrote:
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 19:38         ` Jethro Beekman
@ 2019-04-19 20:39           ` Thomas Gleixner
  2019-04-19 20:46             ` Jethro Beekman
  0 siblings, 1 reply; 318+ messages in thread
From: Thomas Gleixner @ 2019-04-19 20:39 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Andy Lutomirski, Dr. Greg, Dave Hansen, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, 19 Apr 2019, Jethro Beekman wrote:

> On 2019-04-19 08:27, Andy Lutomirski wrote:
> > 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


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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 20:39           ` Thomas Gleixner
@ 2019-04-19 20:46             ` Jethro Beekman
  2019-04-19 20:50               ` Thomas Gleixner
  2019-04-19 21:05               ` Jethro Beekman
  0 siblings, 2 replies; 318+ messages in thread
From: Jethro Beekman @ 2019-04-19 20:46 UTC (permalink / raw)
  To: Thomas Gleixner
  Cc: Andy Lutomirski, Dr. Greg, Dave Hansen, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 2019-04-19 13:39, Thomas Gleixner wrote:
> On Fri, 19 Apr 2019, Jethro Beekman wrote:
> 
>> On 2019-04-19 08:27, Andy Lutomirski wrote:
>>> 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.

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 20:46             ` Jethro Beekman
@ 2019-04-19 20:50               ` Thomas Gleixner
  2019-04-19 20:54                 ` Jethro Beekman
  2019-04-19 21:05               ` Jethro Beekman
  1 sibling, 1 reply; 318+ messages in thread
From: Thomas Gleixner @ 2019-04-19 20:50 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Andy Lutomirski, Dr. Greg, Dave Hansen, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, 19 Apr 2019, Jethro Beekman wrote:
> On 2019-04-19 13:39, Thomas Gleixner wrote:
> > On Fri, 19 Apr 2019, Jethro Beekman wrote:
> > 
> >> On 2019-04-19 08:27, Andy Lutomirski wrote:
> >>> 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.
> 
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 20:50               ` Thomas Gleixner
@ 2019-04-19 20:54                 ` Jethro Beekman
  2019-04-19 21:15                   ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-04-19 20:54 UTC (permalink / raw)
  To: Thomas Gleixner
  Cc: Andy Lutomirski, Dr. Greg, Dave Hansen, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 2019-04-19 13:50, Thomas Gleixner wrote:
> On Fri, 19 Apr 2019, Jethro Beekman wrote:
>> On 2019-04-19 13:39, Thomas Gleixner wrote:
>>> On Fri, 19 Apr 2019, Jethro Beekman wrote:
>>>
>>>> On 2019-04-19 08:27, Andy Lutomirski wrote:
>>>>> 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.
>>
>> 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?

> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 20:46             ` Jethro Beekman
  2019-04-19 20:50               ` Thomas Gleixner
@ 2019-04-19 21:05               ` Jethro Beekman
  1 sibling, 0 replies; 318+ messages in thread
From: Jethro Beekman @ 2019-04-19 21:05 UTC (permalink / raw)
  To: Thomas Gleixner
  Cc: Andy Lutomirski, Dr. Greg, Dave Hansen, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 2019-04-19 13:46, Jethro Beekman wrote:
> On 2019-04-19 13:39, Thomas Gleixner wrote:
>> On Fri, 19 Apr 2019, Jethro Beekman wrote:
>>
>>> On 2019-04-19 08:27, Andy Lutomirski wrote:
>>>> 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.
> 
> 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

Actually, I don't think you even need to include PAGEINFO.SECINFO.FLAGS,
you just need to ensure PROT_WRITE. Regular page table checks take care
of PAGEINFO.SECINFO.FLAGS.

--
Jethro Beekman | Fortanix

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 20:54                 ` Jethro Beekman
@ 2019-04-19 21:15                   ` Andy Lutomirski
  2019-04-19 21:19                     ` Jethro Beekman
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-19 21:15 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Thomas Gleixner, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes





> On Apr 19, 2019, at 1:54 PM, Jethro Beekman <jethro@fortanix.com> wrote:
> 
>> On 2019-04-19 13:50, Thomas Gleixner wrote:
>>> On Fri, 19 Apr 2019, Jethro Beekman wrote:
>>>> On 2019-04-19 13:39, Thomas Gleixner wrote:
>>>>> On Fri, 19 Apr 2019, Jethro Beekman wrote:
>>>>> 
>>>>>> On 2019-04-19 08:27, Andy Lutomirski wrote:
>>>>>> 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.
>>> 
>>> 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?

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.

> 
>> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:15                   ` Andy Lutomirski
@ 2019-04-19 21:19                     ` Jethro Beekman
  2019-04-19 21:31                       ` Andy Lutomirski
  2019-04-19 21:34                       ` Thomas Gleixner
  0 siblings, 2 replies; 318+ messages in thread
From: Jethro Beekman @ 2019-04-19 21:19 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Thomas Gleixner, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes



Jethro Beekman | Fortanix

On 2019-04-19 14:15, Andy Lutomirski wrote:
> 
> 
> 
> 
>> On Apr 19, 2019, at 1:54 PM, Jethro Beekman <jethro@fortanix.com> wrote:
>>
>>> On 2019-04-19 13:50, Thomas Gleixner wrote:
>>>> On Fri, 19 Apr 2019, Jethro Beekman wrote:
>>>>> On 2019-04-19 13:39, Thomas Gleixner wrote:
>>>>>> On Fri, 19 Apr 2019, Jethro Beekman wrote:
>>>>>>
>>>>>>> On 2019-04-19 08:27, Andy Lutomirski wrote:
>>>>>>> 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.
>>>>
>>>> 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?
> 
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:19                     ` Jethro Beekman
@ 2019-04-19 21:31                       ` Andy Lutomirski
  2019-04-19 21:35                         ` Jethro Beekman
  2019-04-19 21:34                       ` Thomas Gleixner
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-19 21:31 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Thomas Gleixner, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes



> On Apr 19, 2019, at 2:19 PM, Jethro Beekman <jethro@fortanix.com> wrote:
> 
>> .
>> 
>> 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.
> 
> 

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.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:19                     ` Jethro Beekman
  2019-04-19 21:31                       ` Andy Lutomirski
@ 2019-04-19 21:34                       ` Thomas Gleixner
  1 sibling, 0 replies; 318+ messages in thread
From: Thomas Gleixner @ 2019-04-19 21:34 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Andy Lutomirski, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

[-- Attachment #1: Type: text/plain, Size: 1134 bytes --]

On Fri, 19 Apr 2019, Jethro Beekman wrote:
> On 2019-04-19 14:15, Andy Lutomirski wrote:
> > 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.

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. Andy clearly made a proposal which solves it in a proper
way.

Thanks,

	tglx

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:31                       ` Andy Lutomirski
@ 2019-04-19 21:35                         ` Jethro Beekman
  2019-04-19 21:38                           ` Thomas Gleixner
  0 siblings, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-04-19 21:35 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Thomas Gleixner, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On 2019-04-19 14:31, Andy Lutomirski wrote:
> 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


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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:35                         ` Jethro Beekman
@ 2019-04-19 21:38                           ` Thomas Gleixner
  2019-04-19 21:56                             ` Jethro Beekman
  0 siblings, 1 reply; 318+ messages in thread
From: Thomas Gleixner @ 2019-04-19 21:38 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Andy Lutomirski, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

[-- Attachment #1: Type: text/plain, Size: 859 bytes --]

On Fri, 19 Apr 2019, Jethro Beekman wrote:
> On 2019-04-19 14:31, Andy Lutomirski wrote:
> > 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.

> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:38                           ` Thomas Gleixner
@ 2019-04-19 21:56                             ` Jethro Beekman
  2019-04-20  5:42                               ` Thomas Gleixner
  2019-04-22 16:26                               ` Andy Lutomirski
  0 siblings, 2 replies; 318+ messages in thread
From: Jethro Beekman @ 2019-04-19 21:56 UTC (permalink / raw)
  To: Thomas Gleixner
  Cc: Andy Lutomirski, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On 2019-04-19 14:34, Thomas Gleixner wrote:
> 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

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:56                             ` Jethro Beekman
@ 2019-04-20  5:42                               ` Thomas Gleixner
  2019-04-20 16:02                                 ` Dr. Greg
  2019-04-22 16:26                               ` Andy Lutomirski
  1 sibling, 1 reply; 318+ messages in thread
From: Thomas Gleixner @ 2019-04-20  5:42 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Andy Lutomirski, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Fri, 19 Apr 2019, Jethro Beekman wrote:
> On 2019-04-19 14:34, Thomas Gleixner wrote:
> > 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

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-20  5:42                               ` Thomas Gleixner
@ 2019-04-20 16:02                                 ` Dr. Greg
  2019-04-22 15:01                                   ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Dr. Greg @ 2019-04-20 16:02 UTC (permalink / raw)
  To: Thomas Gleixner
  Cc: Jethro Beekman, Andy Lutomirski, Andy Lutomirski, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

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

Good morning/weekend to everyone.

> On Fri, 19 Apr 2019, Jethro Beekman wrote:
> > On 2019-04-19 14:34, Thomas Gleixner wrote:
> > > 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

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

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.

> 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: greg@enjellic.com
------------------------------------------------------------------------------
"Simplicity is prerequisite for reliability."
                                -- Edsger W. Dijkstra

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-20 16:02                                 ` Dr. Greg
@ 2019-04-22 15:01                                   ` Sean Christopherson
  2019-04-22 16:24                                     ` Dr. Greg
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-22 15:01 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Thomas Gleixner, Jethro Beekman, Andy Lutomirski,
	Andy Lutomirski, Dave Hansen, Jarkko Sakkinen, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Sat, Apr 20, 2019 at 11:02:47AM -0500, Dr. Greg wrote:
> 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.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-22 15:01                                   ` Sean Christopherson
@ 2019-04-22 16:24                                     ` Dr. Greg
  2019-04-22 16:48                                       ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Dr. Greg @ 2019-04-22 16:24 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Dr. Greg, Thomas Gleixner, Jethro Beekman, Andy Lutomirski,
	Andy Lutomirski, Dave Hansen, Jarkko Sakkinen, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

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

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

> On Sat, Apr 20, 2019 at 11:02:47AM -0500, Dr. Greg wrote:
> > 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: greg@enjellic.com
------------------------------------------------------------------------------
"You and Uncle Pete drank the whole thing?  That was a $250.00 bottle
 of whisky.

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-19 21:56                             ` Jethro Beekman
  2019-04-20  5:42                               ` Thomas Gleixner
@ 2019-04-22 16:26                               ` Andy Lutomirski
  2019-04-23 21:15                                 ` Jethro Beekman
  2019-05-10 17:23                                 ` Xing, Cedric
  1 sibling, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-22 16:26 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Thomas Gleixner, Andy Lutomirski, Dr. Greg, Dave Hansen,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

> On Apr 19, 2019, at 2:56 PM, Jethro Beekman <jethro@fortanix.com> wrote:
>
>> On 2019-04-19 14:34, Thomas Gleixner wrote:
>> 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
>
> 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!

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-22 16:24                                     ` Dr. Greg
@ 2019-04-22 16:48                                       ` Sean Christopherson
  2019-04-22 16:55                                         ` Linus Torvalds
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-22 16:48 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Thomas Gleixner, Jethro Beekman, Andy Lutomirski,
	Andy Lutomirski, Dave Hansen, Jarkko Sakkinen, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Mon, Apr 22, 2019 at 11:24:11AM -0500, Dr. Greg wrote:
> On Mon, Apr 22, 2019 at 08:01:19AM -0700, Sean Christopherson wrote:
> 
> Good morning to everyone, I hope the week is starting well.
> 
> > On Sat, Apr 20, 2019 at 11:02:47AM -0500, Dr. Greg wrote:
> > > 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.

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.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-22 16:48                                       ` Sean Christopherson
@ 2019-04-22 16:55                                         ` Linus Torvalds
  2019-04-22 17:17                                           ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Linus Torvalds @ 2019-04-22 16:55 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Dr. Greg, Thomas Gleixner, Jethro Beekman, Andy Lutomirski,
	Andy Lutomirski, Dave Hansen, Jarkko Sakkinen, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Mon, Apr 22, 2019 at 9:48 AM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-22 16:55                                         ` Linus Torvalds
@ 2019-04-22 17:17                                           ` Sean Christopherson
  2019-04-23  9:11                                             ` Dr. Greg
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-22 17:17 UTC (permalink / raw)
  To: Linus Torvalds
  Cc: Dr. Greg, Thomas Gleixner, Jethro Beekman, Andy Lutomirski,
	Andy Lutomirski, Dave Hansen, Jarkko Sakkinen, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Mon, Apr 22, 2019 at 09:55:47AM -0700, Linus Torvalds wrote:
> On Mon, Apr 22, 2019 at 9:48 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > 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".

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.

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

* [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (28 preceding siblings ...)
  2019-04-18 17:10 ` [PATCH v20 00/28] Intel SGX1 support Dr. Greg
@ 2019-04-22 20:42 ` Cedric Xing
  2019-04-22 22:05   ` Sean Christopherson
                     ` (5 more replies)
  2019-04-22 20:42 ` [RFC PATCH v1 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
                   ` (3 subsequent siblings)
  33 siblings, 6 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-22 20:42 UTC (permalink / raw)
  To: linux-sgx; +Cc: cedric.xing

The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp, which prohibits enclaves from allocating space on the untrusted stack. However, there are existing enclaves (e.g. those built with current Intel SGX SDK libraries) relying on the untrusted stack for passing parameters to untrusted functions (aka. o-calls), which requires allocating space on the untrusted stack by enclaves. And given its simplicity and convenience, it could be desired by future SGX applications as well.

This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto the untrusted stack by decrementing the untrusted %rsp. Additionally, this new __vdso_sgx_enter_enclave() will take one more parameter - a callback function, to be invoked upon all enclave exits (both AEX and normal exits). The callback function will be given the value of %rsp left off by the enclave, so that data "pushed" by the enclave (if any) could be addressed/accessed. Please note that the callback function is optional, and if not supplied (i.e. null), __vdso_sgx_enter_enclave() will just return (i.e. behave the same as the current implementation) after the enclave exits (or AEX due to exceptions).

The SGX selftest is augmented to test out the new callback interface, and to serve as a simple example to showcase how to use the callback interface in practice.

Cedric Xing (3):
  selftests/x86: Fixed Makefile for SGX selftest
  x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing
    on untrusted stack
  selftests/x86: Augment SGX selftest to test new
    __vdso_sgx_enter_enclave() and its callback interface

 arch/x86/entry/vdso/vsgx_enter_enclave.S   | 156 ++++++++++++---------
 arch/x86/include/uapi/asm/sgx.h            |  14 +-
 tools/testing/selftests/x86/Makefile       |  12 +-
 tools/testing/selftests/x86/sgx/Makefile   |  45 +++---
 tools/testing/selftests/x86/sgx/main.c     | 123 +++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 +++++-
 6 files changed, 264 insertions(+), 126 deletions(-)

-- 
2.17.1


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

* [RFC PATCH v1 1/3] selftests/x86: Fixed Makefile for SGX selftest
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (29 preceding siblings ...)
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
@ 2019-04-22 20:42 ` Cedric Xing
  2019-04-23  0:37   ` Cedric Xing
  2019-04-22 20:42 ` [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
                   ` (2 subsequent siblings)
  33 siblings, 1 reply; 318+ messages in thread
From: Cedric Xing @ 2019-04-22 20:42 UTC (permalink / raw)
  To: linux-sgx; +Cc: cedric.xing

The original x86/sgx/Makefile doesn't work when 'x86/sgx' is specified as the test target. This patch fixes that problem, along with minor changes to the dependencies between 'x86' and 'x86/sgx' in selftests/x86/Makefile.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/Makefile     | 12 +++----
 tools/testing/selftests/x86/sgx/Makefile | 45 +++++++++---------------
 2 files changed, 22 insertions(+), 35 deletions(-)

diff --git a/tools/testing/selftests/x86/Makefile b/tools/testing/selftests/x86/Makefile
index 4fc9a42f56ea..1294c5f5b6ca 100644
--- a/tools/testing/selftests/x86/Makefile
+++ b/tools/testing/selftests/x86/Makefile
@@ -70,11 +70,11 @@ 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 $@;	\
+all_64: | $(SUBDIRS_64)
+	@for DIR in $|; do					\
+		BUILD_TARGET=$(OUTPUT)/$$DIR;			\
+		mkdir $$BUILD_TARGET  -p;			\
+		$(MAKE) OUTPUT=$$BUILD_TARGET -C $$DIR $@;	\
 	done
 
 EXTRA_CLEAN := $(BINARIES_32) $(BINARIES_64)
@@ -90,7 +90,7 @@ ifeq ($(CAN_BUILD_I386)$(CAN_BUILD_X86_64),01)
 all: warn_32bit_failure
 
 warn_32bit_failure:
-	@echo "Warning: you seem to have a broken 32-bit build" 2>&1; 	\
+	@echo "Warning: you seem to have a broken 32-bit build" 2>&1;	\
 	echo "environment.  This will reduce test coverage of 64-bit" 2>&1; \
 	echo "kernels.  If you are using a Debian-like distribution," 2>&1; \
 	echo "try:"; 2>&1; \
diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 1fd6f2708e81..3af15d7c8644 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -2,47 +2,34 @@ top_srcdir = ../../../../..
 
 include ../../lib.mk
 
-HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
-ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
+ifeq ($(shell $(CC) -dumpmachine | cut --delimiter=- -f1),x86_64)
+all: all_64
+endif
+
+HOST_CFLAGS := -Wall -Werror -g $(INCLUDES)
+ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIE \
 	       -fno-stack-protector -mrdrnd $(INCLUDES)
 
 TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
-$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
-		      $(OUTPUT)/encl_piggy.o
+$(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
 	$(CC) $(HOST_CFLAGS) -o $@ $^
 
-$(OUTPUT)/main.o: main.c
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
+$(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
-$(OUTPUT)/sgx_call.o: sgx_call.S
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
-	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
-
-$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
+$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
 	objcopy --remove-section=.got.plt -O binary $< $@
 
-$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
-	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
+$(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
 
-$(OUTPUT)/encl.o: encl.c
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
-	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+$(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
+	$^ $@
 
 $(OUTPUT)/sgxsign: sgxsign.c
 	$(CC) -o $@ $< -lcrypto
 
-EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
-	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
-	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
-	       $(OUTPUT)/sgxsign
-
-.PHONY: clean
+EXTRA_CLEAN := $(TEST_CUSTOM_PROGS) $(addprefix $(OUTPUT)/,	\
+		encl.elf encl.bin encl.ss encl_piggy.o sgxsign)
-- 
2.17.1


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

* [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (30 preceding siblings ...)
  2019-04-22 20:42 ` [RFC PATCH v1 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
@ 2019-04-22 20:42 ` Cedric Xing
  2019-04-22 22:26   ` Sean Christopherson
                     ` (3 more replies)
  2019-04-22 20:42 ` [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
  2019-04-23 11:56 ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
  33 siblings, 4 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-22 20:42 UTC (permalink / raw)
  To: linux-sgx; +Cc: cedric.xing

The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp, which prohibits enclaves from allocating and passing parameters for untrusted function calls (aka. o-calls).

This patch addresses the problem above by introducing a new ABI that preserves %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame using %rbp so that enclaves are allowed to allocate space on the untrusted stack by decrementing %rsp. Please note that the stack space allocated in such way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after __vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has been changed to take a callback function as an optional parameter, which if supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave eXit) and normal exits), with the value of %rsp left off by the enclave as a parameter to the callback.

Here's the summary of API/ABI changes in this patch. More details could be found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
* 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo' because it is filled upon both AEX (i.e. exceptions) and normal enclave exits.
* __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in the previous implementation).
* __vdso_sgx_enter_enclave() takes one more parameter - a callback function to be invoked upon enclave exits. This callback is optional, and if not supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave exits (same behavior as previous implementation).
* The callback function is given as a parameter the value of %rsp at enclave exit to address data "pushed" by the enclave. A positive value returned by the callback will be treated as an ENCLU leaf for re-entering the enclave, while a zero or negative value will be passed through as the return value of __vdso_sgx_enter_enclave() to its caller. It's also safe to leave callback by longjmp() or by throwing a C++ exception.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 arch/x86/entry/vdso/vsgx_enter_enclave.S | 156 ++++++++++++++---------
 arch/x86/include/uapi/asm/sgx.h          |  14 +-
 2 files changed, 100 insertions(+), 70 deletions(-)

diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
index fe0bf6671d6d..210f4366374a 100644
--- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
+++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
@@ -14,88 +14,118 @@
 .code64
 .section .text, "ax"
 
-#ifdef SGX_KERNEL_DOC
 /**
  * __vdso_sgx_enter_enclave() - Enter an SGX enclave
  *
  * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
- * @tcs:	**IN \%rbx** - TCS, must be non-NULL
- * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
+ * @tcs:	**IN 0x08(\%rsp)** - TCS, must be non-NULL
+ * @ex_info:	**IN 0x10(\%rsp)** - Optional 'struct sgx_enclave_exinfo'
+ *				     pointer
+ * @callback:	**IN 0x18(\%rsp)** - Optional callback function to be called on
+ *				     enclave exit or exception
  *
  * Return:
  *  **OUT \%eax** -
- *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
- *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
+ *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is not
+ *  allowed, %-EFAULT if ENCLU or the enclave faults, or a non-positive value
+ *  returned from ``callback`` (if one is supplied).
  *
  * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
- * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
- * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
- * the return value passed via ``%eax``.  All registers except ``%rsp`` must
- * be treated as volatile from the caller's perspective, including but not
- * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
- * being run **must** preserve the untrusted ``%rsp`` and stack.
+ * x86-64 ABI, i.e. cannot be called from standard C code. As noted above,
+ * input parameters must be passed via ``%eax``, ``8(%rsp)``, ``0x10(%rsp)`` and
+ * ``0x18(%rsp)``, with the return value passed via ``%eax``. All other registers
+ * will be passed through to the enclave as is. All registers except ``%rbp``
+ * must be treated as volatile from the caller's perspective, including but not
+ * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely, the enclave being
+ * run **must** preserve the untrusted ``%rbp``.
+ *
+ * ``callback`` has the following signature:
+ * int callback(long rdi, long rsi, long rdx,
+ *		struct sgx_enclave_exinfo *ex_info, long r8, long r9,
+ *		void *tcs, long ursp);
+ * ``callback`` **shall** follow x86_64 ABI. All GPRs **except** ``%rax``, ``%rbx``
+ * and ``rcx`` are passed through to ``callback``. ``%rdi``, ``%rsi``, ``%rdx``,
+ * ``%r8``, ``%r9``, along with the value of ``%rsp`` when the enclave exited/excepted,
+ * can be accessed directly as input parameters, while other GPRs can be
+ * accessed in assembly if needed.
+ * A positive value returned from ``callback`` will be treated as an ENCLU leaf
+ * (e.g. EENTER/ERESUME) to reenter the enclave, while 0 or a negative return
+ * value will be passed back to the caller of __vdso_sgx_enter_enclave().
+ * It is also **safe** to ``longjmp()`` out of ``callback``.
  */
-__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
-			 struct sgx_enclave_exception *ex_info)
-{
-	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
-		return -EINVAL;
-
-	if (!tcs)
-		return -EINVAL;
-
-	try {
-		ENCLU[leaf];
-	} catch (exception) {
-		if (e)
-			*e = exception;
-		return -EFAULT;
-	}
-
-	return 0;
-}
-#endif
 ENTRY(__vdso_sgx_enter_enclave)
-	/* EENTER <= leaf <= ERESUME */
+	/* Prolog */
+	.cfi_startproc
+	push	%rbp
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbp, 0
+	mov	%rsp, %rbp
+	.cfi_def_cfa_register	%rbp
+
+1:	/* EENTER <= leaf <= ERESUME */
 	cmp	$0x2, %eax
-	jb	bad_input
-
+	jb	6f
 	cmp	$0x3, %eax
-	ja	bad_input
+	ja	6f
 
-	/* TCS must be non-NULL */
-	test	%rbx, %rbx
-	je	bad_input
+	/* Load TCS and AEP */
+	mov	0x10(%rbp), %rbx
+	lea	2f(%rip), %rcx
 
-	/* Save @exception_info */
-	push	%rcx
-
-	/* Load AEP for ENCLU */
-	lea	1f(%rip),  %rcx
-1:	enclu
-
-	add	$0x8, %rsp
-	xor	%eax, %eax
-	ret
-
-bad_input:
-	mov     $(-EINVAL), %rax
-	ret
-
-.pushsection .fixup, "ax"
-	/* Re-load @exception_info and fill it (if it's non-NULL) */
-2:	pop	%rcx
-	test    %rcx, %rcx
-	je      3f
+	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
+2:	enclu
 
+	/* EEXIT path */
+	xor	%ebx, %ebx
+3:	mov	0x18(%rbp), %rcx
+	jrcxz	4f
 	mov	%eax, EX_LEAF(%rcx)
-	mov	%di,  EX_TRAPNR(%rcx)
-	mov	%si,  EX_ERROR_CODE(%rcx)
+	jnc	4f
+	mov	%di, EX_TRAPNR(%rcx)
+	mov	%si, EX_ERROR_CODE(%rcx)
 	mov	%rdx, EX_ADDRESS(%rcx)
-3:	mov	$(-EFAULT), %rax
+
+4:	/* Call *callback if supplied */
+	mov	0x20(%rbp), %rax
+	test	%rax, %rax
+	cmovz	%rbx, %rax
+	jz	7f
+	/* Align stack and clear RFLAGS.DF per x86_64 ABI */
+	mov	%rsp, %rbx
+	and	$-0x10, %rsp
+	cld
+	/* Parameters for *callback */
+	push	%rbx
+	push	0x10(%rbp)
+	/* Call via retpoline */
+	call	40f
+	/* Cleanup stack */
+	mov	%rbx, %rsp
+	jmp	1b
+40:	/* retpoline */
+	call	42f
+41:	pause
+	lfence
+	jmp	41b
+42:	mov	%rax, (%rsp)
+	ret
+
+5:	/* Exception path */
+	mov	$-EFAULT, %ebx
+	stc
+	jmp	3b
+
+6:	/* Unsupported ENCLU leaf */
+	cmp	$0, %eax
+	jle	7f
+	mov	$-EINVAL, %eax
+
+7:	/* Epilog */
+	leave
+	.cfi_def_cfa		%rsp, 8
 	ret
-.popsection
+	.cfi_endproc
 
-_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
+_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
 
 ENDPROC(__vdso_sgx_enter_enclave)
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 9ed690a38c70..50d2b5143e5e 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -24,7 +24,7 @@
 
 /**
  * struct sgx_enclave_create - parameter structure for the
- *                             %SGX_IOC_ENCLAVE_CREATE ioctl
+ *			       %SGX_IOC_ENCLAVE_CREATE ioctl
  * @src:	address for the SECS page data
  */
 struct sgx_enclave_create  {
@@ -33,7 +33,7 @@ struct sgx_enclave_create  {
 
 /**
  * struct sgx_enclave_add_page - parameter structure for the
- *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
+ *				 %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
  * @addr:	address within the ELRANGE
  * @src:	address for the page data
  * @secinfo:	address for the SECINFO data
@@ -49,7 +49,7 @@ struct sgx_enclave_add_page {
 
 /**
  * struct sgx_enclave_init - parameter structure for the
- *                           %SGX_IOC_ENCLAVE_INIT ioctl
+ *			     %SGX_IOC_ENCLAVE_INIT ioctl
  * @sigstruct:	address for the SIGSTRUCT data
  */
 struct sgx_enclave_init {
@@ -66,16 +66,16 @@ struct sgx_enclave_set_attribute {
 };
 
 /**
- * struct sgx_enclave_exception - structure to report exceptions encountered in
- *				  __vdso_sgx_enter_enclave()
+ * struct sgx_enclave_exinfo - structure to report exceptions encountered in
+ *			       __vdso_sgx_enter_enclave()
  *
- * @leaf:	ENCLU leaf from \%eax at time of exception
+ * @leaf:	ENCLU leaf from \%eax at time of exception/exit
  * @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 {
+struct sgx_enclave_exinfo {
 	__u32 leaf;
 	__u16 trapnr;
 	__u16 error_code;
-- 
2.17.1


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

* [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (31 preceding siblings ...)
  2019-04-22 20:42 ` [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-04-22 20:42 ` Cedric Xing
  2019-04-23  0:37   ` Cedric Xing
  2019-04-23  1:29   ` Andy Lutomirski
  2019-04-23 11:56 ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
  33 siblings, 2 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-22 20:42 UTC (permalink / raw)
  To: linux-sgx; +Cc: cedric.xing

Given the changes to __vdso_sgx_enter_enclave(), the selftest is augmented to test the newly added callback interface. This addtional test marks the whole enclave range as PROT_READ, and calls mprotect() upon #PFs to add necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/sgx/main.c     | 123 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++++++-
 2 files changed, 142 insertions(+), 21 deletions(-)

diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
index e2265f841fb0..234cfbad14a5 100644
--- a/tools/testing/selftests/x86/sgx/main.c
+++ b/tools/testing/selftests/x86/sgx/main.c
@@ -9,6 +9,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <errno.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
@@ -18,6 +19,10 @@
 #include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
 #include "../../../../../arch/x86/include/uapi/asm/sgx.h"
 
+#define _Q(x)	__Q(x)
+#define __Q(x)	#x
+#define ERRLN	"Line " _Q(__LINE__)
+
 static const uint64_t MAGIC = 0x1122334455667788ULL;
 
 struct vdso_symtab {
@@ -138,7 +143,7 @@ static bool encl_create(int dev_fd, unsigned long bin_size,
 	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
 		    MAP_SHARED, dev_fd, 0);
 	if (base == MAP_FAILED) {
-		perror("mmap");
+		perror(ERRLN);
 		return false;
 	}
 
@@ -224,24 +229,113 @@ static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
 	return false;
 }
 
-void sgx_call(void *rdi, void *rsi, void *tcs,
-	      struct sgx_enclave_exception *exception,
-	      void *eenter);
+int sgx_call(void *rdi, void *rsi, long rdx, void *rcx, void *r8, void *r9,
+	     void *tcs, struct sgx_enclave_exinfo *ei, void *cb, void *eenter);
+
+static void show_enclave_exinfo(const struct sgx_enclave_exinfo *exinfop,
+				const char *header)
+{
+	printf("%s: leaf:%d", header, exinfop->leaf);
+	if (exinfop->leaf != 4)
+		printf(" trap#:%d ec:%d addr:0x%llx\n", exinfop->trapnr,
+			exinfop->error_code, exinfop->address);
+	else printf("\n");
+}
+
+static void test1(void *eenter, struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[1] Entering the enclave without callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, NULL, eenter);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Null TCS\n Expect: #PF at EENTER\n");
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 NULL, &exinfo, NULL, eenter);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 2 /*EENTER*/ || exinfo.trapnr != 14 /*#PF*/)
+		exit(1);
+}
+
+static int enclave_ex_callback(long rdi, long rsi, long rdx,
+	struct sgx_enclave_exinfo *ei, long r8, long r9, void *tcs, long ursp)
+{
+	show_enclave_exinfo(ei, "  callback");
+
+	switch (ei->leaf)
+	{
+	case 4:
+		return 0;
+	case 3:
+	case 2:
+		if (ei->trapnr != 14 /*#PF*/ || (ei->error_code & 1) == 0) {
+			fprintf(stderr, ERRLN ": Unexpected exception\n");
+			exit(1);
+		}
+
+		if (mprotect((void*)(ei->address & -0x1000), 0x1000,
+			     ((ei->error_code & 2) ? PROT_WRITE : 0) |
+			     ((ei->error_code & 0x10) ? PROT_EXEC : 0) |
+			     PROT_READ)) {
+			perror(ERRLN);
+			exit(1);
+		}
+
+		return ei->leaf == 2 ? -EAGAIN : ei->leaf;
+	}
+	return -EINVAL;
+}
+
+static void test2(void *eenter, struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[2] Entering the enclave with callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, enclave_ex_callback, eenter);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Read-only enclave (0x%lx-0x%lx)\n"
+	       " Expect: #PFs to be fixed by callback\n",
+	       secs->base, secs->base + (encl_bin_end - encl_bin) - 1);
+	if (mprotect((void*)secs->base, encl_bin_end - encl_bin, PROT_READ)) {
+		perror(ERRLN);
+		exit(1);
+	}
+	while (sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+			(void*)secs->base, &exinfo, enclave_ex_callback,
+			eenter) == -EAGAIN);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 4 /*EEXIT*/)
+		exit(1);
+}
 
 int main(int argc, char *argv[], char *envp[])
 {
 	unsigned long bin_size = encl_bin_end - encl_bin;
 	unsigned long ss_size = encl_ss_end - encl_ss;
-	struct sgx_enclave_exception exception;
 	Elf64_Sym *eenter_sym;
 	struct vdso_symtab symtab;
 	struct sgx_secs secs;
-	uint64_t result = 0;
 	void *eenter;
 	void *addr;
 
-	memset(&exception, 0, sizeof(exception));
-
 	addr = vdso_get_base_addr(envp);
 	if (!addr)
 		exit(1);
@@ -266,14 +360,7 @@ int main(int argc, char *argv[], char *envp[])
 	if (!encl_load(&secs, bin_size))
 		exit(1);
 
-	printf("Input: 0x%lx\n", MAGIC);
-	sgx_call((void *)&MAGIC, &result, (void *)secs.base, &exception,
-		 eenter);
-	if (result != MAGIC) {
-		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
-		exit(1);
-	}
-
-	printf("Output: 0x%lx\n", result);
-	exit(0);
+	test1(eenter, &secs);
+	test2(eenter, &secs);
+	return 0;
 }
diff --git a/tools/testing/selftests/x86/sgx/sgx_call.S b/tools/testing/selftests/x86/sgx/sgx_call.S
index 14bd0a044199..da8f687a60d2 100644
--- a/tools/testing/selftests/x86/sgx/sgx_call.S
+++ b/tools/testing/selftests/x86/sgx/sgx_call.S
@@ -7,9 +7,43 @@
 
 	.global sgx_call
 sgx_call:
+	.cfi_startproc
+	push	%r15
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r15, 0
+	push	%r14
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r14, 0
+	push	%r13
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r13, 0
+	push	%r12
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r12, 0
 	push	%rbx
-	mov	$0x02, %rax
-	mov	%rdx, %rbx
-	call	*%r8
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbx, 0
+	push	$0
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	mov	$2, %eax
+	call	*0x68(%rsp)
+	add	$0x20, %rsp
+	.cfi_adjust_cfa_offset	-0x20
 	pop	%rbx
+	.cfi_adjust_cfa_offset	-8
+	pop	%r12
+	.cfi_adjust_cfa_offset	-8
+	pop	%r13
+	.cfi_adjust_cfa_offset	-8
+	pop	%r14
+	.cfi_adjust_cfa_offset	-8
+	pop	%r15
+	.cfi_adjust_cfa_offset	-8
 	ret
+	.cfi_endproc
-- 
2.17.1


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

* Re: [PATCH v20 09/28] x86/sgx: Add ENCLS architectural error codes
  2019-04-17 10:39 ` [PATCH v20 09/28] x86/sgx: Add ENCLS architectural error codes Jarkko Sakkinen
@ 2019-04-22 21:35   ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-04-22 21:35 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, x86, linux-sgx, akpm, dave.hansen, nhorman,
	npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

On Wed, Apr 17, 2019 at 01:39:19PM +0300, Jarkko Sakkinen wrote:
> 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.
> 
> Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
> Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
> Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
> ---

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.

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-04-17 10:39 ` [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver Jarkko Sakkinen
@ 2019-04-22 21:58   ` Sean Christopherson
  2019-04-23 23:29     ` Jethro Beekman
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-22 21:58 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, x86, linux-sgx, akpm, dave.hansen, nhorman,
	npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes, Jethro Beekman

+Cc Jethro

On Wed, Apr 17, 2019 at 01:39:25PM +0300, Jarkko Sakkinen wrote:
> Intel Software Guard eXtensions (SGX) is a set of CPU instructions that
> can be used by applications to set aside private regions of code and
> data. The code outside the 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.
> 
> Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
> Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
> Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
> Co-developed-by: Serge Ayoun <serge.ayoun@intel.com>
> Signed-off-by: Serge Ayoun <serge.ayoun@intel.com>
> Co-developed-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
> Signed-off-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
> Co-developed-by: Suresh Siddha <suresh.b.siddha@intel.com>
> Signed-off-by: Suresh Siddha <suresh.b.siddha@intel.com>
> ---

...

> +#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,
> +	.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.

> +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);

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

* Re: [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
@ 2019-04-22 22:05   ` Sean Christopherson
  2019-04-23  0:37   ` Cedric Xing
                     ` (4 subsequent siblings)
  5 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-04-22 22:05 UTC (permalink / raw)
  To: Cedric Xing; +Cc: linux-sgx

On Mon, Apr 22, 2019 at 01:42:56PM -0700, Cedric Xing wrote:
> The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
> %rsp, which prohibits enclaves from allocating space on the untrusted stack.
> However, there are existing enclaves (e.g. those built with current Intel SGX
> SDK libraries) relying on the untrusted stack for passing parameters to
> untrusted functions (aka. o-calls), which requires allocating space on the
> untrusted stack by enclaves. And given its simplicity and convenience, it
> could be desired by future SGX applications as well.
> 
> This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor
> its stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push"
> onto the untrusted stack by decrementing the untrusted %rsp. Additionally,
> this new __vdso_sgx_enter_enclave() will take one more parameter - a callback
> function, to be invoked upon all enclave exits (both AEX and normal exits).
> The callback function will be given the value of %rsp left off by the
> enclave, so that data "pushed" by the enclave (if any) could be
> addressed/accessed. Please note that the callback function is optional, and
> if not supplied (i.e. null), __vdso_sgx_enter_enclave() will just return
> (i.e. behave the same as the current implementation) after the enclave exits
> (or AEX due to exceptions).
> 
> The SGX selftest is augmented to test out the new callback interface, and to
> serve as a simple example to showcase how to use the callback interface in
> practice.

Please wrap your emails, or use an editor that will do it for you.  75 chars,
plus or minus a few, is generally preferred.

> Cedric Xing (3):
>   selftests/x86: Fixed Makefile for SGX selftest
>   x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing
>     on untrusted stack
>   selftests/x86: Augment SGX selftest to test new
>     __vdso_sgx_enter_enclave() and its callback interface
> 
>  arch/x86/entry/vdso/vsgx_enter_enclave.S   | 156 ++++++++++++---------
>  arch/x86/include/uapi/asm/sgx.h            |  14 +-
>  tools/testing/selftests/x86/Makefile       |  12 +-
>  tools/testing/selftests/x86/sgx/Makefile   |  45 +++---
>  tools/testing/selftests/x86/sgx/main.c     | 123 +++++++++++++---
>  tools/testing/selftests/x86/sgx/sgx_call.S |  40 +++++-
>  6 files changed, 264 insertions(+), 126 deletions(-)
> 
> -- 
> 2.17.1
> 

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

* Re: [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-04-22 22:26   ` Sean Christopherson
  2019-04-23  0:37   ` Cedric Xing
                     ` (2 subsequent siblings)
  3 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-04-22 22:26 UTC (permalink / raw)
  To: Cedric Xing; +Cc: linux-sgx

On Mon, Apr 22, 2019 at 01:42:58PM -0700, Cedric Xing wrote:
> The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
> which prohibits enclaves from allocating and passing parameters for untrusted
> function calls (aka. o-calls).
> 
> This patch addresses the problem above by introducing a new ABI that
> preserves %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor
> its frame using %rbp so that enclaves are allowed to allocate space on the
> untrusted stack by decrementing %rsp. Please note that the stack space
> allocated in such way will be part of __vdso_sgx_enter_enclave()'s frame so
> will be freed after __vdso_sgx_enter_enclave() returns. Therefore,
> __vdso_sgx_enter_enclave() has been changed to take a callback function as an
> optional parameter, which if supplied, will be invoked upon enclave exits
> (both AEX (Asynchronous Enclave eXit) and normal exits), with the value of
> %rsp left off by the enclave as a parameter to the callback.

Please resend this series with the new code as a separate function, not a
modification to the existing function.  Andy made it pretty clear that he
prefers a separate vDSO function, and it'll be a lot easier to provide
feedback on the code if we're working from a clean slate.  If you want to
push to get everything lumped into a single function then by all means do
so on LKML, but for the RFC let's keep the focus on the code itself and
simplify life for reviewers.

  On Tue, Mar 26, 2019 at 10:08:31AM -0700, Andy Lutomirski wrote:
  > If the answer to both questions is yes, then it seems like it could be
  > reasonable to support it in the vDSO.  But I still think it should
  > probably be a different vDSO entry point so that the normal case
  > doesn't become more complicated.

> Here's the summary of API/ABI changes in this patch. More details could be
> found in arch/x86/entry/vdso/vsgx_enter_enclave.S.  * 'struct
> sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo' because it
> is filled upon both AEX (i.e. exceptions) and normal enclave exits.  *
> __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
> the previous implementation).  * __vdso_sgx_enter_enclave() takes one more
> parameter - a callback function to be invoked upon enclave exits. This
> callback is optional, and if not supplied, will cause
> __vdso_sgx_enter_enclave() to return upon enclave exits (same behavior as
> previous implementation).  * The callback function is given as a parameter
> the value of %rsp at enclave exit to address data "pushed" by the enclave. A
> positive value returned by the callback will be treated as an ENCLU leaf for
> re-entering the enclave, while a zero or negative value will be passed
> through as the return value of __vdso_sgx_enter_enclave() to its caller. It's
> also safe to leave callback by longjmp() or by throwing a C++ exception.

Again, wrap at 75 chars or earlier.  And incorporate checkpatch into your
git send-email flow if you haven't done so already, e.g. checkpatch should
have warned about lines longer than 75 chars.

> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---

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

* [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
  2019-04-22 22:05   ` Sean Christopherson
@ 2019-04-23  0:37   ` Cedric Xing
  2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
                     ` (3 subsequent siblings)
  5 siblings, 0 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-23  0:37 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, Hansen, Dave, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, andriy.shevchenko,
	tglx, Svahn, Kai, bp, josh, luto, Kai, rientjes, Jarkko Sakkinen,
	Cedric Xing

The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
%rsp, which prohibits enclaves from allocating space on the untrusted stack.
However, there are existing enclaves (e.g. those built with current Intel SGX
SDK libraries) relying on the untrusted stack for passing parameters to
untrusted functions (aka. o-calls), which requires allocating space on the
untrusted stack by enclaves. And given its simplicity and convenience, it could
be desired by future SGX applications as well.

This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its
stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto
the untrusted stack by decrementing the untrusted %rsp. Additionally, this new
__vdso_sgx_enter_enclave() will take one more parameter - a callback function,
to be invoked upon all enclave exits (both AEX and normal exits). The
callback function will be given the value of %rsp left off by the enclave,
so that data "pushed" by the enclave (if any) could be addressed/accessed.
Please note that the callback function is optional, and if not supplied
(i.e. null), __vdso_sgx_enter_enclave() will just return (i.e. behave the
same as the current implementation) after the enclave exits (or AEX
due to exceptions).

The SGX selftest is augmented to test out the new callback interface, and to
serve as a simple example to showcase how to use the callback interface in
practice.

Reference:
* This patchset is based upon SGX1 patch v20
  (https://lkml.org/lkml/2019/4/17/344) by Jarkko Sakkinen

Cedric Xing (3):
  selftests/x86: Fixed Makefile for SGX selftest
  x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing
    on untrusted stack
  selftests/x86: Augment SGX selftest to test new
    __vdso_sgx_enter_enclave() and its callback interface

 arch/x86/entry/vdso/vsgx_enter_enclave.S   | 156 ++++++++++++---------
 arch/x86/include/uapi/asm/sgx.h            |  14 +-
 tools/testing/selftests/x86/Makefile       |  12 +-
 tools/testing/selftests/x86/sgx/Makefile   |  45 +++---
 tools/testing/selftests/x86/sgx/main.c     | 123 +++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 +++++-
 6 files changed, 264 insertions(+), 126 deletions(-)

-- 
2.17.1


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

* [RFC PATCH v1 1/3] selftests/x86: Fixed Makefile for SGX selftest
  2019-04-22 20:42 ` [RFC PATCH v1 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
@ 2019-04-23  0:37   ` Cedric Xing
  0 siblings, 0 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-23  0:37 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, Hansen, Dave, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, andriy.shevchenko,
	tglx, Svahn, Kai, bp, josh, luto, Kai, rientjes, Jarkko Sakkinen,
	Cedric Xing

The original x86/sgx/Makefile doesn't work when 'x86/sgx' is specified as the
test target. This patch fixes that problem, along with minor changes to the
dependencies between 'x86' and 'x86/sgx' in selftests/x86/Makefile.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/Makefile     | 12 +++----
 tools/testing/selftests/x86/sgx/Makefile | 45 +++++++++---------------
 2 files changed, 22 insertions(+), 35 deletions(-)

diff --git a/tools/testing/selftests/x86/Makefile b/tools/testing/selftests/x86/Makefile
index 4fc9a42f56ea..1294c5f5b6ca 100644
--- a/tools/testing/selftests/x86/Makefile
+++ b/tools/testing/selftests/x86/Makefile
@@ -70,11 +70,11 @@ 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 $@;	\
+all_64: | $(SUBDIRS_64)
+	@for DIR in $|; do					\
+		BUILD_TARGET=$(OUTPUT)/$$DIR;			\
+		mkdir $$BUILD_TARGET  -p;			\
+		$(MAKE) OUTPUT=$$BUILD_TARGET -C $$DIR $@;	\
 	done
 
 EXTRA_CLEAN := $(BINARIES_32) $(BINARIES_64)
@@ -90,7 +90,7 @@ ifeq ($(CAN_BUILD_I386)$(CAN_BUILD_X86_64),01)
 all: warn_32bit_failure
 
 warn_32bit_failure:
-	@echo "Warning: you seem to have a broken 32-bit build" 2>&1; 	\
+	@echo "Warning: you seem to have a broken 32-bit build" 2>&1;	\
 	echo "environment.  This will reduce test coverage of 64-bit" 2>&1; \
 	echo "kernels.  If you are using a Debian-like distribution," 2>&1; \
 	echo "try:"; 2>&1; \
diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 1fd6f2708e81..3af15d7c8644 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -2,47 +2,34 @@ top_srcdir = ../../../../..
 
 include ../../lib.mk
 
-HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
-ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
+ifeq ($(shell $(CC) -dumpmachine | cut --delimiter=- -f1),x86_64)
+all: all_64
+endif
+
+HOST_CFLAGS := -Wall -Werror -g $(INCLUDES)
+ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIE \
 	       -fno-stack-protector -mrdrnd $(INCLUDES)
 
 TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
-$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
-		      $(OUTPUT)/encl_piggy.o
+$(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
 	$(CC) $(HOST_CFLAGS) -o $@ $^
 
-$(OUTPUT)/main.o: main.c
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
+$(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
-$(OUTPUT)/sgx_call.o: sgx_call.S
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
-	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
-
-$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
+$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
 	objcopy --remove-section=.got.plt -O binary $< $@
 
-$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
-	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
+$(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
 
-$(OUTPUT)/encl.o: encl.c
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
-	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+$(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
+	$^ $@
 
 $(OUTPUT)/sgxsign: sgxsign.c
 	$(CC) -o $@ $< -lcrypto
 
-EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
-	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
-	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
-	       $(OUTPUT)/sgxsign
-
-.PHONY: clean
+EXTRA_CLEAN := $(TEST_CUSTOM_PROGS) $(addprefix $(OUTPUT)/,	\
+		encl.elf encl.bin encl.ss encl_piggy.o sgxsign)
-- 
2.17.1


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

* [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
  2019-04-22 22:26   ` Sean Christopherson
@ 2019-04-23  0:37   ` Cedric Xing
  2019-04-23  1:25   ` Andy Lutomirski
  2019-04-23 19:26   ` Sean Christopherson
  3 siblings, 0 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-23  0:37 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, Hansen, Dave, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, andriy.shevchenko,
	tglx, Svahn, Kai, bp, josh, luto, Kai, rientjes, Jarkko Sakkinen,
	Cedric Xing

The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
which prohibits enclaves from allocating and passing parameters for
untrusted function calls (aka. o-calls).

This patch addresses the problem above by introducing a new ABI that preserves
%rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
using %rbp so that enclaves are allowed to allocate space on the untrusted
stack by decrementing %rsp. Please note that the stack space allocated in such
way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
__vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
been changed to take a callback function as an optional parameter, which if
supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
eXit) and normal exits), with the value of %rsp left
off by the enclave as a parameter to the callback.

Here's the summary of API/ABI changes in this patch. More details could be
found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
* 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
  because it is filled upon both AEX (i.e. exceptions) and normal enclave
  exits.
* __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
  the previous implementation).
* __vdso_sgx_enter_enclave() takes one more parameter - a callback function to
  be invoked upon enclave exits. This callback is optional, and if not
  supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave exits
  (same behavior as previous implementation).
* The callback function is given as a parameter the value of %rsp at enclave
  exit to address data "pushed" by the enclave. A positive value returned by
  the callback will be treated as an ENCLU leaf for re-entering the enclave,
  while a zero or negative value will be passed through as the return
  value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
  leave callback by longjmp() or by throwing a C++ exception.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 arch/x86/entry/vdso/vsgx_enter_enclave.S | 156 ++++++++++++++---------
 arch/x86/include/uapi/asm/sgx.h          |  14 +-
 2 files changed, 100 insertions(+), 70 deletions(-)

diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
index fe0bf6671d6d..210f4366374a 100644
--- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
+++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
@@ -14,88 +14,118 @@
 .code64
 .section .text, "ax"
 
-#ifdef SGX_KERNEL_DOC
 /**
  * __vdso_sgx_enter_enclave() - Enter an SGX enclave
  *
  * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
- * @tcs:	**IN \%rbx** - TCS, must be non-NULL
- * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
+ * @tcs:	**IN 0x08(\%rsp)** - TCS, must be non-NULL
+ * @ex_info:	**IN 0x10(\%rsp)** - Optional 'struct sgx_enclave_exinfo'
+ *				     pointer
+ * @callback:	**IN 0x18(\%rsp)** - Optional callback function to be called on
+ *				     enclave exit or exception
  *
  * Return:
  *  **OUT \%eax** -
- *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
- *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
+ *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is not
+ *  allowed, %-EFAULT if ENCLU or the enclave faults, or a non-positive value
+ *  returned from ``callback`` (if one is supplied).
  *
  * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
- * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
- * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
- * the return value passed via ``%eax``.  All registers except ``%rsp`` must
- * be treated as volatile from the caller's perspective, including but not
- * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
- * being run **must** preserve the untrusted ``%rsp`` and stack.
+ * x86-64 ABI, i.e. cannot be called from standard C code. As noted above,
+ * input parameters must be passed via ``%eax``, ``8(%rsp)``, ``0x10(%rsp)`` and
+ * ``0x18(%rsp)``, with the return value passed via ``%eax``. All other registers
+ * will be passed through to the enclave as is. All registers except ``%rbp``
+ * must be treated as volatile from the caller's perspective, including but not
+ * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely, the enclave being
+ * run **must** preserve the untrusted ``%rbp``.
+ *
+ * ``callback`` has the following signature:
+ * int callback(long rdi, long rsi, long rdx,
+ *		struct sgx_enclave_exinfo *ex_info, long r8, long r9,
+ *		void *tcs, long ursp);
+ * ``callback`` **shall** follow x86_64 ABI. All GPRs **except** ``%rax``, ``%rbx``
+ * and ``rcx`` are passed through to ``callback``. ``%rdi``, ``%rsi``, ``%rdx``,
+ * ``%r8``, ``%r9``, along with the value of ``%rsp`` when the enclave exited/excepted,
+ * can be accessed directly as input parameters, while other GPRs can be
+ * accessed in assembly if needed.
+ * A positive value returned from ``callback`` will be treated as an ENCLU leaf
+ * (e.g. EENTER/ERESUME) to reenter the enclave, while 0 or a negative return
+ * value will be passed back to the caller of __vdso_sgx_enter_enclave().
+ * It is also **safe** to ``longjmp()`` out of ``callback``.
  */
-__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
-			 struct sgx_enclave_exception *ex_info)
-{
-	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
-		return -EINVAL;
-
-	if (!tcs)
-		return -EINVAL;
-
-	try {
-		ENCLU[leaf];
-	} catch (exception) {
-		if (e)
-			*e = exception;
-		return -EFAULT;
-	}
-
-	return 0;
-}
-#endif
 ENTRY(__vdso_sgx_enter_enclave)
-	/* EENTER <= leaf <= ERESUME */
+	/* Prolog */
+	.cfi_startproc
+	push	%rbp
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbp, 0
+	mov	%rsp, %rbp
+	.cfi_def_cfa_register	%rbp
+
+1:	/* EENTER <= leaf <= ERESUME */
 	cmp	$0x2, %eax
-	jb	bad_input
-
+	jb	6f
 	cmp	$0x3, %eax
-	ja	bad_input
+	ja	6f
 
-	/* TCS must be non-NULL */
-	test	%rbx, %rbx
-	je	bad_input
+	/* Load TCS and AEP */
+	mov	0x10(%rbp), %rbx
+	lea	2f(%rip), %rcx
 
-	/* Save @exception_info */
-	push	%rcx
-
-	/* Load AEP for ENCLU */
-	lea	1f(%rip),  %rcx
-1:	enclu
-
-	add	$0x8, %rsp
-	xor	%eax, %eax
-	ret
-
-bad_input:
-	mov     $(-EINVAL), %rax
-	ret
-
-.pushsection .fixup, "ax"
-	/* Re-load @exception_info and fill it (if it's non-NULL) */
-2:	pop	%rcx
-	test    %rcx, %rcx
-	je      3f
+	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
+2:	enclu
 
+	/* EEXIT path */
+	xor	%ebx, %ebx
+3:	mov	0x18(%rbp), %rcx
+	jrcxz	4f
 	mov	%eax, EX_LEAF(%rcx)
-	mov	%di,  EX_TRAPNR(%rcx)
-	mov	%si,  EX_ERROR_CODE(%rcx)
+	jnc	4f
+	mov	%di, EX_TRAPNR(%rcx)
+	mov	%si, EX_ERROR_CODE(%rcx)
 	mov	%rdx, EX_ADDRESS(%rcx)
-3:	mov	$(-EFAULT), %rax
+
+4:	/* Call *callback if supplied */
+	mov	0x20(%rbp), %rax
+	test	%rax, %rax
+	cmovz	%rbx, %rax
+	jz	7f
+	/* Align stack and clear RFLAGS.DF per x86_64 ABI */
+	mov	%rsp, %rbx
+	and	$-0x10, %rsp
+	cld
+	/* Parameters for *callback */
+	push	%rbx
+	push	0x10(%rbp)
+	/* Call via retpoline */
+	call	40f
+	/* Cleanup stack */
+	mov	%rbx, %rsp
+	jmp	1b
+40:	/* retpoline */
+	call	42f
+41:	pause
+	lfence
+	jmp	41b
+42:	mov	%rax, (%rsp)
+	ret
+
+5:	/* Exception path */
+	mov	$-EFAULT, %ebx
+	stc
+	jmp	3b
+
+6:	/* Unsupported ENCLU leaf */
+	cmp	$0, %eax
+	jle	7f
+	mov	$-EINVAL, %eax
+
+7:	/* Epilog */
+	leave
+	.cfi_def_cfa		%rsp, 8
 	ret
-.popsection
+	.cfi_endproc
 
-_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
+_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
 
 ENDPROC(__vdso_sgx_enter_enclave)
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 9ed690a38c70..50d2b5143e5e 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -24,7 +24,7 @@
 
 /**
  * struct sgx_enclave_create - parameter structure for the
- *                             %SGX_IOC_ENCLAVE_CREATE ioctl
+ *			       %SGX_IOC_ENCLAVE_CREATE ioctl
  * @src:	address for the SECS page data
  */
 struct sgx_enclave_create  {
@@ -33,7 +33,7 @@ struct sgx_enclave_create  {
 
 /**
  * struct sgx_enclave_add_page - parameter structure for the
- *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
+ *				 %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
  * @addr:	address within the ELRANGE
  * @src:	address for the page data
  * @secinfo:	address for the SECINFO data
@@ -49,7 +49,7 @@ struct sgx_enclave_add_page {
 
 /**
  * struct sgx_enclave_init - parameter structure for the
- *                           %SGX_IOC_ENCLAVE_INIT ioctl
+ *			     %SGX_IOC_ENCLAVE_INIT ioctl
  * @sigstruct:	address for the SIGSTRUCT data
  */
 struct sgx_enclave_init {
@@ -66,16 +66,16 @@ struct sgx_enclave_set_attribute {
 };
 
 /**
- * struct sgx_enclave_exception - structure to report exceptions encountered in
- *				  __vdso_sgx_enter_enclave()
+ * struct sgx_enclave_exinfo - structure to report exceptions encountered in
+ *			       __vdso_sgx_enter_enclave()
  *
- * @leaf:	ENCLU leaf from \%eax at time of exception
+ * @leaf:	ENCLU leaf from \%eax at time of exception/exit
  * @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 {
+struct sgx_enclave_exinfo {
 	__u32 leaf;
 	__u16 trapnr;
 	__u16 error_code;
-- 
2.17.1


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

* [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-22 20:42 ` [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
@ 2019-04-23  0:37   ` Cedric Xing
  2019-04-23  1:29   ` Andy Lutomirski
  1 sibling, 0 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-23  0:37 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, Hansen, Dave, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, andriy.shevchenko,
	tglx, Svahn, Kai, bp, josh, luto, Kai, rientjes, Jarkko Sakkinen,
	Cedric Xing

Given the changes to __vdso_sgx_enter_enclave(), the selftest is augmented to
test the newly added callback interface. This addtional test marks the whole
enclave range as PROT_READ, and calls mprotect() upon #PFs to add necessary PTE
permissions per PFEC (#PF Error Code) until the enclave finishes.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/sgx/main.c     | 123 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++++++-
 2 files changed, 142 insertions(+), 21 deletions(-)

diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
index e2265f841fb0..234cfbad14a5 100644
--- a/tools/testing/selftests/x86/sgx/main.c
+++ b/tools/testing/selftests/x86/sgx/main.c
@@ -9,6 +9,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <errno.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
@@ -18,6 +19,10 @@
 #include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
 #include "../../../../../arch/x86/include/uapi/asm/sgx.h"
 
+#define _Q(x)	__Q(x)
+#define __Q(x)	#x
+#define ERRLN	"Line " _Q(__LINE__)
+
 static const uint64_t MAGIC = 0x1122334455667788ULL;
 
 struct vdso_symtab {
@@ -138,7 +143,7 @@ static bool encl_create(int dev_fd, unsigned long bin_size,
 	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
 		    MAP_SHARED, dev_fd, 0);
 	if (base == MAP_FAILED) {
-		perror("mmap");
+		perror(ERRLN);
 		return false;
 	}
 
@@ -224,24 +229,113 @@ static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
 	return false;
 }
 
-void sgx_call(void *rdi, void *rsi, void *tcs,
-	      struct sgx_enclave_exception *exception,
-	      void *eenter);
+int sgx_call(void *rdi, void *rsi, long rdx, void *rcx, void *r8, void *r9,
+	     void *tcs, struct sgx_enclave_exinfo *ei, void *cb, void *eenter);
+
+static void show_enclave_exinfo(const struct sgx_enclave_exinfo *exinfop,
+				const char *header)
+{
+	printf("%s: leaf:%d", header, exinfop->leaf);
+	if (exinfop->leaf != 4)
+		printf(" trap#:%d ec:%d addr:0x%llx\n", exinfop->trapnr,
+			exinfop->error_code, exinfop->address);
+	else printf("\n");
+}
+
+static void test1(void *eenter, struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[1] Entering the enclave without callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, NULL, eenter);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Null TCS\n Expect: #PF at EENTER\n");
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 NULL, &exinfo, NULL, eenter);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 2 /*EENTER*/ || exinfo.trapnr != 14 /*#PF*/)
+		exit(1);
+}
+
+static int enclave_ex_callback(long rdi, long rsi, long rdx,
+	struct sgx_enclave_exinfo *ei, long r8, long r9, void *tcs, long ursp)
+{
+	show_enclave_exinfo(ei, "  callback");
+
+	switch (ei->leaf)
+	{
+	case 4:
+		return 0;
+	case 3:
+	case 2:
+		if (ei->trapnr != 14 /*#PF*/ || (ei->error_code & 1) == 0) {
+			fprintf(stderr, ERRLN ": Unexpected exception\n");
+			exit(1);
+		}
+
+		if (mprotect((void*)(ei->address & -0x1000), 0x1000,
+			     ((ei->error_code & 2) ? PROT_WRITE : 0) |
+			     ((ei->error_code & 0x10) ? PROT_EXEC : 0) |
+			     PROT_READ)) {
+			perror(ERRLN);
+			exit(1);
+		}
+
+		return ei->leaf == 2 ? -EAGAIN : ei->leaf;
+	}
+	return -EINVAL;
+}
+
+static void test2(void *eenter, struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[2] Entering the enclave with callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, enclave_ex_callback, eenter);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Read-only enclave (0x%lx-0x%lx)\n"
+	       " Expect: #PFs to be fixed by callback\n",
+	       secs->base, secs->base + (encl_bin_end - encl_bin) - 1);
+	if (mprotect((void*)secs->base, encl_bin_end - encl_bin, PROT_READ)) {
+		perror(ERRLN);
+		exit(1);
+	}
+	while (sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+			(void*)secs->base, &exinfo, enclave_ex_callback,
+			eenter) == -EAGAIN);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 4 /*EEXIT*/)
+		exit(1);
+}
 
 int main(int argc, char *argv[], char *envp[])
 {
 	unsigned long bin_size = encl_bin_end - encl_bin;
 	unsigned long ss_size = encl_ss_end - encl_ss;
-	struct sgx_enclave_exception exception;
 	Elf64_Sym *eenter_sym;
 	struct vdso_symtab symtab;
 	struct sgx_secs secs;
-	uint64_t result = 0;
 	void *eenter;
 	void *addr;
 
-	memset(&exception, 0, sizeof(exception));
-
 	addr = vdso_get_base_addr(envp);
 	if (!addr)
 		exit(1);
@@ -266,14 +360,7 @@ int main(int argc, char *argv[], char *envp[])
 	if (!encl_load(&secs, bin_size))
 		exit(1);
 
-	printf("Input: 0x%lx\n", MAGIC);
-	sgx_call((void *)&MAGIC, &result, (void *)secs.base, &exception,
-		 eenter);
-	if (result != MAGIC) {
-		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
-		exit(1);
-	}
-
-	printf("Output: 0x%lx\n", result);
-	exit(0);
+	test1(eenter, &secs);
+	test2(eenter, &secs);
+	return 0;
 }
diff --git a/tools/testing/selftests/x86/sgx/sgx_call.S b/tools/testing/selftests/x86/sgx/sgx_call.S
index 14bd0a044199..da8f687a60d2 100644
--- a/tools/testing/selftests/x86/sgx/sgx_call.S
+++ b/tools/testing/selftests/x86/sgx/sgx_call.S
@@ -7,9 +7,43 @@
 
 	.global sgx_call
 sgx_call:
+	.cfi_startproc
+	push	%r15
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r15, 0
+	push	%r14
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r14, 0
+	push	%r13
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r13, 0
+	push	%r12
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r12, 0
 	push	%rbx
-	mov	$0x02, %rax
-	mov	%rdx, %rbx
-	call	*%r8
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbx, 0
+	push	$0
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	mov	$2, %eax
+	call	*0x68(%rsp)
+	add	$0x20, %rsp
+	.cfi_adjust_cfa_offset	-0x20
 	pop	%rbx
+	.cfi_adjust_cfa_offset	-8
+	pop	%r12
+	.cfi_adjust_cfa_offset	-8
+	pop	%r13
+	.cfi_adjust_cfa_offset	-8
+	pop	%r14
+	.cfi_adjust_cfa_offset	-8
+	pop	%r15
+	.cfi_adjust_cfa_offset	-8
 	ret
+	.cfi_endproc
-- 
2.17.1


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

* Re: [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
  2019-04-22 22:26   ` Sean Christopherson
  2019-04-23  0:37   ` Cedric Xing
@ 2019-04-23  1:25   ` Andy Lutomirski
  2019-04-24 17:56     ` Xing, Cedric
  2019-04-23 19:26   ` Sean Christopherson
  3 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-23  1:25 UTC (permalink / raw)
  To: Cedric Xing
  Cc: LKML, X86 ML, linux-sgx, Andrew Morton, Dave, Sean J, nhorman,
	npmccallum, Serge, Shay, Haitao, Andy Shevchenko,
	Thomas Gleixner, Kai, Borislav Petkov, Josh Triplett,
	Andrew Lutomirski, Kai, David Rientjes, Jarkko Sakkinen

On Mon, Apr 22, 2019 at 5:37 PM Cedric Xing <cedric.xing@intel.com> wrote:
>
> The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
> which prohibits enclaves from allocating and passing parameters for
> untrusted function calls (aka. o-calls).
>
> This patch addresses the problem above by introducing a new ABI that preserves
> %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
> using %rbp so that enclaves are allowed to allocate space on the untrusted
> stack by decrementing %rsp. Please note that the stack space allocated in such
> way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
> __vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
> been changed to take a callback function as an optional parameter, which if
> supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
> eXit) and normal exits), with the value of %rsp left
> off by the enclave as a parameter to the callback.
>
> Here's the summary of API/ABI changes in this patch. More details could be
> found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
> * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
>   because it is filled upon both AEX (i.e. exceptions) and normal enclave
>   exits.
> * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
>   the previous implementation).
> * __vdso_sgx_enter_enclave() takes one more parameter - a callback function to
>   be invoked upon enclave exits. This callback is optional, and if not
>   supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave exits
>   (same behavior as previous implementation).
> * The callback function is given as a parameter the value of %rsp at enclave
>   exit to address data "pushed" by the enclave. A positive value returned by
>   the callback will be treated as an ENCLU leaf for re-entering the enclave,
>   while a zero or negative value will be passed through as the return
>   value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
>   leave callback by longjmp() or by throwing a C++ exception.
>
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---
>  arch/x86/entry/vdso/vsgx_enter_enclave.S | 156 ++++++++++++++---------
>  arch/x86/include/uapi/asm/sgx.h          |  14 +-
>  2 files changed, 100 insertions(+), 70 deletions(-)
>
> diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> index fe0bf6671d6d..210f4366374a 100644
> --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> @@ -14,88 +14,118 @@
>  .code64
>  .section .text, "ax"
>
> -#ifdef SGX_KERNEL_DOC
>  /**
>   * __vdso_sgx_enter_enclave() - Enter an SGX enclave
>   *
>   * @leaf:      **IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
> - * @tcs:       **IN \%rbx** - TCS, must be non-NULL
> - * @ex_info:   **IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
> + * @tcs:       **IN 0x08(\%rsp)** - TCS, must be non-NULL
> + * @ex_info:   **IN 0x10(\%rsp)** - Optional 'struct sgx_enclave_exinfo'
> + *                                  pointer
> + * @callback:  **IN 0x18(\%rsp)** - Optional callback function to be called on
> + *                                  enclave exit or exception
>   *
>   * Return:
>   *  **OUT \%eax** -
> - *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
> - *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
> + *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is not
> + *  allowed, %-EFAULT if ENCLU or the enclave faults, or a non-positive value
> + *  returned from ``callback`` (if one is supplied).
>   *
>   * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
> - * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
> - * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
> - * the return value passed via ``%eax``.  All registers except ``%rsp`` must
> - * be treated as volatile from the caller's perspective, including but not
> - * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
> - * being run **must** preserve the untrusted ``%rsp`` and stack.
> + * x86-64 ABI, i.e. cannot be called from standard C code. As noted above,
> + * input parameters must be passed via ``%eax``, ``8(%rsp)``, ``0x10(%rsp)`` and
> + * ``0x18(%rsp)``, with the return value passed via ``%eax``. All other registers
> + * will be passed through to the enclave as is. All registers except ``%rbp``
> + * must be treated as volatile from the caller's perspective, including but not
> + * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely, the enclave being
> + * run **must** preserve the untrusted ``%rbp``.
> + *
> + * ``callback`` has the following signature:
> + * int callback(long rdi, long rsi, long rdx,
> + *             struct sgx_enclave_exinfo *ex_info, long r8, long r9,
> + *             void *tcs, long ursp);
> + * ``callback`` **shall** follow x86_64 ABI. All GPRs **except** ``%rax``, ``%rbx``
> + * and ``rcx`` are passed through to ``callback``. ``%rdi``, ``%rsi``, ``%rdx``,
> + * ``%r8``, ``%r9``, along with the value of ``%rsp`` when the enclave exited/excepted,
> + * can be accessed directly as input parameters, while other GPRs can be
> + * accessed in assembly if needed.
> + * A positive value returned from ``callback`` will be treated as an ENCLU leaf
> + * (e.g. EENTER/ERESUME) to reenter the enclave, while 0 or a negative return

"to reenter the enclave without popping the extra data pushed by the
enclave off the stack" or similar.  We really don't want a situation
where someone puts all there "keep on going" logic in the callback and
the stack usage grows without bound.

> + * value will be passed back to the caller of __vdso_sgx_enter_enclave().
> + * It is also **safe** to ``longjmp()`` out of ``callback``.

I'm not sure that "safe" needs emphasis.

>   */
> -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> -                        struct sgx_enclave_exception *ex_info)
> -{
> -       if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> -               return -EINVAL;
> -
> -       if (!tcs)
> -               return -EINVAL;
> -
> -       try {
> -               ENCLU[leaf];
> -       } catch (exception) {
> -               if (e)
> -                       *e = exception;
> -               return -EFAULT;
> -       }
> -
> -       return 0;
> -}
> -#endif
>  ENTRY(__vdso_sgx_enter_enclave)
> -       /* EENTER <= leaf <= ERESUME */
> +       /* Prolog */
> +       .cfi_startproc
> +       push    %rbp
> +       .cfi_adjust_cfa_offset  8
> +       .cfi_rel_offset         %rbp, 0
> +       mov     %rsp, %rbp
> +       .cfi_def_cfa_register   %rbp
> +
> +1:     /* EENTER <= leaf <= ERESUME */
>         cmp     $0x2, %eax
> -       jb      bad_input
> -
> +       jb      6f
>         cmp     $0x3, %eax
> -       ja      bad_input
> +       ja      6f
>
> -       /* TCS must be non-NULL */
> -       test    %rbx, %rbx
> -       je      bad_input
> +       /* Load TCS and AEP */
> +       mov     0x10(%rbp), %rbx
> +       lea     2f(%rip), %rcx
>
> -       /* Save @exception_info */
> -       push    %rcx
> -
> -       /* Load AEP for ENCLU */
> -       lea     1f(%rip),  %rcx
> -1:     enclu
> -
> -       add     $0x8, %rsp
> -       xor     %eax, %eax
> -       ret
> -
> -bad_input:
> -       mov     $(-EINVAL), %rax
> -       ret
> -
> -.pushsection .fixup, "ax"
> -       /* Re-load @exception_info and fill it (if it's non-NULL) */
> -2:     pop     %rcx
> -       test    %rcx, %rcx
> -       je      3f
> +       /* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> +2:     enclu
>
> +       /* EEXIT path */
> +       xor     %ebx, %ebx
> +3:     mov     0x18(%rbp), %rcx
> +       jrcxz   4f
>         mov     %eax, EX_LEAF(%rcx)
> -       mov     %di,  EX_TRAPNR(%rcx)
> -       mov     %si,  EX_ERROR_CODE(%rcx)
> +       jnc     4f
> +       mov     %di, EX_TRAPNR(%rcx)
> +       mov     %si, EX_ERROR_CODE(%rcx)
>         mov     %rdx, EX_ADDRESS(%rcx)
> -3:     mov     $(-EFAULT), %rax
> +
> +4:     /* Call *callback if supplied */
> +       mov     0x20(%rbp), %rax
> +       test    %rax, %rax

Maybe have a comment like "At this point, the effective return value
is in RBX.  If there is no callback, then return it."

> +       cmovz   %rbx, %rax
> +       jz      7f
> +       /* Align stack and clear RFLAGS.DF per x86_64 ABI */
> +       mov     %rsp, %rbx

Whoa, this is too subtle here.  Can you update the comment to clarify
that the uRSP value set by the enclave needs to be saved so that the
enclave can be resumed if needed?

> +       and     $-0x10, %rsp
> +       cld
> +       /* Parameters for *callback */
> +       push    %rbx
> +       push    0x10(%rbp)
> +       /* Call via retpoline */
> +       call    40f
> +       /* Cleanup stack */
> +       mov     %rbx, %rsp

To me, "Cleanup stack" makes me think that you're restoring the
original RSP, but you're actually just undoing in the stack alignment.
How about "Undo stack alignment"?

But I'm not seeing the code that causes a return value RAX <= 0 to just return.

> +       jmp     1b
> +40:    /* retpoline */
> +       call    42f
> +41:    pause
> +       lfence
> +       jmp     41b
> +42:    mov     %rax, (%rsp)
> +       ret
> +
> +5:     /* Exception path */
> +       mov     $-EFAULT, %ebx
> +       stc
> +       jmp     3b
> +
> +6:     /* Unsupported ENCLU leaf */
> +       cmp     $0, %eax
> +       jle     7f
> +       mov     $-EINVAL, %eax
> +
> +7:     /* Epilog */
> +       leave
> +       .cfi_def_cfa            %rsp, 8
>         ret
> -.popsection
> +       .cfi_endproc
>
> -_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
> +_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)

--Andy

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

* Re: [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-22 20:42 ` [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
  2019-04-23  0:37   ` Cedric Xing
@ 2019-04-23  1:29   ` Andy Lutomirski
  2019-04-23  1:48     ` Sean Christopherson
  2019-04-23 18:59     ` Sean Christopherson
  1 sibling, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-23  1:29 UTC (permalink / raw)
  To: Cedric Xing
  Cc: LKML, X86 ML, linux-sgx, Andrew Morton, Dave, Sean J, nhorman,
	npmccallum, Serge, Shay, Haitao, Andy Shevchenko,
	Thomas Gleixner, Kai, Borislav Petkov, Josh Triplett,
	Andrew Lutomirski, Kai, David Rientjes, Jarkko Sakkinen

On Mon, Apr 22, 2019 at 5:37 PM Cedric Xing <cedric.xing@intel.com> wrote:
>
> Given the changes to __vdso_sgx_enter_enclave(), the selftest is augmented to
> test the newly added callback interface. This addtional test marks the whole
> enclave range as PROT_READ, and calls mprotect() upon #PFs to add necessary PTE
> permissions per PFEC (#PF Error Code) until the enclave finishes.

Nifty.

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?

--Andy

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

* Re: [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-23  1:29   ` Andy Lutomirski
@ 2019-04-23  1:48     ` Sean Christopherson
  2019-04-23 18:59     ` Sean Christopherson
  1 sibling, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-04-23  1:48 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Cedric Xing, LKML, X86 ML, linux-sgx, Andrew Morton, Dave,
	nhorman, npmccallum, Serge, Shay, Haitao, Andy Shevchenko,
	Thomas Gleixner, Kai, Borislav Petkov, Josh Triplett, Kai,
	David Rientjes, Jarkko Sakkinen

On Mon, Apr 22, 2019 at 06:29:06PM -0700, Andy Lutomirski wrote:
> On Mon, Apr 22, 2019 at 5:37 PM Cedric Xing <cedric.xing@intel.com> wrote:
> >
> > Given the changes to __vdso_sgx_enter_enclave(), the selftest is augmented to
> > test the newly added callback interface. This addtional test marks the whole
> > enclave range as PROT_READ, and calls mprotect() upon #PFs to add necessary PTE
> > permissions per PFEC (#PF Error Code) until the enclave finishes.
> 
> Nifty.
> 
> 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?

My money would be on the code being broken as opposed to you remembering
wrong.  I'll take a look at it tomorrow.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-22 17:17                                           ` Sean Christopherson
@ 2019-04-23  9:11                                             ` Dr. Greg
  0 siblings, 0 replies; 318+ messages in thread
From: Dr. Greg @ 2019-04-23  9:11 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Linus Torvalds, Thomas Gleixner, Jethro Beekman, Andy Lutomirski,
	Andy Lutomirski, Dave Hansen, Jarkko Sakkinen, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

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

Good morning to everyone.

> On Mon, Apr 22, 2019 at 09:55:47AM -0700, Linus Torvalds wrote:
> > On Mon, Apr 22, 2019 at 9:48 AM Sean Christopherson
> > <sean.j.christopherson@intel.com> wrote:
> > >
> > > 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".

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

> 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: greg@enjellic.com
------------------------------------------------------------------------------
"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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
                   ` (32 preceding siblings ...)
  2019-04-22 20:42 ` [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
@ 2019-04-23 11:56 ` Jarkko Sakkinen
  2019-04-23 16:52   ` Andy Lutomirski
  33 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-23 11:56 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes

On Wed, Apr 17, 2019 at 01:39:10PM +0300, Jarkko Sakkinen wrote:
> 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
> 
> -- 
> 2.19.1
> 

I'm on leave for this week and next week's Monday if you wonder why I'm
so passive in the discussion. Looking at the things next week's Tue.

Just a quick comment about Andy's proposal. Probably pretty DSO like
ELF blob could work with an addition of a section called ".tcs" for
entry points. They need to be recognized so that the loader can add
them as TCS pages.

My self-test already is a PoC for enclave binary with a custom linker
script to define the binary format. Too simplistic for a "generic"
case but still a starting point.

/Jarkko

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

* Re: [PATCH v20 16/28] x86/sgx: Add provisioning
  2019-04-19  3:06   ` Huang, Kai
@ 2019-04-23 14:33     ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-23 14:33 UTC (permalink / raw)
  To: Huang, Kai
  Cc: linux-kernel, linux-sgx, x86, Svahn, Kai, nhorman, jmorris,
	Christopherson, Sean J, josh, tglx, Ayoun, Serge, Huang, Haitao,
	linux-security-module, akpm, npmccallum, rientjes, luto,
	Katz-zamir, Shay, Hansen, Dave, bp, serge, andriy.shevchenko

On Fri, Apr 19, 2019 at 03:06:48AM +0000, Huang, Kai wrote:
> On Wed, 2019-04-17 at 13:39 +0300, Jarkko Sakkinen wrote:
> > 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;
> > 
> Should be params.attribute_fd = prov_fd;
> 
> Thanks,
> -Kai

Thanks.

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-23 11:56 ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
@ 2019-04-23 16:52   ` Andy Lutomirski
  2019-04-24 12:17     ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-23 16:52 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: LKML, X86 ML, linux-sgx, Andrew Morton, Dave Hansen,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Thomas Gleixner, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Andrew Lutomirski, Huang, Kai, David Rientjes

On Tue, Apr 23, 2019 at 4:56 AM Jarkko Sakkinen
<jarkko.sakkinen@linux.intel.com> wrote:
>
> On Wed, Apr 17, 2019 at 01:39:10PM +0300, Jarkko Sakkinen wrote:
> > 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
> >
> > --
> > 2.19.1
> >
>
> I'm on leave for this week and next week's Monday if you wonder why I'm
> so passive in the discussion. Looking at the things next week's Tue.
>
> Just a quick comment about Andy's proposal. Probably pretty DSO like
> ELF blob could work with an addition of a section called ".tcs" for
> entry points. They need to be recognized so that the loader can add
> them as TCS pages.

Hmm.

There's a decent argument for specifically supporting whatever format
Windows uses.  There's also an argument for allowing one or more
enclaves to be bundled in a regular ELF DSO.  FWIW, there's no
fundamental reason we can't support more than one type of enclave
format.

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

* Re: [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-23  1:29   ` Andy Lutomirski
  2019-04-23  1:48     ` Sean Christopherson
@ 2019-04-23 18:59     ` Sean Christopherson
  2019-04-23 19:07       ` Andy Lutomirski
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-23 18:59 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Cedric Xing, LKML, X86 ML, linux-sgx, Andrew Morton, Dave,
	nhorman, npmccallum, Serge, Shay, Haitao, Andy Shevchenko,
	Thomas Gleixner, Kai, Borislav Petkov, Josh Triplett, Kai,
	David Rientjes, Jarkko Sakkinen

On Mon, Apr 22, 2019 at 06:29:06PM -0700, Andy Lutomirski wrote:
> 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...

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

* Re: [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-23 18:59     ` Sean Christopherson
@ 2019-04-23 19:07       ` Andy Lutomirski
  2019-04-23 20:11         ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-23 19:07 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Cedric Xing, LKML, X86 ML, linux-sgx,
	Andrew Morton, Dave, nhorman, npmccallum, Serge, Shay, Haitao,
	Andy Shevchenko, Thomas Gleixner, Kai, Borislav Petkov,
	Josh Triplett, Kai, David Rientjes, Jarkko Sakkinen

On Tue, Apr 23, 2019 at 11:59 AM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Mon, Apr 22, 2019 at 06:29:06PM -0700, Andy Lutomirski wrote:
> > 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...

Ugh.  It sounds like ignoring the fixup for #DB is the right call.
But what happens if the enclave contains an INT3 or ICEBP instruction?
 Are they magically promoted to #GP, perhaps?

As a maybe possible alternative, if we made it so that the AEX address
was not the same as the ENCLU, could we usefully distinguish these
exceptions based on RIP?  I suppose it's also worth considering
whether page faults from *inside* the enclave should result in SIGSEGV
or result in a fixup.  We certainly want page faults from the ENCLU
instruction itself to get fixed up, but maybe we want most exceptions
inside the enclave to work a bit differently.  Of course, if we do
this, we need to make sure that the semantics of returning from the
signal handler are reasonable.

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

* Re: [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
                     ` (2 preceding siblings ...)
  2019-04-23  1:25   ` Andy Lutomirski
@ 2019-04-23 19:26   ` Sean Christopherson
  2019-04-23 19:44     ` Andy Lutomirski
  3 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-23 19:26 UTC (permalink / raw)
  To: Cedric Xing
  Cc: linux-kernel, x86, linux-sgx, akpm, Hansen, Dave, Christopherson,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, andriy.shevchenko, tglx, Svahn, Kai, bp, josh, luto, Kai,
	rientjes, Jarkko Sakkinen

On Mon, Apr 22, 2019 at 05:37:24PM -0700, Cedric Xing wrote:
> The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
> which prohibits enclaves from allocating and passing parameters for
> untrusted function calls (aka. o-calls).
>
> This patch addresses the problem above by introducing a new ABI that preserves
> %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
> using %rbp so that enclaves are allowed to allocate space on the untrusted
> stack by decrementing %rsp. Please note that the stack space allocated in such
> way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
> __vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
> been changed to take a callback function as an optional parameter, which if
> supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
> eXit) and normal exits), with the value of %rsp left
> off by the enclave as a parameter to the callback.
>
> Here's the summary of API/ABI changes in this patch. More details could be
> found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
> * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
>   because it is filled upon both AEX (i.e. exceptions) and normal enclave
>   exits.
> * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
>   the previous implementation).
> * __vdso_sgx_enter_enclave() takes one more parameter - a callback function to
>   be invoked upon enclave exits. This callback is optional, and if not
>   supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave exits
>   (same behavior as previous implementation).
> * The callback function is given as a parameter the value of %rsp at enclave
>   exit to address data "pushed" by the enclave. A positive value returned by
>   the callback will be treated as an ENCLU leaf for re-entering the enclave,
>   while a zero or negative value will be passed through as the return
>   value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
>   leave callback by longjmp() or by throwing a C++ exception.
>
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---
>  arch/x86/entry/vdso/vsgx_enter_enclave.S | 156 ++++++++++++++---------
>  arch/x86/include/uapi/asm/sgx.h          |  14 +-
>  2 files changed, 100 insertions(+), 70 deletions(-)
>
> diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> index fe0bf6671d6d..210f4366374a 100644
> --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> @@ -14,88 +14,118 @@
>  .code64
>  .section .text, "ax"
>
> -#ifdef SGX_KERNEL_DOC

This #ifdef and the pseudo-C code below has a functional purpose.  From
the original commit:

  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.

We don't need full pseudocode, but a C-like prototype is necessary to get
the kernel-doc comment parsed correctly.

I'll try to look at the actual code later today.

>  /**
>   * __vdso_sgx_enter_enclave() - Enter an SGX enclave
>   *
>   * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
> - * @tcs:	**IN \%rbx** - TCS, must be non-NULL
> - * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
> + * @tcs:	**IN 0x08(\%rsp)** - TCS, must be non-NULL
> + * @ex_info:	**IN 0x10(\%rsp)** - Optional 'struct sgx_enclave_exinfo'
> + *				     pointer
> + * @callback:	**IN 0x18(\%rsp)** - Optional callback function to be called on
> + *				     enclave exit or exception
>   *
>   * Return:
>   *  **OUT \%eax** -
> - *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
> - *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
> + *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is not
> + *  allowed, %-EFAULT if ENCLU or the enclave faults, or a non-positive value
> + *  returned from ``callback`` (if one is supplied).
>   *
>   * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
> - * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
> - * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
> - * the return value passed via ``%eax``.  All registers except ``%rsp`` must
> - * be treated as volatile from the caller's perspective, including but not
> - * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
> - * being run **must** preserve the untrusted ``%rsp`` and stack.
> + * x86-64 ABI, i.e. cannot be called from standard C code. As noted above,
> + * input parameters must be passed via ``%eax``, ``8(%rsp)``, ``0x10(%rsp)`` and
> + * ``0x18(%rsp)``, with the return value passed via ``%eax``. All other registers
> + * will be passed through to the enclave as is. All registers except ``%rbp``
> + * must be treated as volatile from the caller's perspective, including but not
> + * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely, the enclave being
> + * run **must** preserve the untrusted ``%rbp``.
> + *
> + * ``callback`` has the following signature:
> + * int callback(long rdi, long rsi, long rdx,
> + *		struct sgx_enclave_exinfo *ex_info, long r8, long r9,
> + *		void *tcs, long ursp);
> + * ``callback`` **shall** follow x86_64 ABI. All GPRs **except** ``%rax``, ``%rbx``
> + * and ``rcx`` are passed through to ``callback``. ``%rdi``, ``%rsi``, ``%rdx``,
> + * ``%r8``, ``%r9``, along with the value of ``%rsp`` when the enclave exited/excepted,
> + * can be accessed directly as input parameters, while other GPRs can be
> + * accessed in assembly if needed.
> + * A positive value returned from ``callback`` will be treated as an ENCLU leaf
> + * (e.g. EENTER/ERESUME) to reenter the enclave, while 0 or a negative return
> + * value will be passed back to the caller of __vdso_sgx_enter_enclave().
> + * It is also **safe** to ``longjmp()`` out of ``callback``.
>   */
> -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> -			 struct sgx_enclave_exception *ex_info)
> -{
> -	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> -		return -EINVAL;
> -
> -	if (!tcs)
> -		return -EINVAL;
> -
> -	try {
> -		ENCLU[leaf];
> -	} catch (exception) {
> -		if (e)
> -			*e = exception;
> -		return -EFAULT;
> -	}
> -
> -	return 0;
> -}
> -#endif

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

* Re: [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-23 19:26   ` Sean Christopherson
@ 2019-04-23 19:44     ` Andy Lutomirski
  0 siblings, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-04-23 19:44 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Cedric Xing, linux-kernel, x86, linux-sgx, akpm, Hansen, Dave,
	Christopherson, nhorman, npmccallum, Ayoun, Serge, Katz-zamir,
	Shay, Huang, Haitao, andriy.shevchenko, tglx, Svahn, Kai, bp,
	josh, luto, Kai, rientjes, Jarkko Sakkinen



> On Apr 23, 2019, at 12:26 PM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> 
>> On Mon, Apr 22, 2019 at 05:37:24PM -0700, Cedric Xing wrote:
>> The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
>> which prohibits enclaves from allocating and passing parameters for
>> untrusted function calls (aka. o-calls).
>> 
>> This patch addresses the problem above by introducing a new ABI that preserves
>> %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
>> using %rbp so that enclaves are allowed to allocate space on the untrusted
>> stack by decrementing %rsp. Please note that the stack space allocated in such
>> way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
>> __vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
>> been changed to take a callback function as an optional parameter, which if
>> supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
>> eXit) and normal exits), with the value of %rsp left
>> off by the enclave as a parameter to the callback.
>> 
>> Here's the summary of API/ABI changes in this patch. More details could be
>> found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
>> * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
>>  because it is filled upon both AEX (i.e. exceptions) and normal enclave
>>  exits.
>> * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
>>  the previous implementation).
>> * __vdso_sgx_enter_enclave() takes one more parameter - a callback function to
>>  be invoked upon enclave exits. This callback is optional, and if not
>>  supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave exits
>>  (same behavior as previous implementation).
>> * The callback function is given as a parameter the value of %rsp at enclave
>>  exit to address data "pushed" by the enclave. A positive value returned by
>>  the callback will be treated as an ENCLU leaf for re-entering the enclave,
>>  while a zero or negative value will be passed through as the return
>>  value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
>>  leave callback by longjmp() or by throwing a C++ exception.
>> 
>> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
>> ---
>> arch/x86/entry/vdso/vsgx_enter_enclave.S | 156 ++++++++++++++---------
>> arch/x86/include/uapi/asm/sgx.h          |  14 +-
>> 2 files changed, 100 insertions(+), 70 deletions(-)
>> 
>> diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
>> index fe0bf6671d6d..210f4366374a 100644
>> --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
>> +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
>> @@ -14,88 +14,118 @@
>> .code64
>> .section .text, "ax"
>> 
>> -#ifdef SGX_KERNEL_DOC
> 
> This #ifdef and the pseudo-C code below has a functional purpose.  From
> the original commit:
> 
>  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.
> 
> We don't need full pseudocode, but a C-like prototype is necessary to get
> the kernel-doc comment parsed correctly.

That should be explained in a comment :)

—Andy


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

* Re: [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-23 19:07       ` Andy Lutomirski
@ 2019-04-23 20:11         ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-04-23 20:11 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Cedric Xing, LKML, X86 ML, linux-sgx, Andrew Morton, Dave,
	nhorman, npmccallum, Serge, Shay, Haitao, Andy Shevchenko,
	Thomas Gleixner, Kai, Borislav Petkov, Josh Triplett, Kai,
	David Rientjes, Jarkko Sakkinen

On Tue, Apr 23, 2019 at 12:07:26PM -0700, Andy Lutomirski wrote:
> On Tue, Apr 23, 2019 at 11:59 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Mon, Apr 22, 2019 at 06:29:06PM -0700, Andy Lutomirski wrote:
> > > 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...
> 
> Ugh.  It sounds like ignoring the fixup for #DB is the right call.
> But what happens if the enclave contains an INT3 or ICEBP instruction?
>  Are they magically promoted to #GP, perhaps?

#UD for opt-out, a.k.a. non-debug, enclaves.  Delivered "normally" for
opt-in debug enclaves, except they're fault-like instead of trap-like.

> As a maybe possible alternative, if we made it so that the AEX address
> was not the same as the ENCLU, could we usefully distinguish these
> exceptions based on RIP?

Not really, because a user could set a code breakpoint on the AEX or
insert an INT3, e.g. to break on exit from the enclave.

Theoretically the kernel could cross-reference addresses to determine
whether or not a DRx match occurred on an enclave address, but a) that'd
be pretty ugly to implement and b) there would still be ambiguity, e.g. if
there's a code breakpoint on the AEX and a #DB occurs in the enclave, then
DR6 will record both the in-enclave DRx match and the AEX (non-enclave)
DRx match.

> I suppose it's also worth considering
> whether page faults from *inside* the enclave should result in SIGSEGV
> or result in a fixup.  We certainly want page faults from the ENCLU
> instruction itself to get fixed up, but maybe we want most exceptions
> inside the enclave to work a bit differently.  Of course, if we do
> this, we need to make sure that the semantics of returning from the
> signal handler are reasonable.

Hmm, I'm pretty sure any fault that is 100% in the domain of the enclave
should result in fixup.

Here are a few use cases off the top of my head that would require the
enclave's runtime to intercept the signal, either to reenter the enclave
or to feed the fault into the enclave's handler:

  - Handle EPC invalidation, e.g. due to VM migration, while a thread is
    in the enclave since the resulting #PF can occur inside the enclave.

  - During enclave development, configure the runtime to call into the
    enclave on any exception so that the enclave can dump register state.

  - Implement copy-on-write or lazy allocation using SGX2 instructions,
    which would require feeding the #PF back into the enclave.  Purely
    theoretical AFAIK, but lazy allocation in particular could be
    interesting, e.g. don't allocate .bss pages at startup time.

  - An enclave and its runtime might feed #UDs back into the enclave,
    e.g. to run an unmodified binary in an enclave by wrapping it in a
    shim of sorts.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-22 16:26                               ` Andy Lutomirski
@ 2019-04-23 21:15                                 ` Jethro Beekman
  2019-05-10 17:23                                 ` Xing, Cedric
  1 sibling, 0 replies; 318+ messages in thread
From: Jethro Beekman @ 2019-04-23 21:15 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Thomas Gleixner, Dr. Greg, Dave Hansen, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

[-- Attachment #1: Type: text/plain, Size: 5839 bytes --]

On 2019-04-22 09:26, Andy Lutomirski wrote:
>> On Apr 19, 2019, at 2:56 PM, Jethro Beekman <jethro@fortanix.com> wrote:
>> 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!
> 
>>
>> 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?

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

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

> 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


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-04-22 21:58   ` Sean Christopherson
@ 2019-04-23 23:29     ` Jethro Beekman
  2019-04-24  0:26       ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-04-23 23:29 UTC (permalink / raw)
  To: Sean Christopherson, Jarkko Sakkinen
  Cc: linux-kernel, x86, linux-sgx, akpm, dave.hansen, nhorman,
	npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

[-- Attachment #1: Type: text/plain, Size: 2739 bytes --]

On 2019-04-22 14:58, Sean Christopherson wrote:
> +Cc Jethro
> 
> On Wed, Apr 17, 2019 at 01:39:25PM +0300, Jarkko Sakkinen wrote:
>> Intel Software Guard eXtensions (SGX) is a set of CPU instructions that
>> can be used by applications to set aside private regions of code and
>> data. The code outside the 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.
>>
>> Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
>> Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
>> Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
>> Co-developed-by: Serge Ayoun <serge.ayoun@intel.com>
>> Signed-off-by: Serge Ayoun <serge.ayoun@intel.com>
>> Co-developed-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
>> Signed-off-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
>> Co-developed-by: Suresh Siddha <suresh.b.siddha@intel.com>
>> Signed-off-by: Suresh Siddha <suresh.b.siddha@intel.com>
>> ---
> 
> ...
> 
>> +#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,
>> +	.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.

> 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


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-04-23 23:29     ` Jethro Beekman
@ 2019-04-24  0:26       ` Sean Christopherson
  2019-04-24  1:04         ` Jethro Beekman
  2019-06-04 20:12         ` Sean Christopherson
  0 siblings, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-04-24  0:26 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Jarkko Sakkinen, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	nhorman, npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

On Tue, Apr 23, 2019 at 11:29:24PM +0000, Jethro Beekman wrote:
> On 2019-04-22 14:58, Sean Christopherson wrote:
> >+Cc Jethro
> >
> >On Wed, Apr 17, 2019 at 01:39:25PM +0300, Jarkko Sakkinen wrote:
> >>Intel Software Guard eXtensions (SGX) is a set of CPU instructions that
> >>can be used by applications to set aside private regions of code and
> >>data. The code outside the 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.
> >>
> >>Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
> >>Co-developed-by: Sean Christopherson <sean.j.christopherson@intel.com>
> >>Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>
> >>Co-developed-by: Serge Ayoun <serge.ayoun@intel.com>
> >>Signed-off-by: Serge Ayoun <serge.ayoun@intel.com>
> >>Co-developed-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
> >>Signed-off-by: Shay Katz-zamir <shay.katz-zamir@intel.com>
> >>Co-developed-by: Suresh Siddha <suresh.b.siddha@intel.com>
> >>Signed-off-by: Suresh Siddha <suresh.b.siddha@intel.com>
> >>---
> >
> >...
> >
> >>+#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,
> >>+	.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.

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.

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

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-04-24  0:26       ` Sean Christopherson
@ 2019-04-24  1:04         ` Jethro Beekman
  2019-04-29 19:08           ` Sean Christopherson
  2019-06-04 20:12         ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-04-24  1:04 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Jarkko Sakkinen, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	nhorman, npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

[-- Attachment #1: Type: text/plain, Size: 903 bytes --]

On 2019-04-23 17:26, Sean Christopherson wrote:
> On Tue, Apr 23, 2019 at 11:29:24PM +0000, Jethro Beekman wrote:
>> On 2019-04-22 14:58, Sean Christopherson wrote:
>>> 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.

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

--
Jethro Beekman | Fortanix


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* Re: [PATCH v20 16/28] x86/sgx: Add provisioning
  2019-04-17 10:39 ` [PATCH v20 16/28] x86/sgx: Add provisioning Jarkko Sakkinen
  2019-04-19  3:06   ` Huang, Kai
@ 2019-04-24  1:34   ` Jethro Beekman
  2019-05-02  8:27     ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-04-24  1:34 UTC (permalink / raw)
  To: Jarkko Sakkinen, linux-kernel, x86, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, nhorman, npmccallum,
	serge.ayoun, shay.katz-zamir, haitao.huang, andriy.shevchenko,
	tglx, kai.svahn, bp, josh, luto, kai.huang, rientjes,
	James Morris, Serge E . Hallyn, linux-security-module

[-- Attachment #1: Type: text/plain, Size: 622 bytes --]

On 2019-04-17 03:39, Jarkko Sakkinen wrote:
> diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
> index 7bf627ac4958..3b80acde8671 100644
> --- a/arch/x86/include/uapi/asm/sgx.h
> +++ b/arch/x86/include/uapi/asm/sgx.h
> @@ -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


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
  2019-04-22 22:05   ` Sean Christopherson
  2019-04-23  0:37   ` Cedric Xing
@ 2019-04-24  6:26   ` Cedric Xing
  2019-07-10 11:17     ` Jarkko Sakkinen
                       ` (4 more replies)
  2019-04-24  6:26   ` [RFC PATCH v2 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
                     ` (2 subsequent siblings)
  5 siblings, 5 replies; 318+ messages in thread
From: Cedric Xing @ 2019-04-24  6:26 UTC (permalink / raw)
  To: linux-kernel, linux-sgx
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang,
	jarkko.sakkinen

The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
%rsp, which prohibits enclaves from allocating space on the untrusted stack.
However, there are existing enclaves (e.g. those built with current Intel SGX
SDK libraries) relying on the untrusted stack for passing parameters to
untrusted functions (aka. o-calls), which requires allocating space on the
untrusted stack by enclaves. And given its simplicity and convenience, it could
be desired by future SGX applications as well.  

This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its
stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto
the untrusted stack by decrementing the untrusted %rsp. Additionally, this new
__vdso_sgx_enter_enclave() will take one more parameter - a callback function,
to be invoked upon all enclave exits (both AEX and normal exits). The callback
function will be given the value of %rsp left off by the enclave, so that data
"pushed" by the enclave (if any) could be addressed/accessed.  Please note that
the callback function is optional, and if not supplied (i.e. null),
__vdso_sgx_enter_enclave() will just return (i.e. behave the same as the
current implementation) after the enclave exits (or AEX due to exceptions).

The SGX selftest is augmented by two new tests. One exercises the new callback
interface, and serves as a simple example to showcase how to use it; while the
other validates the hand-crafted CFI directives in __vdso_sgx_enter_enclave()
by single-stepping through it and unwinding call stack at every instruction.

v2:
  - Revised comments in __vdso_sgx_enter_enclave(). See patch 2/3.
  - Added stack unwind test. See patch 3/3.

v1: https://lkml.org/lkml/2019/4/22/871

Note: This patchset is based upon SGX1 patch v20
(https://lkml.org/lkml/2019/4/17/344) by Jarkko Sakkinen

Cedric Xing (3):
  selftests/x86: Fixed Makefile for SGX selftest
  x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing
    on untrusted stack
  selftests/x86: Augment SGX selftest to test new
    __vdso_sgx_enter_enclave() and its callback interface

 arch/x86/entry/vdso/vsgx_enter_enclave.S   | 175 +++++++----
 arch/x86/include/uapi/asm/sgx.h            |  14 +-
 tools/testing/selftests/x86/Makefile       |  12 +-
 tools/testing/selftests/x86/sgx/Makefile   |  49 ++--
 tools/testing/selftests/x86/sgx/main.c     | 323 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
 6 files changed, 471 insertions(+), 142 deletions(-)

-- 
2.17.1


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

* [RFC PATCH v2 1/3] selftests/x86: Fixed Makefile for SGX selftest
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
                     ` (2 preceding siblings ...)
  2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
@ 2019-04-24  6:26   ` Cedric Xing
  2019-07-12  3:19     ` Jarkko Sakkinen
  2019-04-24  6:26   ` [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
  2019-04-24  6:26   ` [RFC PATCH v2 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
  5 siblings, 1 reply; 318+ messages in thread
From: Cedric Xing @ 2019-04-24  6:26 UTC (permalink / raw)
  To: linux-kernel, linux-sgx
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang,
	jarkko.sakkinen

The original x86/sgx/Makefile doesn't work when 'x86/sgx' is specified as the
test target. This patch fixes that problem, along with minor changes to the
dependencies between 'x86' and 'x86/sgx' in selftests/x86/Makefile.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/Makefile     | 12 +++----
 tools/testing/selftests/x86/sgx/Makefile | 45 +++++++++---------------
 2 files changed, 22 insertions(+), 35 deletions(-)

diff --git a/tools/testing/selftests/x86/Makefile b/tools/testing/selftests/x86/Makefile
index 4fc9a42f56ea..1294c5f5b6ca 100644
--- a/tools/testing/selftests/x86/Makefile
+++ b/tools/testing/selftests/x86/Makefile
@@ -70,11 +70,11 @@ 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 $@;	\
+all_64: | $(SUBDIRS_64)
+	@for DIR in $|; do					\
+		BUILD_TARGET=$(OUTPUT)/$$DIR;			\
+		mkdir $$BUILD_TARGET  -p;			\
+		$(MAKE) OUTPUT=$$BUILD_TARGET -C $$DIR $@;	\
 	done
 
 EXTRA_CLEAN := $(BINARIES_32) $(BINARIES_64)
@@ -90,7 +90,7 @@ ifeq ($(CAN_BUILD_I386)$(CAN_BUILD_X86_64),01)
 all: warn_32bit_failure
 
 warn_32bit_failure:
-	@echo "Warning: you seem to have a broken 32-bit build" 2>&1; 	\
+	@echo "Warning: you seem to have a broken 32-bit build" 2>&1;	\
 	echo "environment.  This will reduce test coverage of 64-bit" 2>&1; \
 	echo "kernels.  If you are using a Debian-like distribution," 2>&1; \
 	echo "try:"; 2>&1; \
diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 1fd6f2708e81..3af15d7c8644 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -2,47 +2,34 @@ top_srcdir = ../../../../..
 
 include ../../lib.mk
 
-HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
-ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
+ifeq ($(shell $(CC) -dumpmachine | cut --delimiter=- -f1),x86_64)
+all: all_64
+endif
+
+HOST_CFLAGS := -Wall -Werror -g $(INCLUDES)
+ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIE \
 	       -fno-stack-protector -mrdrnd $(INCLUDES)
 
 TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
-$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
-		      $(OUTPUT)/encl_piggy.o
+$(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
 	$(CC) $(HOST_CFLAGS) -o $@ $^
 
-$(OUTPUT)/main.o: main.c
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/sgx_call.o: sgx_call.S
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
-	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
+$(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
-$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
+$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
 	objcopy --remove-section=.got.plt -O binary $< $@
 
-$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
-	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
+$(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
 
-$(OUTPUT)/encl.o: encl.c
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
-	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+$(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
+	$^ $@
 
 $(OUTPUT)/sgxsign: sgxsign.c
 	$(CC) -o $@ $< -lcrypto
 
-EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
-	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
-	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
-	       $(OUTPUT)/sgxsign
-
-.PHONY: clean
+EXTRA_CLEAN := $(TEST_CUSTOM_PROGS) $(addprefix $(OUTPUT)/,	\
+		encl.elf encl.bin encl.ss encl_piggy.o sgxsign)
-- 
2.17.1


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

* [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
                     ` (3 preceding siblings ...)
  2019-04-24  6:26   ` [RFC PATCH v2 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
@ 2019-04-24  6:26   ` Cedric Xing
  2019-04-24 19:04     ` Sean Christopherson
  2019-04-24  6:26   ` [RFC PATCH v2 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
  5 siblings, 1 reply; 318+ messages in thread
From: Cedric Xing @ 2019-04-24  6:26 UTC (permalink / raw)
  To: linux-kernel, linux-sgx
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang,
	jarkko.sakkinen

The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
which prohibits enclaves from allocating and passing parameters for
untrusted function calls (aka. o-calls).

This patch addresses the problem above by introducing a new ABI that preserves
%rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
using %rbp so that enclaves are allowed to allocate space on the untrusted
stack by decrementing %rsp. Please note that the stack space allocated in such
way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
__vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
been revised to take a callback function as an optional parameter, which if
supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
eXit) and normal exits), with the value of %rsp left off by the enclave as a
parameter to the callback.

Here's the summary of API/ABI changes in this patch. More details could be
found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
* 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
  because it is filled upon both AEX (i.e. exceptions) and normal enclave
  exits.
* __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
  the previous implementation).
* __vdso_sgx_enter_enclave() takes one more parameter - a callback function to
  be invoked upon enclave exits. This callback is optional, and if not
  supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave exits
  (same behavior as previous implementation).
* The callback function is given as a parameter the value of %rsp at enclave
  exit to address data "pushed" by the enclave. A positive value returned by
  the callback will be treated as an ENCLU leaf for re-entering the enclave,
  while a zero or negative value will be passed through as the return
  value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
  leave callback by longjmp() or by throwing a C++ exception.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 arch/x86/entry/vdso/vsgx_enter_enclave.S | 175 ++++++++++++++++-------
 arch/x86/include/uapi/asm/sgx.h          |  14 +-
 2 files changed, 128 insertions(+), 61 deletions(-)

diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
index fe0bf6671d6d..debecb0d785c 100644
--- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
+++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
@@ -19,83 +19,150 @@
  * __vdso_sgx_enter_enclave() - Enter an SGX enclave
  *
  * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
- * @tcs:	**IN \%rbx** - TCS, must be non-NULL
- * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
+ * @tcs:	**IN 0x08(\%rsp)** - TCS, must be non-NULL
+ * @ex_info:	**IN 0x10(\%rsp)** - Optional 'struct sgx_enclave_exinfo'
+ *				     pointer
+ * @callback:	**IN 0x18(\%rsp)** - Optional callback function to be called on
+ *				     enclave exit or exception
  *
  * Return:
  *  **OUT \%eax** -
- *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
- *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
+ *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is not
+ *  allowed, %-EFAULT if ENCLU or the enclave faults, or a non-positive value
+ *  returned from ``callback`` (if one is supplied).
  *
  * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
- * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
- * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
- * the return value passed via ``%eax``.  All registers except ``%rsp`` must
- * be treated as volatile from the caller's perspective, including but not
- * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
- * being run **must** preserve the untrusted ``%rsp`` and stack.
+ * x86-64 ABI, i.e. cannot be called from standard C code. As noted above,
+ * input parameters must be passed via ``%eax``, ``8(%rsp)``, ``0x10(%rsp)`` and
+ * ``0x18(%rsp)``, with the return value passed via ``%eax``. All other
+ * registers will be passed through to the enclave as is. All registers except
+ * ``%rbp`` must be treated as volatile from the caller's perspective, including
+ * but not limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely, the
+ * enclave being run **must** preserve the untrusted ``%rbp``.
+ *
+ * ``callback`` has the following signature:
+ * int callback(long rdi, long rsi, long rdx,
+ *		struct sgx_enclave_exinfo *exinfo, long r8, long r9,
+ *		void *tcs, long ursp);
+ * ``callback`` **shall** follow x86_64 ABI. All GPRs **except** ``%rax``,
+ * ``%rbx`` and ``rcx`` are passed through to ``callback``. ``%rdi``, ``%rsi``,
+ * ``%rdx``, ``%r8``, ``%r9``, along with the value of ``%rsp`` when the enclave
+ * exited/excepted, can be accessed directly as input parameters, while other
+ * GPRs can be accessed in assembly if needed.  A positive value returned from
+ * ``callback`` will be treated as an ENCLU leaf (e.g. EENTER/ERESUME) to
+ * reenter the enclave (without popping the extra data pushed by the enclave off
+ * the stack), while 0 (zero) or a negative return value will be passed back to
+ * the caller of __vdso_sgx_enter_enclave(). It is also safe to leave
+ * ``callback`` via ``longjmp()`` or by throwing a C++ exception.
  */
-__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
-			 struct sgx_enclave_exception *ex_info)
+typedef int (*sgx_callback)(long rdi, long rsi, long rdx,
+			    struct sgx_enclave_exinfo *exinfo, long r8,
+			    long r9, void *tcs, long ursp);
+int __vdso_sgx_enter_enclave(int leaf, void *tcs,
+			     struct sgx_enclave_exinfo *exinfo,
+			     sgx_callback callback)
 {
-	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
-		return -EINVAL;
-
-	if (!tcs)
-		return -EINVAL;
-
-	try {
-		ENCLU[leaf];
-	} catch (exception) {
-		if (e)
-			*e = exception;
-		return -EFAULT;
+	while (leaf == EENTER || leaf == ERESUME) {
+		int rc;
+		try {
+			ENCLU[leaf];
+			rc = 0;
+			if (exinfo)
+				exinfo->leaf = EEXIT;
+		} catch (exception) {
+			rc = -EFAULT;
+			if (exinfo)
+				*exinfo = exception;
+		}
+
+		leaf = callback ? (*callback)(
+			rdi, rsi, rdx, exinfo, r8, r9, tcs, ursp) : rc;
 	}
 
-	return 0;
+	return leaf > 0 ? -EINVAL : leaf;
 }
 #endif
 ENTRY(__vdso_sgx_enter_enclave)
-	/* EENTER <= leaf <= ERESUME */
+	/* Prolog */
+	.cfi_startproc
+	push	%rbp
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbp, 0
+	mov	%rsp, %rbp
+	.cfi_def_cfa_register	%rbp
+
+1:	/* EENTER <= leaf <= ERESUME */
 	cmp	$0x2, %eax
-	jb	bad_input
-
+	jb	6f
 	cmp	$0x3, %eax
-	ja	bad_input
+	ja	6f
 
-	/* TCS must be non-NULL */
-	test	%rbx, %rbx
-	je	bad_input
+	/* Load TCS and AEP */
+	mov	0x10(%rbp), %rbx
+	lea	2f(%rip), %rcx
 
-	/* Save @exception_info */
-	push	%rcx
+	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
+2:	enclu
 
-	/* Load AEP for ENCLU */
-	lea	1f(%rip),  %rcx
-1:	enclu
+	/* EEXIT path */
+	xor	%ebx, %ebx
+3:	mov	0x18(%rbp), %rcx
+	jrcxz	4f
+	mov	%eax, EX_LEAF(%rcx)
+	jnc	4f
+	mov	%di, EX_TRAPNR(%rcx)
+	mov	%si, EX_ERROR_CODE(%rcx)
+	mov	%rdx, EX_ADDRESS(%rcx)
 
-	add	$0x8, %rsp
-	xor	%eax, %eax
+4:	/* Call *callback if supplied */
+	mov	0x20(%rbp), %rax
+	test	%rax, %rax
+	/* At this point, %ebx holds the effective return value, which shall be
+	 * returned if no callback is specified */
+	cmovz	%rbx, %rax
+	jz	7f
+	/* Align stack per x86_64 ABI. The original %rsp is saved in %rbx to be
+	 * restored after *callback returns. */
+	mov	%rsp, %rbx
+	and	$-0x10, %rsp
+	/* Clear RFLAGS.DF per x86_64 ABI */
+	cld
+	/* Parameters for *callback */
+	push	%rbx
+	push	0x10(%rbp)
+	/* Call *%rax via retpoline */
+	call	40f
+	/* Restore %rsp to its original value left off by the enclave from last
+	 * exit */
+	mov	%rbx, %rsp
+	/* Positive return value from *callback will be interpreted as an ENCLU
+	 * leaf, while a non-positive value will be interpreted as the return
+	 * value to be passed back to the caller. */
+	jmp	1b
+40:	/* retpoline */
+	call	42f
+41:	pause
+	lfence
+	jmp	41b
+42:	mov	%rax, (%rsp)
 	ret
 
-bad_input:
-	mov     $(-EINVAL), %rax
-	ret
+5:	/* Exception path */
+	mov	$-EFAULT, %ebx
+	stc
+	jmp	3b
 
-.pushsection .fixup, "ax"
-	/* Re-load @exception_info and fill it (if it's non-NULL) */
-2:	pop	%rcx
-	test    %rcx, %rcx
-	je      3f
+6:	/* Unsupported ENCLU leaf */
+	cmp	$0, %eax
+	jle	7f
+	mov	$-EINVAL, %eax
 
-	mov	%eax, EX_LEAF(%rcx)
-	mov	%di,  EX_TRAPNR(%rcx)
-	mov	%si,  EX_ERROR_CODE(%rcx)
-	mov	%rdx, EX_ADDRESS(%rcx)
-3:	mov	$(-EFAULT), %rax
+7:	/* Epilog */
+	leave
+	.cfi_def_cfa		%rsp, 8
 	ret
-.popsection
+	.cfi_endproc
 
-_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
+_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
 
 ENDPROC(__vdso_sgx_enter_enclave)
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 9ed690a38c70..50d2b5143e5e 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -24,7 +24,7 @@
 
 /**
  * struct sgx_enclave_create - parameter structure for the
- *                             %SGX_IOC_ENCLAVE_CREATE ioctl
+ *			       %SGX_IOC_ENCLAVE_CREATE ioctl
  * @src:	address for the SECS page data
  */
 struct sgx_enclave_create  {
@@ -33,7 +33,7 @@ struct sgx_enclave_create  {
 
 /**
  * struct sgx_enclave_add_page - parameter structure for the
- *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
+ *				 %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
  * @addr:	address within the ELRANGE
  * @src:	address for the page data
  * @secinfo:	address for the SECINFO data
@@ -49,7 +49,7 @@ struct sgx_enclave_add_page {
 
 /**
  * struct sgx_enclave_init - parameter structure for the
- *                           %SGX_IOC_ENCLAVE_INIT ioctl
+ *			     %SGX_IOC_ENCLAVE_INIT ioctl
  * @sigstruct:	address for the SIGSTRUCT data
  */
 struct sgx_enclave_init {
@@ -66,16 +66,16 @@ struct sgx_enclave_set_attribute {
 };
 
 /**
- * struct sgx_enclave_exception - structure to report exceptions encountered in
- *				  __vdso_sgx_enter_enclave()
+ * struct sgx_enclave_exinfo - structure to report exceptions encountered in
+ *			       __vdso_sgx_enter_enclave()
  *
- * @leaf:	ENCLU leaf from \%eax at time of exception
+ * @leaf:	ENCLU leaf from \%eax at time of exception/exit
  * @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 {
+struct sgx_enclave_exinfo {
 	__u32 leaf;
 	__u16 trapnr;
 	__u16 error_code;
-- 
2.17.1


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

* [RFC PATCH v2 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
                     ` (4 preceding siblings ...)
  2019-04-24  6:26   ` [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-04-24  6:26   ` Cedric Xing
  2019-07-12  3:25     ` Jarkko Sakkinen
  5 siblings, 1 reply; 318+ messages in thread
From: Cedric Xing @ 2019-04-24  6:26 UTC (permalink / raw)
  To: linux-kernel, linux-sgx
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang,
	jarkko.sakkinen

This patch augments SGX selftest with two new tests.

The first test exercises the newly added callback interface, by marking the
whole enclave range as PROT_READ, then calling mprotect() upon #PFs to add
necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.
This test also serves as an example to demonstrate the callback interface.

The second test single-steps through __vdso_sgx_enter_enclave() to make sure
the call stack can be unwound at every instruction within that vDSO API. Its
purpose is to validate the hand-crafted CFI directives in the assembly.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/sgx/Makefile   |   6 +-
 tools/testing/selftests/x86/sgx/main.c     | 323 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
 3 files changed, 322 insertions(+), 47 deletions(-)

diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 3af15d7c8644..31f937e220c4 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -14,16 +14,16 @@ TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
 $(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
-	$(CC) $(HOST_CFLAGS) -o $@ $^
+	$(CC) $(HOST_CFLAGS) -o $@ $^ -lunwind -ldl -Wl,--defsym,__image_base=0 -pie
 
 $(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
 	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
 $(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
-	objcopy --remove-section=.got.plt -O binary $< $@
+	objcopy -O binary $< $@
 
 $(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@ -Wl,--build-id=none
 
 $(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
 	$^ $@
diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
index e2265f841fb0..d3e53c71306d 100644
--- a/tools/testing/selftests/x86/sgx/main.c
+++ b/tools/testing/selftests/x86/sgx/main.c
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
 // Copyright(c) 2016-18 Intel Corporation.
 
+#define _GNU_SOURCE
 #include <elf.h>
 #include <fcntl.h>
 #include <stdbool.h>
@@ -9,16 +10,31 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <errno.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
-#include <sys/time.h>
+#include <sys/auxv.h>
+#include <signal.h>
+#include <sys/ucontext.h>
+
+#define UNW_LOCAL_ONLY
+#include <libunwind.h>
+
 #include "encl_piggy.h"
 #include "defines.h"
 #include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
 #include "../../../../../arch/x86/include/uapi/asm/sgx.h"
 
-static const uint64_t MAGIC = 0x1122334455667788ULL;
+#define _Q(x)	__Q(x)
+#define __Q(x)	#x
+#define ERRLN	"Line " _Q(__LINE__)
+
+#define X86_EFLAGS_TF	(1ul << 8)
+
+extern char __image_base[];
+size_t eenter;
+static size_t vdso_base;
 
 struct vdso_symtab {
 	Elf64_Sym *elf_symtab;
@@ -26,20 +42,11 @@ struct vdso_symtab {
 	Elf64_Word *elf_hashtab;
 };
 
-static void *vdso_get_base_addr(char *envp[])
+static void vdso_init(void)
 {
-	Elf64_auxv_t *auxv;
-	int i;
-
-	for (i = 0; envp[i]; i++);
-	auxv = (Elf64_auxv_t *)&envp[i + 1];
-
-	for (i = 0; auxv[i].a_type != AT_NULL; i++) {
-		if (auxv[i].a_type == AT_SYSINFO_EHDR)
-			return (void *)auxv[i].a_un.a_val;
-	}
-
-	return NULL;
+	vdso_base = getauxval(AT_SYSINFO_EHDR);
+	if (!vdso_base)
+		exit(1);
 }
 
 static Elf64_Dyn *vdso_get_dyntab(void *addr)
@@ -66,8 +73,9 @@ static void *vdso_get_dyn(void *addr, Elf64_Dyn *dyntab, Elf64_Sxword tag)
 	return NULL;
 }
 
-static bool vdso_get_symtab(void *addr, struct vdso_symtab *symtab)
+static bool vdso_get_symtab(struct vdso_symtab *symtab)
 {
+	void *addr = (void *)vdso_base;
 	Elf64_Dyn *dyntab = vdso_get_dyntab(addr);
 
 	symtab->elf_symtab = vdso_get_dyn(addr, dyntab, DT_SYMTAB);
@@ -138,7 +146,7 @@ static bool encl_create(int dev_fd, unsigned long bin_size,
 	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
 		    MAP_SHARED, dev_fd, 0);
 	if (base == MAP_FAILED) {
-		perror("mmap");
+		perror(ERRLN);
 		return false;
 	}
 
@@ -224,35 +232,271 @@ static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
 	return false;
 }
 
-void sgx_call(void *rdi, void *rsi, void *tcs,
-	      struct sgx_enclave_exception *exception,
-	      void *eenter);
+int sgx_call(void *rdi, void *rsi, long rdx, void *rcx, void *r8, void *r9,
+	     void *tcs, struct sgx_enclave_exinfo *ei, void *cb);
+
+static void show_enclave_exinfo(const struct sgx_enclave_exinfo *exinfop,
+				const char *header)
+{
+	static const char * const enclu_leaves[] = {
+		"EREPORT",
+		"EGETKEY",
+		"EENTER",
+		"ERESUME",
+		"EEXIT"
+	};
+	static const char * const exception_names[] = {
+		"#DE",
+		"#DB",
+		"NMI",
+		"#BP",
+		"#OF",
+		"#BR",
+		"#UD",
+		"#NM",
+		"#DF",
+		"CSO",
+		"#TS",
+		"#NP",
+		"#SS",
+		"#GP",
+		"#PF",
+		"Unknown",
+		"#MF",
+		"#AC",
+		"#MC",
+		"#XM",
+		"#VE",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown"
+	};
+
+	printf("%s: leaf:%s(%d)", header,
+		enclu_leaves[exinfop->leaf], exinfop->leaf);
+	if (exinfop->leaf != 4)
+		printf(" trap:%s(%d) ec:%d addr:0x%llx\n",
+			exception_names[exinfop->trapnr], exinfop->trapnr,
+			exinfop->error_code, exinfop->address);
+	else
+		printf("\n");
+}
+
+static const uint64_t MAGIC = 0x1122334455667788ULL;
 
-int main(int argc, char *argv[], char *envp[])
+static void test1(struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[1] Entering the enclave without callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, NULL);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Null TCS\n Expect: #PF at EENTER\n");
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 NULL, &exinfo, NULL);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 2 /*EENTER*/ || exinfo.trapnr != 14 /*#PF*/)
+		exit(1);
+}
+
+static int test2_callback(long rdi, long rsi, long rdx,
+			  struct sgx_enclave_exinfo *ei, long r8, long r9,
+			  void *tcs, long ursp)
+{
+	show_enclave_exinfo(ei, "  callback");
+
+	switch (ei->leaf) {
+	case 4:
+		return 0;
+	case 3:
+	case 2:
+		switch (ei->trapnr) {
+		case 1:	/*#DB*/
+			break;
+		case 14:/*#PF*/
+			if ((ei->error_code & 1) == 0) {
+				fprintf(stderr, ERRLN
+					": Unexpected #PF error code\n");
+				exit(1);
+			}
+			if (mprotect((void *)(ei->address & -0x1000), 0x1000,
+				     ((ei->error_code & 2) ? PROT_WRITE : 0) |
+				     ((ei->error_code & 0x10) ? PROT_EXEC : 0) |
+				     PROT_READ)) {
+				perror(ERRLN);
+				exit(1);
+			}
+			break;
+		default:
+			fprintf(stderr, ERRLN ": Unexpected exception\n");
+			exit(1);
+		}
+		return ei->leaf == 2 ? -EAGAIN : ei->leaf;
+	}
+	return -EINVAL;
+}
+
+static void test2(struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[2] Entering the enclave with callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, test2_callback);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Read-only enclave (0x%lx-0x%lx)\n"
+	       " Expect: #PFs to be fixed by callback\n",
+	       secs->base, secs->base + (encl_bin_end - encl_bin) - 1);
+	if (mprotect((void *)secs->base, encl_bin_end - encl_bin, PROT_READ)) {
+		perror(ERRLN);
+		exit(1);
+	}
+	while (sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+			(void *)secs->base, &exinfo, test2_callback) == -EAGAIN)
+		;
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 4 /*EEXIT*/)
+		exit(1);
+}
+
+static struct test3_proc_context {
+	unw_word_t	ip, bx, sp, bp, r12, r13, r14, r15;
+} test3_ctx;
+
+static unw_word_t test3_getcontext(unw_cursor_t *cursor,
+				   struct test3_proc_context *ctxp)
+{
+	unw_get_reg(cursor, UNW_REG_IP, &ctxp->ip);
+	unw_get_reg(cursor, UNW_REG_SP, &ctxp->sp);
+	unw_get_reg(cursor, UNW_X86_64_RBX, &ctxp->bx);
+	unw_get_reg(cursor, UNW_X86_64_RBP, &ctxp->bp);
+	unw_get_reg(cursor, UNW_X86_64_R12, &ctxp->r12);
+	unw_get_reg(cursor, UNW_X86_64_R13, &ctxp->r13);
+	unw_get_reg(cursor, UNW_X86_64_R14, &ctxp->r14);
+	unw_get_reg(cursor, UNW_X86_64_R15, &ctxp->r15);
+	return ctxp->ip;
+}
+
+static void test3_sigtrap(int sig, siginfo_t *info, ucontext_t *ctxp)
+{
+	static int in_vdso_eenter;
+	static size_t caller;
+
+	unw_cursor_t cursor;
+	unw_context_t uc;
+	struct test3_proc_context pc;
+
+	if (ctxp->uc_mcontext.gregs[REG_RIP] == eenter) {
+		in_vdso_eenter = 1;
+		caller = *(size_t *)(ctxp->uc_mcontext.gregs[REG_RSP]);
+		printf("  trace started at ip:%llx (vdso:0x%llx)\n",
+			ctxp->uc_mcontext.gregs[REG_RIP],
+			ctxp->uc_mcontext.gregs[REG_RIP] - vdso_base);
+	}
+
+	if (!in_vdso_eenter)
+		return;
+
+	if (ctxp->uc_mcontext.gregs[REG_RIP] == caller) {
+		in_vdso_eenter = 0;
+		ctxp->uc_mcontext.gregs[REG_EFL] &= ~X86_EFLAGS_TF;
+		printf("  trace ended successfully at ip:%llx (executable:0x%llx)\n",
+			ctxp->uc_mcontext.gregs[REG_RIP],
+			ctxp->uc_mcontext.gregs[REG_RIP] -
+				(size_t)__image_base);
+		return;
+	}
+
+	unw_getcontext(&uc);
+	unw_init_local(&cursor, &uc);
+	while (unw_step(&cursor) > 0 &&
+	       test3_getcontext(&cursor, &pc) != test3_ctx.ip)
+		;
+
+	if (memcmp(&pc, &test3_ctx, sizeof(pc))) {
+		fprintf(stderr, ERRLN ": Error unwinding\n");
+		exit(1);
+	}
+}
+
+static void test3_set_tf(void)
+{
+	__asm__ ("pushfq; orl %0, (%%rsp); popfq" : : "i"(X86_EFLAGS_TF));
+}
+
+static void test3(struct sgx_secs *secs)
+{
+	unw_cursor_t cursor;
+	unw_context_t uc;
+	struct sigaction sa = {
+		.sa_sigaction = (void (*)(int, siginfo_t*, void*))test3_sigtrap,
+		.sa_flags = SA_SIGINFO,
+	};
+
+	unw_getcontext(&uc);
+	unw_init_local(&cursor, &uc);
+	if (unw_step(&cursor) > 0)
+		test3_getcontext(&cursor, &test3_ctx);
+	else {
+		fprintf(stderr, ERRLN ": error initializing unwind context\n");
+		exit(1);
+	}
+
+	if (sigaction(SIGTRAP, &sa, NULL) < 0) {
+		perror(ERRLN);
+		exit(1);
+	}
+
+	test3_set_tf();
+	test1(secs);
+
+	test3_set_tf();
+	test2(secs);
+}
+
+int main(void)
 {
 	unsigned long bin_size = encl_bin_end - encl_bin;
 	unsigned long ss_size = encl_ss_end - encl_ss;
-	struct sgx_enclave_exception exception;
 	Elf64_Sym *eenter_sym;
 	struct vdso_symtab symtab;
 	struct sgx_secs secs;
-	uint64_t result = 0;
-	void *eenter;
-	void *addr;
-
-	memset(&exception, 0, sizeof(exception));
 
-	addr = vdso_get_base_addr(envp);
-	if (!addr)
-		exit(1);
+	vdso_init();
 
-	if (!vdso_get_symtab(addr, &symtab))
+	if (!vdso_get_symtab(&symtab))
 		exit(1);
 
 	eenter_sym = vdso_symtab_get(&symtab, "__vdso_sgx_enter_enclave");
 	if (!eenter_sym)
 		exit(1);
-	eenter = addr + eenter_sym->st_value;
+	eenter = vdso_base + eenter_sym->st_value;
 
 	printf("Binary size %lu (0x%lx), SIGSTRUCT size %lu\n", bin_size,
 	       bin_size, ss_size);
@@ -266,14 +510,11 @@ int main(int argc, char *argv[], char *envp[])
 	if (!encl_load(&secs, bin_size))
 		exit(1);
 
-	printf("Input: 0x%lx\n", MAGIC);
-	sgx_call((void *)&MAGIC, &result, (void *)secs.base, &exception,
-		 eenter);
-	if (result != MAGIC) {
-		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
-		exit(1);
-	}
+	printf("--- Functional Tests ---\n");
+	test1(&secs);
+	test2(&secs);
 
-	printf("Output: 0x%lx\n", result);
-	exit(0);
+	printf("--- Unwind Tests ---\n");
+	test3(&secs);
+	return 0;
 }
diff --git a/tools/testing/selftests/x86/sgx/sgx_call.S b/tools/testing/selftests/x86/sgx/sgx_call.S
index 14bd0a044199..ca2c0c947758 100644
--- a/tools/testing/selftests/x86/sgx/sgx_call.S
+++ b/tools/testing/selftests/x86/sgx/sgx_call.S
@@ -7,9 +7,43 @@
 
 	.global sgx_call
 sgx_call:
+	.cfi_startproc
+	push	%r15
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r15, 0
+	push	%r14
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r14, 0
+	push	%r13
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r13, 0
+	push	%r12
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r12, 0
 	push	%rbx
-	mov	$0x02, %rax
-	mov	%rdx, %rbx
-	call	*%r8
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbx, 0
+	push	$0
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	mov	$2, %eax
+	call	*eenter(%rip)
+	add	$0x20, %rsp
+	.cfi_adjust_cfa_offset	-0x20
 	pop	%rbx
+	.cfi_adjust_cfa_offset	-8
+	pop	%r12
+	.cfi_adjust_cfa_offset	-8
+	pop	%r13
+	.cfi_adjust_cfa_offset	-8
+	pop	%r14
+	.cfi_adjust_cfa_offset	-8
+	pop	%r15
+	.cfi_adjust_cfa_offset	-8
 	ret
+	.cfi_endproc
-- 
2.17.1


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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-23 16:52   ` Andy Lutomirski
@ 2019-04-24 12:17     ` Jarkko Sakkinen
  2019-05-08 13:45       ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-04-24 12:17 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jarkko Sakkinen, LKML, X86 ML, linux-sgx, Andrew Morton,
	Dave Hansen, Christopherson, Sean J, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Thomas Gleixner, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes, linux-sgx-owner

On 2019-04-23 19:52, Andy Lutomirski wrote:
> On Tue, Apr 23, 2019 at 4:56 AM Jarkko Sakkinen
> <jarkko.sakkinen@linux.intel.com> wrote:
>> 
>> On Wed, Apr 17, 2019 at 01:39:10PM +0300, Jarkko Sakkinen wrote:
>> > 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
>> >
>> > --
>> > 2.19.1
>> >
>> 
>> I'm on leave for this week and next week's Monday if you wonder why 
>> I'm
>> so passive in the discussion. Looking at the things next week's Tue.
>> 
>> Just a quick comment about Andy's proposal. Probably pretty DSO like
>> ELF blob could work with an addition of a section called ".tcs" for
>> entry points. They need to be recognized so that the loader can add
>> them as TCS pages.
> 
> Hmm.
> 
> There's a decent argument for specifically supporting whatever format
> Windows uses.  There's also an argument for allowing one or more
> enclaves to be bundled in a regular ELF DSO.  FWIW, there's no
> fundamental reason we can't support more than one type of enclave
> format.

It would also be better to contain sigstruct so that EINIT can
be performed. I wonder if we could use dlopen() as call path
for this? That would also provide all the DAC/MAC/whatever
security checks.

I can start to PoC this next week once I get back to work (back
on next Tue). I haven't studied Windows format much but I'd
*guess* it is a COFF DLL?

For me easier path to get something done would to do ELF DSO
first. As you said they both could be done, which means that
Windows COFF could be upstreamed later on.

If this approach works, it'd mean that no ioctl's would be
required except SGX_ENCLAVE_SET_ATTRIBUTE.

PS. This quote from LWN got a bit into my feelings:

"After 20 revisions of the patch set over three years, the
authors of this work (which was posted by Jarkko Sakkinen)
might well be forgiven for thinking that it must be about
ready for merging."

I seriously do not make any pre-conclusions ever for any patch
that I post when it should be merged, no matter how big or
small :-) For me this is just work...

/Jarkko

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

* RE: [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-23  1:25   ` Andy Lutomirski
@ 2019-04-24 17:56     ` Xing, Cedric
  0 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-04-24 17:56 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: LKML, X86 ML, linux-sgx, Andrew Morton, Hansen, Dave,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Thomas Gleixner, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes, Jarkko Sakkinen

Hi Andy,

I sent out my RFC patch v2 last night, that has your suggestions incorporated, plus a new unwind test to single step through the vDSO API to test out the CFI directives. Hopefully it is able to address all of your concerns. It's worth noting that, given the current patch fixes up #DB and #BP at ENCLU, the unwind test cannot run to completion. I assume Sean will revise the fixup code soon.

Thanks!

-Cedric

> -----Original Message-----
> From: Andy Lutomirski [mailto:luto@kernel.org]
> Sent: Monday, April 22, 2019 6:26 PM
> To: Xing, Cedric <cedric.xing@intel.com>
> Cc: LKML <linux-kernel@vger.kernel.org>; X86 ML <x86@kernel.org>; linux-
> sgx@vger.kernel.org; Andrew Morton <akpm@linux-foundation.org>; Hansen,
> Dave <dave.hansen@intel.com>; Christopherson, Sean J
> <sean.j.christopherson@intel.com>; nhorman@redhat.com;
> npmccallum@redhat.com; Ayoun, Serge <serge.ayoun@intel.com>; Katz-zamir,
> Shay <shay.katz-zamir@intel.com>; Huang, Haitao <haitao.huang@intel.com>;
> Andy Shevchenko <andriy.shevchenko@linux.intel.com>; Thomas Gleixner
> <tglx@linutronix.de>; Svahn, Kai <kai.svahn@intel.com>; Borislav Petkov
> <bp@alien8.de>; Josh Triplett <josh@joshtriplett.org>; Andrew Lutomirski
> <luto@kernel.org>; Huang, Kai <kai.huang@intel.com>; David Rientjes
> <rientjes@google.com>; Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
> Subject: Re: [RFC PATCH v1 2/3] x86/vdso: Modify
> __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
> 
> On Mon, Apr 22, 2019 at 5:37 PM Cedric Xing <cedric.xing@intel.com>
> wrote:
> >
> > The previous __vdso_sgx_enter_enclave() requires enclaves to preserve
> > %rsp, which prohibits enclaves from allocating and passing parameters
> > for untrusted function calls (aka. o-calls).
> >
> > This patch addresses the problem above by introducing a new ABI that
> > preserves %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can
> > anchor its frame using %rbp so that enclaves are allowed to allocate
> > space on the untrusted stack by decrementing %rsp. Please note that
> > the stack space allocated in such way will be part of
> > __vdso_sgx_enter_enclave()'s frame so will be freed after
> > __vdso_sgx_enter_enclave() returns. Therefore,
> > __vdso_sgx_enter_enclave() has been changed to take a callback
> > function as an optional parameter, which if supplied, will be invoked
> > upon enclave exits (both AEX (Asynchronous Enclave
> > eXit) and normal exits), with the value of %rsp left off by the
> > enclave as a parameter to the callback.
> >
> > Here's the summary of API/ABI changes in this patch. More details
> > could be found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
> > * 'struct sgx_enclave_exception' is renamed to 'struct
> sgx_enclave_exinfo'
> >   because it is filled upon both AEX (i.e. exceptions) and normal
> enclave
> >   exits.
> > * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead
> of %rsp in
> >   the previous implementation).
> > * __vdso_sgx_enter_enclave() takes one more parameter - a callback
> function to
> >   be invoked upon enclave exits. This callback is optional, and if not
> >   supplied, will cause __vdso_sgx_enter_enclave() to return upon
> enclave exits
> >   (same behavior as previous implementation).
> > * The callback function is given as a parameter the value of %rsp at
> enclave
> >   exit to address data "pushed" by the enclave. A positive value
> returned by
> >   the callback will be treated as an ENCLU leaf for re-entering the
> enclave,
> >   while a zero or negative value will be passed through as the return
> >   value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
> >   leave callback by longjmp() or by throwing a C++ exception.
> >
> > Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> > ---
> >  arch/x86/entry/vdso/vsgx_enter_enclave.S | 156 ++++++++++++++--------
> -
> >  arch/x86/include/uapi/asm/sgx.h          |  14 +-
> >  2 files changed, 100 insertions(+), 70 deletions(-)
> >
> > diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> > b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> > index fe0bf6671d6d..210f4366374a 100644
> > --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> > +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> > @@ -14,88 +14,118 @@
> >  .code64
> >  .section .text, "ax"
> >
> > -#ifdef SGX_KERNEL_DOC
> >  /**
> >   * __vdso_sgx_enter_enclave() - Enter an SGX enclave
> >   *
> >   * @leaf:      **IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
> > - * @tcs:       **IN \%rbx** - TCS, must be non-NULL
> > - * @ex_info:   **IN \%rcx** - Optional 'struct sgx_enclave_exception'
> pointer
> > + * @tcs:       **IN 0x08(\%rsp)** - TCS, must be non-NULL
> > + * @ex_info:   **IN 0x10(\%rsp)** - Optional 'struct
> sgx_enclave_exinfo'
> > + *                                  pointer
> > + * @callback:  **IN 0x18(\%rsp)** - Optional callback function to be
> called on
> > + *                                  enclave exit or exception
> >   *
> >   * Return:
> >   *  **OUT \%eax** -
> > - *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU
> > leaf is
> > - *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave
> > faults
> > + *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU
> > + leaf is not
> > + *  allowed, %-EFAULT if ENCLU or the enclave faults, or a
> > + non-positive value
> > + *  returned from ``callback`` (if one is supplied).
> >   *
> >   * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant
> with the
> > - * x86-64 ABI, i.e. cannot be called from standard C code.   As noted
> above,
> > - * input parameters must be passed via ``%eax``, ``%rbx`` and
> > ``%rcx``, with
> > - * the return value passed via ``%eax``.  All registers except
> > ``%rsp`` must
> > - * be treated as volatile from the caller's perspective, including
> > but not
> > - * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the
> > enclave
> > - * being run **must** preserve the untrusted ``%rsp`` and stack.
> > + * x86-64 ABI, i.e. cannot be called from standard C code. As noted
> > + above,
> > + * input parameters must be passed via ``%eax``, ``8(%rsp)``,
> > + ``0x10(%rsp)`` and
> > + * ``0x18(%rsp)``, with the return value passed via ``%eax``. All
> > + other registers
> > + * will be passed through to the enclave as is. All registers except
> > + ``%rbp``
> > + * must be treated as volatile from the caller's perspective,
> > + including but not
> > + * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely, the
> > + enclave being
> > + * run **must** preserve the untrusted ``%rbp``.
> > + *
> > + * ``callback`` has the following signature:
> > + * int callback(long rdi, long rsi, long rdx,
> > + *             struct sgx_enclave_exinfo *ex_info, long r8, long r9,
> > + *             void *tcs, long ursp);
> > + * ``callback`` **shall** follow x86_64 ABI. All GPRs **except**
> > + ``%rax``, ``%rbx``
> > + * and ``rcx`` are passed through to ``callback``. ``%rdi``,
> > + ``%rsi``, ``%rdx``,
> > + * ``%r8``, ``%r9``, along with the value of ``%rsp`` when the
> > + enclave exited/excepted,
> > + * can be accessed directly as input parameters, while other GPRs can
> > + be
> > + * accessed in assembly if needed.
> > + * A positive value returned from ``callback`` will be treated as an
> > + ENCLU leaf
> > + * (e.g. EENTER/ERESUME) to reenter the enclave, while 0 or a
> > + negative return
> 
> "to reenter the enclave without popping the extra data pushed by the
> enclave off the stack" or similar.  We really don't want a situation
> where someone puts all there "keep on going" logic in the callback and
> the stack usage grows without bound.
> 
> > + * value will be passed back to the caller of
> __vdso_sgx_enter_enclave().
> > + * It is also **safe** to ``longjmp()`` out of ``callback``.
> 
> I'm not sure that "safe" needs emphasis.
> 
> >   */
> > -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> > -                        struct sgx_enclave_exception *ex_info)
> > -{
> > -       if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> > -               return -EINVAL;
> > -
> > -       if (!tcs)
> > -               return -EINVAL;
> > -
> > -       try {
> > -               ENCLU[leaf];
> > -       } catch (exception) {
> > -               if (e)
> > -                       *e = exception;
> > -               return -EFAULT;
> > -       }
> > -
> > -       return 0;
> > -}
> > -#endif
> >  ENTRY(__vdso_sgx_enter_enclave)
> > -       /* EENTER <= leaf <= ERESUME */
> > +       /* Prolog */
> > +       .cfi_startproc
> > +       push    %rbp
> > +       .cfi_adjust_cfa_offset  8
> > +       .cfi_rel_offset         %rbp, 0
> > +       mov     %rsp, %rbp
> > +       .cfi_def_cfa_register   %rbp
> > +
> > +1:     /* EENTER <= leaf <= ERESUME */
> >         cmp     $0x2, %eax
> > -       jb      bad_input
> > -
> > +       jb      6f
> >         cmp     $0x3, %eax
> > -       ja      bad_input
> > +       ja      6f
> >
> > -       /* TCS must be non-NULL */
> > -       test    %rbx, %rbx
> > -       je      bad_input
> > +       /* Load TCS and AEP */
> > +       mov     0x10(%rbp), %rbx
> > +       lea     2f(%rip), %rcx
> >
> > -       /* Save @exception_info */
> > -       push    %rcx
> > -
> > -       /* Load AEP for ENCLU */
> > -       lea     1f(%rip),  %rcx
> > -1:     enclu
> > -
> > -       add     $0x8, %rsp
> > -       xor     %eax, %eax
> > -       ret
> > -
> > -bad_input:
> > -       mov     $(-EINVAL), %rax
> > -       ret
> > -
> > -.pushsection .fixup, "ax"
> > -       /* Re-load @exception_info and fill it (if it's non-NULL) */
> > -2:     pop     %rcx
> > -       test    %rcx, %rcx
> > -       je      3f
> > +       /* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> > +2:     enclu
> >
> > +       /* EEXIT path */
> > +       xor     %ebx, %ebx
> > +3:     mov     0x18(%rbp), %rcx
> > +       jrcxz   4f
> >         mov     %eax, EX_LEAF(%rcx)
> > -       mov     %di,  EX_TRAPNR(%rcx)
> > -       mov     %si,  EX_ERROR_CODE(%rcx)
> > +       jnc     4f
> > +       mov     %di, EX_TRAPNR(%rcx)
> > +       mov     %si, EX_ERROR_CODE(%rcx)
> >         mov     %rdx, EX_ADDRESS(%rcx)
> > -3:     mov     $(-EFAULT), %rax
> > +
> > +4:     /* Call *callback if supplied */
> > +       mov     0x20(%rbp), %rax
> > +       test    %rax, %rax
> 
> Maybe have a comment like "At this point, the effective return value is
> in RBX.  If there is no callback, then return it."
> 
> > +       cmovz   %rbx, %rax
> > +       jz      7f
> > +       /* Align stack and clear RFLAGS.DF per x86_64 ABI */
> > +       mov     %rsp, %rbx
> 
> Whoa, this is too subtle here.  Can you update the comment to clarify
> that the uRSP value set by the enclave needs to be saved so that the
> enclave can be resumed if needed?
> 
> > +       and     $-0x10, %rsp
> > +       cld
> > +       /* Parameters for *callback */
> > +       push    %rbx
> > +       push    0x10(%rbp)
> > +       /* Call via retpoline */
> > +       call    40f
> > +       /* Cleanup stack */
> > +       mov     %rbx, %rsp
> 
> To me, "Cleanup stack" makes me think that you're restoring the original
> RSP, but you're actually just undoing in the stack alignment.
> How about "Undo stack alignment"?
> 
> But I'm not seeing the code that causes a return value RAX <= 0 to just
> return.
> 
> > +       jmp     1b
> > +40:    /* retpoline */
> > +       call    42f
> > +41:    pause
> > +       lfence
> > +       jmp     41b
> > +42:    mov     %rax, (%rsp)
> > +       ret
> > +
> > +5:     /* Exception path */
> > +       mov     $-EFAULT, %ebx
> > +       stc
> > +       jmp     3b
> > +
> > +6:     /* Unsupported ENCLU leaf */
> > +       cmp     $0, %eax
> > +       jle     7f
> > +       mov     $-EINVAL, %eax
> > +
> > +7:     /* Epilog */
> > +       leave
> > +       .cfi_def_cfa            %rsp, 8
> >         ret
> > -.popsection
> > +       .cfi_endproc
> >
> > -_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
> > +_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
> 
> --Andy

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

* Re: [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-24  6:26   ` [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-04-24 19:04     ` Sean Christopherson
  2019-04-25 23:31       ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-24 19:04 UTC (permalink / raw)
  To: Cedric Xing
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang,
	jarkko.sakkinen

On Tue, Apr 23, 2019 at 11:26:22PM -0700, Cedric Xing wrote:
> The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
> which prohibits enclaves from allocating and passing parameters for
> untrusted function calls (aka. o-calls).
> 
> This patch addresses the problem above by introducing a new ABI that preserves
> %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
> using %rbp so that enclaves are allowed to allocate space on the untrusted
> stack by decrementing %rsp. Please note that the stack space allocated in such
> way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
> __vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
> been revised to take a callback function as an optional parameter, which if
> supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
> eXit) and normal exits), with the value of %rsp left off by the enclave as a
> parameter to the callback.

AIUI, you and Andy had an off-list discussion regarding rewriting
__vdso_sgx_enter_enclave() vs. providing a second vDSO function.  Can you
please summarize the discussion so that it's clear why you're pursuing a
single function?

In the end I probably agree that's it's desirable to have a single ABI and
vDSO function since the cost is basically that the non-callback case needs
to pass params via the stack instead of registers, but I do miss the
simplicity of separate implementations.

> Here's the summary of API/ABI changes in this patch. More details could be
> found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
> * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
>   because it is filled upon both AEX (i.e. exceptions) and normal enclave
>   exits.
> * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
>   the previous implementation).
> * __vdso_sgx_enter_enclave() takes one more parameter - a callback function to
>   be invoked upon enclave exits. This callback is optional, and if not
>   supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave exits
>   (same behavior as previous implementation).
> * The callback function is given as a parameter the value of %rsp at enclave
>   exit to address data "pushed" by the enclave. A positive value returned by
>   the callback will be treated as an ENCLU leaf for re-entering the enclave,
>   while a zero or negative value will be passed through as the return
>   value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
>   leave callback by longjmp() or by throwing a C++ exception.
> 
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---
>  arch/x86/entry/vdso/vsgx_enter_enclave.S | 175 ++++++++++++++++-------
>  arch/x86/include/uapi/asm/sgx.h          |  14 +-
>  2 files changed, 128 insertions(+), 61 deletions(-)
> 
> diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> index fe0bf6671d6d..debecb0d785c 100644
> --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> @@ -19,83 +19,150 @@
>   * __vdso_sgx_enter_enclave() - Enter an SGX enclave
>   *
>   * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
> - * @tcs:	**IN \%rbx** - TCS, must be non-NULL
> - * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
> + * @tcs:	**IN 0x08(\%rsp)** - TCS, must be non-NULL
> + * @ex_info:	**IN 0x10(\%rsp)** - Optional 'struct sgx_enclave_exinfo'
> + *				     pointer
> + * @callback:	**IN 0x18(\%rsp)** - Optional callback function to be called on
> + *				     enclave exit or exception
>   *
>   * Return:
>   *  **OUT \%eax** -
> - *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
> - *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
> + *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is not
> + *  allowed, %-EFAULT if ENCLU or the enclave faults, or a non-positive value
> + *  returned from ``callback`` (if one is supplied).
>   *
>   * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
> - * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
> - * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
> - * the return value passed via ``%eax``.  All registers except ``%rsp`` must
> - * be treated as volatile from the caller's perspective, including but not
> - * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
> - * being run **must** preserve the untrusted ``%rsp`` and stack.
> + * x86-64 ABI, i.e. cannot be called from standard C code. As noted above,
> + * input parameters must be passed via ``%eax``, ``8(%rsp)``, ``0x10(%rsp)`` and
> + * ``0x18(%rsp)``, with the return value passed via ``%eax``. All other
> + * registers will be passed through to the enclave as is. All registers except
> + * ``%rbp`` must be treated as volatile from the caller's perspective, including

Hmm, this is my fault since I wrote the original comment, but stating
"All registers except %rbp must be treated as volatile" is confusing, e.g.
at first I thought it meant that the assembly blob was mucking with the
registers and that they couldn't be used to pass information out of the
enclave.

Maybe something like:

 * Register ABI:
 *  - As noted above, input parameters are passed via %eax and the stack.
 *  - The return value is passed via %eax.
 *  - %rbx and %rcx must be treated as volatile as they are modified as part of
 *    enclaves transitions and are used as scratch regs.
 *  - %rbp **must** be preserved by the enclave in all cases, as it is used to
 *    reference paramaters when handling enclave exits.
 *  - %rdx, %rdi, %rsi and %r8-%r15 may be freely modified by the enclave
 *    and will not be passed back to the caller untouched.
 *  - %rsp is saved/restored across __vdso_sgx_enter_enclave(), but is passed
 *    as-is to the callback if one is provided, i.e. the enclave may use u_rsp
 *    to pass information to its associated callback.
 *
 * Callback ABI:
 *  <more information about callback ABI>
 * 

> + * but not limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely, the
> + * enclave being run **must** preserve the untrusted ``%rbp``.
> + *
> + * ``callback`` has the following signature:
> + * int callback(long rdi, long rsi, long rdx,
> + *		struct sgx_enclave_exinfo *exinfo, long r8, long r9,
> + *		void *tcs, long ursp);
> + * ``callback`` **shall** follow x86_64 ABI. All GPRs **except** ``%rax``,
> + * ``%rbx`` and ``rcx`` are passed through to ``callback``. ``%rdi``, ``%rsi``,
> + * ``%rdx``, ``%r8``, ``%r9``, along with the value of ``%rsp`` when the enclave
> + * exited/excepted, can be accessed directly as input parameters, while other
> + * GPRs can be accessed in assembly if needed.  A positive value returned from
> + * ``callback`` will be treated as an ENCLU leaf (e.g. EENTER/ERESUME) to
> + * reenter the enclave (without popping the extra data pushed by the enclave off
> + * the stack), while 0 (zero) or a negative return value will be passed back to
> + * the caller of __vdso_sgx_enter_enclave(). It is also safe to leave
> + * ``callback`` via ``longjmp()`` or by throwing a C++ exception.
>   */

While this may format nicely in .rst (I haven't checked), it's damn near
unreadable in its raw form.  Escaping '%' in kernel-doc is unresolved at
this point, but this definitely is an argument for allowing the %CONST
interpretation to be disabled entirely.

longjmp() is probably the only thing that needs to be explicitly marked,
I think it would be better to simply say "the callback" instead of using
``callback``, i.e. use regular English instead of referencing the param.

> -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> -			 struct sgx_enclave_exception *ex_info)
> +typedef int (*sgx_callback)(long rdi, long rsi, long rdx,
> +			    struct sgx_enclave_exinfo *exinfo, long r8,
> +			    long r9, void *tcs, long ursp);
> +int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> +			     struct sgx_enclave_exinfo *exinfo,
> +			     sgx_callback callback)
>  {
> -	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> -		return -EINVAL;
> -
> -	if (!tcs)
> -		return -EINVAL;
> -
> -	try {
> -		ENCLU[leaf];
> -	} catch (exception) {
> -		if (e)
> -			*e = exception;
> -		return -EFAULT;
> +	while (leaf == EENTER || leaf == ERESUME) {

This gives the impression that looping is the common case.  I'd prefer
using 'goto' to show that the common case is a simple fall through whereas
the callback case can effectively loop on ENCLU.

> +		int rc;
> +		try {
> +			ENCLU[leaf];
> +			rc = 0;
> +			if (exinfo)
> +				exinfo->leaf = EEXIT;
> +		} catch (exception) {
> +			rc = -EFAULT;
> +			if (exinfo)
> +				*exinfo = exception;
> +		}
> +
> +		leaf = callback ? (*callback)(
> +			rdi, rsi, rdx, exinfo, r8, r9, tcs, ursp) : rc;
>  	}
>  
> -	return 0;
> +	return leaf > 0 ? -EINVAL : leaf;
>  }
>  #endif
>  ENTRY(__vdso_sgx_enter_enclave)
> -	/* EENTER <= leaf <= ERESUME */
> +	/* Prolog */
> +	.cfi_startproc
> +	push	%rbp
> +	.cfi_adjust_cfa_offset	8
> +	.cfi_rel_offset		%rbp, 0
> +	mov	%rsp, %rbp
> +	.cfi_def_cfa_register	%rbp
> +
> +1:	/* EENTER <= leaf <= ERESUME */
>  	cmp	$0x2, %eax
> -	jb	bad_input
> -
> +	jb	6f
>  	cmp	$0x3, %eax
> -	ja	bad_input
> +	ja	6f
>  
> -	/* TCS must be non-NULL */
> -	test	%rbx, %rbx
> -	je	bad_input
> +	/* Load TCS and AEP */
> +	mov	0x10(%rbp), %rbx
> +	lea	2f(%rip), %rcx
>  
> -	/* Save @exception_info */
> -	push	%rcx
> +	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> +2:	enclu
>  
> -	/* Load AEP for ENCLU */
> -	lea	1f(%rip),  %rcx
> -1:	enclu
> +	/* EEXIT path */
> +	xor	%ebx, %ebx
> +3:	mov	0x18(%rbp), %rcx

@exinfo is optional, i.e. %ecx needs to be tested before its used.

> +	jrcxz	4f

I dislike the number of flags and values that are stashed away only to
be consumed later, it makes the code hard to follow.  AFAICT, a lot of
the shenanigans are done to reuse code because exinfo was overloaded,
but that's actually pointless, i.e. it's unnecessarily complex.

Overlading the struct is pointless becase if you make it mandatory when
using a callback then it can be nullified (when passed to the callback)
to indicate EEXIT.  If it's still optional, then the callback needs an
extra param to explicitly indicate EEXIT vs. -EFAULT, otherwise the
callback has no indication whatsover of why it was invoked.

My preference is for the latter since it's more explicit and obvious.

Tangetially related, I'm not opposed to renaming it
'struct sgx_enclave_exception_info' for clarity.

> +	mov	%eax, EX_LEAF(%rcx)
> +	jnc	4f
> +	mov	%di, EX_TRAPNR(%rcx)
> +	mov	%si, EX_ERROR_CODE(%rcx)
> +	mov	%rdx, EX_ADDRESS(%rcx)

My strong preference would be to organize the code to separate the various
flows, i.e. happy common case, invalid input, exception handler and
callback invocation.  And make the common case a straight shot so that
it's more obvious what happens in the happy non-callback case.

>  
> -	add	$0x8, %rsp
> -	xor	%eax, %eax
> +4:	/* Call *callback if supplied */
> +	mov	0x20(%rbp), %rax
> +	test	%rax, %rax
> +	/* At this point, %ebx holds the effective return value, which shall be
> +	 * returned if no callback is specified */

Use kernel-doc format for multi-line comments.  Missing punctionation at
the end.  Blank lines between logical blocks would also help readability.

E.g.:

4:      /* Call *callback if supplied */
        mov     0x20(%rbp), %rax
        test    %rax, %rax

        /*
         * At this point, %ebx holds the effective return value, which shall be
         * returned if no callback is specified.
         */
        cmovz   %rbx, %rax
        jz      7f

> +	cmovz	%rbx, %rax
> +	jz	7f
> +	/* Align stack per x86_64 ABI. The original %rsp is saved in %rbx to be
> +	 * restored after *callback returns. */
> +	mov	%rsp, %rbx
> +	and	$-0x10, %rsp
> +	/* Clear RFLAGS.DF per x86_64 ABI */
> +	cld
> +	/* Parameters for *callback */
> +	push	%rbx
> +	push	0x10(%rbp)
> +	/* Call *%rax via retpoline */
> +	call	40f

Another case of stashing a value it consuming it later.  This one is
especially brutal since %rax was loaded with CMOVcc, which means the
reader needs to backtrack even further to understand what %rax contains
at this point.

> +	/* Restore %rsp to its original value left off by the enclave from last
> +	 * exit */
> +	mov	%rbx, %rsp
> +	/* Positive return value from *callback will be interpreted as an ENCLU
> +	 * leaf, while a non-positive value will be interpreted as the return
> +	 * value to be passed back to the caller. */

Please use imperative mood in the comments, i.e. simply state what the
code is doing.  E.g. "will be interpreted" makes it sound like something
else is processing the callback's return value.

> +	jmp	1b
> +40:	/* retpoline */
> +	call	42f
> +41:	pause
> +	lfence
> +	jmp	41b
> +42:	mov	%rax, (%rsp)
>  	ret
>  
> -bad_input:
> -	mov     $(-EINVAL), %rax
> -	ret
> +5:	/* Exception path */
> +	mov	$-EFAULT, %ebx
> +	stc
> +	jmp	3b
>  
> -.pushsection .fixup, "ax"
> -	/* Re-load @exception_info and fill it (if it's non-NULL) */
> -2:	pop	%rcx
> -	test    %rcx, %rcx
> -	je      3f
> +6:	/* Unsupported ENCLU leaf */
> +	cmp	$0, %eax
> +	jle	7f
> +	mov	$-EINVAL, %eax
>  
> -	mov	%eax, EX_LEAF(%rcx)
> -	mov	%di,  EX_TRAPNR(%rcx)
> -	mov	%si,  EX_ERROR_CODE(%rcx)
> -	mov	%rdx, EX_ADDRESS(%rcx)
> -3:	mov	$(-EFAULT), %rax
> +7:	/* Epilog */
> +	leave
> +	.cfi_def_cfa		%rsp, 8
>  	ret
> -.popsection
> +	.cfi_endproc
>  
> -_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
> +_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
>  
>  ENDPROC(__vdso_sgx_enter_enclave)

Putting everything together, sans comments, I'd prefer something like the
following.  Pasted in raw code as that'll hopefully be easier to review
and discuss than a diff.

Note, swapping 'long rc' and '... *e' would allow the callback flow
to save one memory access, but IMO the exception info belongs at the end
since it's optional.

#ifdef SGX_KERNEL_DOC
typedef int (*sgx_callback)(long rdi, long rsi, long rdx, long ret, long r8,
			    long r9, void *tcs, long ursp,
			    struct sgx_enclave_exception_info *e);
int __vdso_sgx_enter_enclave(int leaf, void *tcs,
				struct sgx_enclave_exception_info *e,
				sgx_callback callback)
{
	int ret;

enter_enclave:
	if (leaf != EENTER && leaf != ERESUME) {
		ret = -EINVAL;
		goto out;
	}

	try {
		ENCLU[leaf];
		ret = 0;
	} catch (exception) {
		ret = -EFAULT;
		if (e)
			*e = exception;
	}
	if (callback)
		goto do_callback;
out:
	return ret;

do_callback:
	leaf = (*callback)(rdi, rsi, rdx, ret, r8, r9, e, tcs, ursp);
	if (leaf <= 0)
		goto out;
	goto enter_enclave;
}
#endif
ENTRY(__vdso_sgx_enter_enclave)
	/* Prolog */
	.cfi_startproc
	push	%rbp
	.cfi_adjust_cfa_offset	8
	.cfi_rel_offset		%rbp, 0
	mov	%rsp, %rbp
	.cfi_def_cfa_register	%rbp

1:	/* EENTER <= leaf <= ERESUME */
	cmp	$0x2, %eax
	jb	5f
	cmp	$0x3, %eax
	ja	5f

	/* Load TCS and AEP */
	mov	0x10(%rbp), %rbx
	lea	2f(%rip), %rcx

	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
2:	enclu

	/* EEXIT branches here unless the enclave is doing something fancy. */
	xor	%eax, %eax

3:	cmp	$0, 0x20(%rbp)
	jne	8f

4:	leave
	.cfi_def_cfa		%rsp, 8
	ret

5:	mov	$(-EINVAL), %rax
	jmp	4b

6:	mov	0x18(%rbp), %rcx
	test    %rcx, %rcx
	je	7f

	/* Fill optional exception info. */
	mov	%eax, EX_LEAF(%rcx)
	mov	%di,  EX_TRAPNR(%rcx)
	mov	%si,  EX_ERROR_CODE(%rcx)
	mov	%rdx, EX_ADDRESS(%rcx)
7:	mov	$(-EFAULT), %rax
	jmp	3b

8:	/*
	 * Align stack per x86_64 ABI.  Save the original %rsp in %rbx to be
	 * restored after the callback returns.
	 */
	mov	%rsp, %rbx
	and	$-0x10, %rsp

	/* Push @e, u_rsp and @tcs as parameters to the callback. */
	push	0x18(%rbp)
	push	%rbx
	push	0x10(%rbp)

	/* Pass the "return value" to the callback via %rcx. */
	mov	%rax, %rcx

	/* Clear RFLAGS.DF per x86_64 ABI */
	cld

	/* Load the callback pointer to %rax and invoke it via retpoline. */
	mov	0x20(%rbp), %rax
	call	40f

	/* Restore %rsp to its post-exit value. */
	mov	%rbx, %rsp

	/*
	 * If the return from callback is zero or negative, return immediately,
	 * otherwise attempt to re-execute ENCLU with the return interpreted as
	 * the requested ENCLU leaf.
	 */
	cmp	$0, %eax
	jle	4b
	jmp	1b

40:	/* retpoline */
	call	42f
41:	pause
	lfence
	jmp	41b
42:	mov	%rax, (%rsp)
	ret
	.cfi_endproc

_ASM_VDSO_EXTABLE_HANDLE(2b, 6b)

ENDPROC(__vdso_sgx_enter_enclave)

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

* RE: [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-24 19:04     ` Sean Christopherson
@ 2019-04-25 23:31       ` Xing, Cedric
  2019-04-26 21:00         ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-04-25 23:31 UTC (permalink / raw)
  To: Christopherson, Sean J
  Cc: linux-kernel, linux-sgx, akpm, Hansen, Dave, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Svahn, Kai, Huang, Kai,
	jarkko.sakkinen

Hi Sean,

> AIUI, you and Andy had an off-list discussion regarding rewriting
> __vdso_sgx_enter_enclave() vs. providing a second vDSO function.  Can
> you
> please summarize the discussion so that it's clear why you're pursuing a
> single function?
> 
> In the end I probably agree that's it's desirable to have a single ABI
> and
> vDSO function since the cost is basically that the non-callback case
> needs
> to pass params via the stack instead of registers, but I do miss the
> simplicity of separate implementations.
> 

The major reason is we don't want to maintain 2 different ABIs (preserving %rsp vs. %rbp). Given the new one covers all known use cases, we prefer not to keep the other one.

> > Here's the summary of API/ABI changes in this patch. More details
> could be
> > found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
> > * 'struct sgx_enclave_exception' is renamed to 'struct
> sgx_enclave_exinfo'
> >   because it is filled upon both AEX (i.e. exceptions) and normal
> enclave
> >   exits.
> > * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead
> of %rsp in
> >   the previous implementation).
> > * __vdso_sgx_enter_enclave() takes one more parameter - a callback
> function to
> >   be invoked upon enclave exits. This callback is optional, and if not
> >   supplied, will cause __vdso_sgx_enter_enclave() to return upon
> enclave exits
> >   (same behavior as previous implementation).
> > * The callback function is given as a parameter the value of %rsp at
> enclave
> >   exit to address data "pushed" by the enclave. A positive value
> returned by
> >   the callback will be treated as an ENCLU leaf for re-entering the
> enclave,
> >   while a zero or negative value will be passed through as the return
> >   value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
> >   leave callback by longjmp() or by throwing a C++ exception.
> >
> > Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> > ---
> >  arch/x86/entry/vdso/vsgx_enter_enclave.S | 175 ++++++++++++++++------
> -
> >  arch/x86/include/uapi/asm/sgx.h          |  14 +-
> >  2 files changed, 128 insertions(+), 61 deletions(-)
> >
> > diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> > index fe0bf6671d6d..debecb0d785c 100644
> > --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> > +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> > @@ -19,83 +19,150 @@
> >   * __vdso_sgx_enter_enclave() - Enter an SGX enclave
> >   *
> >   * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
> > - * @tcs:	**IN \%rbx** - TCS, must be non-NULL
> > - * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception'
> pointer
> > + * @tcs:	**IN 0x08(\%rsp)** - TCS, must be non-NULL
> > + * @ex_info:	**IN 0x10(\%rsp)** - Optional 'struct
> sgx_enclave_exinfo'
> > + *				     pointer
> > + * @callback:	**IN 0x18(\%rsp)** - Optional callback function to
> be called on
> > + *				     enclave exit or exception
> >   *
> >   * Return:
> >   *  **OUT \%eax** -
> > - *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU
> leaf is
> > - *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave
> faults
> > + *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU
> leaf is not
> > + *  allowed, %-EFAULT if ENCLU or the enclave faults, or a non-
> positive value
> > + *  returned from ``callback`` (if one is supplied).
> >   *
> >   * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant
> with the
> > - * x86-64 ABI, i.e. cannot be called from standard C code.   As noted
> above,
> > - * input parameters must be passed via ``%eax``, ``%rbx`` and
> ``%rcx``, with
> > - * the return value passed via ``%eax``.  All registers except
> ``%rsp`` must
> > - * be treated as volatile from the caller's perspective, including
> but not
> > - * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the
> enclave
> > - * being run **must** preserve the untrusted ``%rsp`` and stack.
> > + * x86-64 ABI, i.e. cannot be called from standard C code. As noted
> above,
> > + * input parameters must be passed via ``%eax``, ``8(%rsp)``,
> ``0x10(%rsp)`` and
> > + * ``0x18(%rsp)``, with the return value passed via ``%eax``. All
> other
> > + * registers will be passed through to the enclave as is. All
> registers except
> > + * ``%rbp`` must be treated as volatile from the caller's perspective,
> including
> 
> Hmm, this is my fault since I wrote the original comment, but stating
> "All registers except %rbp must be treated as volatile" is confusing,
> e.g.
> at first I thought it meant that the assembly blob was mucking with the
> registers and that they couldn't be used to pass information out of the
> enclave.
> 
> Maybe something like:
> 
>  * Register ABI:
>  *  - As noted above, input parameters are passed via %eax and the stack.
>  *  - The return value is passed via %eax.
>  *  - %rbx and %rcx must be treated as volatile as they are modified as
> part of
>  *    enclaves transitions and are used as scratch regs.
>  *  - %rbp **must** be preserved by the enclave in all cases, as it is
> used to
>  *    reference paramaters when handling enclave exits.
>  *  - %rdx, %rdi, %rsi and %r8-%r15 may be freely modified by the
> enclave
>  *    and will not be passed back to the caller untouched.
>  *  - %rsp is saved/restored across __vdso_sgx_enter_enclave(), but is
> passed
>  *    as-is to the callback if one is provided, i.e. the enclave may use
> u_rsp
>  *    to pass information to its associated callback.
>  *
>  * Callback ABI:
>  *  <more information about callback ABI>
>  *

Really appreciated! I'll update the comments in the next revision.

> 
> > + * but not limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc... Conversely,
> the
> > + * enclave being run **must** preserve the untrusted ``%rbp``.
> > + *
> > + * ``callback`` has the following signature:
> > + * int callback(long rdi, long rsi, long rdx,
> > + *		struct sgx_enclave_exinfo *exinfo, long r8, long r9,
> > + *		void *tcs, long ursp);
> > + * ``callback`` **shall** follow x86_64 ABI. All GPRs **except**
> ``%rax``,
> > + * ``%rbx`` and ``rcx`` are passed through to ``callback``. ``%rdi``,
> ``%rsi``,
> > + * ``%rdx``, ``%r8``, ``%r9``, along with the value of ``%rsp`` when
> the enclave
> > + * exited/excepted, can be accessed directly as input parameters,
> while other
> > + * GPRs can be accessed in assembly if needed.  A positive value
> returned from
> > + * ``callback`` will be treated as an ENCLU leaf (e.g. EENTER/ERESUME)
> to
> > + * reenter the enclave (without popping the extra data pushed by the
> enclave off
> > + * the stack), while 0 (zero) or a negative return value will be
> passed back to
> > + * the caller of __vdso_sgx_enter_enclave(). It is also safe to leave
> > + * ``callback`` via ``longjmp()`` or by throwing a C++ exception.
> >   */
> 
> While this may format nicely in .rst (I haven't checked), it's damn near
> unreadable in its raw form.  Escaping '%' in kernel-doc is unresolved at
> this point, but this definitely is an argument for allowing the %CONST
> interpretation to be disabled entirely.
> 

I know very little about kernel-doc. Not quite sure which markup means what. Or if you don't mind, could you just write up the whole thing (you have written half of it in your email already) so I can include it into my next revision?
 
> longjmp() is probably the only thing that needs to be explicitly marked,
> I think it would be better to simply say "the callback" instead of using
> ``callback``, i.e. use regular English instead of referencing the param.
> 

Are you suggesting not to mention C++ exception here?
 
> > -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> > -			 struct sgx_enclave_exception *ex_info)
> > +typedef int (*sgx_callback)(long rdi, long rsi, long rdx,
> > +			    struct sgx_enclave_exinfo *exinfo, long r8,
> > +			    long r9, void *tcs, long ursp);
> > +int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> > +			     struct sgx_enclave_exinfo *exinfo,
> > +			     sgx_callback callback)
> >  {
> > -	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> > -		return -EINVAL;
> > -
> > -	if (!tcs)
> > -		return -EINVAL;
> > -
> > -	try {
> > -		ENCLU[leaf];
> > -	} catch (exception) {
> > -		if (e)
> > -			*e = exception;
> > -		return -EFAULT;
> > +	while (leaf == EENTER || leaf == ERESUME) {
> 
> This gives the impression that looping is the common case.  I'd prefer
> using 'goto' to show that the common case is a simple fall through
> whereas
> the callback case can effectively loop on ENCLU.

Looping IMO is indeed the common case. Just think of the case of an enclave making a sequence of o-calls. 
 
> 
> > +		int rc;
> > +		try {
> > +			ENCLU[leaf];
> > +			rc = 0;
> > +			if (exinfo)
> > +				exinfo->leaf = EEXIT;
> > +		} catch (exception) {
> > +			rc = -EFAULT;
> > +			if (exinfo)
> > +				*exinfo = exception;
> > +		}
> > +
> > +		leaf = callback ? (*callback)(
> > +			rdi, rsi, rdx, exinfo, r8, r9, tcs, ursp) : rc;
> >  	}
> >
> > -	return 0;
> > +	return leaf > 0 ? -EINVAL : leaf;
> >  }
> >  #endif
> >  ENTRY(__vdso_sgx_enter_enclave)
> > -	/* EENTER <= leaf <= ERESUME */
> > +	/* Prolog */
> > +	.cfi_startproc
> > +	push	%rbp
> > +	.cfi_adjust_cfa_offset	8
> > +	.cfi_rel_offset		%rbp, 0
> > +	mov	%rsp, %rbp
> > +	.cfi_def_cfa_register	%rbp
> > +
> > +1:	/* EENTER <= leaf <= ERESUME */
> >  	cmp	$0x2, %eax
> > -	jb	bad_input
> > -
> > +	jb	6f
> >  	cmp	$0x3, %eax
> > -	ja	bad_input
> > +	ja	6f
> >
> > -	/* TCS must be non-NULL */
> > -	test	%rbx, %rbx
> > -	je	bad_input
> > +	/* Load TCS and AEP */
> > +	mov	0x10(%rbp), %rbx
> > +	lea	2f(%rip), %rcx
> >
> > -	/* Save @exception_info */
> > -	push	%rcx
> > +	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> > +2:	enclu
> >
> > -	/* Load AEP for ENCLU */
> > -	lea	1f(%rip),  %rcx
> > -1:	enclu
> > +	/* EEXIT path */
> > +	xor	%ebx, %ebx
> > +3:	mov	0x18(%rbp), %rcx
> 
> @exinfo is optional, i.e. %ecx needs to be tested before its used.
> 
> > +	jrcxz	4f

The above instruction (i.e. jrcxz) does test %rcx.

> 
> I dislike the number of flags and values that are stashed away only to
> be consumed later, it makes the code hard to follow.  AFAICT, a lot of
> the shenanigans are done to reuse code because exinfo was overloaded,
> but that's actually pointless, i.e. it's unnecessarily complex.
> 
> Overlading the struct is pointless becase if you make it mandatory when
> using a callback then it can be nullified (when passed to the callback)
> to indicate EEXIT.  If it's still optional, then the callback needs an
> extra param to explicitly indicate EEXIT vs. -EFAULT, otherwise the
> callback has no indication whatsover of why it was invoked.
> 
> My preference is for the latter since it's more explicit and obvious.

I wouldn't nullify @exinfo at EEXIT because that could be used as a "context" pointer to the callback.

Making it optionally because the callback can still use other registers (e.g. %rdi) determine the reason without it. For example, an enclave may set %rdi to non-zero to signify o-call/e-ret while zero (as set by AEX) would indicate an exception. My intention is not to impose unnecessary restrictions on applications.

> 
> Tangetially related, I'm not opposed to renaming it
> 'struct sgx_enclave_exception_info' for clarity.

I'd still prefer sgx_enclave_exinfo to imply its use in both _ex_it and _ex_ception cases, for the reason stated above.

> 
> > +	mov	%eax, EX_LEAF(%rcx)
> > +	jnc	4f
> > +	mov	%di, EX_TRAPNR(%rcx)
> > +	mov	%si, EX_ERROR_CODE(%rcx)
> > +	mov	%rdx, EX_ADDRESS(%rcx)
> 
> My strong preference would be to organize the code to separate the
> various
> flows, i.e. happy common case, invalid input, exception handler and
> callback invocation.  And make the common case a straight shot so that
> it's more obvious what happens in the happy non-callback case.

I'd prefer more concise code. After all, this is assembly without optimization done by the compiler. If it were for C, I'd agree with you because either case would end up in roughly the same code (in terms of code size or efficiency) due to the optimizer.

> >
> > -	add	$0x8, %rsp
> > -	xor	%eax, %eax
> > +4:	/* Call *callback if supplied */
> > +	mov	0x20(%rbp), %rax
> > +	test	%rax, %rax
> > +	/* At this point, %ebx holds the effective return value, which
> shall be
> > +	 * returned if no callback is specified */
> 
> Use kernel-doc format for multi-line comments.  Missing punctionation at
> the end.  Blank lines between logical blocks would also help readability.
> 
> E.g.:
> 
> 4:      /* Call *callback if supplied */
>         mov     0x20(%rbp), %rax
>         test    %rax, %rax
> 
>         /*
>          * At this point, %ebx holds the effective return value, which
> shall be
>          * returned if no callback is specified.
>          */
>         cmovz   %rbx, %rax
>         jz      7f

I know very little about kernel-doc. Would you please point me to documents describing it? What you suggested here will of course be incorporated into my next revision. 

> > +	cmovz	%rbx, %rax
> > +	jz	7f
> > +	/* Align stack per x86_64 ABI. The original %rsp is saved in %rbx
> to be
> > +	 * restored after *callback returns. */
> > +	mov	%rsp, %rbx
> > +	and	$-0x10, %rsp
> > +	/* Clear RFLAGS.DF per x86_64 ABI */
> > +	cld
> > +	/* Parameters for *callback */
> > +	push	%rbx
> > +	push	0x10(%rbp)
> > +	/* Call *%rax via retpoline */
> > +	call	40f
> 
> Another case of stashing a value it consuming it later.  This one is
> especially brutal since %rax was loaded with CMOVcc, which means the
> reader needs to backtrack even further to understand what %rax contains
> at this point.

%rax was loaded only 2 instructions ago, while what %rbx is containing is described in the comment immediately above it. I think I have done my best to make it readable. After all, this is assembly so can't expect something like giving proper names to variables in C because that just can't be done in assembly.

> 
> > +	/* Restore %rsp to its original value left off by the enclave from
> last
> > +	 * exit */
> > +	mov	%rbx, %rsp
> > +	/* Positive return value from *callback will be interpreted as an
> ENCLU
> > +	 * leaf, while a non-positive value will be interpreted as the
> return
> > +	 * value to be passed back to the caller. */
> 
> Please use imperative mood in the comments, i.e. simply state what the
> code is doing.  E.g. "will be interpreted" makes it sound like something
> else is processing the callback's return value.

Will do in the next revision.

> > +	jmp	1b
> > +40:	/* retpoline */
> > +	call	42f
> > +41:	pause
> > +	lfence
> > +	jmp	41b
> > +42:	mov	%rax, (%rsp)
> >  	ret
> >
> > -bad_input:
> > -	mov     $(-EINVAL), %rax
> > -	ret
> > +5:	/* Exception path */
> > +	mov	$-EFAULT, %ebx
> > +	stc
> > +	jmp	3b
> >
> > -.pushsection .fixup, "ax"
> > -	/* Re-load @exception_info and fill it (if it's non-NULL) */
> > -2:	pop	%rcx
> > -	test    %rcx, %rcx
> > -	je      3f
> > +6:	/* Unsupported ENCLU leaf */
> > +	cmp	$0, %eax
> > +	jle	7f
> > +	mov	$-EINVAL, %eax
> >
> > -	mov	%eax, EX_LEAF(%rcx)
> > -	mov	%di,  EX_TRAPNR(%rcx)
> > -	mov	%si,  EX_ERROR_CODE(%rcx)
> > -	mov	%rdx, EX_ADDRESS(%rcx)
> > -3:	mov	$(-EFAULT), %rax
> > +7:	/* Epilog */
> > +	leave
> > +	.cfi_def_cfa		%rsp, 8
> >  	ret
> > -.popsection
> > +	.cfi_endproc
> >
> > -_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
> > +_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
> >
> >  ENDPROC(__vdso_sgx_enter_enclave)
> 
> Putting everything together, sans comments, I'd prefer something like
> the
> following.  Pasted in raw code as that'll hopefully be easier to review
> and discuss than a diff.
> 
> Note, swapping 'long rc' and '... *e' would allow the callback flow
> to save one memory access, but IMO the exception info belongs at the end
> since it's optional.

You have probably misunderstood my code. 'ret' is _not_ passed while @exinfo is passed in %rcx. exinfo->leaf implies the reason of the callback.

Or are you suggesting to add 'ret' as one more parameter to the callback? I don't think it necessary because exinfo contains everything the callback would ever need.

> #ifdef SGX_KERNEL_DOC
> typedef int (*sgx_callback)(long rdi, long rsi, long rdx, long ret, long
> r8,
> 			    long r9, void *tcs, long ursp,
> 			    struct sgx_enclave_exception_info *e);
> int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> 				struct sgx_enclave_exception_info *e,
> 				sgx_callback callback)
> {
> 	int ret;
> 
> enter_enclave:
> 	if (leaf != EENTER && leaf != ERESUME) {
> 		ret = -EINVAL;
> 		goto out;
> 	}
> 
> 	try {
> 		ENCLU[leaf];
> 		ret = 0;
> 	} catch (exception) {
> 		ret = -EFAULT;
> 		if (e)
> 			*e = exception;
> 	}
> 	if (callback)
> 		goto do_callback;
> out:
> 	return ret;
> 
> do_callback:
> 	leaf = (*callback)(rdi, rsi, rdx, ret, r8, r9, e, tcs, ursp);
> 	if (leaf <= 0)
> 		goto out;
> 	goto enter_enclave;
> }
> #endif
> ENTRY(__vdso_sgx_enter_enclave)
> 	/* Prolog */
> 	.cfi_startproc
> 	push	%rbp
> 	.cfi_adjust_cfa_offset	8
> 	.cfi_rel_offset		%rbp, 0
> 	mov	%rsp, %rbp
> 	.cfi_def_cfa_register	%rbp
> 
> 1:	/* EENTER <= leaf <= ERESUME */
> 	cmp	$0x2, %eax
> 	jb	5f
> 	cmp	$0x3, %eax
> 	ja	5f
> 
> 	/* Load TCS and AEP */
> 	mov	0x10(%rbp), %rbx
> 	lea	2f(%rip), %rcx
> 
> 	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> 2:	enclu
> 
> 	/* EEXIT branches here unless the enclave is doing something fancy.
> */
> 	xor	%eax, %eax
> 
> 3:	cmp	$0, 0x20(%rbp)
> 	jne	8f
> 
> 4:	leave
> 	.cfi_def_cfa		%rsp, 8
> 	ret
> 
> 5:	mov	$(-EINVAL), %rax
> 	jmp	4b
> 
> 6:	mov	0x18(%rbp), %rcx
> 	test    %rcx, %rcx
> 	je	7f
> 
> 	/* Fill optional exception info. */
> 	mov	%eax, EX_LEAF(%rcx)
> 	mov	%di,  EX_TRAPNR(%rcx)
> 	mov	%si,  EX_ERROR_CODE(%rcx)
> 	mov	%rdx, EX_ADDRESS(%rcx)
> 7:	mov	$(-EFAULT), %rax
> 	jmp	3b
> 
> 8:	/*
> 	 * Align stack per x86_64 ABI.  Save the original %rsp in %rbx to
> be
> 	 * restored after the callback returns.
> 	 */
> 	mov	%rsp, %rbx
> 	and	$-0x10, %rsp
> 
> 	/* Push @e, u_rsp and @tcs as parameters to the callback. */
> 	push	0x18(%rbp)
> 	push	%rbx
> 	push	0x10(%rbp)
> 
> 	/* Pass the "return value" to the callback via %rcx. */
> 	mov	%rax, %rcx
> 
> 	/* Clear RFLAGS.DF per x86_64 ABI */
> 	cld
> 
> 	/* Load the callback pointer to %rax and invoke it via retpoline.
> */
> 	mov	0x20(%rbp), %rax
> 	call	40f
> 
> 	/* Restore %rsp to its post-exit value. */
> 	mov	%rbx, %rsp
> 
> 	/*
> 	 * If the return from callback is zero or negative, return
> immediately,
> 	 * otherwise attempt to re-execute ENCLU with the return
> interpreted as
> 	 * the requested ENCLU leaf.
> 	 */
> 	cmp	$0, %eax
> 	jle	4b
> 	jmp	1b
> 
> 40:	/* retpoline */
> 	call	42f
> 41:	pause
> 	lfence
> 	jmp	41b
> 42:	mov	%rax, (%rsp)
> 	ret
> 	.cfi_endproc
> 
> _ASM_VDSO_EXTABLE_HANDLE(2b, 6b)
> 
> ENDPROC(__vdso_sgx_enter_enclave)

Your code will work. The only missing thing is a ".cfi_def_cfa %rbp, 16" after 'ret' instruction in block 4. I decided to keep "leave; ret" at the end to avoid confusion around the frame pointer. As you may also notice, GCC generated code usually does the same thing. 

-Cedric

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

* Re: [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-25 23:31       ` Xing, Cedric
@ 2019-04-26 21:00         ` Sean Christopherson
  2019-05-02  8:28           ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-04-26 21:00 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-kernel, linux-sgx, akpm, Hansen, Dave, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Svahn, Kai, Huang, Kai,
	jarkko.sakkinen

On Thu, Apr 25, 2019 at 04:31:40PM -0700, Xing, Cedric wrote:
> > While this may format nicely in .rst (I haven't checked), it's damn near
> > unreadable in its raw form.  Escaping '%' in kernel-doc is unresolved at
> > this point, but this definitely is an argument for allowing the %CONST
> > interpretation to be disabled entirely.
> > 
> 
> I know very little about kernel-doc. Not quite sure which markup means what.
> Or if you don't mind, could you just write up the whole thing (you have
> written half of it in your email already) so I can include it into my next
> revision?

Hmm, at this point I'd say just ignore the comment entirely.  It's
something we need to sort out in the "official" series anyways.

>  
> > longjmp() is probably the only thing that needs to be explicitly marked,
> > I think it would be better to simply say "the callback" instead of using
> > ``callback``, i.e. use regular English instead of referencing the param.
> > 
> 
> Are you suggesting not to mention C++ exception here?

No, I was saying that rather than do the backtick markup on callback,
just say "the callback".  The copious amount of markup makes it difficult
to read the raw text.

>  
> > > -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> > > -			 struct sgx_enclave_exception *ex_info)
> > > +typedef int (*sgx_callback)(long rdi, long rsi, long rdx,
> > > +			    struct sgx_enclave_exinfo *exinfo, long r8,
> > > +			    long r9, void *tcs, long ursp);
> > > +int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> > > +			     struct sgx_enclave_exinfo *exinfo,
> > > +			     sgx_callback callback)
> > >  {
> > > -	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> > > -		return -EINVAL;
> > > -
> > > -	if (!tcs)
> > > -		return -EINVAL;
> > > -
> > > -	try {
> > > -		ENCLU[leaf];
> > > -	} catch (exception) {
> > > -		if (e)
> > > -			*e = exception;
> > > -		return -EFAULT;
> > > +	while (leaf == EENTER || leaf == ERESUME) {
> > 
> > This gives the impression that looping is the common case.  I'd prefer
> > using 'goto' to show that the common case is a simple fall through
> > whereas
> > the callback case can effectively loop on ENCLU.
> 
> Looping IMO is indeed the common case. Just think of the case of an enclave
> making a sequence of o-calls. 

Except that looping is only done when using a callback, and that most
definitely is not the common case.

> > > +		int rc;
> > > +		try {
> > > +			ENCLU[leaf];
> > > +			rc = 0;
> > > +			if (exinfo)
> > > +				exinfo->leaf = EEXIT;
> > > +		} catch (exception) {
> > > +			rc = -EFAULT;
> > > +			if (exinfo)
> > > +				*exinfo = exception;
> > > +		}
> > > +
> > > +		leaf = callback ? (*callback)(
> > > +			rdi, rsi, rdx, exinfo, r8, r9, tcs, ursp) : rc;
> > >  	}
> > >
> > > -	return 0;
> > > +	return leaf > 0 ? -EINVAL : leaf;
> > >  }
> > >  #endif
> > >  ENTRY(__vdso_sgx_enter_enclave)
> > > -	/* EENTER <= leaf <= ERESUME */
> > > +	/* Prolog */
> > > +	.cfi_startproc
> > > +	push	%rbp
> > > +	.cfi_adjust_cfa_offset	8
> > > +	.cfi_rel_offset		%rbp, 0
> > > +	mov	%rsp, %rbp
> > > +	.cfi_def_cfa_register	%rbp
> > > +
> > > +1:	/* EENTER <= leaf <= ERESUME */
> > >  	cmp	$0x2, %eax
> > > -	jb	bad_input
> > > -
> > > +	jb	6f
> > >  	cmp	$0x3, %eax
> > > -	ja	bad_input
> > > +	ja	6f
> > >
> > > -	/* TCS must be non-NULL */
> > > -	test	%rbx, %rbx
> > > -	je	bad_input
> > > +	/* Load TCS and AEP */
> > > +	mov	0x10(%rbp), %rbx
> > > +	lea	2f(%rip), %rcx
> > >
> > > -	/* Save @exception_info */
> > > -	push	%rcx
> > > +	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> > > +2:	enclu
> > >
> > > -	/* Load AEP for ENCLU */
> > > -	lea	1f(%rip),  %rcx
> > > -1:	enclu
> > > +	/* EEXIT path */
> > > +	xor	%ebx, %ebx
> > > +3:	mov	0x18(%rbp), %rcx
> > 
> > @exinfo is optional, i.e. %ecx needs to be tested before its used.
> > 
> > > +	jrcxz	4f
> 
> The above instruction (i.e. jrcxz) does test %rcx.

I love x86 ISA.

> > I dislike the number of flags and values that are stashed away only to
> > be consumed later, it makes the code hard to follow.  AFAICT, a lot of
> > the shenanigans are done to reuse code because exinfo was overloaded,
> > but that's actually pointless, i.e. it's unnecessarily complex.
> > 
> > Overlading the struct is pointless becase if you make it mandatory when
> > using a callback then it can be nullified (when passed to the callback)
> > to indicate EEXIT.  If it's still optional, then the callback needs an
> > extra param to explicitly indicate EEXIT vs. -EFAULT, otherwise the
> > callback has no indication whatsover of why it was invoked.
> > 
> > My preference is for the latter since it's more explicit and obvious.
> 
> I wouldn't nullify @exinfo at EEXIT because that could be used as a "context"
> pointer to the callback.
> 
> Making it optionally because the callback can still use other registers (e.g.
> %rdi) determine the reason without it. For example, an enclave may set %rdi
> to non-zero to signify o-call/e-ret while zero (as set by AEX) would indicate
> an exception. My intention is not to impose unnecessary restrictions on
> applications.
> > Tangetially related, I'm not opposed to renaming it
> > 'struct sgx_enclave_exception_info' for clarity.
> 
> I'd still prefer sgx_enclave_exinfo to imply its use in both _ex_it and
> _ex_ception cases, for the reason stated above.

Because an enclave *could* choose a different route?  The cost is
essentially one memory access, which is likely offset by the fact that
the callback can directly check %rcx for the exit reason.  You are not
the sole consumer of this code.

> > > +	mov	%eax, EX_LEAF(%rcx)
> > > +	jnc	4f
> > > +	mov	%di, EX_TRAPNR(%rcx)
> > > +	mov	%si, EX_ERROR_CODE(%rcx)
> > > +	mov	%rdx, EX_ADDRESS(%rcx)
> > 
> > My strong preference would be to organize the code to separate the
> > various
> > flows, i.e. happy common case, invalid input, exception handler and
> > callback invocation.  And make the common case a straight shot so that
> > it's more obvious what happens in the happy non-callback case.
> 
> I'd prefer more concise code. After all, this is assembly without
> optimization done by the compiler. If it were for C, I'd agree with you
> because either case would end up in roughly the same code (in terms of code
> size or efficiency) due to the optimizer.

a) You've argued multiple times this isn't performance critical code.

b) A straight shot is optimal for the common case where userspace is not
   using a callback.

c) The performance difference is something like one or two memory accesses.
   That's peanuts compared to how readable the code is by people without
   prior knowledge of exactly what this code is doing.

> > > -	add	$0x8, %rsp
> > > -	xor	%eax, %eax
> > > +4:	/* Call *callback if supplied */
> > > +	mov	0x20(%rbp), %rax
> > > +	test	%rax, %rax
> > > +	/* At this point, %ebx holds the effective return value, which
> > shall be
> > > +	 * returned if no callback is specified */
> > 
> > Use kernel-doc format for multi-line comments.  Missing punctionation at
> > the end.  Blank lines between logical blocks would also help readability.
> > 
> > E.g.:
> > 
> > 4:      /* Call *callback if supplied */
> >         mov     0x20(%rbp), %rax
> >         test    %rax, %rax
> > 
> >         /*
> >          * At this point, %ebx holds the effective return value, which
> > shall be
> >          * returned if no callback is specified.
> >          */
> >         cmovz   %rbx, %rax
> >         jz      7f
> 
> I know very little about kernel-doc. Would you please point me to documents
> describing it? What you suggested here will of course be incorporated into my
> next revision. 

Documentation/doc-guide/kernel-doc.rst

[...]

> > Note, swapping 'long rc' and '... *e' would allow the callback flow
> > to save one memory access, but IMO the exception info belongs at the end
> > since it's optional.
> 
> You have probably misunderstood my code. 'ret' is _not_ passed while @exinfo
> is passed in %rcx. exinfo->leaf implies the reason of the callback.
> 
> Or are you suggesting to add 'ret' as one more parameter to the callback? I
> don't think it necessary because exinfo contains everything the callback
> would ever need.

The latter, because exinfo is optional, as stated above.

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-04-24  1:04         ` Jethro Beekman
@ 2019-04-29 19:08           ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-04-29 19:08 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Jarkko Sakkinen, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	nhorman, npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

On Wed, Apr 24, 2019 at 01:04:21AM +0000, Jethro Beekman wrote:
> On 2019-04-23 17:26, Sean Christopherson wrote:
> >On Tue, Apr 23, 2019 at 11:29:24PM +0000, Jethro Beekman wrote:
> >>On 2019-04-22 14:58, Sean Christopherson wrote:
> >>>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.
> 
> 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.

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

* Re: [PATCH v20 16/28] x86/sgx: Add provisioning
  2019-04-24  1:34   ` Jethro Beekman
@ 2019-05-02  8:27     ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-02  8:27 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes, James Morris,
	Serge E . Hallyn, linux-security-module

On Wed, Apr 24, 2019 at 01:34:03AM +0000, Jethro Beekman wrote:
> On 2019-04-17 03:39, Jarkko Sakkinen wrote:
> > diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
> > index 7bf627ac4958..3b80acde8671 100644
> > --- a/arch/x86/include/uapi/asm/sgx.h
> > +++ b/arch/x86/include/uapi/asm/sgx.h
> > @@ -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

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

* Re: [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-26 21:00         ` Sean Christopherson
@ 2019-05-02  8:28           ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-02  8:28 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, linux-kernel, linux-sgx, akpm, Hansen, Dave, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Svahn, Kai, Huang, Kai

On Fri, Apr 26, 2019 at 02:00:18PM -0700, Sean Christopherson wrote:
> On Thu, Apr 25, 2019 at 04:31:40PM -0700, Xing, Cedric wrote:
> > > While this may format nicely in .rst (I haven't checked), it's damn near
> > > unreadable in its raw form.  Escaping '%' in kernel-doc is unresolved at
> > > this point, but this definitely is an argument for allowing the %CONST
> > > interpretation to be disabled entirely.
> > > 
> > 
> > I know very little about kernel-doc. Not quite sure which markup means what.
> > Or if you don't mind, could you just write up the whole thing (you have
> > written half of it in your email already) so I can include it into my next
> > revision?
> 
> Hmm, at this point I'd say just ignore the comment entirely.  It's
> something we need to sort out in the "official" series anyways.

To get started: https://www.kernel.org/doc/Documentation/kernel-doc-nano-HOWTO.txt

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-04-24 12:17     ` Jarkko Sakkinen
@ 2019-05-08 13:45       ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-08 13:45 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: LKML, X86 ML, linux-sgx, Andrew Morton, Dave Hansen,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Thomas Gleixner, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes, linux-sgx-owner

On Wed, Apr 24, 2019 at 03:17:47PM +0300, Jarkko Sakkinen wrote:
> For me easier path to get something done would to do ELF DSO
> first. As you said they both could be done, which means that
> Windows COFF could be upstreamed later on.
> 
> If this approach works, it'd mean that no ioctl's would be
> required except SGX_ENCLAVE_SET_ATTRIBUTE.
> 
> PS. This quote from LWN got a bit into my feelings:
> 
> "After 20 revisions of the patch set over three years, the
> authors of this work (which was posted by Jarkko Sakkinen)
> might well be forgiven for thinking that it must be about
> ready for merging."
> 
> I seriously do not make any pre-conclusions ever for any patch
> that I post when it should be merged, no matter how big or
> small :-) For me this is just work...

Just throwing this out of my head so that all options are considered but
wouldn't one alternative to get things right be to replace ioctl with a
syscall? Not endorsing this option in particular but I think you could
get security right by doing this.

Even with dlopen() you need ioctl's for setting attributes (e.g.
provisioning) and EINIT. A syscall would be in some ways more sound.

/Jarkko

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

* RE: [PATCH v20 00/28] Intel SGX1 support
  2019-04-22 16:26                               ` Andy Lutomirski
  2019-04-23 21:15                                 ` Jethro Beekman
@ 2019-05-10 17:23                                 ` Xing, Cedric
  2019-05-10 17:37                                   ` Jethro Beekman
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-10 17:23 UTC (permalink / raw)
  To: Andy Lutomirski, Jethro Beekman
  Cc: Thomas Gleixner, Dr. Greg, Hansen, Dave, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

Hi Andy,

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

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 17:23                                 ` Xing, Cedric
@ 2019-05-10 17:37                                   ` Jethro Beekman
  2019-05-10 17:54                                     ` Dave Hansen
  0 siblings, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-05-10 17:37 UTC (permalink / raw)
  To: Xing, Cedric, Andy Lutomirski
  Cc: Thomas Gleixner, Dr. Greg, Hansen, Dave, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

[-- Attachment #1: Type: text/plain, Size: 1926 bytes --]

On 2019-05-10 10:23, Xing, Cedric wrote:
> ... 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.

> * 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


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 17:37                                   ` Jethro Beekman
@ 2019-05-10 17:54                                     ` Dave Hansen
  2019-05-10 18:04                                       ` Jethro Beekman
  2019-05-10 18:44                                       ` Xing, Cedric
  0 siblings, 2 replies; 318+ messages in thread
From: Dave Hansen @ 2019-05-10 17:54 UTC (permalink / raw)
  To: Jethro Beekman, Xing, Cedric, Andy Lutomirski
  Cc: Thomas Gleixner, Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, Christopherson, Sean J,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On 5/10/19 10:37 AM, Jethro Beekman wrote:
> 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?


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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 17:54                                     ` Dave Hansen
@ 2019-05-10 18:04                                       ` Jethro Beekman
  2019-05-10 18:56                                         ` Xing, Cedric
  2019-05-10 18:44                                       ` Xing, Cedric
  1 sibling, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-05-10 18:04 UTC (permalink / raw)
  To: Dave Hansen, Xing, Cedric, Andy Lutomirski
  Cc: Thomas Gleixner, Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, Christopherson, Sean J,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

[-- Attachment #1: Type: text/plain, Size: 1224 bytes --]

On 2019-05-10 10:54, Dave Hansen wrote:
> On 5/10/19 10:37 AM, Jethro Beekman wrote:
>> 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?
> 

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


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* RE: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 17:54                                     ` Dave Hansen
  2019-05-10 18:04                                       ` Jethro Beekman
@ 2019-05-10 18:44                                       ` Xing, Cedric
  1 sibling, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-10 18:44 UTC (permalink / raw)
  To: Hansen, Dave, Jethro Beekman, Andy Lutomirski
  Cc: Thomas Gleixner, Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, Christopherson, Sean J,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

Hi Dave,

> On 5/10/19 10:37 AM, Jethro Beekman wrote:
> > 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?

The key idea here is for enclave files to "inherit" the checks applicable to regular shared objects. And how we are going to do it is for user process to map every loadable segment of the enclave file into its address space using *multiple* mmap() calls, just in the same way as dlopen() would do for loading regular shared objects. Then those open()/mmap() syscalls will trigger all applicable checks (by means of security_file_open(), security_mmap_file() and ima_file_mmap() hooks) transparently. That said, IMA/LSM implementations/policies will dictate the success/failure of those open()/mmap() syscalls. And by depending EPCM attributes on permissions of source VMAs, no EXEC page could be ever created unless the source page (which has to be EXEC, btw) has passed IMA/LSM checks (as if it were loaded from a regular shared object file).

-Cedric 


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

* RE: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 18:04                                       ` Jethro Beekman
@ 2019-05-10 18:56                                         ` Xing, Cedric
  2019-05-10 19:04                                           ` Jethro Beekman
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-10 18:56 UTC (permalink / raw)
  To: Jethro Beekman, Hansen, Dave, Andy Lutomirski
  Cc: Thomas Gleixner, Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, Christopherson, Sean J,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

Hi Jethro,
 
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 18:56                                         ` Xing, Cedric
@ 2019-05-10 19:04                                           ` Jethro Beekman
  2019-05-10 19:22                                             ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-05-10 19:04 UTC (permalink / raw)
  To: Xing, Cedric, Hansen, Dave, Andy Lutomirski
  Cc: Thomas Gleixner, Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, Christopherson, Sean J,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

[-- Attachment #1: Type: text/plain, Size: 1050 bytes --]

On 2019-05-10 11:56, Xing, Cedric wrote:
> Hi Jethro,
>   
>> 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


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 19:04                                           ` Jethro Beekman
@ 2019-05-10 19:22                                             ` Andy Lutomirski
  2019-05-11  1:06                                               ` Xing, Cedric
                                                                 ` (2 more replies)
  0 siblings, 3 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-10 19:22 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Xing, Cedric, Hansen, Dave, Andy Lutomirski, Thomas Gleixner,
	Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 10, 2019 at 12:04 PM Jethro Beekman <jethro@fortanix.com> wrote:
>
> On 2019-05-10 11:56, Xing, Cedric wrote:
> > Hi Jethro,
> >
> >> 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.
>

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.

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

* RE: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 19:22                                             ` Andy Lutomirski
@ 2019-05-11  1:06                                               ` Xing, Cedric
  2019-05-14 15:08                                                 ` Andy Lutomirski
       [not found]                                               ` <20190513102926.GD8743@linux.intel.com>
  2019-05-14 14:33                                               ` Haitao Huang
  2 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-11  1:06 UTC (permalink / raw)
  To: Andy Lutomirski, Jethro Beekman
  Cc: Hansen, Dave, Thomas Gleixner, Dr. Greg, Jarkko Sakkinen,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

Hi Andy and Jethro,

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

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.

> 
> 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.)

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?

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

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.
 
> 
> 2a is by far the most complicated kernel implementation.
> 

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

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

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

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.

> 
> 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.
 
> * 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
       [not found]                                               ` <20190513102926.GD8743@linux.intel.com>
@ 2019-05-14 10:43                                                 ` Jarkko Sakkinen
  2019-05-14 15:13                                                   ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-14 10:43 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-10 19:22                                             ` Andy Lutomirski
  2019-05-11  1:06                                               ` Xing, Cedric
       [not found]                                               ` <20190513102926.GD8743@linux.intel.com>
@ 2019-05-14 14:33                                               ` Haitao Huang
  2019-05-14 15:17                                                 ` Andy Lutomirski
  2 siblings, 1 reply; 318+ messages in thread
From: Haitao Huang @ 2019-05-14 14:33 UTC (permalink / raw)
  To: Jethro Beekman, Andy Lutomirski
  Cc: Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Fri, 10 May 2019 14:22:34 -0500, Andy Lutomirski <luto@kernel.org>  
wrote:

> On Fri, May 10, 2019 at 12:04 PM Jethro Beekman <jethro@fortanix.com>  
> wrote:
>>
>> On 2019-05-10 11:56, Xing, Cedric wrote:
>> > Hi Jethro,
>> >
>> >> 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.
>>
>
> 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.

Given this, I just want to step back a little to understand the exact  
issue that SGX is causing here for LSM/IMA. Sorry if I missed points  
discussed earlier.

By the time of EADD, enclave file is opened and should have passed IMA and  
SELinux policy enforcement gates if any. We really don't need extra mmaps  
on the enclave files to be IMA and SELinux compliant. We are loading  
enclave files as RO and copying those into EPC. An IMA policy can enforce  
RO files (or any file). And SELinux policy can say which processes can  
open the file for what permissions. No extra needed here.

And sgx enclaves are always signed and integrity protected and verified at  
the time of EINIT. So if EINIT passes, we know the content loaded  
(including permission flags) is matching the sigstruct.  But  
sigstruct/signature is part of the file, should be accounted for in IMA  
measurement of the whole file, so it is also verified by IMA during file  
open, right?

The only potential gap/difference comparing to regular ELF executable or  
DSOs:for enclaves, we need mmap portions of enclave linear range with RW  
to do EADD IOC, then mprotect those pages to RX after EINIT. But this is  
operated on enclave fd provided by driver. So we can have an SELinux  
policy say: only this type of processes is allowed to open enclave fd, and  
allowed to do mmap/mprotect with read, write, execute on it. Wouldn't that  
be enough?


Thanks
Haitao

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-11  1:06                                               ` Xing, Cedric
@ 2019-05-14 15:08                                                 ` Andy Lutomirski
  2019-05-15  8:31                                                   ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-14 15:08 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 10, 2019 at 6:06 PM Xing, Cedric <cedric.xing@intel.com> wrote:
>
> Hi Andy and Jethro,
>
> > > > 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.
> > >
>
> 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.
>
> >
> > 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.)
>
> 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.

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

>
> >
> > 2a is by far the most complicated kernel implementation.
> >
>
> Agreed. I don't see any reason 2a would be necessary.
>
> > 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.

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

> 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.)

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 10:43                                                 ` Jarkko Sakkinen
@ 2019-05-14 15:13                                                   ` Andy Lutomirski
  2019-05-14 20:45                                                     ` Sean Christopherson
  2019-05-15  8:49                                                     ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-14 15:13 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 3:43 AM Jarkko Sakkinen
<jarkko.sakkinen@linux.intel.com> wrote:
>
> On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> > 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.
>
> 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.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 14:33                                               ` Haitao Huang
@ 2019-05-14 15:17                                                 ` Andy Lutomirski
  2019-05-14 15:30                                                   ` Haitao Huang
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-14 15:17 UTC (permalink / raw)
  To: Haitao Huang
  Cc: Jethro Beekman, Andy Lutomirski, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, Christopherson, Sean J,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 7:33 AM Haitao Huang
<haitao.huang@linux.intel.com> wrote:
>
> On Fri, 10 May 2019 14:22:34 -0500, Andy Lutomirski <luto@kernel.org>
> wrote:
>
> > On Fri, May 10, 2019 at 12:04 PM Jethro Beekman <jethro@fortanix.com>
> > wrote:
> >>
> >> On 2019-05-10 11:56, Xing, Cedric wrote:
> >> > Hi Jethro,
> >> >
> >> >> 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.
> >>
> >
> > 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.
>
> Given this, I just want to step back a little to understand the exact
> issue that SGX is causing here for LSM/IMA. Sorry if I missed points
> discussed earlier.
>
> By the time of EADD, enclave file is opened and should have passed IMA and
> SELinux policy enforcement gates if any. We really don't need extra mmaps
> on the enclave files to be IMA and SELinux compliant.

The problem, as i see it, is that they passed the *wrong* checks,
because, as you noticed:

> We are loading
> enclave files as RO and copying those into EPC.

Which is, semantically, a lot like loading a normal file as RO and
then mprotecting() it to RX, which is disallowed under quite a few LSM
policies.

> An IMA policy can enforce
> RO files (or any file). And SELinux policy can say which processes can
> open the file for what permissions. No extra needed here.

If SELinux says a process may open a file as RO, that does *not* mean
that it can be opened as RX.

>
> And sgx enclaves are always signed and integrity protected and verified at
> the time of EINIT. So if EINIT passes, we know the content loaded
> (including permission flags) is matching the sigstruct.  But
> sigstruct/signature is part of the file, should be accounted for in IMA
> measurement of the whole file, so it is also verified by IMA during file
> open, right?

This does work, but only if the kernel parses that file so that the
kernel can trust that the enclave data actually came from the file as
intended.  And moving the parsing to the kernel seems like a mess that
no one really wants to do.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 15:17                                                 ` Andy Lutomirski
@ 2019-05-14 15:30                                                   ` Haitao Huang
  2019-05-14 20:45                                                     ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Haitao Huang @ 2019-05-14 15:30 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Tue, 14 May 2019 10:17:29 -0500, Andy Lutomirski <luto@kernel.org>  
wrote:

> On Tue, May 14, 2019 at 7:33 AM Haitao Huang
> <haitao.huang@linux.intel.com> wrote:
>>
>> On Fri, 10 May 2019 14:22:34 -0500, Andy Lutomirski <luto@kernel.org>
>> wrote:
>>
>> > On Fri, May 10, 2019 at 12:04 PM Jethro Beekman <jethro@fortanix.com>
>> > wrote:
>> >>
>> >> On 2019-05-10 11:56, Xing, Cedric wrote:
>> >> > Hi Jethro,
>> >> >
>> >> >> 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.
>> >>
>> >
>> > 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.
>>
>> Given this, I just want to step back a little to understand the exact
>> issue that SGX is causing here for LSM/IMA. Sorry if I missed points
>> discussed earlier.
>>
>> By the time of EADD, enclave file is opened and should have passed IMA  
>> and
>> SELinux policy enforcement gates if any. We really don't need extra  
>> mmaps
>> on the enclave files to be IMA and SELinux compliant.
>
> The problem, as i see it, is that they passed the *wrong* checks,
> because, as you noticed:
>
>> We are loading
>> enclave files as RO and copying those into EPC.
>
> Which is, semantically, a lot like loading a normal file as RO and
> then mprotecting() it to RX, which is disallowed under quite a few LSM
> policies.
>
>> An IMA policy can enforce
>> RO files (or any file). And SELinux policy can say which processes can
>> open the file for what permissions. No extra needed here.
>
> If SELinux says a process may open a file as RO, that does *not* mean
> that it can be opened as RX.
>

But in this case, file itself is mapped as RO treated like data and it is  
not for execution. SGX enclave pages have EPCM enforced permissions. So  
 from SELinux point of view I would think it can treat it as RO and that's  
fine.

>>
>> And sgx enclaves are always signed and integrity protected and verified  
>> at
>> the time of EINIT. So if EINIT passes, we know the content loaded
>> (including permission flags) is matching the sigstruct.  But
>> sigstruct/signature is part of the file, should be accounted for in IMA
>> measurement of the whole file, so it is also verified by IMA during file
>> open, right?
>
> This does work, but only if the kernel parses that file so that the
> kernel can trust that the enclave data actually came from the file as
> intended.  And moving the parsing to the kernel seems like a mess that
> no one really wants to do.

If kernel only needs to know the source bytes are from a file that passed  
IMA integrity and SELinux RO enforcement, then it can just check if the  
source pointer belongs to a VMA with valid fd and no parsing or checking  
permissions needed.
Understood if you want to make enclave file code segment stick to the RX  
semantics mentioned above, then this doesn't qualify.

Thanks

Haitao

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 15:13                                                   ` Andy Lutomirski
@ 2019-05-14 20:45                                                     ` Sean Christopherson
  2019-05-14 21:27                                                       ` Andy Lutomirski
  2019-05-15 10:35                                                       ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
  2019-05-15  8:49                                                     ` Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-14 20:45 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jarkko Sakkinen, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> On Tue, May 14, 2019 at 3:43 AM Jarkko Sakkinen
> <jarkko.sakkinen@linux.intel.com> wrote:
> >
> > On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> > > 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.
> >
> > 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.

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 15:30                                                   ` Haitao Huang
@ 2019-05-14 20:45                                                     ` Andy Lutomirski
  2019-05-14 21:08                                                       ` Haitao Huang
  2019-05-14 21:58                                                       ` Xing, Cedric
  0 siblings, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-14 20:45 UTC (permalink / raw)
  To: Haitao Huang
  Cc: Andy Lutomirski, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, Christopherson, Sean J,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

> On May 14, 2019, at 8:30 AM, Haitao Huang <haitao.huang@linux.intel.com> wrote:
>
>> On Tue, 14 May 2019 10:17:29 -0500, Andy Lutomirski <luto@kernel.org> wrote:
>>
>> On Tue, May 14, 2019 at 7:33 AM Haitao Huang
>> <haitao.huang@linux.intel.com> wrote:
>>>
>>> On Fri, 10 May 2019 14:22:34 -0500, Andy Lutomirski <luto@kernel.org>
>>> wrote:
>>>
>>> > On Fri, May 10, 2019 at 12:04 PM Jethro Beekman <jethro@fortanix.com>
>>> > wrote:
>>> >>
>>> >> On 2019-05-10 11:56, Xing, Cedric wrote:
>>> >> > Hi Jethro,
>>> >> >
>>> >> >> 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.
>>> >>
>>> >
>>> > 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.
>>>
>>> Given this, I just want to step back a little to understand the exact
>>> issue that SGX is causing here for LSM/IMA. Sorry if I missed points
>>> discussed earlier.
>>>
>>> By the time of EADD, enclave file is opened and should have passed IMA and
>>> SELinux policy enforcement gates if any. We really don't need extra mmaps
>>> on the enclave files to be IMA and SELinux compliant.
>>
>> The problem, as i see it, is that they passed the *wrong* checks,
>> because, as you noticed:
>>
>>> We are loading
>>> enclave files as RO and copying those into EPC.
>>
>> Which is, semantically, a lot like loading a normal file as RO and
>> then mprotecting() it to RX, which is disallowed under quite a few LSM
>> policies.
>>
>>> An IMA policy can enforce
>>> RO files (or any file). And SELinux policy can say which processes can
>>> open the file for what permissions. No extra needed here.
>>
>> If SELinux says a process may open a file as RO, that does *not* mean
>> that it can be opened as RX.
>>
>
> But in this case, file itself is mapped as RO treated like data and it is not for execution. SGX enclave pages have EPCM enforced permissions. So from SELinux point of view I would think it can treat it as RO and that's fine.

As an example, SELinux has an “execute” permission (via
security_mmap_file — see file_map_prot_check()) that controls whether
you can execute code from that file.  If you lack this permission on a
file, you may still be able to map it PROT_READ, but you may not map
it PROT_EXEC.  Similarly, if you want to malloc() some memory, write
*code* to it, and execute it, you need a specific permission.

So, unless we somehow think it’s okay for SGX to break the existing
model, we need to respect these restrictions in the SGX driver. In
other words, we either need to respect execmem, etc or require
PROT_EXEC or the equivalent. I like the latter a lot more.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 20:45                                                     ` Andy Lutomirski
@ 2019-05-14 21:08                                                       ` Haitao Huang
  2019-05-14 21:58                                                       ` Xing, Cedric
  1 sibling, 0 replies; 318+ messages in thread
From: Haitao Huang @ 2019-05-14 21:08 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, Christopherson, Sean J, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Tue, 14 May 2019 15:45:54 -0500, Andy Lutomirski <luto@kernel.org>  
wrote:

>> On May 14, 2019, at 8:30 AM, Haitao Huang  
>> <haitao.huang@linux.intel.com> wrote:
>>
>>> On Tue, 14 May 2019 10:17:29 -0500, Andy Lutomirski <luto@kernel.org>  
>>> wrote:
>>>
>>> On Tue, May 14, 2019 at 7:33 AM Haitao Huang
>>> <haitao.huang@linux.intel.com> wrote:
>>>>
>>>> On Fri, 10 May 2019 14:22:34 -0500, Andy Lutomirski <luto@kernel.org>
>>>> wrote:
>>>>
>>>> > On Fri, May 10, 2019 at 12:04 PM Jethro Beekman  
>>>> <jethro@fortanix.com>
>>>> > wrote:
>>>> >>
>>>> >> On 2019-05-10 11:56, Xing, Cedric wrote:
>>>> >> > Hi Jethro,
>>>> >> >
>>>> >> >> 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.
>>>> >>
>>>> >
>>>> > 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.
>>>>
>>>> Given this, I just want to step back a little to understand the exact
>>>> issue that SGX is causing here for LSM/IMA. Sorry if I missed points
>>>> discussed earlier.
>>>>
>>>> By the time of EADD, enclave file is opened and should have passed  
>>>> IMA and
>>>> SELinux policy enforcement gates if any. We really don't need extra  
>>>> mmaps
>>>> on the enclave files to be IMA and SELinux compliant.
>>>
>>> The problem, as i see it, is that they passed the *wrong* checks,
>>> because, as you noticed:
>>>
>>>> We are loading
>>>> enclave files as RO and copying those into EPC.
>>>
>>> Which is, semantically, a lot like loading a normal file as RO and
>>> then mprotecting() it to RX, which is disallowed under quite a few LSM
>>> policies.
>>>
>>>> An IMA policy can enforce
>>>> RO files (or any file). And SELinux policy can say which processes can
>>>> open the file for what permissions. No extra needed here.
>>>
>>> If SELinux says a process may open a file as RO, that does *not* mean
>>> that it can be opened as RX.
>>>
>>
>> But in this case, file itself is mapped as RO treated like data and it  
>> is not for execution. SGX enclave pages have EPCM enforced permissions.  
>> So from SELinux point of view I would think it can treat it as RO and  
>> that's fine.
>
> As an example, SELinux has an “execute” permission (via
> security_mmap_file — see file_map_prot_check()) that controls whether
> you can execute code from that file.  If you lack this permission on a
> file, you may still be able to map it PROT_READ, but you may not map
> it PROT_EXEC.  Similarly, if you want to malloc() some memory, write
> *code* to it, and execute it, you need a specific permission.
>
> So, unless we somehow think it’s okay for SGX to break the existing
> model, we need to respect these restrictions in the SGX driver. In
> other words, we either need to respect execmem, etc or require
> PROT_EXEC or the equivalent. I like the latter a lot more.

What puzzles me is that this restriction does not add real value to  
security.
When enclave files are mapped with PROT_READ, without SE execute  
permission. No breakage to LSM model in normal process address space as no  
one can execute code directly from the file in normal memory. When enclave  
is built and loaded into EPC by EADDs, if the SIGSTRUCT is trusted (either  
signer or MRENCLAVE), EINIT will guarantee security (both integrity and  
permissions). LSM may not like the fact the a piece of code got loaded  
into EPC page without specifically giving SE execute permission. However,  
LSM can be used to control what SIGSTRUCTs can be trusted as you suggested  
and indirectly enforce what code got executed inside EPC.

So to me, only SIGSTRUCT verification would add value.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 20:45                                                     ` Sean Christopherson
@ 2019-05-14 21:27                                                       ` Andy Lutomirski
  2019-05-14 22:28                                                         ` Xing, Cedric
  2019-05-15  1:30                                                         ` Sean Christopherson
  2019-05-15 10:35                                                       ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-14 21:27 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Jarkko Sakkinen, Jethro Beekman, Xing, Cedric,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 1:45 PM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> > On Tue, May 14, 2019 at 3:43 AM Jarkko Sakkinen
> > <jarkko.sakkinen@linux.intel.com> wrote:
> > >
> > > On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> > > > 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.
> > >
> > > 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.

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.

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

* RE: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 20:45                                                     ` Andy Lutomirski
  2019-05-14 21:08                                                       ` Haitao Huang
@ 2019-05-14 21:58                                                       ` Xing, Cedric
  2019-05-15  5:15                                                         ` Haitao Huang
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-14 21:58 UTC (permalink / raw)
  To: Andy Lutomirski, Haitao Huang
  Cc: Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

Hi Everyone,

I think we are talking about 2 different kinds of criteria for determining the sanity of an enclave. 

The first kind determines an enclave's sanity by generally accepted good practices. For example, no executable pages shall ever be writable.

The second kind determines an enclave's sanity by "who stands behind it", such as whether the file containing SIGSTRUCT has the proper SELinux label/type, or whether the signing key is trusted.

I'd say those 2 kinds of criteria should be orthogonal because they don't get into each other's way and it could also be beneficial to enable both at the same time. For example, a user may want to allow launching enclaves signed by himself/herself only, however, as a human being he/she may make mistakes so would also like to ensure no RWX pages even for those enclaves explicitly authorized.

I think those 2 kinds of criteria could be abstracted as 2 new LSM hooks - security_sgx_add_pages() and security_sgx_initialize_enclave().

security_sgx_add_pages() is invoked by SGX driver to determine if a range of source pages are allowed to be EADD'ed with the requested EPCM attributes, and by default it returns 0 (allowed) iff the requested EPCM attributes are a subset of the permissions of the VMA covering that range of source pages. An (SGX-aware) LSM module/policy could employ different criteria, such as making sure the source pages are backed by an enclave file (using SELinux label, for example). 

security_sgx_initialize_enclave() is invoked by SGX driver to determine if a given SIGSTRUCT is valid (hence allowed to be EINIT'ed), and it always returns 0 (allowed) by default. An LSM implementation may enforce custom policies, such as whether the signing public key is trusted by the current user, or whether it was backed (mmap()'ed) by an authorized file (e.g. of an expected type in the case of SELinux, or located in a particular directory in the case of AppArmor).

With regard to SGX2/EDMM (Enclave Dynamic Memory Management) support, RW->RX transitions are inevitable to support certain usages such as dynamic loading/linking, meaning those usages may be blocked by existing policies. But from security perspective, I think they should be allowed by default (i.e. for non-SGX-aware LSM modules/policies) because such permission changes are inherent behaviors of the enclave itself, which is considered "sane" after passing all the checks performed in security_sgx_add_pages()/security_sgx_initialize_enclave(). Of course, an SGX-aware LSM module/policy shall be allowed to override. How about adding a new security_sgx_mprotect() LSM hook?

> From: Andy Lutomirski [mailto:luto@kernel.org]
> 
> > On May 14, 2019, at 8:30 AM, Haitao Huang
> <haitao.huang@linux.intel.com> wrote:
> >
> >> On Tue, 14 May 2019 10:17:29 -0500, Andy Lutomirski <luto@kernel.org>
> wrote:
> >>
> >> On Tue, May 14, 2019 at 7:33 AM Haitao Huang
> >> <haitao.huang@linux.intel.com> wrote:
> >>>
> >>> On Fri, 10 May 2019 14:22:34 -0500, Andy Lutomirski
> >>> <luto@kernel.org>
> >>> wrote:
> >>>
> >>> > On Fri, May 10, 2019 at 12:04 PM Jethro Beekman
> >>> > <jethro@fortanix.com>
> >>> > wrote:
> >>> >>
> >>> >> On 2019-05-10 11:56, Xing, Cedric wrote:
> >>> >> > Hi Jethro,
> >>> >> >
> >>> >> >> 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.
> >>> >>
> >>> >
> >>> > 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.
> >>>
> >>> Given this, I just want to step back a little to understand the
> >>> exact issue that SGX is causing here for LSM/IMA. Sorry if I missed
> >>> points discussed earlier.
> >>>
> >>> By the time of EADD, enclave file is opened and should have passed
> >>> IMA and SELinux policy enforcement gates if any. We really don't
> >>> need extra mmaps on the enclave files to be IMA and SELinux
> compliant.
> >>
> >> The problem, as i see it, is that they passed the *wrong* checks,
> >> because, as you noticed:
> >>
> >>> We are loading
> >>> enclave files as RO and copying those into EPC.
> >>
> >> Which is, semantically, a lot like loading a normal file as RO and
> >> then mprotecting() it to RX, which is disallowed under quite a few
> >> LSM policies.
> >>
> >>> An IMA policy can enforce
> >>> RO files (or any file). And SELinux policy can say which processes
> >>> can open the file for what permissions. No extra needed here.
> >>
> >> If SELinux says a process may open a file as RO, that does *not* mean
> >> that it can be opened as RX.
> >>
> >
> > But in this case, file itself is mapped as RO treated like data and it
> is not for execution. SGX enclave pages have EPCM enforced permissions.
> So from SELinux point of view I would think it can treat it as RO and
> that's fine.
> 
> As an example, SELinux has an “execute” permission (via
> security_mmap_file — see file_map_prot_check()) that controls whether
> you can execute code from that file.  If you lack this permission on a
> file, you may still be able to map it PROT_READ, but you may not map it
> PROT_EXEC.  Similarly, if you want to malloc() some memory, write
> *code* to it, and execute it, you need a specific permission.
> 
> So, unless we somehow think it’s okay for SGX to break the existing
> model, we need to respect these restrictions in the SGX driver. In other
> words, we either need to respect execmem, etc or require PROT_EXEC or
> the equivalent. I like the latter a lot more.

-Cedric

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

* RE: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 21:27                                                       ` Andy Lutomirski
@ 2019-05-14 22:28                                                         ` Xing, Cedric
  2019-05-15  1:30                                                         ` Sean Christopherson
  1 sibling, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-14 22:28 UTC (permalink / raw)
  To: Andy Lutomirski, Christopherson, Sean J
  Cc: Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

Hi Andy,

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

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.

> 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).

> 
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 21:27                                                       ` Andy Lutomirski
  2019-05-14 22:28                                                         ` Xing, Cedric
@ 2019-05-15  1:30                                                         ` Sean Christopherson
  2019-05-15 18:27                                                           ` SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support) Andy Lutomirski
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-15  1:30 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jarkko Sakkinen, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 02:27:08PM -0700, Andy Lutomirski wrote:
> On Tue, May 14, 2019 at 1:45 PM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> > > On Tue, May 14, 2019 at 3:43 AM Jarkko Sakkinen
> > > <jarkko.sakkinen@linux.intel.com> wrote:
> > > >
> > > > On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> > > > > 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.
> > > >
> > > > 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.
> 
> 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.

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

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

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

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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 21:58                                                       ` Xing, Cedric
@ 2019-05-15  5:15                                                         ` Haitao Huang
  0 siblings, 0 replies; 318+ messages in thread
From: Haitao Huang @ 2019-05-15  5:15 UTC (permalink / raw)
  To: Andy Lutomirski, Xing, Cedric
  Cc: Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Jarkko Sakkinen, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, Christopherson, Sean J, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Tue, 14 May 2019 16:58:24 -0500, Xing, Cedric <cedric.xing@intel.com>  
wrote:

> Hi Everyone,
>
> I think we are talking about 2 different kinds of criteria for  
> determining the sanity of an enclave.
>
> The first kind determines an enclave's sanity by generally accepted good  
> practices. For example, no executable pages shall ever be writable.
>

We'll have to trust user space doing mmap with right permissions as  
SELinux does not enforce which segment to be RW and which to be RX. The  
file needs to have SELinux EXECUTE and WRITE both, if we need map some  
segments with RW and others with RX.

We could say EINIT would ensure user is doing the right thing because it  
would fail if user map permission wrongly. Then the extra mmaps are  
redundant of doing SIGSTRUCT verification.

Additionally, per Sean's comments, after EADD in current implementation,  
we will still need PROCESS_EXECMEM for mprotect on enclave fd to change  
some EPC pages PTE to RX before enclave can execute. So I don't think mmap  
the source enclave file would gain anything in addition to what your  
proposed security_sgx_initialize_enclave() does.


Since security_sgx_initialize_enclave() is a lot like launch control  
policy enforcement we discussed a lot and resolved, I tend to agree with  
Andy's assessment we can just do nothing for the initial merge and add  
hooks needed if someone wants them. And the initial merge would require  
the enclave hosting processes ask for PROCESS_EXECMEM permission to do  
mmap/mprotect with enclave fd.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 15:08                                                 ` Andy Lutomirski
@ 2019-05-15  8:31                                                   ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-15  8:31 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Xing, Cedric, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 08:08:03AM -0700, Andy Lutomirski wrote:
> > 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 15:13                                                   ` Andy Lutomirski
  2019-05-14 20:45                                                     ` Sean Christopherson
@ 2019-05-15  8:49                                                     ` Jarkko Sakkinen
  2019-05-15  9:58                                                       ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-15  8:49 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> On Tue, May 14, 2019 at 3:43 AM Jarkko Sakkinen
> <jarkko.sakkinen@linux.intel.com> wrote:
> >
> > On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> > > 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.
> >
> > 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.

OK, so you would actually go on to check whether the VMA where the data
is copied contains executable data?

What if SECINFO.X is not set and you EADD to region that is executable
in the enclave VMA? E.g. have RWX VMA for the enclave just to give a
simple example. Then you could carry executable code in the data
sections of the binary.

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-15  8:49                                                     ` Jarkko Sakkinen
@ 2019-05-15  9:58                                                       ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-15  9:58 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	Christopherson, Sean J, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 11:49:09AM +0300, Jarkko Sakkinen wrote:
> On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> > On Tue, May 14, 2019 at 3:43 AM Jarkko Sakkinen
> > <jarkko.sakkinen@linux.intel.com> wrote:
> > >
> > > On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> > > > 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.
> > >
> > > 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.
> 
> OK, so you would actually go on to check whether the VMA where the data
> is copied contains executable data?
> 
> What if SECINFO.X is not set and you EADD to region that is executable
> in the enclave VMA? E.g. have RWX VMA for the enclave just to give a
> simple example. Then you could carry executable code in the data
> sections of the binary.

This would require to be done after the enclave is initialized of course
with EMODPR, which requires the enclave to accept the permission change
with EACCEPT, which limits somewhat. This means that the static enclave
would be fully covered.

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-14 20:45                                                     ` Sean Christopherson
  2019-05-14 21:27                                                       ` Andy Lutomirski
@ 2019-05-15 10:35                                                       ` Jarkko Sakkinen
  2019-05-15 11:00                                                         ` Jarkko Sakkinen
  2019-05-15 13:21                                                         ` Sean Christopherson
  1 sibling, 2 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-15 10:35 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 14, 2019 at 01:45:27PM -0700, Sean Christopherson wrote:
> On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> > On Tue, May 14, 2019 at 3:43 AM Jarkko Sakkinen
> > <jarkko.sakkinen@linux.intel.com> wrote:
> > >
> > > On Mon, May 13, 2019 at 01:29:26PM +0300, Jarkko Sakkinen wrote:
> > > > 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.
> > >
> > > 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.

Small correction: it is EMODPR.

Anyway, it is good to mention that these would require EACCEPT from the
enclave side. In order to take advantage of this is in a malicous
enclave, one would require SELinux/IMA/whatnot policy to have permitted
it in the first place.

Thus, it cannot be said that it breaks the security policy if this would
happen because policy has allowed to use the particular enclave.

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

If the security policy can define who can create legit SIGSTRUCT files,
this should not be a problem. Neither should be how EEXTEND is used.

This brings me to an open question in Andy's model: lets say that we
change the source for SIGSTRUCT from memory address to fd. How can the
policy prevent the use not creating a file containing a SIGSTRUCT and
passing fd of that to the EINIT ioctl?

If we can sort this question out, then SIGSTRUCT-centered way to control
enclave would actually be robust.

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-15 10:35                                                       ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
@ 2019-05-15 11:00                                                         ` Jarkko Sakkinen
  2019-05-15 14:27                                                           ` Andy Lutomirski
  2019-05-15 13:21                                                         ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-15 11:00 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 01:35:31PM +0300, Jarkko Sakkinen wrote:
> This brings me to an open question in Andy's model: lets say that we
> change the source for SIGSTRUCT from memory address to fd. How can the
> policy prevent the use not creating a file containing a SIGSTRUCT and
> passing fd of that to the EINIT ioctl?

Also wondering if a path would be better than plain fd for defining a
reasonable policy i.e. have sigstruct_path as part of the ioctl
parameters and not sigstruct_fd.

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-15 10:35                                                       ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
  2019-05-15 11:00                                                         ` Jarkko Sakkinen
@ 2019-05-15 13:21                                                         ` Sean Christopherson
  2019-05-16  5:01                                                           ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-15 13:21 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 01:35:31PM +0300, Jarkko Sakkinen wrote:
> On Tue, May 14, 2019 at 01:45:27PM -0700, Sean Christopherson wrote:
> > On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> > > 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.
> 
> Small correction: it is EMODPR.

No, I'm referring to EMODPE, note the ENCLU classification.

> Anyway, it is good to mention that these would require EACCEPT from the
> enclave side. In order to take advantage of this is in a malicous
> enclave, one would require SELinux/IMA/whatnot policy to have permitted
> it in the first place.

EMODPE doesn't require EACCEPT or any equivalent from the kernel.  As
you alluded to, the page tables would still need to allow PROT_EXEC.  I
was simply trying to answer Andy's question regarding SECINFO.

> Thus, it cannot be said that it breaks the security policy if this would
> happen because policy has allowed to use the particular enclave.

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-15 11:00                                                         ` Jarkko Sakkinen
@ 2019-05-15 14:27                                                           ` Andy Lutomirski
  2019-05-16  5:07                                                             ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-15 14:27 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Sean Christopherson, Andy Lutomirski, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes


> On May 15, 2019, at 4:00 AM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
> 
>> On Wed, May 15, 2019 at 01:35:31PM +0300, Jarkko Sakkinen wrote:
>> This brings me to an open question in Andy's model: lets say that we
>> change the source for SIGSTRUCT from memory address to fd. How can the
>> policy prevent the use not creating a file containing a SIGSTRUCT and
>> passing fd of that to the EINIT ioctl?
> 

The policy will presumably check the label on the file that the fd points to.

> Also wondering if a path would be better than plain fd for defining a
> reasonable policy i.e. have sigstruct_path as part of the ioctl
> parameters and not sigstruct_fd.
> 

It would save two syscalls at the cost of a decent amount of complexity.

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

* SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15  1:30                                                         ` Sean Christopherson
@ 2019-05-15 18:27                                                           ` Andy Lutomirski
  2019-05-15 19:58                                                             ` James Morris
                                                                               ` (3 more replies)
  0 siblings, 4 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-15 18:27 UTC (permalink / raw)
  To: Sean Christopherson, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux
  Cc: Andy Lutomirski, Jarkko Sakkinen, Jethro Beekman, Xing, Cedric,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

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!

> On May 14, 2019, at 6:30 PM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
>
>
>> 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.
>
>> 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?

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.

>  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.)

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 18:27                                                           ` SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support) Andy Lutomirski
@ 2019-05-15 19:58                                                             ` James Morris
  2019-05-15 20:35                                                               ` Andy Lutomirski
  2019-05-15 21:38                                                             ` Sean Christopherson
                                                                               ` (2 subsequent siblings)
  3 siblings, 1 reply; 318+ messages in thread
From: James Morris @ 2019-05-15 19:58 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, 15 May 2019, Andy Lutomirski wrote:

> 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 ?

> 
> 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?

Would it be possible to provide multiple fds (perhaps via a pseudo fs 
interface) which can be mapped to different types of VMAs?

-- 
James Morris
<jmorris@namei.org>


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 19:58                                                             ` James Morris
@ 2019-05-15 20:35                                                               ` Andy Lutomirski
  2019-05-15 22:46                                                                 ` James Morris
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-15 20:35 UTC (permalink / raw)
  To: James Morris
  Cc: Andy Lutomirski, Sean Christopherson, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 12:58 PM James Morris <jmorris@namei.org> wrote:
>
> On Wed, 15 May 2019, Andy Lutomirski wrote:
>
> > 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?

Yes, unless an LSM wants to examine it to make a decision.

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

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

>
> >
> > 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?
>
> 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?

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 18:27                                                           ` SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support) Andy Lutomirski
  2019-05-15 19:58                                                             ` James Morris
@ 2019-05-15 21:38                                                             ` Sean Christopherson
  2019-05-16  1:19                                                               ` Haitao Huang
  2019-05-16  5:16                                                             ` Jarkko Sakkinen
  2019-05-17  0:03                                                             ` Sean Christopherson
  3 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-15 21:38 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: James Morris, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 11:27:04AM -0700, Andy Lutomirski wrote:
> 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.

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 20:35                                                               ` Andy Lutomirski
@ 2019-05-15 22:46                                                                 ` James Morris
  2019-05-15 23:13                                                                   ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: James Morris @ 2019-05-15 22:46 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, 15 May 2019, Andy Lutomirski wrote:

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

-- 
James Morris
<jmorris@namei.org>


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 22:46                                                                 ` James Morris
@ 2019-05-15 23:13                                                                   ` Andy Lutomirski
  2019-05-16  3:03                                                                     ` Xing, Cedric
  2019-05-16  7:24                                                                     ` James Morris
  0 siblings, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-15 23:13 UTC (permalink / raw)
  To: James Morris
  Cc: Andy Lutomirski, Sean Christopherson, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 3:46 PM James Morris <jmorris@namei.org> wrote:
>
> On Wed, 15 May 2019, Andy Lutomirski wrote:
>
> > > 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.
>

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 21:38                                                             ` Sean Christopherson
@ 2019-05-16  1:19                                                               ` Haitao Huang
  0 siblings, 0 replies; 318+ messages in thread
From: Haitao Huang @ 2019-05-16  1:19 UTC (permalink / raw)
  To: Andy Lutomirski, Sean Christopherson
  Cc: James Morris, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, 15 May 2019 16:38:58 -0500, Sean Christopherson  
<sean.j.christopherson@intel.com> wrote:

> On Wed, May 15, 2019 at 11:27:04AM -0700, Andy Lutomirski wrote:
>> 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.
>
> 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.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 23:13                                                                   ` Andy Lutomirski
@ 2019-05-16  3:03                                                                     ` Xing, Cedric
  2019-05-16  4:40                                                                       ` Andy Lutomirski
  2019-05-16  7:24                                                                     ` James Morris
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-16  3:03 UTC (permalink / raw)
  To: Andy Lutomirski, James Morris
  Cc: Christopherson, Sean J, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

Hi Andy,

> From: Andy Lutomirski [mailto:luto@kernel.org]
> 
> On Wed, May 15, 2019 at 3:46 PM James Morris <jmorris@namei.org> wrote:
> >
> > On Wed, 15 May 2019, Andy Lutomirski wrote:
> >
> > > > 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.
> >
> 
> 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);

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.

> 
> /* 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.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16  3:03                                                                     ` Xing, Cedric
@ 2019-05-16  4:40                                                                       ` Andy Lutomirski
  2019-05-16 22:23                                                                         ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-16  4:40 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, James Morris, Christopherson, Sean J,
	Serge E. Hallyn, LSM List, Paul Moore, Stephen Smalley,
	Eric Paris, selinux, Jarkko Sakkinen, Jethro Beekman, Hansen,
	Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

> On May 15, 2019, at 8:03 PM, Xing, Cedric <cedric.xing@intel.com> wrote:
>
> Hi Andy,
>
>> From: Andy Lutomirski [mailto:luto@kernel.org]
>>
>>> On Wed, May 15, 2019 at 3:46 PM James Morris <jmorris@namei.org> wrote:
>>>
>>> On Wed, 15 May 2019, Andy Lutomirski wrote:
>>>
>>>>> 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.
>>>
>>
>> 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);
>
> 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.

>
>>
>> /* 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.
>
> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-15 13:21                                                         ` Sean Christopherson
@ 2019-05-16  5:01                                                           ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-16  5:01 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 06:21:47AM -0700, Sean Christopherson wrote:
> On Wed, May 15, 2019 at 01:35:31PM +0300, Jarkko Sakkinen wrote:
> > On Tue, May 14, 2019 at 01:45:27PM -0700, Sean Christopherson wrote:
> > > On Tue, May 14, 2019 at 08:13:36AM -0700, Andy Lutomirski wrote:
> > > > 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.
> > 
> > Small correction: it is EMODPR.
> 
> No, I'm referring to EMODPE, note the ENCLU classification.
> 
> > Anyway, it is good to mention that these would require EACCEPT from the
> > enclave side. In order to take advantage of this is in a malicous
> > enclave, one would require SELinux/IMA/whatnot policy to have permitted
> > it in the first place.
> 
> EMODPE doesn't require EACCEPT or any equivalent from the kernel.  As
> you alluded to, the page tables would still need to allow PROT_EXEC.  I
> was simply trying to answer Andy's question regarding SECINFO.

Ah, have to admit that I had totally forgot EMODPE :-) Have not had
to deal with that opcode that much.

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-15 14:27                                                           ` Andy Lutomirski
@ 2019-05-16  5:07                                                             ` Jarkko Sakkinen
  2019-05-16  6:51                                                               ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-16  5:07 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Andy Lutomirski, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Wed, May 15, 2019 at 07:27:02AM -0700, Andy Lutomirski wrote:
> 
> > On May 15, 2019, at 4:00 AM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
> > 
> >> On Wed, May 15, 2019 at 01:35:31PM +0300, Jarkko Sakkinen wrote:
> >> This brings me to an open question in Andy's model: lets say that we
> >> change the source for SIGSTRUCT from memory address to fd. How can the
> >> policy prevent the use not creating a file containing a SIGSTRUCT and
> >> passing fd of that to the EINIT ioctl?
> > 
> 
> The policy will presumably check the label on the file that the fd points to.

Right (checked SELinux documentation).

Got one idea from this. Right now creation and initialization does not
require any VMAs to be created (since v20). Requiring to map a VMA for
copying the data would bring in my opinion a glitch to this model that
we have done effort to build up.

What if we similarly change EADD ioctl in a way that it'd take an fd
and an offset? This way we can enforce policy to the source where the
enclave data is loaded from. On the other hand, loading SIGSTRUCT from
fd enforces a legit structure for the enclave.

This would still allow to construct enclaves in VMA independent way.

> > Also wondering if a path would be better than plain fd for defining a
> > reasonable policy i.e. have sigstruct_path as part of the ioctl
> > parameters and not sigstruct_fd.
> > 
> 
> It would save two syscalls at the cost of a decent amount of complexity.

And also using fd gives robustness because it allows SIGSTRUCT
pulled from a file containing it (among other things).

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 18:27                                                           ` SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support) Andy Lutomirski
  2019-05-15 19:58                                                             ` James Morris
  2019-05-15 21:38                                                             ` Sean Christopherson
@ 2019-05-16  5:16                                                             ` Jarkko Sakkinen
  2019-05-16 21:02                                                               ` Andy Lutomirski
  2019-05-17  0:03                                                             ` Sean Christopherson
  3 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-16  5:16 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 11:27:04AM -0700, Andy Lutomirski wrote:
> 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.

Similarly if we could take data for the enclave from fd and enforce
it with sgx_enclave_t label.

> 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

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-16  5:07                                                             ` Jarkko Sakkinen
@ 2019-05-16  6:51                                                               ` Jarkko Sakkinen
  2019-05-16  7:02                                                                 ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-16  6:51 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Andy Lutomirski, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Thu, May 16, 2019 at 08:07:05AM +0300, Jarkko Sakkinen wrote:
> On Wed, May 15, 2019 at 07:27:02AM -0700, Andy Lutomirski wrote:
> > 
> > > On May 15, 2019, at 4:00 AM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
> > > 
> > >> On Wed, May 15, 2019 at 01:35:31PM +0300, Jarkko Sakkinen wrote:
> > >> This brings me to an open question in Andy's model: lets say that we
> > >> change the source for SIGSTRUCT from memory address to fd. How can the
> > >> policy prevent the use not creating a file containing a SIGSTRUCT and
> > >> passing fd of that to the EINIT ioctl?
> > > 
> > 
> > The policy will presumably check the label on the file that the fd points to.
> 
> Right (checked SELinux documentation).
> 
> Got one idea from this. Right now creation and initialization does not
> require any VMAs to be created (since v20). Requiring to map a VMA for
> copying the data would bring in my opinion a glitch to this model that
> we have done effort to build up.
> 
> What if we similarly change EADD ioctl in a way that it'd take an fd
> and an offset? This way we can enforce policy to the source where the
> enclave data is loaded from. On the other hand, loading SIGSTRUCT from
> fd enforces a legit structure for the enclave.
> 
> This would still allow to construct enclaves in VMA independent way.

The API would turn into this:

/**
 * struct sgx_enclave_add_page - parameter structure for the
 *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
 * @fd:		file containing the page data
 * @offset:	offset in the file containing the page data
 * @secinfo:	address for the SECINFO data
 * @mrmask:	bitmask for the measured 256 byte chunks
 */
struct sgx_enclave_add_page {
	__u64	fd;
	__u64	offset;
	__u64	secinfo;
	__u16	mrmask;
} __attribute__((__packed__));


/**
 * struct sgx_enclave_init - parameter structure for the
 *                           %SGX_IOC_ENCLAVE_INIT ioctl
 * @fd:		file containing the sigstruct
 * @offset:	offset in the file containing the sigstruct
 */
struct sgx_enclave_init {
	__u64	fd;
	__u64	offset;
};

/Jarkko

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

* Re: [PATCH v20 00/28] Intel SGX1 support
  2019-05-16  6:51                                                               ` Jarkko Sakkinen
@ 2019-05-16  7:02                                                                 ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-16  7:02 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Andy Lutomirski, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Thu, May 16, 2019 at 09:51:03AM +0300, Jarkko Sakkinen wrote:
> On Thu, May 16, 2019 at 08:07:05AM +0300, Jarkko Sakkinen wrote:
> > On Wed, May 15, 2019 at 07:27:02AM -0700, Andy Lutomirski wrote:
> > > 
> > > > On May 15, 2019, at 4:00 AM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
> > > > 
> > > >> On Wed, May 15, 2019 at 01:35:31PM +0300, Jarkko Sakkinen wrote:
> > > >> This brings me to an open question in Andy's model: lets say that we
> > > >> change the source for SIGSTRUCT from memory address to fd. How can the
> > > >> policy prevent the use not creating a file containing a SIGSTRUCT and
> > > >> passing fd of that to the EINIT ioctl?
> > > > 
> > > 
> > > The policy will presumably check the label on the file that the fd points to.
> > 
> > Right (checked SELinux documentation).
> > 
> > Got one idea from this. Right now creation and initialization does not
> > require any VMAs to be created (since v20). Requiring to map a VMA for
> > copying the data would bring in my opinion a glitch to this model that
> > we have done effort to build up.
> > 
> > What if we similarly change EADD ioctl in a way that it'd take an fd
> > and an offset? This way we can enforce policy to the source where the
> > enclave data is loaded from. On the other hand, loading SIGSTRUCT from
> > fd enforces a legit structure for the enclave.
> > 
> > This would still allow to construct enclaves in VMA independent way.
> 
> The API would turn into this:
> 
> /**
>  * struct sgx_enclave_add_page - parameter structure for the
>  *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
>  * @fd:		file containing the page data
>  * @offset:	offset in the file containing the page data
>  * @secinfo:	address for the SECINFO data
>  * @mrmask:	bitmask for the measured 256 byte chunks
>  */
> struct sgx_enclave_add_page {
> 	__u64	fd;
> 	__u64	offset;
> 	__u64	secinfo;
> 	__u16	mrmask;
> } __attribute__((__packed__));
> 
> 
> /**
>  * struct sgx_enclave_init - parameter structure for the
>  *                           %SGX_IOC_ENCLAVE_INIT ioctl
>  * @fd:		file containing the sigstruct
>  * @offset:	offset in the file containing the sigstruct
>  */
> struct sgx_enclave_init {
> 	__u64	fd;
> 	__u64	offset;
> };

The change to EADD/EINIT ioctl's would be simply fget/kernel_read/fput
sequence replacing copy_from_user().

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 23:13                                                                   ` Andy Lutomirski
  2019-05-16  3:03                                                                     ` Xing, Cedric
@ 2019-05-16  7:24                                                                     ` James Morris
  2019-05-16 21:00                                                                       ` Andy Lutomirski
  2019-05-20  9:38                                                                       ` Dr. Greg
  1 sibling, 2 replies; 318+ messages in thread
From: James Morris @ 2019-05-16  7:24 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, 15 May 2019, Andy Lutomirski wrote:

> On Wed, May 15, 2019 at 3:46 PM James Morris <jmorris@namei.org> wrote:
> >
> > 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.


-- 
James Morris
<jmorris@namei.org>


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16  7:24                                                                     ` James Morris
@ 2019-05-16 21:00                                                                       ` Andy Lutomirski
  2019-05-20  9:38                                                                       ` Dr. Greg
  1 sibling, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-16 21:00 UTC (permalink / raw)
  To: James Morris
  Cc: Andy Lutomirski, Sean Christopherson, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

> On May 16, 2019, at 12:24 AM, James Morris <jmorris@namei.org> wrote:
>
>> On Wed, 15 May 2019, Andy Lutomirski wrote:
>>
>>> On Wed, May 15, 2019 at 3:46 PM James Morris <jmorris@namei.org> wrote:
>>>
>>> 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.
>
>

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16  5:16                                                             ` Jarkko Sakkinen
@ 2019-05-16 21:02                                                               ` Andy Lutomirski
  2019-05-16 22:45                                                                 ` Sean Christopherson
  2019-05-20 11:33                                                                 ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-16 21:02 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Sean Christopherson, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Stephen Smalley,
	Eric Paris, selinux, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

> On May 15, 2019, at 10:16 PM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
>
>> On Wed, May 15, 2019 at 11:27:04AM -0700, Andy Lutomirski wrote:
>> 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.
>
> 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?

>
>> 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
>

ISTM you should need EXECMEM or similar to run Graphene, then.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16  4:40                                                                       ` Andy Lutomirski
@ 2019-05-16 22:23                                                                         ` Xing, Cedric
  2019-05-17  0:35                                                                           ` Andy Lutomirski
  2019-05-17 13:53                                                                           ` Stephen Smalley
  0 siblings, 2 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-16 22:23 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: James Morris, Christopherson, Sean J, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

Hi Andy,

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

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.

> >
> >>
> >> /* 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.
> >
> > 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.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16 21:02                                                               ` Andy Lutomirski
@ 2019-05-16 22:45                                                                 ` Sean Christopherson
  2019-05-16 23:29                                                                   ` Xing, Cedric
  2019-05-20 11:29                                                                   ` Jarkko Sakkinen
  2019-05-20 11:33                                                                 ` Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-16 22:45 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 02:02:58PM -0700, Andy Lutomirski wrote:
> > On May 15, 2019, at 10:16 PM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
> > 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.

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.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16 22:45                                                                 ` Sean Christopherson
@ 2019-05-16 23:29                                                                   ` Xing, Cedric
  2019-05-20 11:29                                                                   ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-16 23:29 UTC (permalink / raw)
  To: Christopherson, Sean J, Andy Lutomirski
  Cc: Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-15 18:27                                                           ` SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support) Andy Lutomirski
                                                                               ` (2 preceding siblings ...)
  2019-05-16  5:16                                                             ` Jarkko Sakkinen
@ 2019-05-17  0:03                                                             ` Sean Christopherson
  2019-05-17  0:26                                                               ` Andy Lutomirski
  2019-05-20 11:36                                                               ` Jarkko Sakkinen
  3 siblings, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17  0:03 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: James Morris, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 15, 2019 at 11:27:04AM -0700, Andy Lutomirski wrote:
> 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.

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17  0:03                                                             ` Sean Christopherson
@ 2019-05-17  0:26                                                               ` Andy Lutomirski
  2019-05-17 15:41                                                                 ` Sean Christopherson
  2019-05-20 11:41                                                                 ` Jarkko Sakkinen
  2019-05-20 11:36                                                               ` Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17  0:26 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 5:03 PM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Wed, May 15, 2019 at 11:27:04AM -0700, Andy Lutomirski wrote:
> > 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.
>
> 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:

> 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?

>
>   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?

>
>   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?

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16 22:23                                                                         ` Xing, Cedric
@ 2019-05-17  0:35                                                                           ` Andy Lutomirski
  2019-05-17  1:06                                                                             ` Xing, Cedric
  2019-05-17 16:05                                                                             ` Sean Christopherson
  2019-05-17 13:53                                                                           ` Stephen Smalley
  1 sibling, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17  0:35 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, James Morris, Christopherson, Sean J,
	Serge E. Hallyn, LSM List, Paul Moore, Stephen Smalley,
	Eric Paris, selinux, Jarkko Sakkinen, Jethro Beekman, Hansen,
	Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 3:23 PM Xing, Cedric <cedric.xing@intel.com> wrote:
>
> Hi Andy,
>
> > > 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.
>
> 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.

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

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

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17  0:35                                                                           ` Andy Lutomirski
@ 2019-05-17  1:06                                                                             ` Xing, Cedric
  2019-05-17  1:21                                                                               ` Andy Lutomirski
  2019-05-17 16:05                                                                             ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-17  1:06 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: James Morris, Christopherson, Sean J, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

> From: Andy Lutomirski [mailto:luto@kernel.org]
> 
> On Thu, May 16, 2019 at 3:23 PM Xing, Cedric <cedric.xing@intel.com>
> wrote:
> >
> > Hi Andy,
> >
> > > > 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.
> >
> > 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.
> 
> > 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.

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!

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

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

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17  1:06                                                                             ` Xing, Cedric
@ 2019-05-17  1:21                                                                               ` Andy Lutomirski
  0 siblings, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17  1:21 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, James Morris, Christopherson, Sean J,
	Serge E. Hallyn, LSM List, Paul Moore, Stephen Smalley,
	Eric Paris, selinux, Jarkko Sakkinen, Jethro Beekman, Hansen,
	Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 6:06 PM Xing, Cedric <cedric.xing@intel.com> wrote:
>
> > From: Andy Lutomirski [mailto:luto@kernel.org]
> >
> > On Thu, May 16, 2019 at 3:23 PM Xing, Cedric <cedric.xing@intel.com>
> > wrote:
> > >
> > > Hi Andy,
> > >
> > > > > 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.
> > >
> > > 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.
> >
> > > 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.
>
> 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!
>
> >
> > 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.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16 22:23                                                                         ` Xing, Cedric
  2019-05-17  0:35                                                                           ` Andy Lutomirski
@ 2019-05-17 13:53                                                                           ` Stephen Smalley
  2019-05-17 15:09                                                                             ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 13:53 UTC (permalink / raw)
  To: Xing, Cedric, Andy Lutomirski
  Cc: James Morris, Christopherson, Sean J, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jarkko Sakkinen, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 5/16/19 6:23 PM, Xing, Cedric wrote:
> Hi Andy,
> 
>>> 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.
> 
> 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.
> 
>>>
>>>>
>>>> /* 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.
>>>
>>>  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.
> 
> 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.

> 
> 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
> 


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 13:53                                                                           ` Stephen Smalley
@ 2019-05-17 15:09                                                                             ` Sean Christopherson
  2019-05-17 16:20                                                                               ` Stephen Smalley
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 15:09 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Xing, Cedric, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 09:53:06AM -0400, Stephen Smalley wrote:
> On 5/16/19 6:23 PM, Xing, Cedric wrote:
> >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.

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).

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17  0:26                                                               ` Andy Lutomirski
@ 2019-05-17 15:41                                                                 ` Sean Christopherson
  2019-05-20 11:42                                                                   ` Jarkko Sakkinen
  2019-05-20 11:41                                                                 ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 15:41 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: James Morris, Serge E. Hallyn, LSM List, Paul Moore,
	Stephen Smalley, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 05:26:15PM -0700, Andy Lutomirski wrote:
> On Thu, May 16, 2019 at 5:03 PM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Wed, May 15, 2019 at 11:27:04AM -0700, Andy Lutomirski wrote:
> > > 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.
> >
> > 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:
> 
> > 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?

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.

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

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

> >
> >   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).

> 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().

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17  0:35                                                                           ` Andy Lutomirski
  2019-05-17  1:06                                                                             ` Xing, Cedric
@ 2019-05-17 16:05                                                                             ` Sean Christopherson
  1 sibling, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 16:05 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Xing, Cedric, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 05:35:16PM -0700, Andy Lutomirski wrote:
> On Thu, May 16, 2019 at 3:23 PM Xing, Cedric <cedric.xing@intel.com> wrote:
> > 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.

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 15:09                                                                             ` Sean Christopherson
@ 2019-05-17 16:20                                                                               ` Stephen Smalley
  2019-05-17 16:24                                                                                 ` Andy Lutomirski
  2019-05-17 16:37                                                                                 ` Stephen Smalley
  0 siblings, 2 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 16:20 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On 5/17/19 11:09 AM, Sean Christopherson wrote:
> On Fri, May 17, 2019 at 09:53:06AM -0400, Stephen Smalley wrote:
>> On 5/16/19 6:23 PM, Xing, Cedric wrote:
>>> 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.
> 
> 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).

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).

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 16:20                                                                               ` Stephen Smalley
@ 2019-05-17 16:24                                                                                 ` Andy Lutomirski
  2019-05-17 16:37                                                                                 ` Stephen Smalley
  1 sibling, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17 16:24 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Sean Christopherson, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes



> On May 17, 2019, at 9:20 AM, Stephen Smalley <sds@tycho.nsa.gov> wrote:
> 
>> On 5/17/19 11:09 AM, Sean Christopherson wrote:
>>> On Fri, May 17, 2019 at 09:53:06AM -0400, Stephen Smalley wrote:
>>>> On 5/16/19 6:23 PM, Xing, Cedric wrote:
>>>> 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.
>> 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).
> 
> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 16:20                                                                               ` Stephen Smalley
  2019-05-17 16:24                                                                                 ` Andy Lutomirski
@ 2019-05-17 16:37                                                                                 ` Stephen Smalley
  2019-05-17 17:12                                                                                   ` Andy Lutomirski
  2019-05-17 17:29                                                                                   ` Sean Christopherson
  1 sibling, 2 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 16:37 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On 5/17/19 12:20 PM, Stephen Smalley wrote:
> On 5/17/19 11:09 AM, Sean Christopherson wrote:
>> On Fri, May 17, 2019 at 09:53:06AM -0400, Stephen Smalley wrote:
>>> On 5/16/19 6:23 PM, Xing, Cedric wrote:
>>>> 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.
>>
>> 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).
> 
> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 16:37                                                                                 ` Stephen Smalley
@ 2019-05-17 17:12                                                                                   ` Andy Lutomirski
  2019-05-17 18:05                                                                                     ` Stephen Smalley
  2019-05-17 17:29                                                                                   ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17 17:12 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Sean Christopherson, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes



> On May 17, 2019, at 9:37 AM, Stephen Smalley <sds@tycho.nsa.gov> wrote:
> 
>> On 5/17/19 12:20 PM, Stephen Smalley wrote:
>>> On 5/17/19 11:09 AM, Sean Christopherson wrote:
>>>> On Fri, May 17, 2019 at 09:53:06AM -0400, Stephen Smalley wrote:
>>>>> On 5/16/19 6:23 PM, Xing, Cedric wrote:
>>>>> 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.
>>> 
>>> 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).
>> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 16:37                                                                                 ` Stephen Smalley
  2019-05-17 17:12                                                                                   ` Andy Lutomirski
@ 2019-05-17 17:29                                                                                   ` Sean Christopherson
  2019-05-17 17:42                                                                                     ` Stephen Smalley
  2019-05-17 17:43                                                                                     ` Andy Lutomirski
  1 sibling, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 17:29 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Xing, Cedric, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 12:37:40PM -0400, Stephen Smalley wrote:
> On 5/17/19 12:20 PM, Stephen Smalley wrote:
> >On 5/17/19 11:09 AM, Sean Christopherson wrote:
> >>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).

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.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 17:29                                                                                   ` Sean Christopherson
@ 2019-05-17 17:42                                                                                     ` Stephen Smalley
  2019-05-17 17:50                                                                                       ` Sean Christopherson
  2019-05-17 17:43                                                                                     ` Andy Lutomirski
  1 sibling, 1 reply; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 17:42 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On 5/17/19 1:29 PM, Sean Christopherson wrote:
> On Fri, May 17, 2019 at 12:37:40PM -0400, Stephen Smalley wrote:
>> On 5/17/19 12:20 PM, Stephen Smalley wrote:
>>> On 5/17/19 11:09 AM, Sean Christopherson wrote:
>>>> 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).
> 
> 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.
> 
>> 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.
> 

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.


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 17:29                                                                                   ` Sean Christopherson
  2019-05-17 17:42                                                                                     ` Stephen Smalley
@ 2019-05-17 17:43                                                                                     ` Andy Lutomirski
  2019-05-17 17:55                                                                                       ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17 17:43 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Stephen Smalley, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes



> On May 17, 2019, at 10:29 AM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> 
>> On Fri, May 17, 2019 at 12:37:40PM -0400, Stephen Smalley wrote:
>>> On 5/17/19 12:20 PM, Stephen Smalley wrote:
>>>> On 5/17/19 11:09 AM, Sean Christopherson wrote:
>>>> 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).
> 
> 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.
> 
>> 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.

How does anon_inode make any difference?  Anon_inode is not the same thing as anon_vma.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 17:42                                                                                     ` Stephen Smalley
@ 2019-05-17 17:50                                                                                       ` Sean Christopherson
  2019-05-17 18:16                                                                                         ` Stephen Smalley
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 17:50 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Xing, Cedric, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 01:42:50PM -0400, Stephen Smalley wrote:
> On 5/17/19 1:29 PM, Sean Christopherson wrote:
> >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?

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 17:43                                                                                     ` Andy Lutomirski
@ 2019-05-17 17:55                                                                                       ` Sean Christopherson
  2019-05-17 18:04                                                                                         ` Linus Torvalds
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 17:55 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 10:43:01AM -0700, Andy Lutomirski wrote:
> 
> > On May 17, 2019, at 10:29 AM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> > 
> > 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;
        }

	...
}

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 17:55                                                                                       ` Sean Christopherson
@ 2019-05-17 18:04                                                                                         ` Linus Torvalds
  2019-05-17 18:21                                                                                           ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Linus Torvalds @ 2019-05-17 18:04 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, Andy Lutomirski,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jarkko Sakkinen, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, LKML, X86 ML, linux-sgx,
	Andrew Morton, nhorman, npmccallum, Ayoun, Serge, Katz-zamir,
	Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 10:55 AM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 17:12                                                                                   ` Andy Lutomirski
@ 2019-05-17 18:05                                                                                     ` Stephen Smalley
  2019-05-17 19:20                                                                                       ` Stephen Smalley
  2019-05-17 19:28                                                                                       ` Sean Christopherson
  0 siblings, 2 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 18:05 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On 5/17/19 1:12 PM, Andy Lutomirski wrote:
> 
> 
>> On May 17, 2019, at 9:37 AM, Stephen Smalley <sds@tycho.nsa.gov> wrote:
>>
>>> On 5/17/19 12:20 PM, Stephen Smalley wrote:
>>>> On 5/17/19 11:09 AM, Sean Christopherson wrote:
>>>>> On Fri, May 17, 2019 at 09:53:06AM -0400, Stephen Smalley wrote:
>>>>>> On 5/16/19 6:23 PM, Xing, Cedric wrote:
>>>>>> 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.
>>>>
>>>> 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).
>>> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 17:50                                                                                       ` Sean Christopherson
@ 2019-05-17 18:16                                                                                         ` Stephen Smalley
  0 siblings, 0 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 18:16 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jarkko Sakkinen,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On 5/17/19 1:50 PM, Sean Christopherson wrote:
> On Fri, May 17, 2019 at 01:42:50PM -0400, Stephen Smalley wrote:
>> On 5/17/19 1:29 PM, Sean Christopherson wrote:
>>> 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?

That's correct.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 18:04                                                                                         ` Linus Torvalds
@ 2019-05-17 18:21                                                                                           ` Sean Christopherson
  2019-05-17 18:33                                                                                             ` Linus Torvalds
  2019-05-17 18:53                                                                                             ` Andy Lutomirski
  0 siblings, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 18:21 UTC (permalink / raw)
  To: Linus Torvalds
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, Andy Lutomirski,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jarkko Sakkinen, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, LKML, X86 ML, linux-sgx,
	Andrew Morton, nhorman, npmccallum, Ayoun, Serge, Katz-zamir,
	Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 11:04:22AM -0700, Linus Torvalds wrote:
> On Fri, May 17, 2019 at 10:55 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > 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?

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));

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 18:21                                                                                           ` Sean Christopherson
@ 2019-05-17 18:33                                                                                             ` Linus Torvalds
  2019-05-17 18:52                                                                                               ` Sean Christopherson
  2019-05-17 18:53                                                                                             ` Andy Lutomirski
  1 sibling, 1 reply; 318+ messages in thread
From: Linus Torvalds @ 2019-05-17 18:33 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, Andy Lutomirski,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jarkko Sakkinen, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, LKML, X86 ML, linux-sgx,
	Andrew Morton, nhorman, npmccallum, Ayoun, Serge, Katz-zamir,
	Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 11:21 AM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 18:33                                                                                             ` Linus Torvalds
@ 2019-05-17 18:52                                                                                               ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 18:52 UTC (permalink / raw)
  To: Linus Torvalds
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, Andy Lutomirski,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jarkko Sakkinen, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, LKML, X86 ML, linux-sgx,
	Andrew Morton, nhorman, npmccallum, Ayoun, Serge, Katz-zamir,
	Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 11:33:30AM -0700, Linus Torvalds wrote:
> On Fri, May 17, 2019 at 11:21 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > 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.

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].

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

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.

> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 18:21                                                                                           ` Sean Christopherson
  2019-05-17 18:33                                                                                             ` Linus Torvalds
@ 2019-05-17 18:53                                                                                             ` Andy Lutomirski
  1 sibling, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17 18:53 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Linus Torvalds, Stephen Smalley, Xing, Cedric, Andy Lutomirski,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jarkko Sakkinen, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, LKML, X86 ML, linux-sgx,
	Andrew Morton, nhorman, npmccallum, Ayoun, Serge, Katz-zamir,
	Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes



> On May 17, 2019, at 11:21 AM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> 
>> On Fri, May 17, 2019 at 11:04:22AM -0700, Linus Torvalds wrote:
>> On Fri, May 17, 2019 at 10:55 AM Sean Christopherson
>> <sean.j.christopherson@intel.com> wrote:
>>> 
>>> 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?
> 
> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 18:05                                                                                     ` Stephen Smalley
@ 2019-05-17 19:20                                                                                       ` Stephen Smalley
  2019-05-17 19:28                                                                                       ` Sean Christopherson
  1 sibling, 0 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 19:20 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On 5/17/19 2:05 PM, Stephen Smalley wrote:
> On 5/17/19 1:12 PM, Andy Lutomirski wrote:
>>
>>
>>> On May 17, 2019, at 9:37 AM, Stephen Smalley <sds@tycho.nsa.gov> wrote:
>>>
>>>> On 5/17/19 12:20 PM, Stephen Smalley wrote:
>>>>> On 5/17/19 11:09 AM, Sean Christopherson wrote:
>>>>>> On Fri, May 17, 2019 at 09:53:06AM -0400, Stephen Smalley wrote:
>>>>>>> On 5/16/19 6:23 PM, Xing, Cedric wrote:
>>>>>>> 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.
>>>>>
>>>>> 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).
>>>> 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.

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 18:05                                                                                     ` Stephen Smalley
  2019-05-17 19:20                                                                                       ` Stephen Smalley
@ 2019-05-17 19:28                                                                                       ` Sean Christopherson
  2019-05-17 20:09                                                                                         ` Stephen Smalley
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 19:28 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Andy Lutomirski, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 02:05:39PM -0400, Stephen Smalley wrote:
> On 5/17/19 1:12 PM, Andy Lutomirski wrote:
> >
> >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);

That's rougly the flow, except that that all enclaves need to have RW and
X EPC pages.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 19:28                                                                                       ` Sean Christopherson
@ 2019-05-17 20:09                                                                                         ` Stephen Smalley
  2019-05-17 20:14                                                                                           ` Andy Lutomirski
  2019-05-17 21:36                                                                                           ` Sean Christopherson
  0 siblings, 2 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 20:09 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On 5/17/19 3:28 PM, Sean Christopherson wrote:
> On Fri, May 17, 2019 at 02:05:39PM -0400, Stephen Smalley wrote:
>> On 5/17/19 1:12 PM, Andy Lutomirski wrote:
>>>
>>> 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);
> 
> That's rougly the flow, except that that all enclaves need to have RW and
> X EPC pages.
> 
>> 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.

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).

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 20:09                                                                                         ` Stephen Smalley
@ 2019-05-17 20:14                                                                                           ` Andy Lutomirski
  2019-05-17 20:34                                                                                             ` Stephen Smalley
  2019-05-17 21:36                                                                                           ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-17 20:14 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Sean Christopherson, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes


> On May 17, 2019, at 1:09 PM, Stephen Smalley <sds@tycho.nsa.gov> wrote:
> 
>> On 5/17/19 3:28 PM, Sean Christopherson wrote:
>>> On Fri, May 17, 2019 at 02:05:39PM -0400, Stephen Smalley wrote:
>>>> On 5/17/19 1:12 PM, Andy Lutomirski wrote:
>>>> 
>>>> 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);
>> That's rougly the flow, except that that all enclaves need to have RW and
>> X EPC pages.
>>> 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.
> 
> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 20:14                                                                                           ` Andy Lutomirski
@ 2019-05-17 20:34                                                                                             ` Stephen Smalley
  0 siblings, 0 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-17 20:34 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On 5/17/19 4:14 PM, Andy Lutomirski wrote:
> 
>> On May 17, 2019, at 1:09 PM, Stephen Smalley <sds@tycho.nsa.gov> wrote:
>>
>>> On 5/17/19 3:28 PM, Sean Christopherson wrote:
>>>> On Fri, May 17, 2019 at 02:05:39PM -0400, Stephen Smalley wrote:
>>>>> On 5/17/19 1:12 PM, Andy Lutomirski wrote:
>>>>>
>>>>> 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);
>>> That's rougly the flow, except that that all enclaves need to have RW and
>>> X EPC pages.
>>>> 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.
>>
>> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 20:09                                                                                         ` Stephen Smalley
  2019-05-17 20:14                                                                                           ` Andy Lutomirski
@ 2019-05-17 21:36                                                                                           ` Sean Christopherson
  1 sibling, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-17 21:36 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Andy Lutomirski, Xing, Cedric, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 04:09:22PM -0400, Stephen Smalley wrote:
> On 5/17/19 3:28 PM, Sean Christopherson wrote:
> >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, ...);
> >
> >
> >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.

> 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!

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16  7:24                                                                     ` James Morris
  2019-05-16 21:00                                                                       ` Andy Lutomirski
@ 2019-05-20  9:38                                                                       ` Dr. Greg
  1 sibling, 0 replies; 318+ messages in thread
From: Dr. Greg @ 2019-05-20  9:38 UTC (permalink / raw)
  To: James Morris
  Cc: Andy Lutomirski, Sean Christopherson, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux,
	Jarkko Sakkinen, Jethro Beekman, Xing, Cedric, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

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.

> On Wed, 15 May 2019, Andy Lutomirski wrote:
> 
> > On Wed, May 15, 2019 at 3:46 PM James Morris <jmorris@namei.org> wrote:
> > >
> > > 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.

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.

> 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: greg@enjellic.com
------------------------------------------------------------------------------
"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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16 22:45                                                                 ` Sean Christopherson
  2019-05-16 23:29                                                                   ` Xing, Cedric
@ 2019-05-20 11:29                                                                   ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-20 11:29 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 03:45:50PM -0700, Sean Christopherson wrote:
> On Thu, May 16, 2019 at 02:02:58PM -0700, Andy Lutomirski wrote:
> > > On May 15, 2019, at 10:16 PM, Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com> wrote:
> > > 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.
> 
> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-16 21:02                                                               ` Andy Lutomirski
  2019-05-16 22:45                                                                 ` Sean Christopherson
@ 2019-05-20 11:33                                                                 ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-20 11:33 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 02:02:58PM -0700, Andy Lutomirski wrote:
> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17  0:03                                                             ` Sean Christopherson
  2019-05-17  0:26                                                               ` Andy Lutomirski
@ 2019-05-20 11:36                                                               ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-20 11:36 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 05:03:31PM -0700, Sean Christopherson wrote:
> 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.

This should be easy enough to add as the EADD operations are already
batched internally to a worker thread.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17  0:26                                                               ` Andy Lutomirski
  2019-05-17 15:41                                                                 ` Sean Christopherson
@ 2019-05-20 11:41                                                                 ` Jarkko Sakkinen
  2019-05-21 15:19                                                                   ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-20 11:41 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 16, 2019 at 05:26:15PM -0700, Andy Lutomirski wrote:
> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-17 15:41                                                                 ` Sean Christopherson
@ 2019-05-20 11:42                                                                   ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-20 11:42 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 17, 2019 at 08:41:28AM -0700, Sean Christopherson wrote:
> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-20 11:41                                                                 ` Jarkko Sakkinen
@ 2019-05-21 15:19                                                                   ` Jarkko Sakkinen
  2019-05-21 15:24                                                                     ` Jethro Beekman
  2019-05-21 15:51                                                                     ` Sean Christopherson
  0 siblings, 2 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-21 15:19 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Mon, May 20, 2019 at 02:41:05PM +0300, Jarkko Sakkinen wrote:
> On Thu, May 16, 2019 at 05:26:15PM -0700, Andy Lutomirski wrote:
> > 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.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-21 15:19                                                                   ` Jarkko Sakkinen
@ 2019-05-21 15:24                                                                     ` Jethro Beekman
  2019-05-22 13:10                                                                       ` Jarkko Sakkinen
  2019-05-21 15:51                                                                     ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Jethro Beekman @ 2019-05-21 15:24 UTC (permalink / raw)
  To: Jarkko Sakkinen, Andy Lutomirski
  Cc: Sean Christopherson, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Xing, Cedric,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

[-- Attachment #1: Type: text/plain, Size: 275 bytes --]

On 2019-05-21 08:19, Jarkko Sakkinen wrote:
> 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


[-- Attachment #2: S/MIME Cryptographic Signature --]
[-- Type: application/pkcs7-signature, Size: 3990 bytes --]

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-21 15:19                                                                   ` Jarkko Sakkinen
  2019-05-21 15:24                                                                     ` Jethro Beekman
@ 2019-05-21 15:51                                                                     ` Sean Christopherson
  2019-05-22 13:20                                                                       ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-21 15:51 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Tue, May 21, 2019 at 06:19:37PM +0300, Jarkko Sakkinen wrote:
> On Mon, May 20, 2019 at 02:41:05PM +0300, Jarkko Sakkinen wrote:
> > On Thu, May 16, 2019 at 05:26:15PM -0700, Andy Lutomirski wrote:
> > > 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.
> 
> 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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-21 15:24                                                                     ` Jethro Beekman
@ 2019-05-22 13:10                                                                       ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-22 13:10 UTC (permalink / raw)
  To: Jethro Beekman
  Cc: Andy Lutomirski, Sean Christopherson, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Stephen Smalley,
	Eric Paris, selinux, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Tue, May 21, 2019 at 03:24:18PM +0000, Jethro Beekman wrote:
> On 2019-05-21 08:19, Jarkko Sakkinen wrote:
> > 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-21 15:51                                                                     ` Sean Christopherson
@ 2019-05-22 13:20                                                                       ` Jarkko Sakkinen
  2019-05-22 13:22                                                                         ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-22 13:20 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Tue, May 21, 2019 at 08:51:40AM -0700, Sean Christopherson wrote:
> 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.

> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-22 13:20                                                                       ` Jarkko Sakkinen
@ 2019-05-22 13:22                                                                         ` Jarkko Sakkinen
  2019-05-22 13:56                                                                           ` Stephen Smalley
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-22 13:22 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Stephen Smalley, Eric Paris, selinux, Jethro Beekman,
	Xing, Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Wed, May 22, 2019 at 04:20:22PM +0300, Jarkko Sakkinen wrote:
> On Tue, May 21, 2019 at 08:51:40AM -0700, Sean Christopherson wrote:
> > 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.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-22 13:22                                                                         ` Jarkko Sakkinen
@ 2019-05-22 13:56                                                                           ` Stephen Smalley
  2019-05-22 15:38                                                                             ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Stephen Smalley @ 2019-05-22 13:56 UTC (permalink / raw)
  To: Jarkko Sakkinen, Sean Christopherson
  Cc: Andy Lutomirski, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing, Cedric,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 5/22/19 9:22 AM, Jarkko Sakkinen wrote:
> On Wed, May 22, 2019 at 04:20:22PM +0300, Jarkko Sakkinen wrote:
>> On Tue, May 21, 2019 at 08:51:40AM -0700, Sean Christopherson wrote:
>>> 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.
> 
> 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?

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-22 13:56                                                                           ` Stephen Smalley
@ 2019-05-22 15:38                                                                             ` Sean Christopherson
  2019-05-22 22:42                                                                               ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-22 15:38 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Jarkko Sakkinen, Andy Lutomirski, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Wed, May 22, 2019 at 09:56:30AM -0400, Stephen Smalley wrote:
> On 5/22/19 9:22 AM, Jarkko Sakkinen wrote:
> >On Wed, May 22, 2019 at 04:20:22PM +0300, Jarkko Sakkinen wrote:
> >>On Tue, May 21, 2019 at 08:51:40AM -0700, Sean Christopherson wrote:
> >>>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.
> >
> >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?

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-22 15:38                                                                             ` Sean Christopherson
@ 2019-05-22 22:42                                                                               ` Andy Lutomirski
  2019-05-23  2:35                                                                                 ` Sean Christopherson
  2019-05-23  8:10                                                                                 ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-22 22:42 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Stephen Smalley, Jarkko Sakkinen, Andy Lutomirski, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 22, 2019 at 8:38 AM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Wed, May 22, 2019 at 09:56:30AM -0400, Stephen Smalley wrote:
> > On 5/22/19 9:22 AM, Jarkko Sakkinen wrote:
> > >On Wed, May 22, 2019 at 04:20:22PM +0300, Jarkko Sakkinen wrote:
> > >>On Tue, May 21, 2019 at 08:51:40AM -0700, Sean Christopherson wrote:
> > >>>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.
> > >
> > >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?
>
> 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.

That presumably needs to change.

Are we entirely missing an API to allocate a naturally aligned VA
range?  That's kind of annoying.

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

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-22 22:42                                                                               ` Andy Lutomirski
@ 2019-05-23  2:35                                                                                 ` Sean Christopherson
  2019-05-23 10:26                                                                                   ` Jarkko Sakkinen
  2019-05-23  8:10                                                                                 ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-23  2:35 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Wed, May 22, 2019 at 03:42:45PM -0700, Andy Lutomirski wrote:
> On Wed, May 22, 2019 at 8:38 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > 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.

> Are we entirely missing an API to allocate a naturally aligned VA
> range?  That's kind of annoying.

Yes?

> > 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.
> 
> This isn't necessarily a problem, but we pretty much have to use
> mprotect() then.

You lost me there.  Who needs to mprotect() what?

> 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;
}


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-22 22:42                                                                               ` Andy Lutomirski
  2019-05-23  2:35                                                                                 ` Sean Christopherson
@ 2019-05-23  8:10                                                                                 ` Jarkko Sakkinen
  2019-05-23  8:23                                                                                   ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-23  8:10 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Stephen Smalley, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Wed, May 22, 2019 at 03:42:45PM -0700, Andy Lutomirski wrote:
> 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.

So is this in the context that the enclave is read from another VMA
and not through a file descriptor? Is that locked in?

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23  8:10                                                                                 ` Jarkko Sakkinen
@ 2019-05-23  8:23                                                                                   ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-23  8:23 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Stephen Smalley, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 23, 2019 at 11:10:48AM +0300, Jarkko Sakkinen wrote:
> On Wed, May 22, 2019 at 03:42:45PM -0700, Andy Lutomirski wrote:
> > 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.
> 
> So is this in the context that the enclave is read from another VMA
> and not through a file descriptor? Is that locked in?

No need to answer. Got in page from Sean's response.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23  2:35                                                                                 ` Sean Christopherson
@ 2019-05-23 10:26                                                                                   ` Jarkko Sakkinen
  2019-05-23 14:17                                                                                     ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-23 10:26 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> 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.

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

Dropped off here completely. What if the mmap() is done before any of
the EADD operations?

> 
> 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;
> }

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 10:26                                                                                   ` Jarkko Sakkinen
@ 2019-05-23 14:17                                                                                     ` Sean Christopherson
  2019-05-23 15:38                                                                                       ` Andy Lutomirski
                                                                                                         ` (2 more replies)
  0 siblings, 3 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-23 14:17 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Stephen Smalley, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > 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.

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

> > 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;
> > }
> 
> 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)

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).

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 14:17                                                                                     ` Sean Christopherson
@ 2019-05-23 15:38                                                                                       ` Andy Lutomirski
  2019-05-23 23:40                                                                                         ` Sean Christopherson
                                                                                                           ` (2 more replies)
  2019-05-23 19:58                                                                                       ` Sean Christopherson
  2019-05-27 13:34                                                                                       ` Jarkko Sakkinen
  2 siblings, 3 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-23 15:38 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Jarkko Sakkinen, Andy Lutomirski, Stephen Smalley, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> > On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > > 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.
>

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 14:17                                                                                     ` Sean Christopherson
  2019-05-23 15:38                                                                                       ` Andy Lutomirski
@ 2019-05-23 19:58                                                                                       ` Sean Christopherson
  2019-05-27 13:34                                                                                       ` Jarkko Sakkinen
  2 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-23 19:58 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Stephen Smalley, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Thu, May 23, 2019 at 07:17:52AM -0700, Sean Christopherson wrote:
> On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> > On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > > 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.

Argh, as I was working through Andy's latest proposal I realized that I
was subconciously making FILE__READ imply FILE__EXECUTE.

The idea behind inheriting permissions from the source VMA is to exempt
"standard" enclaves from needing FILE__WRITE.  But if we don't add an
exemption for FILE__EXECUTE as well, then all enclaves need FILE__EXECUTE,
which means FILE__EXECUTE can't be used to identify the case where
userspace is mapping an inherited PROT_WRITE page as PROT_EXEC.  And if
the SGX magic exempts FILE__EXECUTE, then FILE__READ implies FILE__EXECUTE.

Yuck.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 15:38                                                                                       ` Andy Lutomirski
@ 2019-05-23 23:40                                                                                         ` Sean Christopherson
  2019-05-24  1:17                                                                                           ` Andy Lutomirski
  2019-05-24 14:44                                                                                         ` Stephen Smalley
  2019-05-27 13:48                                                                                         ` Jarkko Sakkinen
  2 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-23 23:40 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Jarkko Sakkinen, Stephen Smalley, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Thu, May 23, 2019 at 08:38:17AM -0700, Andy Lutomirski wrote:
> On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> > > On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > > > 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.
> >
> 
> 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

I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?

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

> Associated with the enclave are a bunch (up to 7) "enclave segment

I assume 7 = R, W, X, RW, RX, WX and RWX?

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

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?

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

> [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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 23:40                                                                                         ` Sean Christopherson
@ 2019-05-24  1:17                                                                                           ` Andy Lutomirski
  2019-05-24  7:24                                                                                             ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24  1:17 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Jarkko Sakkinen, Stephen Smalley, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 23, 2019 at 4:40 PM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Thu, May 23, 2019 at 08:38:17AM -0700, Andy Lutomirski wrote:
> > On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
> > <sean.j.christopherson@intel.com> wrote:
> > >
> > > On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> > > > On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > > > > 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.
> > >
> >
> > 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
>
> I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?
>
> > 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

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24  1:17                                                                                           ` Andy Lutomirski
@ 2019-05-24  7:24                                                                                             ` Xing, Cedric
  2019-05-24 15:41                                                                                               ` Stephen Smalley
  2019-05-24 16:43                                                                                               ` Andy Lutomirski
  0 siblings, 2 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-24  7:24 UTC (permalink / raw)
  To: Andy Lutomirski, Christopherson, Sean J
  Cc: Jarkko Sakkinen, Stephen Smalley, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

Hi Andy,

> From: Andy Lutomirski [mailto:luto@kernel.org]
> Sent: Thursday, May 23, 2019 6:18 PM
> 
> On Thu, May 23, 2019 at 4:40 PM Sean Christopherson <sean.j.christopherson@intel.com>
> wrote:
> >
> > On Thu, May 23, 2019 at 08:38:17AM -0700, Andy Lutomirski wrote:
> > > On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
> > > <sean.j.christopherson@intel.com> wrote:
> > > >
> > > > On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> > > > > On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > > > > > 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.
> > > >
> > >
> > > 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
> >
> > I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?
> >
> > > 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.

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.

> 
>  - 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 ...);

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). 
 
> 
> 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:

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?

> 
> 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()?

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

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). 

> 
> 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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 15:38                                                                                       ` Andy Lutomirski
  2019-05-23 23:40                                                                                         ` Sean Christopherson
@ 2019-05-24 14:44                                                                                         ` Stephen Smalley
  2019-05-27 13:48                                                                                         ` Jarkko Sakkinen
  2 siblings, 0 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-24 14:44 UTC (permalink / raw)
  To: Andy Lutomirski, Sean Christopherson
  Cc: Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing, Cedric,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 5/23/19 11:38 AM, Andy Lutomirski wrote:
> On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
>>
>> On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
>>> On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
>>>> 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.
>>
> 
> 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.

I don't follow that.  socket inodes are not anon inodes, and anon inodes 
have no per-instance data by definition, and typically you're only 
dealing with a single anon inode for all files, and hence they were long 
ago marked S_PRIVATE and exempted from all LSM checking except for 
EXECMEM on mmap/mprotect PROT_EXEC.  We have no way to perform useful 
security checking on them currently.  socket inodes we can label from 
their creating process but even that's not going to support multiple 
labels for different sockets created by the same process unless the 
process explicitly used setsockcreatecon(3) aka /proc/self/attr/sockcreate

> 
> [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.
> 


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24  7:24                                                                                             ` Xing, Cedric
@ 2019-05-24 15:41                                                                                               ` Stephen Smalley
  2019-05-24 16:57                                                                                                 ` Xing, Cedric
  2019-05-24 17:42                                                                                                 ` Sean Christopherson
  2019-05-24 16:43                                                                                               ` Andy Lutomirski
  1 sibling, 2 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-24 15:41 UTC (permalink / raw)
  To: Xing, Cedric, Andy Lutomirski, Christopherson, Sean J
  Cc: Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 5/24/19 3:24 AM, Xing, Cedric wrote:
> Hi Andy,
> 
>> From: Andy Lutomirski [mailto:luto@kernel.org]
>> Sent: Thursday, May 23, 2019 6:18 PM
>>
>> On Thu, May 23, 2019 at 4:40 PM Sean Christopherson <sean.j.christopherson@intel.com>
>> wrote:
>>>
>>> On Thu, May 23, 2019 at 08:38:17AM -0700, Andy Lutomirski wrote:
>>>> On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
>>>> <sean.j.christopherson@intel.com> wrote:
>>>>>
>>>>> On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
>>>>>> On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
>>>>>>> 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.
>>>>>
>>>>
>>>> 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
>>>
>>> I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?
>>>
>>>> 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.
> 
> 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.
> 
>>
>>   - 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 ...);
> 
> 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).
>   
>>
>> 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:
> 
> 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?
> 
>>
>> 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()?
> 
>>
>> 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.
>   
>>
>>
>> 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.
> 
> 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).
> 
>>
>> 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

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.

>   *   + <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().

> 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).

> }
> 
> /* 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.

> 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().

> 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);

FILE__READ and FILE__WRITE revalidated to /dev/sgx/enclave upon mprotect().

> 
> /* 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?

> 
> -Cedric
> 


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24  7:24                                                                                             ` Xing, Cedric
  2019-05-24 15:41                                                                                               ` Stephen Smalley
@ 2019-05-24 16:43                                                                                               ` Andy Lutomirski
  2019-05-24 17:07                                                                                                 ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24 16:43 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, Christopherson, Sean J, Jarkko Sakkinen,
	Stephen Smalley, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 12:24 AM Xing, Cedric <cedric.xing@intel.com> wrote:
>
> Hi Andy,
>
> > From: Andy Lutomirski [mailto:luto@kernel.org]
> > Sent: Thursday, May 23, 2019 6:18 PM
> >
> > On Thu, May 23, 2019 at 4:40 PM Sean Christopherson <sean.j.christopherson@intel.com>
> > wrote:
> > >
> > > On Thu, May 23, 2019 at 08:38:17AM -0700, Andy Lutomirski wrote:
> > > > On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
> > > > <sean.j.christopherson@intel.com> wrote:
> > > > >
> > > > > On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> > > > > > On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > > > > > > 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.
> > > > >
> > > >
> > > > 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
> > >
> > > I assume you're thinking of clearing all VM_MAY* flags in sgx_mmap()?
> > >
> > > > 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.
>
> 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.

My objection is to the fact that it's implicit.  I have no problem
with some operation succeeding if the source address is X and failing
if it's !X, but I don't think it's fantastic to have it succeed in
either case but do different things.

For what it's worth, while this is a bit of a theoretical issue for X,
but I think it's a real problem with W.  To avoid accidentally mapping
an enclave page X and then later mapping the same page W (potentially
in a different VMA), I think it will be a lot simpler if the driver
can track which pages are allowed to ever be W.  We definitely *don't*
want an interface in which the eventual writability of a page is
inferred from the W permission on the source address, since we do
*not* want to force anyone to map their enclave file PROT_WRITE or
even to open it O_RDWR.

With the explicit MAXPERM passed in, this issue goes away.  You can
specify W if you want W.

>
> >
> >  - 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 ...);
>
> 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).

That's exactly what I intended here.  If you specify MAXPERM=RX, then
the kernel can validate that the source address is executable.

>
> >
> > 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:
>
> 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?

I think we just let /dev/sgx/enclave be FILE__EXECUTE.  We don't
*have* to make it so that FILE__WRITE and FILE__EXECUTE on
/dev/sgx/enclave means you can create RWX enclave mappings.

>
> >
> > 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()?

Hmm.  I guess we either use FILE__WRITE and FILE__EXECUTE or we use ioctl().

>
> >
> > 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.
>
> >
> >
> > 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.
>
> 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).
>

If the driver works like that, then whatever call sets up this lazily
allocated heap could do the MAXPERM part.

That being said, is the performance advantage from putting this logic
in the kernel instead of in the untrusted part of the SDK really
worthwhile?

> >
> > 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.)

I think this is a non-starter :(  FILE__WRITE also means that you can
write to the file, and the admin / policy author will almost never
want to allow that.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 15:41                                                                                               ` Stephen Smalley
@ 2019-05-24 16:57                                                                                                 ` Xing, Cedric
  2019-05-24 17:42                                                                                                 ` Sean Christopherson
  1 sibling, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-24 16:57 UTC (permalink / raw)
  To: Stephen Smalley, Andy Lutomirski, Christopherson, Sean J
  Cc: Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

Hi Stephen,

> On 5/24/19 3:24 AM, Xing, Cedric wrote:
> >
> > 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
> 
> 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.
> 
> >   *   + <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.

> 
> > 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).

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.

> 
> > }
> >
> > /* 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.

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).

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

> 
> > 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);
> 
> 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. 

> 
> >
> > /* 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?

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.

> 
> >
> > -Cedric
> >


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 16:43                                                                                               ` Andy Lutomirski
@ 2019-05-24 17:07                                                                                                 ` Sean Christopherson
  2019-05-24 17:51                                                                                                   ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 17:07 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Xing, Cedric, Jarkko Sakkinen, Stephen Smalley, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 09:43:27AM -0700, Andy Lutomirski wrote:
> On Fri, May 24, 2019 at 12:24 AM Xing, Cedric <cedric.xing@intel.com> wrote:
> > /**
> >  * 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.)
> 
> I think this is a non-starter :(  FILE__WRITE also means that you can
> write to the file, and the admin / policy author will almost never
> want to allow that.

Why would FILE__WRITE on /dev/sgx/enclave be a problem?  An actual
write to /dev/sgx/enclave would yield -EINVAL, no?

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 15:41                                                                                               ` Stephen Smalley
  2019-05-24 16:57                                                                                                 ` Xing, Cedric
@ 2019-05-24 17:42                                                                                                 ` Sean Christopherson
  2019-05-24 17:54                                                                                                   ` Andy Lutomirski
  2019-05-24 17:54                                                                                                   ` Sean Christopherson
  1 sibling, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 17:42 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Xing, Cedric, Andy Lutomirski, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 11:41:29AM -0400, Stephen Smalley wrote:
> On 5/24/19 3:24 AM, Xing, Cedric wrote:
> >/**
> >  * 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.
> 
> >  *   + <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().
> 
> >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).

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.


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 17:07                                                                                                 ` Sean Christopherson
@ 2019-05-24 17:51                                                                                                   ` Andy Lutomirski
  0 siblings, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24 17:51 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Xing, Cedric, Jarkko Sakkinen, Stephen Smalley,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes


> On May 24, 2019, at 10:07 AM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> 
>> On Fri, May 24, 2019 at 09:43:27AM -0700, Andy Lutomirski wrote:
>>> On Fri, May 24, 2019 at 12:24 AM Xing, Cedric <cedric.xing@intel.com> wrote:
>>> /**
>>> * 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.)
>> 
>> I think this is a non-starter :(  FILE__WRITE also means that you can
>> write to the file, and the admin / policy author will almost never
>> want to allow that.
> 
> Why would FILE__WRITE on /dev/sgx/enclave be a problem?  An actual
> write to /dev/sgx/enclave would yield -EINVAL, no?

Bah, read it wrong — FILE__WRITE on the enclave file on disk is no good.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 17:42                                                                                                 ` Sean Christopherson
@ 2019-05-24 17:54                                                                                                   ` Andy Lutomirski
  2019-05-24 17:56                                                                                                     ` Sean Christopherson
  2019-05-24 17:54                                                                                                   ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24 17:54 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Stephen Smalley, Xing, Cedric, Andy Lutomirski, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes



> On May 24, 2019, at 10:42 AM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> 
>> On Fri, May 24, 2019 at 11:41:29AM -0400, Stephen Smalley wrote:
>>> On 5/24/19 3:24 AM, Xing, Cedric wrote:
>>> /**
>>> * 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.
>> 
>>> *   + <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().
>> 
>>> 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).
> 
> 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?

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.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 17:42                                                                                                 ` Sean Christopherson
  2019-05-24 17:54                                                                                                   ` Andy Lutomirski
@ 2019-05-24 17:54                                                                                                   ` Sean Christopherson
  2019-05-24 18:34                                                                                                     ` Xing, Cedric
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 17:54 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Xing, Cedric, Andy Lutomirski, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 10:42:43AM -0700, Sean Christopherson wrote:
> 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.

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.

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

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 17:54                                                                                                   ` Andy Lutomirski
@ 2019-05-24 17:56                                                                                                     ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 17:56 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Xing, Cedric, Andy Lutomirski, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 10:54:34AM -0700, Andy Lutomirski wrote:
> 
> > On May 24, 2019, at 10:42 AM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> > 
> > 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?
> 
> 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.

> But maybe I’m nuts.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 17:54                                                                                                   ` Sean Christopherson
@ 2019-05-24 18:34                                                                                                     ` Xing, Cedric
  2019-05-24 19:13                                                                                                       ` Sean Christopherson
  2019-05-24 19:37                                                                                                       ` Andy Lutomirski
  0 siblings, 2 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-24 18:34 UTC (permalink / raw)
  To: Christopherson, Sean J, Stephen Smalley
  Cc: Andy Lutomirski, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

> From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> owner@vger.kernel.org] On Behalf Of Sean Christopherson
> Sent: Friday, May 24, 2019 10:55 AM
> 
> On Fri, May 24, 2019 at 10:42:43AM -0700, Sean Christopherson wrote:
> > 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.
> 
> 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.

If "initial permissions" for enclaves are less restrictive than shared objects, then it'd become a backdoor for circumventing LSM when enclave whitelisting is *not* in place. For example, an adversary may load a page, which would otherwise never be executable, as an executable page in EPC.

In the case a RWX page is needed, the calling process has to have a RWX page serving as the source for EADD so PROCESS__EXECMEM will have been checked. For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM on /dev/sgx/enclave, which I see as a security benefit because it only affects the enclave but not the whole process hosting it.

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

I'm not sure I understand the motivation behind this proposal to decouple initial EPC permissions from source pages.

I don't think it a big deal to fully mmap() enclave files, which have to be parsed by user mode anyway to determine various things including but not limited to the size of heap(s), size and number of TCSs/stacks/TLS areas, and the overall enclave size. So with PHDRs parsed, it's trivial to mmap() each segment with permissions from its PHDR.

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

I'm lost. Why is EAUG tied to permissions on .sigstruct? 

-Cedric

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 18:34                                                                                                     ` Xing, Cedric
@ 2019-05-24 19:13                                                                                                       ` Sean Christopherson
  2019-05-24 19:30                                                                                                         ` Andy Lutomirski
  2019-05-24 20:42                                                                                                         ` Xing, Cedric
  2019-05-24 19:37                                                                                                       ` Andy Lutomirski
  1 sibling, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 19:13 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Stephen Smalley, Andy Lutomirski, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 11:34:32AM -0700, Xing, Cedric wrote:
> > From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> > owner@vger.kernel.org] On Behalf Of Sean Christopherson
> > Sent: Friday, May 24, 2019 10:55 AM
> > 
> > On Fri, May 24, 2019 at 10:42:43AM -0700, Sean Christopherson wrote:
> > > 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.
> > 
> > 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.
> 
> If "initial permissions" for enclaves are less restrictive than shared
> objects, then it'd become a backdoor for circumventing LSM when enclave
> whitelisting is *not* in place. For example, an adversary may load a page,
> which would otherwise never be executable, as an executable page in EPC.

My point is that enclaves have different properties than shared objects.

Normal LSM behavior with regard to executing files is to label files with
e.g. FILE__EXECUTE.  Because an enclave must be built to the exact
specifications of .sigstruct, requring FILE__EXECUTE on the .sigstruct is
effectively the same as requiring FILE__EXECUTE on the enclave itself.

Addressing your scenario of loading an executable page in EPC, doing so
would require one of the following:

  - Ability to install a .sigstruct with FILE__EXECUTE

  - PROCESS__EXECMEM

  - FILE__EXECMOD and SGX2 support

> In the case a RWX page is needed, the calling process has to have a RWX page
> serving as the source for EADD so PROCESS__EXECMEM will have been checked.
> For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM on
> /dev/sgx/enclave, which I see as a security benefit because it only affects
> the enclave but not the whole process hosting it.

There is no FILE__EXECMEM check, only PROCESS__EXECMEM and FILE__EXECMOD.
I assume you're referring to the latter?

I don't see a fundamental difference between having RWX in an enclave and
RWX in normal memory, either way the process can execute arbitrary code,
i.e. PROCESS__EXECMEM is appropriate.  Yes, an enclave will #UD on certain
instructions, but that's easily sidestepped by having a trampoline in the
host (marked RX) and piping arbitrary code into the enclave.  Or using
EEXIT to do a bit of ROP.

> > > 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.
> 
> I'm not sure I understand the motivation behind this proposal to decouple
> initial EPC permissions from source pages.

Pulling permissions from source pages means userspace needs to fully map
the in normal memory, including marking pages executable.  That exposes
the loader to having executable pages in its address space that it has no
intention of executing (outside of the enclave).  And for Graphene, it
means having to actively avoid PROCESS__EXECMEM, e.g. by using a dummy
backing file to build the enclave instead of anon memory.

> I don't think it a big deal to fully mmap() enclave files, which have to be
> parsed by user mode anyway to determine various things including but not
> limited to the size of heap(s), size and number of TCSs/stacks/TLS areas, and
> the overall enclave size. So with PHDRs parsed, it's trivial to mmap() each
> segment with permissions from its PHDR.
>
> > > 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.
> > >
> 
> I'm lost. Why is EAUG tied to permissions on .sigstruct? 

Because for the purposes of LSM checks, .sigstruct is the enclave's
backing file, and mapping a previously writable enclave page as exectuable
is roughly equivalent to mapping a CoW'd page as exectuable.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 19:13                                                                                                       ` Sean Christopherson
@ 2019-05-24 19:30                                                                                                         ` Andy Lutomirski
  2019-05-24 20:42                                                                                                         ` Xing, Cedric
  1 sibling, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24 19:30 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, Stephen Smalley, Andy Lutomirski, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 12:13 PM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Fri, May 24, 2019 at 11:34:32AM -0700, Xing, Cedric wrote:
> > > From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> > > owner@vger.kernel.org] On Behalf Of Sean Christopherson
> > > Sent: Friday, May 24, 2019 10:55 AM

> I don't see a fundamental difference between having RWX in an enclave and
> RWX in normal memory, either way the process can execute arbitrary code,
> i.e. PROCESS__EXECMEM is appropriate.  Yes, an enclave will #UD on certain
> instructions, but that's easily sidestepped by having a trampoline in the
> host (marked RX) and piping arbitrary code into the enclave.  Or using
> EEXIT to do a bit of ROP.

There's a difference, albeit a somewhat weak one, if sigstructs are
whitelisted.  FILE__EXECMOD on
either /dev/sgx/enclave or on the sigstruct is not an entirely crazy
way to express this.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 18:34                                                                                                     ` Xing, Cedric
  2019-05-24 19:13                                                                                                       ` Sean Christopherson
@ 2019-05-24 19:37                                                                                                       ` Andy Lutomirski
  2019-05-24 20:03                                                                                                         ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24 19:37 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Christopherson, Sean J, Stephen Smalley, Andy Lutomirski,
	Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
>
> > From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> > owner@vger.kernel.org] On Behalf Of Sean Christopherson
> > Sent: Friday, May 24, 2019 10:55 AM
> >
> > On Fri, May 24, 2019 at 10:42:43AM -0700, Sean Christopherson wrote:
> > > 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.
> >
> > 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.
>
> If "initial permissions" for enclaves are less restrictive than shared objects, then it'd become a backdoor for circumventing LSM when enclave whitelisting is *not* in place. For example, an adversary may load a page, which would otherwise never be executable, as an executable page in EPC.
>
> In the case a RWX page is needed, the calling process has to have a RWX page serving as the source for EADD so PROCESS__EXECMEM will have been checked. For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM on /dev/sgx/enclave, which I see as a security benefit because it only affects the enclave but not the whole process hosting it.

So the permission would be like FILE__EXECMOD on the source enclave
page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
MAP_SHARED, PROT_WRITE isn't going to work because that means you can
modify the file.

I'm starting to think that looking at the source VMA permission bits
or source PTE permission bits is putting a bit too much policy into
the driver as opposed to the LSM.  How about delegating the whole
thing to an LSM hook?  The EADD operation would invoke a new hook,
something like:

int security_enclave_load_bytes(void *source_addr, struct
vm_area_struct *source_vma, loff_t source_offset, unsigned int
maxperm);

Then you don't have to muck with mapping anything PROT_EXEC.  Instead
you load from a mapping of a file and the LSM applies whatever policy
it feels appropriate.  If the first pass gets something wrong, the
application or library authors can take it up with the SELinux folks
without breaking the whole ABI :)

(I'm proposing passing in the source_vma because this hook would be
called with mmap_sem held for read to avoid a TOCTOU race.)

If we go this route, the only substantial change to the existing
driver that's needed for an initial upstream merge is the maxperm
mechanism and whatever hopefully minimal API changes are needed to
allow users to conveniently set up the mappings.  And we don't need to
worry about how to hack around mprotect() calling into the LSM,
because the LSM will actually be aware of SGX and can just do the
right thing.

--Andy

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 19:37                                                                                                       ` Andy Lutomirski
@ 2019-05-24 20:03                                                                                                         ` Sean Christopherson
  2019-05-24 20:58                                                                                                           ` Xing, Cedric
                                                                                                                             ` (2 more replies)
  0 siblings, 3 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 20:03 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Xing, Cedric, Stephen Smalley, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
> >
> > If "initial permissions" for enclaves are less restrictive than shared
> > objects, then it'd become a backdoor for circumventing LSM when enclave
> > whitelisting is *not* in place. For example, an adversary may load a page,
> > which would otherwise never be executable, as an executable page in EPC.
> >
> > In the case a RWX page is needed, the calling process has to have a RWX
> > page serving as the source for EADD so PROCESS__EXECMEM will have been
> > checked. For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM
> > on /dev/sgx/enclave, which I see as a security benefit because it only
> > affects the enclave but not the whole process hosting it.
> 
> So the permission would be like FILE__EXECMOD on the source enclave
> page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
> MAP_SHARED, PROT_WRITE isn't going to work because that means you can
> modify the file.

Was this in response to Cedric's comment, or to my comment?

> I'm starting to think that looking at the source VMA permission bits
> or source PTE permission bits is putting a bit too much policy into
> the driver as opposed to the LSM.  How about delegating the whole
> thing to an LSM hook?  The EADD operation would invoke a new hook,
> something like:
> 
> int security_enclave_load_bytes(void *source_addr, struct
> vm_area_struct *source_vma, loff_t source_offset, unsigned int
> maxperm);
> 
> Then you don't have to muck with mapping anything PROT_EXEC.  Instead
> you load from a mapping of a file and the LSM applies whatever policy
> it feels appropriate.  If the first pass gets something wrong, the
> application or library authors can take it up with the SELinux folks
> without breaking the whole ABI :)
> 
> (I'm proposing passing in the source_vma because this hook would be
> called with mmap_sem held for read to avoid a TOCTOU race.)
> 
> If we go this route, the only substantial change to the existing
> driver that's needed for an initial upstream merge is the maxperm
> mechanism and whatever hopefully minimal API changes are needed to
> allow users to conveniently set up the mappings.  And we don't need to
> worry about how to hack around mprotect() calling into the LSM,
> because the LSM will actually be aware of SGX and can just do the
> right thing.

This doesn't address restricting which processes can run which enclaves,
it only allows restricting the build flow.  Or are you suggesting this
be done in addition to whitelisting sigstructs?

What's the value prop beyond whitelisting sigstructs?  Realistically, I
doubt LSMs/users will want to take the performance hit of scanning the
source bytes every time an enclave is loaded.

We could add seomthing like security_enclave_mprotect() in lieu of abusing
security_file_mprotect(), but passing the full source bytes seems a bit
much.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 19:13                                                                                                       ` Sean Christopherson
  2019-05-24 19:30                                                                                                         ` Andy Lutomirski
@ 2019-05-24 20:42                                                                                                         ` Xing, Cedric
  2019-05-24 21:11                                                                                                           ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-24 20:42 UTC (permalink / raw)
  To: Christopherson, Sean J
  Cc: Stephen Smalley, Andy Lutomirski, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

> From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> owner@vger.kernel.org] On Behalf Of Sean Christopherson
> Sent: Friday, May 24, 2019 12:14 PM
> 
> My point is that enclaves have different properties than shared objects.
> 
> Normal LSM behavior with regard to executing files is to label files
> with e.g. FILE__EXECUTE.  Because an enclave must be built to the exact
> specifications of .sigstruct, requring FILE__EXECUTE on the .sigstruct
> is effectively the same as requiring FILE__EXECUTE on the enclave itself.
> 
> Addressing your scenario of loading an executable page in EPC, doing so
> would require one of the following:
> 
>   - Ability to install a .sigstruct with FILE__EXECUTE
> 
>   - PROCESS__EXECMEM
> 
>   - FILE__EXECMOD and SGX2 support

Now I got your point. It sounds a great idea to me!

But instead of using .sigstruct file, I'd still recommend using file mapping (i.e. SIGSTRUCT needs to reside in executable memory). But then there'll be a hole - a process having FILE__EXECMOD on any file could use that file as a SIGSTRUCT. Probably we'll need a new type in SELinux to label enclave/sigstruct files.

> 
> > In the case a RWX page is needed, the calling process has to have a
> > RWX page serving as the source for EADD so PROCESS__EXECMEM will have
> been checked.
> > For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM on
> > /dev/sgx/enclave, which I see as a security benefit because it only
> > affects the enclave but not the whole process hosting it.
> 
> There is no FILE__EXECMEM check, only PROCESS__EXECMEM and FILE__EXECMOD.
> I assume you're referring to the latter?

Yes.

> 
> I don't see a fundamental difference between having RWX in an enclave
> and RWX in normal memory, either way the process can execute arbitrary
> code, i.e. PROCESS__EXECMEM is appropriate.  Yes, an enclave will #UD on
> certain instructions, but that's easily sidestepped by having a
> trampoline in the host (marked RX) and piping arbitrary code into the
> enclave.  Or using EEXIT to do a bit of ROP.

I'm with you.

With your proposal only FILE__EXECMOD is needed on /dev/sgx/enclave to launch Graphene enclaves or the like.

> 
> > > > 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.
> >
> > I'm not sure I understand the motivation behind this proposal to
> > decouple initial EPC permissions from source pages.
> 
> Pulling permissions from source pages means userspace needs to fully map
> the in normal memory, including marking pages executable.  That exposes
> the loader to having executable pages in its address space that it has
> no intention of executing (outside of the enclave).  And for Graphene,
> it means having to actively avoid PROCESS__EXECMEM, e.g. by using a
> dummy backing file to build the enclave instead of anon memory.

Agreed.

> 
> > I don't think it a big deal to fully mmap() enclave files, which have
> > to be parsed by user mode anyway to determine various things including
> > but not limited to the size of heap(s), size and number of
> > TCSs/stacks/TLS areas, and the overall enclave size. So with PHDRs
> > parsed, it's trivial to mmap() each segment with permissions from its
> PHDR.
> >
> > > > 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.
> > > >
> >
> > I'm lost. Why is EAUG tied to permissions on .sigstruct?
> 
> Because for the purposes of LSM checks, .sigstruct is the enclave's
> backing file, and mapping a previously writable enclave page as
> exectuable is roughly equivalent to mapping a CoW'd page as exectuable.

I think I've got your idea. You are trying to use permissions on .sigstruct to determine whether EAUG will be available to that specific enclave. Am I right?

I'd tie EAUG to the permissions of /dev/sgx/enclave instead. But why? There are couple of reasons. For one, a SIGSTRUCT identifies the behavior of the enclave, hence the SGX features needed by that enclave. So if an enclave requires EAUG, the .sigstruct has to allow EAUG or the enclave wouldn't work. That means the system admin wouldn't have a choice but to match up what's needed by the enclave. For two, whether to allow, say loading code dynamically into an enclave, depends on whether the host process can tolerate the inherent risk. And that decision is seldom made on individual enclaves but to the host process as a whole. And /dev/sgx/enclave serves that purpose.

-Cedric


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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 20:03                                                                                                         ` Sean Christopherson
@ 2019-05-24 20:58                                                                                                           ` Xing, Cedric
  2019-05-24 21:27                                                                                                           ` Andy Lutomirski
  2019-05-25 17:31                                                                                                           ` Dr. Greg
  2 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-05-24 20:58 UTC (permalink / raw)
  To: Christopherson, Sean J, Andy Lutomirski
  Cc: Stephen Smalley, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

> From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> owner@vger.kernel.org] On Behalf Of Sean Christopherson
> Sent: Friday, May 24, 2019 1:04 PM
> 
> On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> > On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com>
> wrote:
> > >
> > > If "initial permissions" for enclaves are less restrictive than
> > > shared objects, then it'd become a backdoor for circumventing LSM
> > > when enclave whitelisting is *not* in place. For example, an
> > > adversary may load a page, which would otherwise never be executable,
> as an executable page in EPC.
> > >
> > > In the case a RWX page is needed, the calling process has to have a
> > > RWX page serving as the source for EADD so PROCESS__EXECMEM will
> > > have been checked. For SGX2, changing an EPC page to RWX is subject
> > > to FILE__EXECMEM on /dev/sgx/enclave, which I see as a security
> > > benefit because it only affects the enclave but not the whole
> process hosting it.
> >
> > So the permission would be like FILE__EXECMOD on the source enclave
> > page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
> > MAP_SHARED, PROT_WRITE isn't going to work because that means you can
> > modify the file.
> 
> Was this in response to Cedric's comment, or to my comment?

Creating RWX source page requires PROCESS_EXECMEM. But as I responded to Sean earlier, I think his proposal of "aggregating" all "initial" permission checks into a single SIGSTRUCT check is probably a better approach.

> 
> > I'm starting to think that looking at the source VMA permission bits
> > or source PTE permission bits is putting a bit too much policy into
> > the driver as opposed to the LSM.  How about delegating the whole
> > thing to an LSM hook?  The EADD operation would invoke a new hook,
> > something like:
> >
> > int security_enclave_load_bytes(void *source_addr, struct
> > vm_area_struct *source_vma, loff_t source_offset, unsigned int
> > maxperm);

This is exactly what I was thinking. But with Sean's proposal this is probably no longer necessary.

> >
> > Then you don't have to muck with mapping anything PROT_EXEC.  Instead
> > you load from a mapping of a file and the LSM applies whatever policy
> > it feels appropriate.  If the first pass gets something wrong, the
> > application or library authors can take it up with the SELinux folks
> > without breaking the whole ABI :)
> >
> > (I'm proposing passing in the source_vma because this hook would be
> > called with mmap_sem held for read to avoid a TOCTOU race.)
> >
> > If we go this route, the only substantial change to the existing
> > driver that's needed for an initial upstream merge is the maxperm
> > mechanism and whatever hopefully minimal API changes are needed to
> > allow users to conveniently set up the mappings.  And we don't need to
> > worry about how to hack around mprotect() calling into the LSM,
> > because the LSM will actually be aware of SGX and can just do the
> > right thing.
> 
> This doesn't address restricting which processes can run which enclaves,
> it only allows restricting the build flow.  Or are you suggesting this
> be done in addition to whitelisting sigstructs?

In the context of SELinux, new types could be defined to be associated with SIGSTRUCT (or more precisely, files containing SIGSTRUCTs). Then the LSM hook (I'd propose security_sgx_initialize_enclave) could enforce whatever...

> 
> What's the value prop beyond whitelisting sigstructs?  Realistically, I
> doubt LSMs/users will want to take the performance hit of scanning the
> source bytes every time an enclave is loaded.
> 
> We could add seomthing like security_enclave_mprotect() in lieu of
> abusing security_file_mprotect(), but passing the full source bytes
> seems a bit much.

I'd just use /dev/sgx/enclave to govern "runtime" permissions any EPC page can mmap()/mprotect() to. Then we won't need any code changes in LSM.

-Cedric

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 20:42                                                                                                         ` Xing, Cedric
@ 2019-05-24 21:11                                                                                                           ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 21:11 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Stephen Smalley, Andy Lutomirski, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 01:42:13PM -0700, Xing, Cedric wrote:
> > From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> > owner@vger.kernel.org] On Behalf Of Sean Christopherson
> > Sent: Friday, May 24, 2019 12:14 PM
> > 
> > My point is that enclaves have different properties than shared objects.
> > 
> > Normal LSM behavior with regard to executing files is to label files
> > with e.g. FILE__EXECUTE.  Because an enclave must be built to the exact
> > specifications of .sigstruct, requring FILE__EXECUTE on the .sigstruct
> > is effectively the same as requiring FILE__EXECUTE on the enclave itself.
> > 
> > Addressing your scenario of loading an executable page in EPC, doing so
> > would require one of the following:
> > 
> >   - Ability to install a .sigstruct with FILE__EXECUTE
> > 
> >   - PROCESS__EXECMEM
> > 
> >   - FILE__EXECMOD and SGX2 support
> 
> Now I got your point. It sounds a great idea to me!
> 
> But instead of using .sigstruct file, I'd still recommend using file mapping
> (i.e. SIGSTRUCT needs to reside in executable memory). But then there'll be a

Why?  Even in the Graphene case the final .sigstruct can be known ahead of
time.  Userspace can always use memfd() if it's generating SIGSTRUCT on
the fly.

> hole - a process having FILE__EXECMOD on any file could use that file as a
> SIGSTRUCT. Probably we'll need a new type in SELinux to label
> enclave/sigstruct files.
>
> > I don't see a fundamental difference between having RWX in an enclave
> > and RWX in normal memory, either way the process can execute arbitrary
> > code, i.e. PROCESS__EXECMEM is appropriate.  Yes, an enclave will #UD on
> > certain instructions, but that's easily sidestepped by having a
> > trampoline in the host (marked RX) and piping arbitrary code into the
> > enclave.  Or using EEXIT to do a bit of ROP.
> 
> I'm with you.
> 
> With your proposal only FILE__EXECMOD is needed on /dev/sgx/enclave to launch
> Graphene enclaves or the like.

It wouldn't even need FILE__EXECMOD, assuming Graphene does all of its
libc rewriting before building the enclave, i.e. doesn't EADD RWX pages.

> > > > > 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.
> > >
> > > I'm not sure I understand the motivation behind this proposal to
> > > decouple initial EPC permissions from source pages.
> > 
> > Pulling permissions from source pages means userspace needs to fully map
> > the in normal memory, including marking pages executable.  That exposes
> > the loader to having executable pages in its address space that it has
> > no intention of executing (outside of the enclave).  And for Graphene,
> > it means having to actively avoid PROCESS__EXECMEM, e.g. by using a
> > dummy backing file to build the enclave instead of anon memory.
> 
> Agreed.
> 
> > 
> > > I don't think it a big deal to fully mmap() enclave files, which have
> > > to be parsed by user mode anyway to determine various things including
> > > but not limited to the size of heap(s), size and number of
> > > TCSs/stacks/TLS areas, and the overall enclave size. So with PHDRs
> > > parsed, it's trivial to mmap() each segment with permissions from its
> > PHDR.
> > >
> > > > > 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.
> > > > >
> > >
> > > I'm lost. Why is EAUG tied to permissions on .sigstruct?
> > 
> > Because for the purposes of LSM checks, .sigstruct is the enclave's
> > backing file, and mapping a previously writable enclave page as
> > exectuable is roughly equivalent to mapping a CoW'd page as exectuable.
> 
> I think I've got your idea. You are trying to use permissions on .sigstruct
> to determine whether EAUG will be available to that specific enclave. Am I
> right?

Yep.

> I'd tie EAUG to the permissions of /dev/sgx/enclave instead. But why? There
> are couple of reasons. For one, a SIGSTRUCT identifies the behavior of the
> enclave, hence the SGX features needed by that enclave. So if an enclave
> requires EAUG, the .sigstruct has to allow EAUG or the enclave wouldn't work.
> That means the system admin wouldn't have a choice but to match up what's
> needed by the enclave. For two, whether to allow, say loading code
> dynamically into an enclave, depends on whether the host process can tolerate
> the inherent risk. And that decision is seldom made on individual enclaves
> but to the host process as a whole. And /dev/sgx/enclave serves that purpose.

I think I'd be ok either way?  What I really care about is having line of
sight to a sane way to support for SGX2, and both seem sane.  I.e. we can
hash this detail out when SGX2 goes in.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 20:03                                                                                                         ` Sean Christopherson
  2019-05-24 20:58                                                                                                           ` Xing, Cedric
@ 2019-05-24 21:27                                                                                                           ` Andy Lutomirski
  2019-05-24 22:41                                                                                                             ` Sean Christopherson
  2019-05-25 17:31                                                                                                           ` Dr. Greg
  2 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24 21:27 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Xing, Cedric, Stephen Smalley, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 1:03 PM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> > On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
> > >
> > > If "initial permissions" for enclaves are less restrictive than shared
> > > objects, then it'd become a backdoor for circumventing LSM when enclave
> > > whitelisting is *not* in place. For example, an adversary may load a page,
> > > which would otherwise never be executable, as an executable page in EPC.
> > >
> > > In the case a RWX page is needed, the calling process has to have a RWX
> > > page serving as the source for EADD so PROCESS__EXECMEM will have been
> > > checked. For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM
> > > on /dev/sgx/enclave, which I see as a security benefit because it only
> > > affects the enclave but not the whole process hosting it.
> >
> > So the permission would be like FILE__EXECMOD on the source enclave
> > page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
> > MAP_SHARED, PROT_WRITE isn't going to work because that means you can
> > modify the file.
>
> Was this in response to Cedric's comment, or to my comment?

Yours.  I think that requiring source pages to be actually mapped W is
not such a great idea.

>
> > I'm starting to think that looking at the source VMA permission bits
> > or source PTE permission bits is putting a bit too much policy into
> > the driver as opposed to the LSM.  How about delegating the whole
> > thing to an LSM hook?  The EADD operation would invoke a new hook,
> > something like:
> >
> > int security_enclave_load_bytes(void *source_addr, struct
> > vm_area_struct *source_vma, loff_t source_offset, unsigned int
> > maxperm);
> >
> > Then you don't have to muck with mapping anything PROT_EXEC.  Instead
> > you load from a mapping of a file and the LSM applies whatever policy
> > it feels appropriate.  If the first pass gets something wrong, the
> > application or library authors can take it up with the SELinux folks
> > without breaking the whole ABI :)
> >
> > (I'm proposing passing in the source_vma because this hook would be
> > called with mmap_sem held for read to avoid a TOCTOU race.)
> >
> > If we go this route, the only substantial change to the existing
> > driver that's needed for an initial upstream merge is the maxperm
> > mechanism and whatever hopefully minimal API changes are needed to
> > allow users to conveniently set up the mappings.  And we don't need to
> > worry about how to hack around mprotect() calling into the LSM,
> > because the LSM will actually be aware of SGX and can just do the
> > right thing.
>
> This doesn't address restricting which processes can run which enclaves,
> it only allows restricting the build flow.  Or are you suggesting this
> be done in addition to whitelisting sigstructs?

In addition.

But I named the function badly and gave it a bad signature, which
confused you.  Let's try again:

int security_enclave_load_from_memory(const struct vm_area_struct
*source, unsigned int maxperm);

Maybe some really fancy future LSM would also want loff_t
source_offset, but it's probably not terribly useful.  This same
callback would be used for EAUG.

Following up on your discussion with Cedric about sigstruct, the other
callback would be something like:

int security_enclave_init(struct file *sigstruct_file);

The main issue I see is that we also want to control the enclave's
ability to have RWX pages or to change a W page to X.  We might also
want:

int security_enclave_load_zeros(unsigned int maxperm);

An enclave that's going to modify its own code will need memory with
maxperm = RWX or WX.

But this is a bit awkward if the LSM's decision depends on the
sigstruct.  We could get fancy and require that the sigstruct be
supplied before any EADD operations so that the maxperm decisions can
depend on the sigstruct.

Am I making more sense now?

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 21:27                                                                                                           ` Andy Lutomirski
@ 2019-05-24 22:41                                                                                                             ` Sean Christopherson
  2019-05-24 23:42                                                                                                               ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-24 22:41 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Xing, Cedric, Stephen Smalley, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 02:27:34PM -0700, Andy Lutomirski wrote:
> On Fri, May 24, 2019 at 1:03 PM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> > > On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
> > > >
> > > > If "initial permissions" for enclaves are less restrictive than shared
> > > > objects, then it'd become a backdoor for circumventing LSM when enclave
> > > > whitelisting is *not* in place. For example, an adversary may load a page,
> > > > which would otherwise never be executable, as an executable page in EPC.
> > > >
> > > > In the case a RWX page is needed, the calling process has to have a RWX
> > > > page serving as the source for EADD so PROCESS__EXECMEM will have been
> > > > checked. For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM
> > > > on /dev/sgx/enclave, which I see as a security benefit because it only
> > > > affects the enclave but not the whole process hosting it.
> > >
> > > So the permission would be like FILE__EXECMOD on the source enclave
> > > page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
> > > MAP_SHARED, PROT_WRITE isn't going to work because that means you can
> > > modify the file.
> >
> > Was this in response to Cedric's comment, or to my comment?
> 
> Yours.  I think that requiring source pages to be actually mapped W is
> not such a great idea.

I wasn't requiring source pages to be mapped W.  At least I didn't intend
to require W.  What I was trying to say is that SGX could trigger an
EXECMEM check if userspace attempted to EADD or EAUG an enclave page with
RWX permissions, e.g.:

  if ((SECINFO.PERMS & RWX) == RWX) {
      ret = security_mmap_file(NULL, RWX, ???);
      if (ret)
          return ret;
  }

But that's a moot point if we add security_enclave_load() or whatever.

> 
> >
> > > I'm starting to think that looking at the source VMA permission bits
> > > or source PTE permission bits is putting a bit too much policy into
> > > the driver as opposed to the LSM.  How about delegating the whole
> > > thing to an LSM hook?  The EADD operation would invoke a new hook,
> > > something like:
> > >
> > > int security_enclave_load_bytes(void *source_addr, struct
> > > vm_area_struct *source_vma, loff_t source_offset, unsigned int
> > > maxperm);
> > >
> > > Then you don't have to muck with mapping anything PROT_EXEC.  Instead
> > > you load from a mapping of a file and the LSM applies whatever policy
> > > it feels appropriate.  If the first pass gets something wrong, the
> > > application or library authors can take it up with the SELinux folks
> > > without breaking the whole ABI :)
> > >
> > > (I'm proposing passing in the source_vma because this hook would be
> > > called with mmap_sem held for read to avoid a TOCTOU race.)
> > >
> > > If we go this route, the only substantial change to the existing
> > > driver that's needed for an initial upstream merge is the maxperm
> > > mechanism and whatever hopefully minimal API changes are needed to
> > > allow users to conveniently set up the mappings.  And we don't need to
> > > worry about how to hack around mprotect() calling into the LSM,
> > > because the LSM will actually be aware of SGX and can just do the
> > > right thing.
> >
> > This doesn't address restricting which processes can run which enclaves,
> > it only allows restricting the build flow.  Or are you suggesting this
> > be done in addition to whitelisting sigstructs?
> 
> In addition.
> 
> But I named the function badly and gave it a bad signature, which
> confused you.  Let's try again:
> 
> int security_enclave_load_from_memory(const struct vm_area_struct
> *source, unsigned int maxperm);

I prefer security_enclave_load(), "from_memory" seems redundant at best.

> Maybe some really fancy future LSM would also want loff_t
> source_offset, but it's probably not terribly useful.  This same
> callback would be used for EAUG.
> 
> Following up on your discussion with Cedric about sigstruct, the other
> callback would be something like:
> 
> int security_enclave_init(struct file *sigstruct_file);
> 
> The main issue I see is that we also want to control the enclave's
> ability to have RWX pages or to change a W page to X.  We might also
> want:
> 
> int security_enclave_load_zeros(unsigned int maxperm);

What's the use case for this?  @maxperm will always be at least RW in
this case, otherwise the page is useless to the enclave, and if the
enclave can write the page, the fact that it started as zeros is
irrelevant.

> An enclave that's going to modify its own code will need memory with
> maxperm = RWX or WX.
> 
> But this is a bit awkward if the LSM's decision depends on the
> sigstruct.  We could get fancy and require that the sigstruct be
> supplied before any EADD operations so that the maxperm decisions can
> depend on the sigstruct.
> 
> Am I making more sense now?

Yep.  Requiring .sigstruct at ECREATE would be trivial.  If we wanted
flexibility we could do:

   int security_enclave_load(struct file *file, struct vm_area_struct *vma,
                             unsigned long prot);

And for ultimate flexibility we could pass both .sigstruct and the file
pointer for /dev/sgx/enclave, but that seems a bit ridiculous.

Passing both would allow tying EXECMOD to /dev/sgx/enclave as Cedric
wanted (without having to play games and pass /dev/sgx/enclave to
security_enclave_load()), but I don't think there's anything fundamentally
broken with using .sigstruct for EXECMOD.  It requires more verbose
labeling, but that's not a bad thing.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 22:41                                                                                                             ` Sean Christopherson
@ 2019-05-24 23:42                                                                                                               ` Andy Lutomirski
  2019-05-25 22:40                                                                                                                 ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-24 23:42 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Xing, Cedric, Stephen Smalley, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes



> On May 24, 2019, at 3:41 PM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> 
>> On Fri, May 24, 2019 at 02:27:34PM -0700, Andy Lutomirski wrote:
>> On Fri, May 24, 2019 at 1:03 PM Sean Christopherson
>> <sean.j.christopherson@intel.com> wrote:
>>> 
>>>> On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
>>>>> On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
>>>>> 
>>>>> If "initial permissions" for enclaves are less restrictive than shared
>>>>> objects, then it'd become a backdoor for circumventing LSM when enclave
>>>>> whitelisting is *not* in place. For example, an adversary may load a page,
>>>>> which would otherwise never be executable, as an executable page in EPC.
>>>>> 
>>>>> In the case a RWX page is needed, the calling process has to have a RWX
>>>>> page serving as the source for EADD so PROCESS__EXECMEM will have been
>>>>> checked. For SGX2, changing an EPC page to RWX is subject to FILE__EXECMEM
>>>>> on /dev/sgx/enclave, which I see as a security benefit because it only
>>>>> affects the enclave but not the whole process hosting it.
>>>> 
>>>> So the permission would be like FILE__EXECMOD on the source enclave
>>>> page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
>>>> MAP_SHARED, PROT_WRITE isn't going to work because that means you can
>>>> modify the file.
>>> 
>>> Was this in response to Cedric's comment, or to my comment?
>> 
>> Yours.  I think that requiring source pages to be actually mapped W is
>> not such a great idea.
> 
> I wasn't requiring source pages to be mapped W.  At least I didn't intend
> to require W.  What I was trying to say is that SGX could trigger an
> EXECMEM check if userspace attempted to EADD or EAUG an enclave page with
> RWX permissions, e.g.:
> 
>  if ((SECINFO.PERMS & RWX) == RWX) {
>      ret = security_mmap_file(NULL, RWX, ???);
>      if (ret)
>          return ret;
>  }
> 
> But that's a moot point if we add security_enclave_load() or whatever.
> 
>> 
>>> 
>>>> I'm starting to think that looking at the source VMA permission bits
>>>> or source PTE permission bits is putting a bit too much policy into
>>>> the driver as opposed to the LSM.  How about delegating the whole
>>>> thing to an LSM hook?  The EADD operation would invoke a new hook,
>>>> something like:
>>>> 
>>>> int security_enclave_load_bytes(void *source_addr, struct
>>>> vm_area_struct *source_vma, loff_t source_offset, unsigned int
>>>> maxperm);
>>>> 
>>>> Then you don't have to muck with mapping anything PROT_EXEC.  Instead
>>>> you load from a mapping of a file and the LSM applies whatever policy
>>>> it feels appropriate.  If the first pass gets something wrong, the
>>>> application or library authors can take it up with the SELinux folks
>>>> without breaking the whole ABI :)
>>>> 
>>>> (I'm proposing passing in the source_vma because this hook would be
>>>> called with mmap_sem held for read to avoid a TOCTOU race.)
>>>> 
>>>> If we go this route, the only substantial change to the existing
>>>> driver that's needed for an initial upstream merge is the maxperm
>>>> mechanism and whatever hopefully minimal API changes are needed to
>>>> allow users to conveniently set up the mappings.  And we don't need to
>>>> worry about how to hack around mprotect() calling into the LSM,
>>>> because the LSM will actually be aware of SGX and can just do the
>>>> right thing.
>>> 
>>> This doesn't address restricting which processes can run which enclaves,
>>> it only allows restricting the build flow.  Or are you suggesting this
>>> be done in addition to whitelisting sigstructs?
>> 
>> In addition.
>> 
>> But I named the function badly and gave it a bad signature, which
>> confused you.  Let's try again:
>> 
>> int security_enclave_load_from_memory(const struct vm_area_struct
>> *source, unsigned int maxperm);
> 
> I prefer security_enclave_load(), "from_memory" seems redundant at best.

Fine with me.

> 
>> Maybe some really fancy future LSM would also want loff_t
>> source_offset, but it's probably not terribly useful.  This same
>> callback would be used for EAUG.
>> 
>> Following up on your discussion with Cedric about sigstruct, the other
>> callback would be something like:
>> 
>> int security_enclave_init(struct file *sigstruct_file);
>> 
>> The main issue I see is that we also want to control the enclave's
>> ability to have RWX pages or to change a W page to X.  We might also
>> want:
>> 
>> int security_enclave_load_zeros(unsigned int maxperm);
> 
> What's the use case for this?  @maxperm will always be at least RW in
> this case, otherwise the page is useless to the enclave, and if the
> enclave can write the page, the fact that it started as zeros is
> irrelevant.

This is how EAUG could ask if RWX is okay. If an enclave is internally doing dynamic loading, the it will need a heap page with maxperm = RWX.  (If it’s well designed, it will make it RW and then RX, either by changing SECINFO or by asking the host to mprotect() it, but it still needs the overall RWX mask.).

Also, do real SGX1 enclave formats have BSS? If so, then either we need an ioctl or load zeros or user code is going to load from /dev/zero or just from the heap, but the LSM is going to play better with an ioctl, I suspect :)

> 
>> An enclave that's going to modify its own code will need memory with
>> maxperm = RWX or WX.
>> 
>> But this is a bit awkward if the LSM's decision depends on the
>> sigstruct.  We could get fancy and require that the sigstruct be
>> supplied before any EADD operations so that the maxperm decisions can
>> depend on the sigstruct.
>> 
>> Am I making more sense now?
> 
> Yep.  Requiring .sigstruct at ECREATE would be trivial.  If we wanted
> flexibility we could do:
> 
>   int security_enclave_load(struct file *file, struct vm_area_struct *vma,
>                             unsigned long prot);
> 
> And for ultimate flexibility we could pass both .sigstruct and the file
> pointer for /dev/sgx/enclave, but that seems a bit ridiculous.

I agree.

> 
> Passing both would allow tying EXECMOD to /dev/sgx/enclave as Cedric
> wanted (without having to play games and pass /dev/sgx/enclave to
> security_enclave_load()), but I don't think there's anything fundamentally
> broken with using .sigstruct for EXECMOD.  It requires more verbose
> labeling, but that's not a bad thing.

The benefit of putting it on .sigstruct is that it can be per-enclave.

As I understand it from Fedora packaging, the way this works on distros is generally that a package will include some files and their associated labels, and, if the package needs EXECMOD, then the files are labeled with EXECMOD and the author of the relevant code might get a dirty look.

This could translate to the author of an exclave that needs RWX regions getting a dirty look without leaking this permission into other enclaves.

(In my opinion, the dirty looks are actually the best security benefit of the entire concept of LSMs making RWX difficult.  A sufficiently creative attacker can almost always bypass W^X restrictions once they’ve pwned you, but W^X makes it harder to pwn you in the first place, and SELinux makes it really obvious when packaging a program that doesn’t respect W^X.  The upshot is that a lot of programs got fixed.)

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 20:03                                                                                                         ` Sean Christopherson
  2019-05-24 20:58                                                                                                           ` Xing, Cedric
  2019-05-24 21:27                                                                                                           ` Andy Lutomirski
@ 2019-05-25 17:31                                                                                                           ` Dr. Greg
  2 siblings, 0 replies; 318+ messages in thread
From: Dr. Greg @ 2019-05-25 17:31 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Xing, Cedric, Stephen Smalley, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Fri, May 24, 2019 at 01:03:33PM -0700, Sean Christopherson wrote:

Good morning, I hope the weekend is going well for everyone.  Skunky
holiday weather out here in West-Central Minnesota.

> On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> > If we go this route, the only substantial change to the existing
> > driver that's needed for an initial upstream merge is the maxperm
> > mechanism and whatever hopefully minimal API changes are needed to
> > allow users to conveniently set up the mappings.  And we don't need to
> > worry about how to hack around mprotect() calling into the LSM,
> > because the LSM will actually be aware of SGX and can just do the
> > right thing.

> This doesn't address restricting which processes can run which
> enclaves, it only allows restricting the build flow.  Or are you
> suggesting this be done in addition to whitelisting sigstructs?
>
> What's the value prop beyond whitelisting sigstructs?
> Realistically, I doubt LSMs/users will want to take the performance
> hit of scanning the source bytes every time an enclave is loaded.
>
> We could add seomthing like security_enclave_mprotect() in lieu of
> abusing security_file_mprotect(), but passing the full source bytes
> seems a bit much.

It would seem that we hold the moniker of responsibility for this
conversation, since without our provocation regarding cryptographic
verification of enclave source, there would be a driver headed
upstream whose only constraint against W^X sourced executable code,
running with full confidentiality and integrity protections, would be
a character device with o666 permissions.  Given that, a couple of
reflections to facilitate further conversation, if nothing else for
the benefit of Jonathan Corbet and his bystanders... :-)

As the conversations to date have indicated, imposing LSM controls on
enclave executable code is a bit problematic, in no small part since
it is the theological equivalent of driving a square peg into a round
hole.  SGX, as a technology, was designed around the concept of
cryptographic verification of code provenance and origin.

The decision to take that off the table, for reasons of political
idealogy only, means that mainstream Linux will not be a platform that
can achieve the full hardware security capabilities and protections of
SGX, nor will mainstream Linux be able to enjoy full protections from
the technology itself.

We will be dealing with that, from a driver and runtime perspective,
but that is a conversation for another day.

The issue of SGX2 and Enclave Dynamic Memory Management (EDMM) has
come up and to date there doesn't appear to have been a serious
conversation regarding whether or not all of the LSM machinations in
the world will make any difference when this technology goes mainline.
The agenda driving mainlining of the driver is to support Graphene for
cloud based solutions and without EDMM, dynamic code loading support
is decidedly more problematic.

Dynamic enclave code loading isn't problematic from a security
perspective when the code is being loaded from the platform itself,
since presumably, the encompassing conversation will result in LSM
controls being applied to the necessary code paths.  However, with the
ability to exploit SGX2 instructions, an enclave with adverserial
intent could simply setup a mutually attested security context and
pull whatever executable code it wants from the INTERNET at large,
using an encrypted and integrity protected communications channel.

That has at least been our interpretation and experience with the
ENCLU[EMODPE] and ENCLU[EACCEPTCOPY] instructions and the out-of-tree
driver.  Given the use of an encrypted channel, and the fact that
these instructions are ring 3 enclave mode only, it would seem that
all of the LSM controls in the world won't have visibility or control
over code that is being loaded and executed using such a mechanism.

We could have arguably missed something that the new driver will do to
address this issue.  To date the only discussion seems to have been
about controls over ENCLS[EAUG], which are arguably a bit blunt for
this purpose.

In the land of SGX, if one is intellectually honest from an
engineering perspective, the only solid security contract one has to
work with is the notion of cryptographic identity.  Hence our concern
and patches that implemented an absolutely minimal footprint ring-0
control infrastructure over the contents of an enclave's SIGSTRUCT.
Which is where we have arguably circled back to after 3-4 months and
one kernel release cycle.

Wrapping an LSM hook around our policy mechanism would seem to
achieve, from a security perspective, about the same level of security
effect that more major and invasive modifications would achieve, given
Cedric's proposal to inherit page permissions from the source, which
is what our runtime already does.

As always, apologies for excessive verbosity beyond LKML sensibilities.

Best wishes for a pleasant remainder of the spring weekend to
everyone.

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: greg@enjellic.com
------------------------------------------------------------------------------
"Heaven goes by favor.  If it went by merit, you would stay out and your
 dog would go in."
                                -- Mark Twain

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-24 23:42                                                                                                               ` Andy Lutomirski
@ 2019-05-25 22:40                                                                                                                 ` Xing, Cedric
  2019-05-26  0:57                                                                                                                   ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-25 22:40 UTC (permalink / raw)
  To: Andy Lutomirski, Christopherson, Sean J
  Cc: Andy Lutomirski, Stephen Smalley, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

> From: Andy Lutomirski [mailto:luto@amacapital.net]
> Sent: Friday, May 24, 2019 4:42 PM
> 
> > On May 24, 2019, at 3:41 PM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> >
> >> On Fri, May 24, 2019 at 02:27:34PM -0700, Andy Lutomirski wrote:
> >> On Fri, May 24, 2019 at 1:03 PM Sean Christopherson
> >> <sean.j.christopherson@intel.com> wrote:
> >>>
> >>>> On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> >>>>> On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
> >>>>>
> >>>>> If "initial permissions" for enclaves are less restrictive than
> >>>>> shared objects, then it'd become a backdoor for circumventing LSM
> >>>>> when enclave whitelisting is *not* in place. For example, an
> >>>>> adversary may load a page, which would otherwise never be executable, as an executable
> page in EPC.
> >>>>>
> >>>>> In the case a RWX page is needed, the calling process has to have
> >>>>> a RWX page serving as the source for EADD so PROCESS__EXECMEM will
> >>>>> have been checked. For SGX2, changing an EPC page to RWX is
> >>>>> subject to FILE__EXECMEM on /dev/sgx/enclave, which I see as a
> >>>>> security benefit because it only affects the enclave but not the whole process hosting
> it.
> >>>>
> >>>> So the permission would be like FILE__EXECMOD on the source enclave
> >>>> page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
> >>>> MAP_SHARED, PROT_WRITE isn't going to work because that means you
> >>>> can modify the file.
> >>>
> >>> Was this in response to Cedric's comment, or to my comment?
> >>
> >> Yours.  I think that requiring source pages to be actually mapped W
> >> is not such a great idea.
> >
> > I wasn't requiring source pages to be mapped W.  At least I didn't
> > intend to require W.  What I was trying to say is that SGX could
> > trigger an EXECMEM check if userspace attempted to EADD or EAUG an
> > enclave page with RWX permissions, e.g.:
> >
> >  if ((SECINFO.PERMS & RWX) == RWX) {
> >      ret = security_mmap_file(NULL, RWX, ???);
> >      if (ret)
> >          return ret;
> >  }
> >
> > But that's a moot point if we add security_enclave_load() or whatever.
> >
> >>
> >>>
> >>>> I'm starting to think that looking at the source VMA permission
> >>>> bits or source PTE permission bits is putting a bit too much policy
> >>>> into the driver as opposed to the LSM.  How about delegating the
> >>>> whole thing to an LSM hook?  The EADD operation would invoke a new
> >>>> hook, something like:
> >>>>
> >>>> int security_enclave_load_bytes(void *source_addr, struct
> >>>> vm_area_struct *source_vma, loff_t source_offset, unsigned int
> >>>> maxperm);
> >>>>
> >>>> Then you don't have to muck with mapping anything PROT_EXEC.
> >>>> Instead you load from a mapping of a file and the LSM applies
> >>>> whatever policy it feels appropriate.  If the first pass gets
> >>>> something wrong, the application or library authors can take it up
> >>>> with the SELinux folks without breaking the whole ABI :)
> >>>>
> >>>> (I'm proposing passing in the source_vma because this hook would be
> >>>> called with mmap_sem held for read to avoid a TOCTOU race.)
> >>>>
> >>>> If we go this route, the only substantial change to the existing
> >>>> driver that's needed for an initial upstream merge is the maxperm
> >>>> mechanism and whatever hopefully minimal API changes are needed to
> >>>> allow users to conveniently set up the mappings.  And we don't need
> >>>> to worry about how to hack around mprotect() calling into the LSM,
> >>>> because the LSM will actually be aware of SGX and can just do the
> >>>> right thing.
> >>>
> >>> This doesn't address restricting which processes can run which
> >>> enclaves, it only allows restricting the build flow.  Or are you
> >>> suggesting this be done in addition to whitelisting sigstructs?
> >>
> >> In addition.
> >>
> >> But I named the function badly and gave it a bad signature, which
> >> confused you.  Let's try again:
> >>
> >> int security_enclave_load_from_memory(const struct vm_area_struct
> >> *source, unsigned int maxperm);
> >
> > I prefer security_enclave_load(), "from_memory" seems redundant at best.
> 
> Fine with me.

If we think of EADD as a way of mmap()'ing an enclave file into memory, would this security_enclave_load() be the same as security_mmap_file(source_vma->vm_file, maxperm, MAP_PRIVATE), except that the target is now EPC instead of regular pages? 

> 
> >
> >> Maybe some really fancy future LSM would also want loff_t
> >> source_offset, but it's probably not terribly useful.  This same
> >> callback would be used for EAUG.

EAUG always zeroes the EPC page before making it available to an enclave. So I don't think there's anything needed to done here.

> >>
> >> Following up on your discussion with Cedric about sigstruct, the
> >> other callback would be something like:
> >>
> >> int security_enclave_init(struct file *sigstruct_file);

I'd still insist in using a pointer rather than a file, for reasons that we've discussed before. For those who can't recall, the major reason is that most implementation would embed SIGSTRUCT into the same file as the enclave (or at least I don't want to prevent anyone from doing so), which could also be part of another file, such as a shared object or even the main executable itself. It could be difficult to obtain a fd in those cases. memfd won't work because it can't retain the same attributes of the original file containing the SIGSTRUCT. 

After all, what matters is the attributes associated with the backing file, which could be easily retrieve from vm_file of the covering VMA. So for the sake of flexibility, let's stay with what we've agreed before - a pointer to SIGSTRUCT.
 
> >>
> >> The main issue I see is that we also want to control the enclave's
> >> ability to have RWX pages or to change a W page to X.  We might also
> >> want:
> >>
> >> int security_enclave_load_zeros(unsigned int maxperm);
> >
> > What's the use case for this?  @maxperm will always be at least RW in
> > this case, otherwise the page is useless to the enclave, and if the
> > enclave can write the page, the fact that it started as zeros is
> > irrelevant.
> 
> This is how EAUG could ask if RWX is okay. If an enclave is internally doing dynamic loading,
> the it will need a heap page with maxperm = RWX.  (If it’s well designed, it will make it RW
> and then RX, either by changing SECINFO or by asking the host to mprotect() it, but it still
> needs the overall RWX mask.).

Any new page EAUG'ed will start in RW (as dictated by SGX ISA). EACCEPTCOPY will then change it to RX. RWX is never needed for all practical purposes. This in fact could be gated by mprotect() and the attributes associated with /dev/sgx/enclave. In the case of SELinux, FILE__EXECMOD is the right attribute and mprotect() will take care of all the rest. I don't see why the driver need a role here.
 
> 
> Also, do real SGX1 enclave formats have BSS? If so, then either we need an ioctl or load zeros
> or user code is going to load from /dev/zero or just from the heap, but the LSM is going to
> play better with an ioctl, I suspect :)

Yes, it does. But an enclave would either measure BSS, in which case the initial bytes have to be zero or MRENCLAVE will change; or zero BSS explicitly in its initialization code. 

But from LSM's perspective it makes no difference than EADD'ing a page with non-zero content. And security_enclave_load(NULL, RW) would take care of it in exactly in the same way. 

> 
> >
> >> An enclave that's going to modify its own code will need memory with
> >> maxperm = RWX or WX.

With SGX2/EDMM, RWX is *never* needed for all practical purposes.

In theory, in terms of security, no page shall be made executable while it is still being prepared. So W and X shall always be mutually exclusive, regardless it's in EPC or regular memory.

RWX is only needed in SGX1, as a workaround for certain usages, because EPCM permissions can never change at runtime.

> >>
> >> But this is a bit awkward if the LSM's decision depends on the
> >> sigstruct.  We could get fancy and require that the sigstruct be
> >> supplied before any EADD operations so that the maxperm decisions can
> >> depend on the sigstruct.
> >>
> >> Am I making more sense now?
> >
> > Yep.  Requiring .sigstruct at ECREATE would be trivial.  If we wanted
> > flexibility we could do:
> >
> >   int security_enclave_load(struct file *file, struct vm_area_struct *vma,
> >                             unsigned long prot);
> >
> > And for ultimate flexibility we could pass both .sigstruct and the
> > file pointer for /dev/sgx/enclave, but that seems a bit ridiculous.
> 
> I agree.

Loosely speaking, an enclave (including initial contents of all of its pages and their permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision resistant property of SHA-2). So only one is needed for a decision, and either one would lead to the same decision. So I don't see anything making any sense here.

Theoretically speaking, if LSM can make a decision at EINIT by means of security_enclave_load(), then security_enclave_load() is never needed.

In practice, I support keeping both because security_enclave_load() can only approve an enumerable set while security_enclave_load() can approve a non-enumerable set of enclaves. Moreover, in order to determine the validity of a MRENCLAVE (as in development of a policy or in creation of a white/black list), system admins will need the audit log produced by security_enclave_load().

> 
> >
> > Passing both would allow tying EXECMOD to /dev/sgx/enclave as Cedric
> > wanted (without having to play games and pass /dev/sgx/enclave to
> > security_enclave_load()), but I don't think there's anything
> > fundamentally broken with using .sigstruct for EXECMOD.  It requires
> > more verbose labeling, but that's not a bad thing.
> 
> The benefit of putting it on .sigstruct is that it can be per-enclave.
> 
> As I understand it from Fedora packaging, the way this works on distros is generally that a
> package will include some files and their associated labels, and, if the package needs EXECMOD,
> then the files are labeled with EXECMOD and the author of the relevant code might get a dirty
> look.
> 
> This could translate to the author of an exclave that needs RWX regions getting a dirty look
> without leaking this permission into other enclaves.
> 
> (In my opinion, the dirty looks are actually the best security benefit of the entire concept
> of LSMs making RWX difficult.  A sufficiently creative attacker can almost always bypass W^X
> restrictions once they’ve pwned you, but W^X makes it harder to pwn you in the first place,
> and SELinux makes it really obvious when packaging a program that doesn’t respect W^X.  The
> upshot is that a lot of programs got fixed.)

I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX, i.e. FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM. 

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-25 22:40                                                                                                                 ` Xing, Cedric
@ 2019-05-26  0:57                                                                                                                   ` Andy Lutomirski
  2019-05-26  6:09                                                                                                                     ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-26  0:57 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Christopherson, Sean J, Andy Lutomirski, Stephen Smalley,
	Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Sat, May 25, 2019 at 3:40 PM Xing, Cedric <cedric.xing@intel.com> wrote:
>
> > From: Andy Lutomirski [mailto:luto@amacapital.net]
> > Sent: Friday, May 24, 2019 4:42 PM
> >
> > > On May 24, 2019, at 3:41 PM, Sean Christopherson <sean.j.christopherson@intel.com> wrote:
> > >
> > >> On Fri, May 24, 2019 at 02:27:34PM -0700, Andy Lutomirski wrote:
> > >> On Fri, May 24, 2019 at 1:03 PM Sean Christopherson
> > >> <sean.j.christopherson@intel.com> wrote:
> > >>>
> > >>>> On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> > >>>>> On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
> > >>>>>
> > >>>>> If "initial permissions" for enclaves are less restrictive than
> > >>>>> shared objects, then it'd become a backdoor for circumventing LSM
> > >>>>> when enclave whitelisting is *not* in place. For example, an
> > >>>>> adversary may load a page, which would otherwise never be executable, as an executable
> > page in EPC.
> > >>>>>
> > >>>>> In the case a RWX page is needed, the calling process has to have
> > >>>>> a RWX page serving as the source for EADD so PROCESS__EXECMEM will
> > >>>>> have been checked. For SGX2, changing an EPC page to RWX is
> > >>>>> subject to FILE__EXECMEM on /dev/sgx/enclave, which I see as a
> > >>>>> security benefit because it only affects the enclave but not the whole process hosting
> > it.
> > >>>>
> > >>>> So the permission would be like FILE__EXECMOD on the source enclave
> > >>>> page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
> > >>>> MAP_SHARED, PROT_WRITE isn't going to work because that means you
> > >>>> can modify the file.
> > >>>
> > >>> Was this in response to Cedric's comment, or to my comment?
> > >>
> > >> Yours.  I think that requiring source pages to be actually mapped W
> > >> is not such a great idea.
> > >
> > > I wasn't requiring source pages to be mapped W.  At least I didn't
> > > intend to require W.  What I was trying to say is that SGX could
> > > trigger an EXECMEM check if userspace attempted to EADD or EAUG an
> > > enclave page with RWX permissions, e.g.:
> > >
> > >  if ((SECINFO.PERMS & RWX) == RWX) {
> > >      ret = security_mmap_file(NULL, RWX, ???);
> > >      if (ret)
> > >          return ret;
> > >  }
> > >
> > > But that's a moot point if we add security_enclave_load() or whatever.
> > >
> > >>
> > >>>
> > >>>> I'm starting to think that looking at the source VMA permission
> > >>>> bits or source PTE permission bits is putting a bit too much policy
> > >>>> into the driver as opposed to the LSM.  How about delegating the
> > >>>> whole thing to an LSM hook?  The EADD operation would invoke a new
> > >>>> hook, something like:
> > >>>>
> > >>>> int security_enclave_load_bytes(void *source_addr, struct
> > >>>> vm_area_struct *source_vma, loff_t source_offset, unsigned int
> > >>>> maxperm);
> > >>>>
> > >>>> Then you don't have to muck with mapping anything PROT_EXEC.
> > >>>> Instead you load from a mapping of a file and the LSM applies
> > >>>> whatever policy it feels appropriate.  If the first pass gets
> > >>>> something wrong, the application or library authors can take it up
> > >>>> with the SELinux folks without breaking the whole ABI :)
> > >>>>
> > >>>> (I'm proposing passing in the source_vma because this hook would be
> > >>>> called with mmap_sem held for read to avoid a TOCTOU race.)
> > >>>>
> > >>>> If we go this route, the only substantial change to the existing
> > >>>> driver that's needed for an initial upstream merge is the maxperm
> > >>>> mechanism and whatever hopefully minimal API changes are needed to
> > >>>> allow users to conveniently set up the mappings.  And we don't need
> > >>>> to worry about how to hack around mprotect() calling into the LSM,
> > >>>> because the LSM will actually be aware of SGX and can just do the
> > >>>> right thing.
> > >>>
> > >>> This doesn't address restricting which processes can run which
> > >>> enclaves, it only allows restricting the build flow.  Or are you
> > >>> suggesting this be done in addition to whitelisting sigstructs?
> > >>
> > >> In addition.
> > >>
> > >> But I named the function badly and gave it a bad signature, which
> > >> confused you.  Let's try again:
> > >>
> > >> int security_enclave_load_from_memory(const struct vm_area_struct
> > >> *source, unsigned int maxperm);
> > >
> > > I prefer security_enclave_load(), "from_memory" seems redundant at best.
> >
> > Fine with me.
>
> If we think of EADD as a way of mmap()'ing an enclave file into memory, would this security_enclave_load() be the same as security_mmap_file(source_vma->vm_file, maxperm, MAP_PRIVATE), except that the target is now EPC instead of regular pages?

Hmm, that's clever.  Although it seems plausible that an LSM would
want to allow RX or RWX of a given file page but only in the context
of an approved enclave, so I think it should still be its own hook.

>
> >
> > >
> > >> Maybe some really fancy future LSM would also want loff_t
> > >> source_offset, but it's probably not terribly useful.  This same
> > >> callback would be used for EAUG.
>
> EAUG always zeroes the EPC page before making it available to an enclave. So I don't think there's anything needed to done here.

Duh.  So security_enclave_load_zeros() for EAUG.  See below.

>
> > >>
> > >> Following up on your discussion with Cedric about sigstruct, the
> > >> other callback would be something like:
> > >>
> > >> int security_enclave_init(struct file *sigstruct_file);
>
> I'd still insist in using a pointer rather than a file, for reasons that we've discussed before. For those who can't recall, the major reason is that most implementation would embed SIGSTRUCT into the same file as the enclave (or at least I don't want to prevent anyone from doing so), which could also be part of another file, such as a shared object or even the main executable itself. It could be difficult to obtain a fd in those cases. memfd won't work because it can't retain the same attributes of the original file containing the SIGSTRUCT.
>
> After all, what matters is the attributes associated with the backing file, which could be easily retrieve from vm_file of the covering VMA. So for the sake of flexibility, let's stay with what we've agreed before - a pointer to SIGSTRUCT.

I'm okay with this, except for one nastiness: there's a big difference
between a file that is just a sigstruct and a file that contains
essentially arbitrary data plus a sigstruct at an arbitrary offset.
We could do something tricky like saying that SIGSTRUCT can be in a
file that's just a SIGSTRUCT or it can be in a special SIGSTRUCT ELF
note in a file that isn't just a SIGSTRUCT, but that could be
annoyingly restrictive.

If it's going to be in an arbitrary file, then I think the signature
needs to be more like:

int security_enclave_init(struct vm_area_struct *sigstruct_vma, loff_t
sigstruct_offset, const sgx_sigstruct *sigstruct);

So that the LSM still has the opportunity to base its decision on the
contents of the SIGSTRUCT.  Actually, we need that change regardless.

>
> > >>
> > >> The main issue I see is that we also want to control the enclave's
> > >> ability to have RWX pages or to change a W page to X.  We might also
> > >> want:
> > >>
> > >> int security_enclave_load_zeros(unsigned int maxperm);
> > >
> > > What's the use case for this?  @maxperm will always be at least RW in
> > > this case, otherwise the page is useless to the enclave, and if the
> > > enclave can write the page, the fact that it started as zeros is
> > > irrelevant.
> >
> > This is how EAUG could ask if RWX is okay. If an enclave is internally doing dynamic loading,
> > the it will need a heap page with maxperm = RWX.  (If it’s well designed, it will make it RW
> > and then RX, either by changing SECINFO or by asking the host to mprotect() it, but it still
> > needs the overall RWX mask.).
>
> Any new page EAUG'ed will start in RW (as dictated by SGX ISA). EACCEPTCOPY will then change it to RX. RWX is never needed for all practical purposes. This in fact could be gated by mprotect() and the attributes associated with /dev/sgx/enclave. In the case of SELinux, FILE__EXECMOD is the right attribute and mprotect() will take care of all the rest. I don't see why the driver need a role here.

I find the SDM's discussion of EAUG, EACCEPT, and EACCEPTCOPY to be
extremely confusing.  My copy of the SDM has EACCEPT's SECINFO
argument as "Read access permitted by Non Enclave".  Is that an error?
 And is EACCEPTCOPY just EACCEPT + memcpy or is there some other
fundamental difference?  38.5.7 doesn't even mention EACCEPTCOPY.

Anyway, all my confusion aside, I was talking about the page table,
not the EPCM.  I think the enclave should need permission to write its
own content into a page that will ever become X, and the enclave's
untrusted host library would do this by adding the page with
MAXPERM=RWX and then mapping/mprotecting it as PROT_WRITE and then
(later or simultaneously) PROT_EXEC.

Since SGX2 doesn't seem to have a way to add an initialized page to
EPC after an enclave starts, I guess that it's impossible to have the
enclave do something like dlopen() without MAXPERM=RWX.  So be it.
Maybe someone will find this annoying someday and SGX3 will add
EAUG-but-don't-zero and EACCEPT-with-existing-contents.

>
> >
> > Also, do real SGX1 enclave formats have BSS? If so, then either we need an ioctl or load zeros
> > or user code is going to load from /dev/zero or just from the heap, but the LSM is going to
> > play better with an ioctl, I suspect :)
>
> Yes, it does. But an enclave would either measure BSS, in which case the initial bytes have to be zero or MRENCLAVE will change; or zero BSS explicitly in its initialization code.
>
> But from LSM's perspective it makes no difference than EADD'ing a page with non-zero content. And security_enclave_load(NULL, RW) would take care of it in exactly in the same way.

Sure, I suppose the same hook with NULL parameters would be equivalent.

>
> >
> > >
> > >> An enclave that's going to modify its own code will need memory with
> > >> maxperm = RWX or WX.
>
> With SGX2/EDMM, RWX is *never* needed for all practical purposes.
>
> In theory, in terms of security, no page shall be made executable while it is still being prepared. So W and X shall always be mutually exclusive, regardless it's in EPC or regular memory.
>
> RWX is only needed in SGX1, as a workaround for certain usages, because EPCM permissions can never change at runtime.

As above, I think I disagree.  MAXPERM is intended as an upper bound
on the permissions that a page can ever have, at least until it's
EREMOVEd and re-added.  Since there's no EAUG-but-don't-zero, EAUG
with MAXPERM.W=0 is basically useless because the page can never
contain anything other than zeros, so a dynamically allocated page
that is ever executed has to have MAXPERM=RWX or MAXPERM=WX.  And that
will need special permissions, which I think is consistent with your
recent emails on how this could all map to SELinux permissions.

>
> > >>
> > >> But this is a bit awkward if the LSM's decision depends on the
> > >> sigstruct.  We could get fancy and require that the sigstruct be
> > >> supplied before any EADD operations so that the maxperm decisions can
> > >> depend on the sigstruct.
> > >>
> > >> Am I making more sense now?
> > >
> > > Yep.  Requiring .sigstruct at ECREATE would be trivial.  If we wanted
> > > flexibility we could do:
> > >
> > >   int security_enclave_load(struct file *file, struct vm_area_struct *vma,
> > >                             unsigned long prot);
> > >
> > > And for ultimate flexibility we could pass both .sigstruct and the
> > > file pointer for /dev/sgx/enclave, but that seems a bit ridiculous.
> >
> > I agree.
>
> Loosely speaking, an enclave (including initial contents of all of its pages and their permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision resistant property of SHA-2). So only one is needed for a decision, and either one would lead to the same decision. So I don't see anything making any sense here.
>
> Theoretically speaking, if LSM can make a decision at EINIT by means of security_enclave_load(), then security_enclave_load() is never needed.
>
> In practice, I support keeping both because security_enclave_load() can only approve an enumerable set while security_enclave_load() can approve a non-enumerable set of enclaves. Moreover, in order to determine the validity of a MRENCLAVE (as in development of a policy or in creation of a white/black list), system admins will need the audit log produced by security_enclave_load().

I'm confused.  Things like MRSIGNER aren't known until the SIGSTRUCT
shows up.  Also, security_enclave_load() provides no protection
against loading a mishmash of two different enclave files.  I see
security_enclave_init() as "verify this SIGSTRUCT against your policy
on who may sign enclaves and/or grant EXECMOD depending on SIGSTRUCT"
and security_enclave_load() as "implement your EXECMOD / EXECUTE /
WRITE / whatever policy and possibly check enclave files for some
label."

>
> >
> > >
> > > Passing both would allow tying EXECMOD to /dev/sgx/enclave as Cedric
> > > wanted (without having to play games and pass /dev/sgx/enclave to
> > > security_enclave_load()), but I don't think there's anything
> > > fundamentally broken with using .sigstruct for EXECMOD.  It requires
> > > more verbose labeling, but that's not a bad thing.
> >
> > The benefit of putting it on .sigstruct is that it can be per-enclave.
> >
> > As I understand it from Fedora packaging, the way this works on distros is generally that a
> > package will include some files and their associated labels, and, if the package needs EXECMOD,
> > then the files are labeled with EXECMOD and the author of the relevant code might get a dirty
> > look.
> >
> > This could translate to the author of an exclave that needs RWX regions getting a dirty look
> > without leaking this permission into other enclaves.
> >
> > (In my opinion, the dirty looks are actually the best security benefit of the entire concept
> > of LSMs making RWX difficult.  A sufficiently creative attacker can almost always bypass W^X
> > restrictions once they’ve pwned you, but W^X makes it harder to pwn you in the first place,
> > and SELinux makes it really obvious when packaging a program that doesn’t respect W^X.  The
> > upshot is that a lot of programs got fixed.)
>
> I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX, i.e. FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM.

Hmm.  If we want to make this distinction, we need something a big
richer than my proposed callbacks.  A check of the actual mprotect() /
mmap() permissions would also be needed.  Specifically, allowing
MAXPERM=RWX wouldn't imply that PROT_WRITE | PROT_EXEC is allowed.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-26  0:57                                                                                                                   ` Andy Lutomirski
@ 2019-05-26  6:09                                                                                                                     ` Xing, Cedric
  2019-05-28 20:24                                                                                                                       ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-26  6:09 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Christopherson, Sean J, Stephen Smalley, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

> From: Andy Lutomirski [mailto:luto@kernel.org]
> Sent: Saturday, May 25, 2019 5:58 PM
> 
> On Sat, May 25, 2019 at 3:40 PM Xing, Cedric <cedric.xing@intel.com> wrote:
> >
> > > From: Andy Lutomirski [mailto:luto@amacapital.net]
> > > Sent: Friday, May 24, 2019 4:42 PM
> > >
> > > > On May 24, 2019, at 3:41 PM, Sean Christopherson <sean.j.christopherson@intel.com>
> wrote:
> > > >
> > > >> On Fri, May 24, 2019 at 02:27:34PM -0700, Andy Lutomirski wrote:
> > > >> On Fri, May 24, 2019 at 1:03 PM Sean Christopherson
> > > >> <sean.j.christopherson@intel.com> wrote:
> > > >>>
> > > >>>> On Fri, May 24, 2019 at 12:37:44PM -0700, Andy Lutomirski wrote:
> > > >>>>> On Fri, May 24, 2019 at 11:34 AM Xing, Cedric <cedric.xing@intel.com> wrote:
> > > >>>>>
> > > >>>>> If "initial permissions" for enclaves are less restrictive
> > > >>>>> than shared objects, then it'd become a backdoor for
> > > >>>>> circumventing LSM when enclave whitelisting is *not* in place.
> > > >>>>> For example, an adversary may load a page, which would
> > > >>>>> otherwise never be executable, as an executable
> > > page in EPC.
> > > >>>>>
> > > >>>>> In the case a RWX page is needed, the calling process has to
> > > >>>>> have a RWX page serving as the source for EADD so
> > > >>>>> PROCESS__EXECMEM will have been checked. For SGX2, changing an
> > > >>>>> EPC page to RWX is subject to FILE__EXECMEM on
> > > >>>>> /dev/sgx/enclave, which I see as a security benefit because it
> > > >>>>> only affects the enclave but not the whole process hosting
> > > it.
> > > >>>>
> > > >>>> So the permission would be like FILE__EXECMOD on the source
> > > >>>> enclave page, because it would be mapped MAP_ANONYMOUS, PROT_WRITE?
> > > >>>> MAP_SHARED, PROT_WRITE isn't going to work because that means
> > > >>>> you can modify the file.
> > > >>>
> > > >>> Was this in response to Cedric's comment, or to my comment?
> > > >>
> > > >> Yours.  I think that requiring source pages to be actually mapped
> > > >> W is not such a great idea.
> > > >
> > > > I wasn't requiring source pages to be mapped W.  At least I didn't
> > > > intend to require W.  What I was trying to say is that SGX could
> > > > trigger an EXECMEM check if userspace attempted to EADD or EAUG an
> > > > enclave page with RWX permissions, e.g.:
> > > >
> > > >  if ((SECINFO.PERMS & RWX) == RWX) {
> > > >      ret = security_mmap_file(NULL, RWX, ???);
> > > >      if (ret)
> > > >          return ret;
> > > >  }
> > > >
> > > > But that's a moot point if we add security_enclave_load() or whatever.
> > > >
> > > >>
> > > >>>
> > > >>>> I'm starting to think that looking at the source VMA permission
> > > >>>> bits or source PTE permission bits is putting a bit too much
> > > >>>> policy into the driver as opposed to the LSM.  How about
> > > >>>> delegating the whole thing to an LSM hook?  The EADD operation
> > > >>>> would invoke a new hook, something like:
> > > >>>>
> > > >>>> int security_enclave_load_bytes(void *source_addr, struct
> > > >>>> vm_area_struct *source_vma, loff_t source_offset, unsigned int
> > > >>>> maxperm);
> > > >>>>
> > > >>>> Then you don't have to muck with mapping anything PROT_EXEC.
> > > >>>> Instead you load from a mapping of a file and the LSM applies
> > > >>>> whatever policy it feels appropriate.  If the first pass gets
> > > >>>> something wrong, the application or library authors can take it
> > > >>>> up with the SELinux folks without breaking the whole ABI :)
> > > >>>>
> > > >>>> (I'm proposing passing in the source_vma because this hook
> > > >>>> would be called with mmap_sem held for read to avoid a TOCTOU
> > > >>>> race.)
> > > >>>>
> > > >>>> If we go this route, the only substantial change to the
> > > >>>> existing driver that's needed for an initial upstream merge is
> > > >>>> the maxperm mechanism and whatever hopefully minimal API
> > > >>>> changes are needed to allow users to conveniently set up the
> > > >>>> mappings.  And we don't need to worry about how to hack around
> > > >>>> mprotect() calling into the LSM, because the LSM will actually
> > > >>>> be aware of SGX and can just do the right thing.
> > > >>>
> > > >>> This doesn't address restricting which processes can run which
> > > >>> enclaves, it only allows restricting the build flow.  Or are you
> > > >>> suggesting this be done in addition to whitelisting sigstructs?
> > > >>
> > > >> In addition.
> > > >>
> > > >> But I named the function badly and gave it a bad signature, which
> > > >> confused you.  Let's try again:
> > > >>
> > > >> int security_enclave_load_from_memory(const struct vm_area_struct
> > > >> *source, unsigned int maxperm);
> > > >
> > > > I prefer security_enclave_load(), "from_memory" seems redundant at best.
> > >
> > > Fine with me.
> >
> > If we think of EADD as a way of mmap()'ing an enclave file into memory, would this
> security_enclave_load() be the same as security_mmap_file(source_vma->vm_file, maxperm,
> MAP_PRIVATE), except that the target is now EPC instead of regular pages?
> 
> Hmm, that's clever.  Although it seems plausible that an LSM would want to allow RX or RWX
> of a given file page but only in the context of an approved enclave, so I think it should
> still be its own hook.

What do you mean by "in the context of an approved enclave"? EPC pages are *inaccessible* to any software until after EINIT. So it would never be a security concern to EADD a page with wrong permissions as long as the enclave would be denied eventually by LSM at EINIT.

But I acknowledge the difference between loading a page into regular memory vs. into EPC. So it's beneficial to have a separate hook, which if not hooked, would pass through to security_mmap_file() by default? 

> 
> >
> > >
> > > >
> > > >> Maybe some really fancy future LSM would also want loff_t
> > > >> source_offset, but it's probably not terribly useful.  This same
> > > >> callback would be used for EAUG.
> >
> > EAUG always zeroes the EPC page before making it available to an enclave. So I don't
> think there's anything needed to done here.
> 
> Duh.  So security_enclave_load_zeros() for EAUG.  See below.
> 
> >
> > > >>
> > > >> Following up on your discussion with Cedric about sigstruct, the
> > > >> other callback would be something like:
> > > >>
> > > >> int security_enclave_init(struct file *sigstruct_file);
> >
> > I'd still insist in using a pointer rather than a file, for reasons that we've discussed
> before. For those who can't recall, the major reason is that most implementation would
> embed SIGSTRUCT into the same file as the enclave (or at least I don't want to prevent
> anyone from doing so), which could also be part of another file, such as a shared object
> or even the main executable itself. It could be difficult to obtain a fd in those cases.
> memfd won't work because it can't retain the same attributes of the original file
> containing the SIGSTRUCT.
> >
> > After all, what matters is the attributes associated with the backing file, which could
> be easily retrieve from vm_file of the covering VMA. So for the sake of flexibility, let's
> stay with what we've agreed before - a pointer to SIGSTRUCT.
> 
> I'm okay with this, except for one nastiness: there's a big difference between a file that
> is just a sigstruct and a file that contains essentially arbitrary data plus a sigstruct
> at an arbitrary offset.
> We could do something tricky like saying that SIGSTRUCT can be in a file that's just a
> SIGSTRUCT or it can be in a special SIGSTRUCT ELF note in a file that isn't just a
> SIGSTRUCT, but that could be annoyingly restrictive.

Agreed. Approving a file implies approving all SIGSTRUCTs within that file. But I guess it wouldn't cause practical problems.

> 
> If it's going to be in an arbitrary file, then I think the signature needs to be more like:
> 
> int security_enclave_init(struct vm_area_struct *sigstruct_vma, loff_t sigstruct_offset,
> const sgx_sigstruct *sigstruct);
> 
> So that the LSM still has the opportunity to base its decision on the contents of the
> SIGSTRUCT.  Actually, we need that change regardless.

Wouldn't the pair of { sigstruct_vma, sigstruct_offset } be the same as just a pointer, because the VMA could be looked up using the pointer and the offset would then be (pointer - vma->vm_start)?

> 
> >
> > > >>
> > > >> The main issue I see is that we also want to control the
> > > >> enclave's ability to have RWX pages or to change a W page to X.
> > > >> We might also
> > > >> want:
> > > >>
> > > >> int security_enclave_load_zeros(unsigned int maxperm);
> > > >
> > > > What's the use case for this?  @maxperm will always be at least RW
> > > > in this case, otherwise the page is useless to the enclave, and if
> > > > the enclave can write the page, the fact that it started as zeros
> > > > is irrelevant.
> > >
> > > This is how EAUG could ask if RWX is okay. If an enclave is
> > > internally doing dynamic loading, the it will need a heap page with
> > > maxperm = RWX.  (If it’s well designed, it will make it RW and then
> > > RX, either by changing SECINFO or by asking the host to mprotect() it, but it still
> needs the overall RWX mask.).
> >
> > Any new page EAUG'ed will start in RW (as dictated by SGX ISA). EACCEPTCOPY will then
> change it to RX. RWX is never needed for all practical purposes. This in fact could be
> gated by mprotect() and the attributes associated with /dev/sgx/enclave. In the case of
> SELinux, FILE__EXECMOD is the right attribute and mprotect() will take care of all the
> rest. I don't see why the driver need a role here.
> 
> I find the SDM's discussion of EAUG, EACCEPT, and EACCEPTCOPY to be extremely confusing.
> My copy of the SDM has EACCEPT's SECINFO argument as "Read access permitted by Non
> Enclave".  Is that an error?

I'm confused by those descriptions too. Guess I cannot comment if that's an error or not.

Anyway, per our internal documents, for EAUG, SECINFO has to be set to PT_REG|RW. For EACCEPT, SGX ISA compares supplied SECINFO with EPCM attributes and returns an error if they don't match. EACCEPTCOPY only works on pending pages (i.e. SECINFO.P must be set), and sets EPCM access permissions to whatever supplied in SECINFO. 
 
>  And is EACCEPTCOPY just EACCEPT + memcpy or is there some other fundamental difference?
> 38.5.7 doesn't even mention EACCEPTCOPY.

2 differences: 1) EACCEPT only *compares* but EACCEPTCOPY *sets* EPCM permissions; and 2) EACCEPTCOPY does EACCEPT+memcpy atomically.
 
> 
> Anyway, all my confusion aside, I was talking about the page table, not the EPCM.  I think
> the enclave should need permission to write its own content into a page that will ever
> become X, and the enclave's untrusted host library would do this by adding the page with
> MAXPERM=RWX and then mapping/mprotecting it as PROT_WRITE and then (later or
> simultaneously) PROT_EXEC.

I was talking about the same thing. A code page in EPC will start in RW (both EPCM and PTE) and end in RX (both EPCM and PTE). EACCEPTCOPY takes care of EPCM, while mprotect() could take care of PTE as long as /dev/sgx/enclave has FILE__EXECMOD.

I understand your intention to enclave pages to segments with different MAXPERMs. My concern is though the host process may not always have a priori knowledge on which ranges to be used as code vs. data. After all, only the weakest link matters in security so I think what a host process cares would be whether the enclave loads code dynamically, or expands its data segments only, or neither. And for that reason, I think it more "user friendly" to keep just one MAXPERM - i.e. the most permissive one. Then we could associate that with /dev/sgx/enclave so as to relieve the driver from keeping track of too many things. 

> 
> Since SGX2 doesn't seem to have a way to add an initialized page to EPC after an enclave
> starts, I guess that it's impossible to have the enclave do something like dlopen()
> without MAXPERM=RWX.  So be it.

That's true. The reason behind it is SGX doesn’t trust anything from outside. So non-predetermined contents must be measured (e.g. EADD+EEXTEND), but it's hard to measure (or attest to) dynamically added contents so we decided to allow predetermined contents (i.e. all zeros in the case of EAUG) only.
 
> Maybe someone will find this annoying someday and SGX3 will add EAUG-but-don't-zero and
> EACCEPT-with-existing-contents.

From security perspective, accepting a page that is measured/hashed to XYZ is equivalent to overwriting that page with content hashed to XYZ. EACCEPTCOPY actually does the latter. The annoying part is due to the mismatch between SGX ISA and the s/w model adopted by LSM, but that has nothing to do with security. 

> 
> >
> > >
> > > Also, do real SGX1 enclave formats have BSS? If so, then either we
> > > need an ioctl or load zeros or user code is going to load from
> > > /dev/zero or just from the heap, but the LSM is going to play better
> > > with an ioctl, I suspect :)
> >
> > Yes, it does. But an enclave would either measure BSS, in which case the initial bytes
> have to be zero or MRENCLAVE will change; or zero BSS explicitly in its initialization
> code.
> >
> > But from LSM's perspective it makes no difference than EADD'ing a page with non-zero
> content. And security_enclave_load(NULL, RW) would take care of it in exactly in the same
> way.
> 
> Sure, I suppose the same hook with NULL parameters would be equivalent.
> 
> >
> > >
> > > >
> > > >> An enclave that's going to modify its own code will need memory
> > > >> with maxperm = RWX or WX.
> >
> > With SGX2/EDMM, RWX is *never* needed for all practical purposes.
> >
> > In theory, in terms of security, no page shall be made executable while it is still
> being prepared. So W and X shall always be mutually exclusive, regardless it's in EPC or
> regular memory.
> >
> > RWX is only needed in SGX1, as a workaround for certain usages, because EPCM permissions
> can never change at runtime.
> 
> As above, I think I disagree.  MAXPERM is intended as an upper bound on the permissions
> that a page can ever have, at least until it's EREMOVEd and re-added.  Since there's no
> EAUG-but-don't-zero, EAUG with MAXPERM.W=0 is basically useless because the page can never
> contain anything other than zeros, so a dynamically allocated page that is ever executed
> has to have MAXPERM=RWX or MAXPERM=WX.  And that will need special permissions, which I
> think is consistent with your recent emails on how this could all map to SELinux
> permissions.

I'm totally with you. What I was trying to say was that only W or X would be needed at any given time. That said, MAXPERM=RWX but PROCESS__EXECMEM will not be needed, while FILE__EXECMOD will be needed only on /dev/sgx/enclave. So the inherent risk is contained. 

> 
> >
> > > >>
> > > >> But this is a bit awkward if the LSM's decision depends on the
> > > >> sigstruct.  We could get fancy and require that the sigstruct be
> > > >> supplied before any EADD operations so that the maxperm decisions
> > > >> can depend on the sigstruct.
> > > >>
> > > >> Am I making more sense now?
> > > >
> > > > Yep.  Requiring .sigstruct at ECREATE would be trivial.  If we
> > > > wanted flexibility we could do:
> > > >
> > > >   int security_enclave_load(struct file *file, struct vm_area_struct *vma,
> > > >                             unsigned long prot);
> > > >
> > > > And for ultimate flexibility we could pass both .sigstruct and the
> > > > file pointer for /dev/sgx/enclave, but that seems a bit ridiculous.
> > >
> > > I agree.
> >
> > Loosely speaking, an enclave (including initial contents of all of its pages and their
> permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision resistant
> property of SHA-2). So only one is needed for a decision, and either one would lead to the
> same decision. So I don't see anything making any sense here.
> >
> > Theoretically speaking, if LSM can make a decision at EINIT by means of
> security_enclave_load(), then security_enclave_load() is never needed.
> >
> > In practice, I support keeping both because security_enclave_load() can only approve an
> enumerable set while security_enclave_load() can approve a non-enumerable set of enclaves.
> Moreover, in order to determine the validity of a MRENCLAVE (as in development of a policy
> or in creation of a white/black list), system admins will need the audit log produced by
> security_enclave_load().
> 
> I'm confused.  Things like MRSIGNER aren't known until the SIGSTRUCT shows up.  Also,
> security_enclave_load() provides no protection against loading a mishmash of two different
> enclave files.  I see
> security_enclave_init() as "verify this SIGSTRUCT against your policy on who may sign
> enclaves and/or grant EXECMOD depending on SIGSTRUCT"
> and security_enclave_load() as "implement your EXECMOD / EXECUTE / WRITE / whatever policy
> and possibly check enclave files for some label."

Sorry for the confusion. I was saying the same thing except that the decision of security_enclave_load() doesn't have to depend on SIGSTRUCT. Given your prototype of security_enclave_load(), I think we are on the same page. I made the above comment to object to the idea of "require that the sigstruct be supplied before any EADD operations so that the maxperm decisions can depend on the sigstruct".

> 
> >
> > >
> > > >
> > > > Passing both would allow tying EXECMOD to /dev/sgx/enclave as
> > > > Cedric wanted (without having to play games and pass
> > > > /dev/sgx/enclave to security_enclave_load()), but I don't think
> > > > there's anything fundamentally broken with using .sigstruct for
> > > > EXECMOD.  It requires more verbose labeling, but that's not a bad thing.
> > >
> > > The benefit of putting it on .sigstruct is that it can be per-enclave.
> > >
> > > As I understand it from Fedora packaging, the way this works on
> > > distros is generally that a package will include some files and
> > > their associated labels, and, if the package needs EXECMOD, then the
> > > files are labeled with EXECMOD and the author of the relevant code might get a dirty
> look.
> > >
> > > This could translate to the author of an exclave that needs RWX
> > > regions getting a dirty look without leaking this permission into other enclaves.
> > >
> > > (In my opinion, the dirty looks are actually the best security
> > > benefit of the entire concept of LSMs making RWX difficult.  A
> > > sufficiently creative attacker can almost always bypass W^X
> > > restrictions once they’ve pwned you, but W^X makes it harder to pwn
> > > you in the first place, and SELinux makes it really obvious when
> > > packaging a program that doesn’t respect W^X.  The upshot is that a
> > > lot of programs got fixed.)
> >
> > I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX, i.e.
> FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM.
> 
> Hmm.  If we want to make this distinction, we need something a big richer than my proposed
> callbacks.  A check of the actual mprotect() /
> mmap() permissions would also be needed.  Specifically, allowing MAXPERM=RWX wouldn't
> imply that PROT_WRITE | PROT_EXEC is allowed.

If we keep only one MAXPERM, wouldn't this be the current behavior of mmap()/mprotect()?

To be a bit more clear, system admin sets MAXPERM upper bound in the form of FILE__{READ|WRITE|EXECUTE|EXECMOD} of /dev/sgx/enclave. Then for a process/enclave, if what it requires falls below what's allowed on /dev/sgx/enclave, then everything will just work. Otherwise, it fails in the form of -EPERM returned from mmap()/mprotect(). Please note that MAXPERM here applies to "runtime" permissions, while "initial" permissions are taken care of by security_enclave_{load|init}. "initial" permissions could be more permissive than "runtime" permissions, e.g., RX is still required for initial code pages even though system admins could disable dynamically loaded code pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial" mapping would still have to be done by the driver (to bypass LSM), either via a new ioctl or as part of IOC_EINIT.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 14:17                                                                                     ` Sean Christopherson
  2019-05-23 15:38                                                                                       ` Andy Lutomirski
  2019-05-23 19:58                                                                                       ` Sean Christopherson
@ 2019-05-27 13:34                                                                                       ` Jarkko Sakkinen
  2019-05-27 13:38                                                                                         ` Jarkko Sakkinen
  2 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-27 13:34 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Thu, May 23, 2019 at 07:17:52AM -0700, Sean Christopherson wrote:
>   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.

What it'd break to return error if mmap() is done before EINIT?

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

Right now you can do multiple mmap's. If the mmap's must be done after
EINIT, the driver could check that permissions match the permissions in
that range.

This leaves open how to deal with mprotect() but if the process does not
have FILE__WRITE I guess you cannot do much.

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

For me it looks that allowing mmap's only after EINIT would result the
least confusing implemntation.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-27 13:34                                                                                       ` Jarkko Sakkinen
@ 2019-05-27 13:38                                                                                         ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-27 13:38 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman, Xing,
	Cedric, Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds,
	LKML, X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum,
	Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko,
	Svahn, Kai, Borislav Petkov, Josh Triplett, Huang, Kai,
	David Rientjes

On Mon, May 27, 2019 at 04:34:31PM +0300, Jarkko Sakkinen wrote:
> On Thu, May 23, 2019 at 07:17:52AM -0700, Sean Christopherson wrote:
> >   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.
> 
> What it'd break to return error if mmap() is done before EINIT?
> 
> >   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.
> 
> Right now you can do multiple mmap's. If the mmap's must be done after
> EINIT, the driver could check that permissions match the permissions in
> that range.
> 
> This leaves open how to deal with mprotect() but if the process does not
> have FILE__WRITE I guess you cannot do much.
> 
> >   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.
> 
> For me it looks that allowing mmap's only after EINIT would result the
> least confusing implemntation.

Obvious problem is of course the requirement of fixed mapping, which is
of course nasty.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-23 15:38                                                                                       ` Andy Lutomirski
  2019-05-23 23:40                                                                                         ` Sean Christopherson
  2019-05-24 14:44                                                                                         ` Stephen Smalley
@ 2019-05-27 13:48                                                                                         ` Jarkko Sakkinen
  2 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-05-27 13:48 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Sean Christopherson, Stephen Smalley, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Xing, Cedric, Hansen, Dave, Thomas Gleixner,
	Dr. Greg, Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton,
	nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, Andy Shevchenko, Svahn, Kai, Borislav Petkov,
	Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 23, 2019 at 08:38:17AM -0700, Andy Lutomirski wrote:
> On Thu, May 23, 2019 at 7:17 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Thu, May 23, 2019 at 01:26:28PM +0300, Jarkko Sakkinen wrote:
> > > On Wed, May 22, 2019 at 07:35:17PM -0700, Sean Christopherson wrote:
> > > > 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.
> >
> 
> 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.

How to deny mprotect()? struct file_operations does not have callback
for that (AFAIK).

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

What if instead simply:

- Require to do PROT_NONE mmap() for the ELRANGE before ECREATE.
- Disallow mprotect() up until EINIT.
- Given that we have a callback for mprotect() check that permissions
  match EADD'd permissions.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-26  6:09                                                                                                                     ` Xing, Cedric
@ 2019-05-28 20:24                                                                                                                       ` Sean Christopherson
  2019-05-28 20:48                                                                                                                         ` Andy Lutomirski
  2019-05-29 14:08                                                                                                                         ` Stephen Smalley
  0 siblings, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-28 20:24 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, Stephen Smalley, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Sat, May 25, 2019 at 11:09:38PM -0700, Xing, Cedric wrote:
> > From: Andy Lutomirski [mailto:luto@kernel.org]
> > Sent: Saturday, May 25, 2019 5:58 PM
> > 
> > On Sat, May 25, 2019 at 3:40 PM Xing, Cedric <cedric.xing@intel.com> wrote:
> > >
> > > If we think of EADD as a way of mmap()'ing an enclave file into memory,
> > > would this
> > security_enclave_load() be the same as
> > security_mmap_file(source_vma->vm_file, maxperm, MAP_PRIVATE), except that
> > the target is now EPC instead of regular pages?
> > 
> > Hmm, that's clever.  Although it seems plausible that an LSM would want to
> > allow RX or RWX of a given file page but only in the context of an approved
> > enclave, so I think it should still be its own hook.
> 
> What do you mean by "in the context of an approved enclave"? EPC pages are
> *inaccessible* to any software until after EINIT. So it would never be a
> security concern to EADD a page with wrong permissions as long as the enclave
> would be denied eventually by LSM at EINIT.
> 
> But I acknowledge the difference between loading a page into regular memory
> vs. into EPC. So it's beneficial to have a separate hook, which if not
> hooked, would pass through to security_mmap_file() by default? 

Mapping the enclave will still go through security_mmap_file(), the extra
security_enclave_load() hook allows the mmap() to use PROT_NONE.

> > If it's going to be in an arbitrary file, then I think the signature needs to be more like:
> > 
> > int security_enclave_init(struct vm_area_struct *sigstruct_vma, loff_t sigstruct_offset,
> > const sgx_sigstruct *sigstruct);
> > 
> > So that the LSM still has the opportunity to base its decision on the contents of the
> > SIGSTRUCT.  Actually, we need that change regardless.
> 
> Wouldn't the pair of { sigstruct_vma, sigstruct_offset } be the same as just
> a pointer, because the VMA could be looked up using the pointer and the
> offset would then be (pointer - vma->vm_start)?

VMA has vm_file, e.g. the .sigstruct file labeled by LSMs.  That being
said, why does the LSM need the VMA?  E.g. why not this?

  int security_enclave_init(struct file *file, struct sgx_sigstruct *sigstruct);

> > > Loosely speaking, an enclave (including initial contents of all of its pages and their
> > permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision resistant
> > property of SHA-2). So only one is needed for a decision, and either one would lead to the
> > same decision. So I don't see anything making any sense here.
> > >
> > > Theoretically speaking, if LSM can make a decision at EINIT by means of
> > security_enclave_load(), then security_enclave_load() is never needed.
> > >
> > > In practice, I support keeping both because security_enclave_load() can only approve an
> > enumerable set while security_enclave_load() can approve a non-enumerable set of enclaves.
> > Moreover, in order to determine the validity of a MRENCLAVE (as in development of a policy
> > or in creation of a white/black list), system admins will need the audit log produced by
> > security_enclave_load().
> > 
> > I'm confused.  Things like MRSIGNER aren't known until the SIGSTRUCT shows
> > up.  Also, security_enclave_load() provides no protection against loading a
> > mishmash of two different enclave files.  I see security_enclave_init() as
> > "verify this SIGSTRUCT against your policy on who may sign enclaves and/or
> > grant EXECMOD depending on SIGSTRUCT" and security_enclave_load() as
> > "implement your EXECMOD / EXECUTE / WRITE / whatever policy and possibly
> > check enclave files for some label."
> 
> Sorry for the confusion. I was saying the same thing except that the decision
> of security_enclave_load() doesn't have to depend on SIGSTRUCT. Given your
> prototype of security_enclave_load(), I think we are on the same page. I made
> the above comment to object to the idea of "require that the sigstruct be
> supplied before any EADD operations so that the maxperm decisions can depend
> on the sigstruct".

Except that having the sigstruct allows using the sigstruct as the proxy
for the enclave.  I think the last big disconnect is that Andy and I want
to tie everything to an enclave-specific file, i.e. sigstruct, while you
are proposing labeling /dev/sgx/enclave.  If someone wants to cram several
sigstructs into a single file, so be it, but using /dev/sgx/enclave means
users can't do per-enclave permissions, period.

What is your objection to working on the sigstruct?  

> > > > > Passing both would allow tying EXECMOD to /dev/sgx/enclave as
> > > > > Cedric wanted (without having to play games and pass
> > > > > /dev/sgx/enclave to security_enclave_load()), but I don't think
> > > > > there's anything fundamentally broken with using .sigstruct for
> > > > > EXECMOD.  It requires more verbose labeling, but that's not a bad thing.
> > > >
> > > > The benefit of putting it on .sigstruct is that it can be per-enclave.
> > > >
> > > > As I understand it from Fedora packaging, the way this works on
> > > > distros is generally that a package will include some files and
> > > > their associated labels, and, if the package needs EXECMOD, then the
> > > > files are labeled with EXECMOD and the author of the relevant code might get a dirty
> > look.
> > > >
> > > > This could translate to the author of an exclave that needs RWX
> > > > regions getting a dirty look without leaking this permission into other enclaves.
> > > >
> > > > (In my opinion, the dirty looks are actually the best security
> > > > benefit of the entire concept of LSMs making RWX difficult.  A
> > > > sufficiently creative attacker can almost always bypass W^X
> > > > restrictions once they’ve pwned you, but W^X makes it harder to pwn
> > > > you in the first place, and SELinux makes it really obvious when
> > > > packaging a program that doesn’t respect W^X.  The upshot is that a
> > > > lot of programs got fixed.)
> > >
> > > I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX, i.e.
> > FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM.
> > 
> > Hmm.  If we want to make this distinction, we need something a big richer
> > than my proposed callbacks.  A check of the actual mprotect() / mmap()
> > permissions would also be needed.  Specifically, allowing MAXPERM=RWX
> > wouldn't imply that PROT_WRITE | PROT_EXEC is allowed.

Actually, I think we do have everything we need from an LSM perspective.
LSMs just need to understand that sgx_enclave_load() with a NULL vma
implies a transition from RW.  For example, SELinux would interpret
sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.

As Cedric mentioned earlier, the host process doesn't necessarily know
which pages will end up RW vs RX, i.e. sgx_enclave_load(NULL, RX)
already has to be invoked at runtime, and when that happens, the kernel
can take the opportunity to change the VMAs from MAY_RW to MAY_RX.

For simplicity in the kernel and clarity in userspace, it makes sense to
require an explicit ioctl() to add the to-be-EAUG'd range.  That just
leaves us wanting an ioctl() to set the post-EACCEPT{COPY} permissions.

E.g.:

    ioctl(<prefix>_ADD_REGION, { NULL }) /* NULL == EAUG, MAY_RW */

    mprotect(addr, size, RW);
    ...

    EACCEPTCOPY -> EAUG /* page fault handler */

    ioctl(<prefix>_ACTIVATE_REGION, { addr, size, RX}) /* MAY_RX */

    mprotect(addr, size, RX);

    ... 

And making ACTIVATE_REGION a single-shot per page eliminates the need for
the MAXPERMS concept (see below).

> If we keep only one MAXPERM, wouldn't this be the current behavior of
> mmap()/mprotect()?
>
> To be a bit more clear, system admin sets MAXPERM upper bound in the form of
> FILE__{READ|WRITE|EXECUTE|EXECMOD} of /dev/sgx/enclave. Then for a
> process/enclave, if what it requires falls below what's allowed on
> /dev/sgx/enclave, then everything will just work. Otherwise, it fails in the
> form of -EPERM returned from mmap()/mprotect(). Please note that MAXPERM here
> applies to "runtime" permissions, while "initial" permissions are taken care
> of by security_enclave_{load|init}. "initial" permissions could be more
> permissive than "runtime" permissions, e.g., RX is still required for initial
> code pages even though system admins could disable dynamically loaded code
> pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial"
> mapping would still have to be done by the driver (to bypass LSM), either via
> a new ioctl or as part of IOC_EINIT.

Aha!

Starting with Cedric's assertion that initial permissions can be taken
directly from SECINFO:

  - Initial permissions for *EADD* pages are explicitly handled via
    sgx_enclave_load() with the exact SECINFO permissions.

  - Initial permissions for *EAUG* are unconditionally RW.  EACCEPTCOPY
    requires the target EPC page to be RW, and EACCEPT with RO is useless.

  - Runtime permissions break down as follows:
      R   - N/A, subset of RW (EAUG)
      W   - N/A, subset of RW (EAUG) and x86 paging can't do W
      X   - N/A, subset of RX (x86 paging can't do XO)
      RW  - Handled by EAUG LSM hook (uses RW unconditionally)
      WX  - N/A, subset of RWX (x86 paging can't do WX)
      RX  - Handled by ACTIVATE_REGION
      RWX - Handled by ACTIVATE_REGION

In other words, if we define the SGX -> LSM calls as follows (minus the
file pointer and other params for brevity):

  - <prefix>_ACTIVATE_REGION(vma, perms) -> sgx_enclave_load(NULL, perms)

  - <prefix>_ADD_REGION(vma) -> sgx_enclave_load(vma, SECINFO.perms)

  - <prefix>_ADD_REGION(NULL) -> sgx_enclave_load(NULL, RW)

then SGX and LSMs have all the information and hooks needed.  The catch
is that the LSM semantics of sgx_enclave_load(..., RW) would need to be
different than normal shared memory, e.g. FILE__WRITE should *not* be
required, but that's ok since it's an SGX specific hook.  And if for some
reason an LSM wanted to gate access to EAUG *without* FILE__EXECMOD, it'd
have the necessary information to do so.

The userspace changes are fairly minimal:

  - For SGX1, use PROT_NONE for the initial mmap() and refactor ADD_PAGE
    to ADD_REGION.

  - For SGX2, do an explicit ADD_REGION on the ranges to be EAUG'd, and an
    ACTIVATE_REGION to make a region RX or R (no extra ioctl() required to
    keep RW permissions).

Because ACTIVATE_REGION can only be done once per page, to do *abitrary*
mprotect() transitions, userspace would need to set the added/activated
permissions to be a superset of the transitions, e.g. RW -> RX would
require RWX, but that's a non-issue.

  - For SGX1 it's a nop since it's impossible to change the EPCM
    permissions, i.e. the page would need to be RWX regardless.

  - For SGX2, userspace can suck it up and request RWX to do completely
    arbitrary transitions (working as intended), or the kernel can support
    trimming (removing) pages from an enclave, which would allow userspace
    to do "arbitrary" transitions by first removing the page.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-28 20:24                                                                                                                       ` Sean Christopherson
@ 2019-05-28 20:48                                                                                                                         ` Andy Lutomirski
  2019-05-28 21:41                                                                                                                           ` Sean Christopherson
  2019-05-29 14:08                                                                                                                         ` Stephen Smalley
  1 sibling, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-28 20:48 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, Andy Lutomirski, Stephen Smalley, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Tue, May 28, 2019 at 1:24 PM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Sat, May 25, 2019 at 11:09:38PM -0700, Xing, Cedric wrote:
> > > From: Andy Lutomirski [mailto:luto@kernel.org]
> > > Sent: Saturday, May 25, 2019 5:58 PM
> > >
> > > On Sat, May 25, 2019 at 3:40 PM Xing, Cedric <cedric.xing@intel.com> wrote:
> > > >
> > > > If we think of EADD as a way of mmap()'ing an enclave file into memory,
> > > > would this
> > > security_enclave_load() be the same as
> > > security_mmap_file(source_vma->vm_file, maxperm, MAP_PRIVATE), except that
> > > the target is now EPC instead of regular pages?
> > >
> > > Hmm, that's clever.  Although it seems plausible that an LSM would want to
> > > allow RX or RWX of a given file page but only in the context of an approved
> > > enclave, so I think it should still be its own hook.
> >
> > What do you mean by "in the context of an approved enclave"? EPC pages are
> > *inaccessible* to any software until after EINIT. So it would never be a
> > security concern to EADD a page with wrong permissions as long as the enclave
> > would be denied eventually by LSM at EINIT.
> >
> > But I acknowledge the difference between loading a page into regular memory
> > vs. into EPC. So it's beneficial to have a separate hook, which if not
> > hooked, would pass through to security_mmap_file() by default?
>
> Mapping the enclave will still go through security_mmap_file(), the extra
> security_enclave_load() hook allows the mmap() to use PROT_NONE.
>
> > > If it's going to be in an arbitrary file, then I think the signature needs to be more like:
> > >
> > > int security_enclave_init(struct vm_area_struct *sigstruct_vma, loff_t sigstruct_offset,
> > > const sgx_sigstruct *sigstruct);
> > >
> > > So that the LSM still has the opportunity to base its decision on the contents of the
> > > SIGSTRUCT.  Actually, we need that change regardless.
> >
> > Wouldn't the pair of { sigstruct_vma, sigstruct_offset } be the same as just
> > a pointer, because the VMA could be looked up using the pointer and the
> > offset would then be (pointer - vma->vm_start)?
>
> VMA has vm_file, e.g. the .sigstruct file labeled by LSMs.  That being
> said, why does the LSM need the VMA?  E.g. why not this?
>
>   int security_enclave_init(struct file *file, struct sgx_sigstruct *sigstruct);
>
> > > > Loosely speaking, an enclave (including initial contents of all of its pages and their
> > > permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision resistant
> > > property of SHA-2). So only one is needed for a decision, and either one would lead to the
> > > same decision. So I don't see anything making any sense here.
> > > >
> > > > Theoretically speaking, if LSM can make a decision at EINIT by means of
> > > security_enclave_load(), then security_enclave_load() is never needed.
> > > >
> > > > In practice, I support keeping both because security_enclave_load() can only approve an
> > > enumerable set while security_enclave_load() can approve a non-enumerable set of enclaves.
> > > Moreover, in order to determine the validity of a MRENCLAVE (as in development of a policy
> > > or in creation of a white/black list), system admins will need the audit log produced by
> > > security_enclave_load().
> > >
> > > I'm confused.  Things like MRSIGNER aren't known until the SIGSTRUCT shows
> > > up.  Also, security_enclave_load() provides no protection against loading a
> > > mishmash of two different enclave files.  I see security_enclave_init() as
> > > "verify this SIGSTRUCT against your policy on who may sign enclaves and/or
> > > grant EXECMOD depending on SIGSTRUCT" and security_enclave_load() as
> > > "implement your EXECMOD / EXECUTE / WRITE / whatever policy and possibly
> > > check enclave files for some label."
> >
> > Sorry for the confusion. I was saying the same thing except that the decision
> > of security_enclave_load() doesn't have to depend on SIGSTRUCT. Given your
> > prototype of security_enclave_load(), I think we are on the same page. I made
> > the above comment to object to the idea of "require that the sigstruct be
> > supplied before any EADD operations so that the maxperm decisions can depend
> > on the sigstruct".
>
> Except that having the sigstruct allows using the sigstruct as the proxy
> for the enclave.  I think the last big disconnect is that Andy and I want
> to tie everything to an enclave-specific file, i.e. sigstruct, while you
> are proposing labeling /dev/sgx/enclave.  If someone wants to cram several
> sigstructs into a single file, so be it, but using /dev/sgx/enclave means
> users can't do per-enclave permissions, period.
>
> What is your objection to working on the sigstruct?
>
> > > > > > Passing both would allow tying EXECMOD to /dev/sgx/enclave as
> > > > > > Cedric wanted (without having to play games and pass
> > > > > > /dev/sgx/enclave to security_enclave_load()), but I don't think
> > > > > > there's anything fundamentally broken with using .sigstruct for
> > > > > > EXECMOD.  It requires more verbose labeling, but that's not a bad thing.
> > > > >
> > > > > The benefit of putting it on .sigstruct is that it can be per-enclave.
> > > > >
> > > > > As I understand it from Fedora packaging, the way this works on
> > > > > distros is generally that a package will include some files and
> > > > > their associated labels, and, if the package needs EXECMOD, then the
> > > > > files are labeled with EXECMOD and the author of the relevant code might get a dirty
> > > look.
> > > > >
> > > > > This could translate to the author of an exclave that needs RWX
> > > > > regions getting a dirty look without leaking this permission into other enclaves.
> > > > >
> > > > > (In my opinion, the dirty looks are actually the best security
> > > > > benefit of the entire concept of LSMs making RWX difficult.  A
> > > > > sufficiently creative attacker can almost always bypass W^X
> > > > > restrictions once they’ve pwned you, but W^X makes it harder to pwn
> > > > > you in the first place, and SELinux makes it really obvious when
> > > > > packaging a program that doesn’t respect W^X.  The upshot is that a
> > > > > lot of programs got fixed.)
> > > >
> > > > I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX, i.e.
> > > FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM.
> > >
> > > Hmm.  If we want to make this distinction, we need something a big richer
> > > than my proposed callbacks.  A check of the actual mprotect() / mmap()
> > > permissions would also be needed.  Specifically, allowing MAXPERM=RWX
> > > wouldn't imply that PROT_WRITE | PROT_EXEC is allowed.
>
> Actually, I think we do have everything we need from an LSM perspective.
> LSMs just need to understand that sgx_enclave_load() with a NULL vma
> implies a transition from RW.  For example, SELinux would interpret
> sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.

You lost me here.  What operation triggers this callback?  And
wouldn't sgx_enclave_load(NULL, RX) sometimes be a transition from RO
or just some fresh executable zero bytes?

>
> As Cedric mentioned earlier, the host process doesn't necessarily know
> which pages will end up RW vs RX, i.e. sgx_enclave_load(NULL, RX)
> already has to be invoked at runtime, and when that happens, the kernel
> can take the opportunity to change the VMAs from MAY_RW to MAY_RX.
>
> For simplicity in the kernel and clarity in userspace, it makes sense to
> require an explicit ioctl() to add the to-be-EAUG'd range.  That just
> leaves us wanting an ioctl() to set the post-EACCEPT{COPY} permissions.
>
> E.g.:
>
>     ioctl(<prefix>_ADD_REGION, { NULL }) /* NULL == EAUG, MAY_RW */
>
>     mprotect(addr, size, RW);
>     ...
>
>     EACCEPTCOPY -> EAUG /* page fault handler */
>
>     ioctl(<prefix>_ACTIVATE_REGION, { addr, size, RX}) /* MAY_RX */
>
>     mprotect(addr, size, RX);

In the maxperm model, this mprotect() will fail unless MAXPERM
contains RX, which could only happen if MAXPERM=RWX.  So, regardless
of how it's actually mapped to SELinux policy, MAXPERM=RWX is
functionally like EXECMOD and actual RWX PTEs are functionally like
EXECMEM.

>
>     ...
>
> And making ACTIVATE_REGION a single-shot per page eliminates the need for
> the MAXPERMS concept (see below).
>
> > If we keep only one MAXPERM, wouldn't this be the current behavior of
> > mmap()/mprotect()?
> >
> > To be a bit more clear, system admin sets MAXPERM upper bound in the form of
> > FILE__{READ|WRITE|EXECUTE|EXECMOD} of /dev/sgx/enclave. Then for a
> > process/enclave, if what it requires falls below what's allowed on
> > /dev/sgx/enclave, then everything will just work. Otherwise, it fails in the
> > form of -EPERM returned from mmap()/mprotect(). Please note that MAXPERM here
> > applies to "runtime" permissions, while "initial" permissions are taken care
> > of by security_enclave_{load|init}. "initial" permissions could be more
> > permissive than "runtime" permissions, e.g., RX is still required for initial
> > code pages even though system admins could disable dynamically loaded code
> > pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial"
> > mapping would still have to be done by the driver (to bypass LSM), either via
> > a new ioctl or as part of IOC_EINIT.
>
> Aha!
>
> Starting with Cedric's assertion that initial permissions can be taken
> directly from SECINFO:
>
>   - Initial permissions for *EADD* pages are explicitly handled via
>     sgx_enclave_load() with the exact SECINFO permissions.
>
>   - Initial permissions for *EAUG* are unconditionally RW.  EACCEPTCOPY
>     requires the target EPC page to be RW, and EACCEPT with RO is useless.
>
>   - Runtime permissions break down as follows:
>       R   - N/A, subset of RW (EAUG)
>       W   - N/A, subset of RW (EAUG) and x86 paging can't do W
>       X   - N/A, subset of RX (x86 paging can't do XO)

Sure it can!  You just have a hypervisor that maps a PA bit to EPT
no-read.  Then you can use that PA bit to suppress read.  Also, Linux
already abuses PKRU to simulate XO, although that won't work for
enclaves.

>       RW  - Handled by EAUG LSM hook (uses RW unconditionally)
>       WX  - N/A, subset of RWX (x86 paging can't do WX)
>       RX  - Handled by ACTIVATE_REGION
>       RWX - Handled by ACTIVATE_REGION
>
> In other words, if we define the SGX -> LSM calls as follows (minus the
> file pointer and other params for brevity):
>
>   - <prefix>_ACTIVATE_REGION(vma, perms) -> sgx_enclave_load(NULL, perms)
>
>   - <prefix>_ADD_REGION(vma) -> sgx_enclave_load(vma, SECINFO.perms)
>
>   - <prefix>_ADD_REGION(NULL) -> sgx_enclave_load(NULL, RW)
>
> then SGX and LSMs have all the information and hooks needed.  The catch
> is that the LSM semantics of sgx_enclave_load(..., RW) would need to be
> different than normal shared memory, e.g. FILE__WRITE should *not* be
> required, but that's ok since it's an SGX specific hook.  And if for some
> reason an LSM wanted to gate access to EAUG *without* FILE__EXECMOD, it'd
> have the necessary information to do so.
>
> The userspace changes are fairly minimal:
>
>   - For SGX1, use PROT_NONE for the initial mmap() and refactor ADD_PAGE
>     to ADD_REGION.
>
>   - For SGX2, do an explicit ADD_REGION on the ranges to be EAUG'd, and an
>     ACTIVATE_REGION to make a region RX or R (no extra ioctl() required to
>     keep RW permissions).
>
> Because ACTIVATE_REGION can only be done once per page, to do *abitrary*
> mprotect() transitions, userspace would need to set the added/activated
> permissions to be a superset of the transitions, e.g. RW -> RX would
> require RWX, but that's a non-issue.
>

I may be misunderstanding or just be biased to my own proposal, but
this seems potentially more complicated and less flexible than the
MAXPERM model.  One of the main things that made me come up with
MAXPERM is that I wanted to avoid any complicated PTE/VMA modification
or runtime changes.  So, with MAXPERM, we still need to track the
MAXPERM bits per page, but we don't ever need to *change* them or to
worry about what is or is not mapped anywhere at any given time.  With
ACTIVATE_REGION, don't we need to make sure that we don't have a
second VMA pointing at the same pages?  Or am I just confused?

>   - For SGX1 it's a nop since it's impossible to change the EPCM
>     permissions, i.e. the page would need to be RWX regardless.

I may still be missing something, but, for SGX1, it's possible at
least in principle for the enclave to request, via ocall or similar,
that the untrusted runtime do mprotect().  It's not even such a bad
idea.  Honestly, enclaves *shouldn't* have anything actually writable
and executable at once because the enclaves don't want to be easily
exploited.

>
>   - For SGX2, userspace can suck it up and request RWX to do completely
>     arbitrary transitions (working as intended), or the kernel can support
>     trimming (removing) pages from an enclave, which would allow userspace
>     to do "arbitrary" transitions by first removing the page.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-28 20:48                                                                                                                         ` Andy Lutomirski
@ 2019-05-28 21:41                                                                                                                           ` Sean Christopherson
  2019-05-30  5:38                                                                                                                             ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-28 21:41 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Xing, Cedric, Stephen Smalley, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Tue, May 28, 2019 at 01:48:02PM -0700, Andy Lutomirski wrote:
> On Tue, May 28, 2019 at 1:24 PM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > Actually, I think we do have everything we need from an LSM perspective.
> > LSMs just need to understand that sgx_enclave_load() with a NULL vma
> > implies a transition from RW.  For example, SELinux would interpret
> > sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.
> 
> You lost me here.  What operation triggers this callback?  And
> wouldn't sgx_enclave_load(NULL, RX) sometimes be a transition from RO
> or just some fresh executable zero bytes?

An explicit ioctl() after EACCEPTCOPY to update the allowed permissions.
For all intents and purposes, the EAUG'd page must start RW.  Maybe a
better way to phrase it is that at some point the page must be writable
to have any value whatsover.  EACCEPTCOPY explicitly requires the page to
be at least RW.  EACCEPT technically doesn't require RW, but a RO or RX
zero page is useless.  Userspace could still EACCEPT with RO or RX, but
SGX would assume a minimum of RW for the purposes of the LSM check.

> > As Cedric mentioned earlier, the host process doesn't necessarily know
> > which pages will end up RW vs RX, i.e. sgx_enclave_load(NULL, RX)
> > already has to be invoked at runtime, and when that happens, the kernel
> > can take the opportunity to change the VMAs from MAY_RW to MAY_RX.
> >
> > For simplicity in the kernel and clarity in userspace, it makes sense to
> > require an explicit ioctl() to add the to-be-EAUG'd range.  That just
> > leaves us wanting an ioctl() to set the post-EACCEPT{COPY} permissions.
> >
> > E.g.:
> >
> >     ioctl(<prefix>_ADD_REGION, { NULL }) /* NULL == EAUG, MAY_RW */
> >
> >     mprotect(addr, size, RW);
> >     ...
> >
> >     EACCEPTCOPY -> EAUG /* page fault handler */
> >
> >     ioctl(<prefix>_ACTIVATE_REGION, { addr, size, RX}) /* MAY_RX */
> >
> >     mprotect(addr, size, RX);
> 
> In the maxperm model, this mprotect() will fail unless MAXPERM
> contains RX, which could only happen if MAXPERM=RWX.  So, regardless
> of how it's actually mapped to SELinux policy, MAXPERM=RWX is
> functionally like EXECMOD and actual RWX PTEs are functionally like
> EXECMEM.

Yep, same idea, except in the proposed flow ACTIVATE_REGION.

> >     ...
> >
> > And making ACTIVATE_REGION a single-shot per page eliminates the need for
> > the MAXPERMS concept (see below).
> >
> > > If we keep only one MAXPERM, wouldn't this be the current behavior of
> > > mmap()/mprotect()?
> > >
> > > To be a bit more clear, system admin sets MAXPERM upper bound in the form of
> > > FILE__{READ|WRITE|EXECUTE|EXECMOD} of /dev/sgx/enclave. Then for a
> > > process/enclave, if what it requires falls below what's allowed on
> > > /dev/sgx/enclave, then everything will just work. Otherwise, it fails in the
> > > form of -EPERM returned from mmap()/mprotect(). Please note that MAXPERM here
> > > applies to "runtime" permissions, while "initial" permissions are taken care
> > > of by security_enclave_{load|init}. "initial" permissions could be more
> > > permissive than "runtime" permissions, e.g., RX is still required for initial
> > > code pages even though system admins could disable dynamically loaded code
> > > pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial"
> > > mapping would still have to be done by the driver (to bypass LSM), either via
> > > a new ioctl or as part of IOC_EINIT.
> >
> > Aha!
> >
> > Starting with Cedric's assertion that initial permissions can be taken
> > directly from SECINFO:
> >
> >   - Initial permissions for *EADD* pages are explicitly handled via
> >     sgx_enclave_load() with the exact SECINFO permissions.
> >
> >   - Initial permissions for *EAUG* are unconditionally RW.  EACCEPTCOPY
> >     requires the target EPC page to be RW, and EACCEPT with RO is useless.
> >
> >   - Runtime permissions break down as follows:
> >       R   - N/A, subset of RW (EAUG)
> >       W   - N/A, subset of RW (EAUG) and x86 paging can't do W
> >       X   - N/A, subset of RX (x86 paging can't do XO)
> 
> Sure it can!  You just have a hypervisor that maps a PA bit to EPT
> no-read.  Then you can use that PA bit to suppress read.  Also, Linux
> already abuses PKRU to simulate XO, although that won't work for
> enclaves.

Heh, I intentionally said "x86 paging" to rule out EPT :-)  I'm pretty
sure it's a moot point though, I have a hard time believing an LSM will
allow RW->X and not RW->RX.

> >       RW  - Handled by EAUG LSM hook (uses RW unconditionally)
> >       WX  - N/A, subset of RWX (x86 paging can't do WX)
> >       RX  - Handled by ACTIVATE_REGION
> >       RWX - Handled by ACTIVATE_REGION
> >
> > In other words, if we define the SGX -> LSM calls as follows (minus the
> > file pointer and other params for brevity):
> >
> >   - <prefix>_ACTIVATE_REGION(vma, perms) -> sgx_enclave_load(NULL, perms)
> >
> >   - <prefix>_ADD_REGION(vma) -> sgx_enclave_load(vma, SECINFO.perms)
> >
> >   - <prefix>_ADD_REGION(NULL) -> sgx_enclave_load(NULL, RW)
> >
> > then SGX and LSMs have all the information and hooks needed.  The catch
> > is that the LSM semantics of sgx_enclave_load(..., RW) would need to be
> > different than normal shared memory, e.g. FILE__WRITE should *not* be
> > required, but that's ok since it's an SGX specific hook.  And if for some
> > reason an LSM wanted to gate access to EAUG *without* FILE__EXECMOD, it'd
> > have the necessary information to do so.
> >
> > The userspace changes are fairly minimal:
> >
> >   - For SGX1, use PROT_NONE for the initial mmap() and refactor ADD_PAGE
> >     to ADD_REGION.
> >
> >   - For SGX2, do an explicit ADD_REGION on the ranges to be EAUG'd, and an
> >     ACTIVATE_REGION to make a region RX or R (no extra ioctl() required to
> >     keep RW permissions).
> >
> > Because ACTIVATE_REGION can only be done once per page, to do *abitrary*
> > mprotect() transitions, userspace would need to set the added/activated
> > permissions to be a superset of the transitions, e.g. RW -> RX would
> > require RWX, but that's a non-issue.
> >
> 
> I may be misunderstanding or just be biased to my own proposal, but
> this seems potentially more complicated and less flexible than the
> MAXPERM model.  One of the main things that made me come up with
> MAXPERM is that I wanted to avoid any complicated PTE/VMA modification
> or runtime changes.  So, with MAXPERM, we still need to track the
> MAXPERM bits per page, but we don't ever need to *change* them or to
> worry about what is or is not mapped anywhere at any given time.  With
> ACTIVATE_REGION, don't we need to make sure that we don't have a
> second VMA pointing at the same pages?  Or am I just confused?

In theory, it's still your MAXPERM model, but with the unnecessary states
removed and the others enforced/handled by the natural SGX transitions
instead of explictly in ioctls.  Underneath the hood the SGX driver would
still need to track the MAXPERM.

With SGX1, SECINFO == MAXPERM.  With SGX2, ACTIVATE_REGION == MAXPERM,
with the implication that the previous state is always RW.

> >   - For SGX1 it's a nop since it's impossible to change the EPCM
> >     permissions, i.e. the page would need to be RWX regardless.
> 
> I may still be missing something, but, for SGX1, it's possible at
> least in principle for the enclave to request, via ocall or similar,
> that the untrusted runtime do mprotect().  It's not even such a bad
> idea.  Honestly, enclaves *shouldn't* have anything actually writable
> and executable at once because the enclaves don't want to be easily
> exploited.

Yes, but the *EPCM* permissions are immutable.  So if an enclave wants
to do RW->RX it has to intialize its pages to RWX.  And because the
untrusted runtime is, ahem, untrusted, the enclave cannot rely on
userspace to never map its pages RWX.  In other words, from a enclave
security perspective, an SGX1 enclave+runtime that uses RW->RX is no
different than an enclave that uses RWX.  Using your earlier terminology,
an SGX1 enclave *should* get a dirty looks if maps a page RWX in the EPCM,
even if it only intends RW->RX behavior.

> >   - For SGX2, userspace can suck it up and request RWX to do completely
> >     arbitrary transitions (working as intended), or the kernel can support
> >     trimming (removing) pages from an enclave, which would allow userspace
> >     to do "arbitrary" transitions by first removing the page.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-28 20:24                                                                                                                       ` Sean Christopherson
  2019-05-28 20:48                                                                                                                         ` Andy Lutomirski
@ 2019-05-29 14:08                                                                                                                         ` Stephen Smalley
  2019-05-30  6:12                                                                                                                           ` Xing, Cedric
  1 sibling, 1 reply; 318+ messages in thread
From: Stephen Smalley @ 2019-05-29 14:08 UTC (permalink / raw)
  To: Sean Christopherson, Xing, Cedric, William Roberts
  Cc: Andy Lutomirski, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 5/28/19 4:24 PM, Sean Christopherson wrote:
> On Sat, May 25, 2019 at 11:09:38PM -0700, Xing, Cedric wrote:
>>> From: Andy Lutomirski [mailto:luto@kernel.org]
>>> Sent: Saturday, May 25, 2019 5:58 PM
>>>
>>> On Sat, May 25, 2019 at 3:40 PM Xing, Cedric <cedric.xing@intel.com> wrote:
>>>>
>>>> If we think of EADD as a way of mmap()'ing an enclave file into memory,
>>>> would this
>>> security_enclave_load() be the same as
>>> security_mmap_file(source_vma->vm_file, maxperm, MAP_PRIVATE), except that
>>> the target is now EPC instead of regular pages?
>>>
>>> Hmm, that's clever.  Although it seems plausible that an LSM would want to
>>> allow RX or RWX of a given file page but only in the context of an approved
>>> enclave, so I think it should still be its own hook.
>>
>> What do you mean by "in the context of an approved enclave"? EPC pages are
>> *inaccessible* to any software until after EINIT. So it would never be a
>> security concern to EADD a page with wrong permissions as long as the enclave
>> would be denied eventually by LSM at EINIT.
>>
>> But I acknowledge the difference between loading a page into regular memory
>> vs. into EPC. So it's beneficial to have a separate hook, which if not
>> hooked, would pass through to security_mmap_file() by default?
> 
> Mapping the enclave will still go through security_mmap_file(), the extra
> security_enclave_load() hook allows the mmap() to use PROT_NONE.
> 
>>> If it's going to be in an arbitrary file, then I think the signature needs to be more like:
>>>
>>> int security_enclave_init(struct vm_area_struct *sigstruct_vma, loff_t sigstruct_offset,
>>> const sgx_sigstruct *sigstruct);
>>>
>>> So that the LSM still has the opportunity to base its decision on the contents of the
>>> SIGSTRUCT.  Actually, we need that change regardless.
>>
>> Wouldn't the pair of { sigstruct_vma, sigstruct_offset } be the same as just
>> a pointer, because the VMA could be looked up using the pointer and the
>> offset would then be (pointer - vma->vm_start)?
> 
> VMA has vm_file, e.g. the .sigstruct file labeled by LSMs.  That being
> said, why does the LSM need the VMA?  E.g. why not this?
> 
>    int security_enclave_init(struct file *file, struct sgx_sigstruct *sigstruct);
> 
>>>> Loosely speaking, an enclave (including initial contents of all of its pages and their
>>> permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision resistant
>>> property of SHA-2). So only one is needed for a decision, and either one would lead to the
>>> same decision. So I don't see anything making any sense here.
>>>>
>>>> Theoretically speaking, if LSM can make a decision at EINIT by means of
>>> security_enclave_load(), then security_enclave_load() is never needed.
>>>>
>>>> In practice, I support keeping both because security_enclave_load() can only approve an
>>> enumerable set while security_enclave_load() can approve a non-enumerable set of enclaves.
>>> Moreover, in order to determine the validity of a MRENCLAVE (as in development of a policy
>>> or in creation of a white/black list), system admins will need the audit log produced by
>>> security_enclave_load().
>>>
>>> I'm confused.  Things like MRSIGNER aren't known until the SIGSTRUCT shows
>>> up.  Also, security_enclave_load() provides no protection against loading a
>>> mishmash of two different enclave files.  I see security_enclave_init() as
>>> "verify this SIGSTRUCT against your policy on who may sign enclaves and/or
>>> grant EXECMOD depending on SIGSTRUCT" and security_enclave_load() as
>>> "implement your EXECMOD / EXECUTE / WRITE / whatever policy and possibly
>>> check enclave files for some label."
>>
>> Sorry for the confusion. I was saying the same thing except that the decision
>> of security_enclave_load() doesn't have to depend on SIGSTRUCT. Given your
>> prototype of security_enclave_load(), I think we are on the same page. I made
>> the above comment to object to the idea of "require that the sigstruct be
>> supplied before any EADD operations so that the maxperm decisions can depend
>> on the sigstruct".
> 
> Except that having the sigstruct allows using the sigstruct as the proxy
> for the enclave.  I think the last big disconnect is that Andy and I want
> to tie everything to an enclave-specific file, i.e. sigstruct, while you
> are proposing labeling /dev/sgx/enclave.  If someone wants to cram several
> sigstructs into a single file, so be it, but using /dev/sgx/enclave means
> users can't do per-enclave permissions, period.
> 
> What is your objection to working on the sigstruct?
> 
>>>>>> Passing both would allow tying EXECMOD to /dev/sgx/enclave as
>>>>>> Cedric wanted (without having to play games and pass
>>>>>> /dev/sgx/enclave to security_enclave_load()), but I don't think
>>>>>> there's anything fundamentally broken with using .sigstruct for
>>>>>> EXECMOD.  It requires more verbose labeling, but that's not a bad thing.
>>>>>
>>>>> The benefit of putting it on .sigstruct is that it can be per-enclave.
>>>>>
>>>>> As I understand it from Fedora packaging, the way this works on
>>>>> distros is generally that a package will include some files and
>>>>> their associated labels, and, if the package needs EXECMOD, then the
>>>>> files are labeled with EXECMOD and the author of the relevant code might get a dirty
>>> look.
>>>>>
>>>>> This could translate to the author of an exclave that needs RWX
>>>>> regions getting a dirty look without leaking this permission into other enclaves.
>>>>>
>>>>> (In my opinion, the dirty looks are actually the best security
>>>>> benefit of the entire concept of LSMs making RWX difficult.  A
>>>>> sufficiently creative attacker can almost always bypass W^X
>>>>> restrictions once they’ve pwned you, but W^X makes it harder to pwn
>>>>> you in the first place, and SELinux makes it really obvious when
>>>>> packaging a program that doesn’t respect W^X.  The upshot is that a
>>>>> lot of programs got fixed.)
>>>>
>>>> I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX, i.e.
>>> FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM.
>>>
>>> Hmm.  If we want to make this distinction, we need something a big richer
>>> than my proposed callbacks.  A check of the actual mprotect() / mmap()
>>> permissions would also be needed.  Specifically, allowing MAXPERM=RWX
>>> wouldn't imply that PROT_WRITE | PROT_EXEC is allowed.
> 
> Actually, I think we do have everything we need from an LSM perspective.
> LSMs just need to understand that sgx_enclave_load() with a NULL vma
> implies a transition from RW.  For example, SELinux would interpret
> sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.
> 
> As Cedric mentioned earlier, the host process doesn't necessarily know
> which pages will end up RW vs RX, i.e. sgx_enclave_load(NULL, RX)
> already has to be invoked at runtime, and when that happens, the kernel
> can take the opportunity to change the VMAs from MAY_RW to MAY_RX.
> 
> For simplicity in the kernel and clarity in userspace, it makes sense to
> require an explicit ioctl() to add the to-be-EAUG'd range.  That just
> leaves us wanting an ioctl() to set the post-EACCEPT{COPY} permissions.
> 
> E.g.:
> 
>      ioctl(<prefix>_ADD_REGION, { NULL }) /* NULL == EAUG, MAY_RW */
> 
>      mprotect(addr, size, RW);
>      ...
> 
>      EACCEPTCOPY -> EAUG /* page fault handler */
> 
>      ioctl(<prefix>_ACTIVATE_REGION, { addr, size, RX}) /* MAY_RX */
> 
>      mprotect(addr, size, RX);
> 
>      ...
> 
> And making ACTIVATE_REGION a single-shot per page eliminates the need for
> the MAXPERMS concept (see below).
> 
>> If we keep only one MAXPERM, wouldn't this be the current behavior of
>> mmap()/mprotect()?
>>
>> To be a bit more clear, system admin sets MAXPERM upper bound in the form of
>> FILE__{READ|WRITE|EXECUTE|EXECMOD} of /dev/sgx/enclave. Then for a
>> process/enclave, if what it requires falls below what's allowed on
>> /dev/sgx/enclave, then everything will just work. Otherwise, it fails in the
>> form of -EPERM returned from mmap()/mprotect(). Please note that MAXPERM here
>> applies to "runtime" permissions, while "initial" permissions are taken care
>> of by security_enclave_{load|init}. "initial" permissions could be more
>> permissive than "runtime" permissions, e.g., RX is still required for initial
>> code pages even though system admins could disable dynamically loaded code
>> pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial"
>> mapping would still have to be done by the driver (to bypass LSM), either via
>> a new ioctl or as part of IOC_EINIT.
> 
> Aha!
> 
> Starting with Cedric's assertion that initial permissions can be taken
> directly from SECINFO:
> 
>    - Initial permissions for *EADD* pages are explicitly handled via
>      sgx_enclave_load() with the exact SECINFO permissions.
> 
>    - Initial permissions for *EAUG* are unconditionally RW.  EACCEPTCOPY
>      requires the target EPC page to be RW, and EACCEPT with RO is useless.
> 
>    - Runtime permissions break down as follows:
>        R   - N/A, subset of RW (EAUG)
>        W   - N/A, subset of RW (EAUG) and x86 paging can't do W
>        X   - N/A, subset of RX (x86 paging can't do XO)
>        RW  - Handled by EAUG LSM hook (uses RW unconditionally)
>        WX  - N/A, subset of RWX (x86 paging can't do WX)
>        RX  - Handled by ACTIVATE_REGION
>        RWX - Handled by ACTIVATE_REGION
> 
> In other words, if we define the SGX -> LSM calls as follows (minus the
> file pointer and other params for brevity):
> 
>    - <prefix>_ACTIVATE_REGION(vma, perms) -> sgx_enclave_load(NULL, perms)
> 
>    - <prefix>_ADD_REGION(vma) -> sgx_enclave_load(vma, SECINFO.perms)
> 
>    - <prefix>_ADD_REGION(NULL) -> sgx_enclave_load(NULL, RW)
> 
> then SGX and LSMs have all the information and hooks needed.  The catch
> is that the LSM semantics of sgx_enclave_load(..., RW) would need to be
> different than normal shared memory, e.g. FILE__WRITE should *not* be
> required, but that's ok since it's an SGX specific hook.  And if for some
> reason an LSM wanted to gate access to EAUG *without* FILE__EXECMOD, it'd
> have the necessary information to do so.

Assuming that sgx_enclave_load() is a LSM hook (probably named 
security_enclave_load() instead), then:

a) Does the sigstruct file get passed to this hook in every case, even 
when vma is NULL?  I think the answer is yes, just want to confirm.

b) Should we use a different hook for ACTIVATE_REGION than for 
ADD_REGION or is the distinction between them irrelevant/unnecessary 
from an access control point of view? At present LSM/SELinux won't be 
able to distinguish ACTIVATE_REGION(vma, RW) from ADD_REGION(NULL) above 
since they will both invoke the same hook with the same arguments IIUC. 
Does it matter?  It's ok if the answer is no, just want to confirm.

c) Is there still also a separate security_enclave_init() hook that will 
be called, and if so, how does it differ and when is it called relative 
to security_enclave_load()?

d) What checks were you envisioning each of these calls making?

With the separate security_enclave_*() hooks, we could define and use 
new ENCLAVE__* permissions, e.g. ENCLAVE__LOAD, ENCLAVE__INIT, 
ENCLAVE__EXECUTE, ENCLAVE__EXECMEM, ENCLAVE__EXECMOD, if we want to 
distinguish these operations from regular file mmap/mprotect operations.

> 
> The userspace changes are fairly minimal:
> 
>    - For SGX1, use PROT_NONE for the initial mmap() and refactor ADD_PAGE
>      to ADD_REGION.
> 
>    - For SGX2, do an explicit ADD_REGION on the ranges to be EAUG'd, and an
>      ACTIVATE_REGION to make a region RX or R (no extra ioctl() required to
>      keep RW permissions).
> 
> Because ACTIVATE_REGION can only be done once per page, to do *abitrary*
> mprotect() transitions, userspace would need to set the added/activated
> permissions to be a superset of the transitions, e.g. RW -> RX would
> require RWX, but that's a non-issue.
> 
>    - For SGX1 it's a nop since it's impossible to change the EPCM
>      permissions, i.e. the page would need to be RWX regardless.
> 
>    - For SGX2, userspace can suck it up and request RWX to do completely
>      arbitrary transitions (working as intended), or the kernel can support
>      trimming (removing) pages from an enclave, which would allow userspace
>      to do "arbitrary" transitions by first removing the page.
> 


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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-28 21:41                                                                                                                           ` Sean Christopherson
@ 2019-05-30  5:38                                                                                                                             ` Xing, Cedric
  2019-05-30 17:21                                                                                                                               ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-30  5:38 UTC (permalink / raw)
  To: Christopherson, Sean J, Andy Lutomirski
  Cc: Stephen Smalley, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

> From: Christopherson, Sean J
> Sent: Tuesday, May 28, 2019 2:41 PM
> 
> On Tue, May 28, 2019 at 01:48:02PM -0700, Andy Lutomirski wrote:
> > On Tue, May 28, 2019 at 1:24 PM Sean Christopherson
> > <sean.j.christopherson@intel.com> wrote:
> > >
> > > Actually, I think we do have everything we need from an LSM perspective.
> > > LSMs just need to understand that sgx_enclave_load() with a NULL vma
> > > implies a transition from RW.  For example, SELinux would interpret
> > > sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.
> >
> > You lost me here.  What operation triggers this callback?  And
> > wouldn't sgx_enclave_load(NULL, RX) sometimes be a transition from RO
> > or just some fresh executable zero bytes?
> 
> An explicit ioctl() after EACCEPTCOPY to update the allowed permissions.
> For all intents and purposes, the EAUG'd page must start RW.  Maybe a better way to phrase
> it is that at some point the page must be writable to have any value whatsover.
> EACCEPTCOPY explicitly requires the page to be at least RW.  EACCEPT technically doesn't
> require RW, but a RO or RX zero page is useless.  Userspace could still EACCEPT with RO or
> RX, but SGX would assume a minimum of RW for the purposes of the LSM check.

Why is an explicit ioctl() necessary after EACCEPTCOPY? Or why is mprotect() not sufficient?

I tend to agree on Andy's MAXPERM model where MAXPERM never changes once established.

> 
> > > As Cedric mentioned earlier, the host process doesn't necessarily
> > > know which pages will end up RW vs RX, i.e. sgx_enclave_load(NULL,
> > > RX) already has to be invoked at runtime, and when that happens, the
> > > kernel can take the opportunity to change the VMAs from MAY_RW to MAY_RX.
> > >
> > > For simplicity in the kernel and clarity in userspace, it makes
> > > sense to require an explicit ioctl() to add the to-be-EAUG'd range.
> > > That just leaves us wanting an ioctl() to set the post-EACCEPT{COPY} permissions.
> > >
> > > E.g.:
> > >
> > >     ioctl(<prefix>_ADD_REGION, { NULL }) /* NULL == EAUG, MAY_RW */
> > >
> > >     mprotect(addr, size, RW);
> > >     ...
> > >
> > >     EACCEPTCOPY -> EAUG /* page fault handler */
> > >
> > >     ioctl(<prefix>_ACTIVATE_REGION, { addr, size, RX}) /* MAY_RX */
> > >
> > >     mprotect(addr, size, RX);
> >
> > In the maxperm model, this mprotect() will fail unless MAXPERM
> > contains RX, which could only happen if MAXPERM=RWX.  So, regardless
> > of how it's actually mapped to SELinux policy, MAXPERM=RWX is
> > functionally like EXECMOD and actual RWX PTEs are functionally like
> > EXECMEM.
> 
> Yep, same idea, except in the proposed flow ACTIVATE_REGION.


> 
> > >     ...
> > >
> > > And making ACTIVATE_REGION a single-shot per page eliminates the
> > > need for the MAXPERMS concept (see below).
> > >
> > > > If we keep only one MAXPERM, wouldn't this be the current behavior
> > > > of mmap()/mprotect()?
> > > >
> > > > To be a bit more clear, system admin sets MAXPERM upper bound in
> > > > the form of FILE__{READ|WRITE|EXECUTE|EXECMOD} of
> > > > /dev/sgx/enclave. Then for a process/enclave, if what it requires
> > > > falls below what's allowed on /dev/sgx/enclave, then everything
> > > > will just work. Otherwise, it fails in the form of -EPERM returned
> > > > from mmap()/mprotect(). Please note that MAXPERM here applies to
> > > > "runtime" permissions, while "initial" permissions are taken care
> > > > of by security_enclave_{load|init}. "initial" permissions could be
> > > > more permissive than "runtime" permissions, e.g., RX is still
> > > > required for initial code pages even though system admins could disable dynamically
> loaded code pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial"
> > > > mapping would still have to be done by the driver (to bypass LSM),
> > > > either via a new ioctl or as part of IOC_EINIT.
> > >
> > > Aha!
> > >
> > > Starting with Cedric's assertion that initial permissions can be
> > > taken directly from SECINFO:
> > >
> > >   - Initial permissions for *EADD* pages are explicitly handled via
> > >     sgx_enclave_load() with the exact SECINFO permissions.
> > >
> > >   - Initial permissions for *EAUG* are unconditionally RW.  EACCEPTCOPY
> > >     requires the target EPC page to be RW, and EACCEPT with RO is useless.
> > >
> > >   - Runtime permissions break down as follows:
> > >       R   - N/A, subset of RW (EAUG)
> > >       W   - N/A, subset of RW (EAUG) and x86 paging can't do W
> > >       X   - N/A, subset of RX (x86 paging can't do XO)
> >
> > Sure it can!  You just have a hypervisor that maps a PA bit to EPT
> > no-read.  Then you can use that PA bit to suppress read.  Also, Linux
> > already abuses PKRU to simulate XO, although that won't work for
> > enclaves.
> 
> Heh, I intentionally said "x86 paging" to rule out EPT :-)  I'm pretty sure it's a moot
> point though, I have a hard time believing an LSM will allow RW->X and not RW->RX.
> 
> > >       RW  - Handled by EAUG LSM hook (uses RW unconditionally)
> > >       WX  - N/A, subset of RWX (x86 paging can't do WX)
> > >       RX  - Handled by ACTIVATE_REGION
> > >       RWX - Handled by ACTIVATE_REGION
> > >
> > > In other words, if we define the SGX -> LSM calls as follows (minus
> > > the file pointer and other params for brevity):
> > >
> > >   - <prefix>_ACTIVATE_REGION(vma, perms) -> sgx_enclave_load(NULL,
> > > perms)

I'm not sure on what security_enclave_load()'s decision would be based.

> > >
> > >   - <prefix>_ADD_REGION(vma) -> sgx_enclave_load(vma, SECINFO.perms)
> > >
> > >   - <prefix>_ADD_REGION(NULL) -> sgx_enclave_load(NULL, RW)
> > >
> > > then SGX and LSMs have all the information and hooks needed.  The
> > > catch is that the LSM semantics of sgx_enclave_load(..., RW) would
> > > need to be different than normal shared memory, e.g. FILE__WRITE
> > > should *not* be required, but that's ok since it's an SGX specific
> > > hook.  And if for some reason an LSM wanted to gate access to EAUG
> > > *without* FILE__EXECMOD, it'd have the necessary information to do so.
> > >
> > > The userspace changes are fairly minimal:
> > >
> > >   - For SGX1, use PROT_NONE for the initial mmap() and refactor ADD_PAGE
> > >     to ADD_REGION.
> > >
> > >   - For SGX2, do an explicit ADD_REGION on the ranges to be EAUG'd, and an
> > >     ACTIVATE_REGION to make a region RX or R (no extra ioctl() required to
> > >     keep RW permissions).
> > >
> > > Because ACTIVATE_REGION can only be done once per page, to do
> > > *abitrary*
> > > mprotect() transitions, userspace would need to set the
> > > added/activated permissions to be a superset of the transitions,
> > > e.g. RW -> RX would require RWX, but that's a non-issue.
> > >
> >
> > I may be misunderstanding or just be biased to my own proposal, but
> > this seems potentially more complicated and less flexible than the
> > MAXPERM model.  One of the main things that made me come up with
> > MAXPERM is that I wanted to avoid any complicated PTE/VMA modification
> > or runtime changes.  So, with MAXPERM, we still need to track the
> > MAXPERM bits per page, but we don't ever need to *change* them or to
> > worry about what is or is not mapped anywhere at any given time.  With
> > ACTIVATE_REGION, don't we need to make sure that we don't have a
> > second VMA pointing at the same pages?  Or am I just confused?
> 
> In theory, it's still your MAXPERM model, but with the unnecessary states removed and the
> others enforced/handled by the natural SGX transitions instead of explictly in ioctls.
> Underneath the hood the SGX driver would still need to track the MAXPERM.

What are the "unnecessary states" removed? 

I'm not sure understand the proposal fully. The whole thing looks to me like the driver is undertaking things that should/would otherwise be done by mmap()/mprotect() syscalls. It also imposes unnecessary restrictions on user mode code, such as mmap(PROT_NONE), ACTIVATE_REGION can be called only once, etc. What'd happen if ACTIVATE_REGION is called with a range spanning multiple/partial VMAs? What'd happen if an enclave was unmapped than mapped again? I'd say the proposal is unintuitive at least.

In theory, if the driver can keep track of MAXPERM for all pages within an enclave, then it could fail mmap() if the requested prot conflicts with any page's MAXPERM within that range. Otherwise, MAXPERM could be copied into VM_MAY* flags then mprotect() will just follow through. Wouldn't that be a much simpler and more intuitive approach?

> 
> With SGX1, SECINFO == MAXPERM.  With SGX2, ACTIVATE_REGION == MAXPERM, with the
> implication that the previous state is always RW.
> 
> > >   - For SGX1 it's a nop since it's impossible to change the EPCM
> > >     permissions, i.e. the page would need to be RWX regardless.
> >
> > I may still be missing something, but, for SGX1, it's possible at
> > least in principle for the enclave to request, via ocall or similar,
> > that the untrusted runtime do mprotect().  It's not even such a bad
> > idea.  Honestly, enclaves *shouldn't* have anything actually writable
> > and executable at once because the enclaves don't want to be easily
> > exploited.
> 
> Yes, but the *EPCM* permissions are immutable.  So if an enclave wants to do RW->RX it has
> to intialize its pages to RWX.  And because the untrusted runtime is, ahem, untrusted, the
> enclave cannot rely on userspace to never map its pages RWX.  In other words, from a
> enclave security perspective, an SGX1 enclave+runtime that uses RW->RX is no different
> than an enclave that uses RWX.  Using your earlier terminology, an SGX1 enclave *should*
> get a dirty looks if maps a page RWX in the EPCM, even if it only intends RW->RX behavior.
> 
> > >   - For SGX2, userspace can suck it up and request RWX to do completely
> > >     arbitrary transitions (working as intended), or the kernel can support
> > >     trimming (removing) pages from an enclave, which would allow userspace
> > >     to do "arbitrary" transitions by first removing the page.

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-29 14:08                                                                                                                         ` Stephen Smalley
@ 2019-05-30  6:12                                                                                                                           ` Xing, Cedric
  2019-05-30 14:22                                                                                                                             ` Stephen Smalley
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-30  6:12 UTC (permalink / raw)
  To: Stephen Smalley, Christopherson, Sean J, William Roberts
  Cc: Andy Lutomirski, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

> From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-owner@vger.kernel.org] On Behalf
> Of Stephen Smalley
> Sent: Wednesday, May 29, 2019 7:08 AM
> 
> On 5/28/19 4:24 PM, Sean Christopherson wrote:
> > On Sat, May 25, 2019 at 11:09:38PM -0700, Xing, Cedric wrote:
> >>> From: Andy Lutomirski [mailto:luto@kernel.org]
> >>> Sent: Saturday, May 25, 2019 5:58 PM
> >>>
> >>> On Sat, May 25, 2019 at 3:40 PM Xing, Cedric <cedric.xing@intel.com> wrote:
> >>>>
> >>>> If we think of EADD as a way of mmap()'ing an enclave file into memory,
> >>>> would this
> >>> security_enclave_load() be the same as
> >>> security_mmap_file(source_vma->vm_file, maxperm, MAP_PRIVATE), except that
> >>> the target is now EPC instead of regular pages?
> >>>
> >>> Hmm, that's clever.  Although it seems plausible that an LSM would want to
> >>> allow RX or RWX of a given file page but only in the context of an approved
> >>> enclave, so I think it should still be its own hook.
> >>
> >> What do you mean by "in the context of an approved enclave"? EPC pages are
> >> *inaccessible* to any software until after EINIT. So it would never be a
> >> security concern to EADD a page with wrong permissions as long as the enclave
> >> would be denied eventually by LSM at EINIT.
> >>
> >> But I acknowledge the difference between loading a page into regular memory
> >> vs. into EPC. So it's beneficial to have a separate hook, which if not
> >> hooked, would pass through to security_mmap_file() by default?
> >
> > Mapping the enclave will still go through security_mmap_file(), the extra
> > security_enclave_load() hook allows the mmap() to use PROT_NONE.
> >
> >>> If it's going to be in an arbitrary file, then I think the signature needs to be more
> like:
> >>>
> >>> int security_enclave_init(struct vm_area_struct *sigstruct_vma, loff_t
> sigstruct_offset,
> >>> const sgx_sigstruct *sigstruct);
> >>>
> >>> So that the LSM still has the opportunity to base its decision on the contents of the
> >>> SIGSTRUCT.  Actually, we need that change regardless.
> >>
> >> Wouldn't the pair of { sigstruct_vma, sigstruct_offset } be the same as just
> >> a pointer, because the VMA could be looked up using the pointer and the
> >> offset would then be (pointer - vma->vm_start)?
> >
> > VMA has vm_file, e.g. the .sigstruct file labeled by LSMs.  That being
> > said, why does the LSM need the VMA?  E.g. why not this?
> >
> >    int security_enclave_init(struct file *file, struct sgx_sigstruct *sigstruct);
> >
> >>>> Loosely speaking, an enclave (including initial contents of all of its pages and
> their
> >>> permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision
> resistant
> >>> property of SHA-2). So only one is needed for a decision, and either one would lead to
> the
> >>> same decision. So I don't see anything making any sense here.
> >>>>
> >>>> Theoretically speaking, if LSM can make a decision at EINIT by means of
> >>> security_enclave_load(), then security_enclave_load() is never needed.
> >>>>
> >>>> In practice, I support keeping both because security_enclave_load() can only approve
> an
> >>> enumerable set while security_enclave_load() can approve a non-enumerable set of
> enclaves.
> >>> Moreover, in order to determine the validity of a MRENCLAVE (as in development of a
> policy
> >>> or in creation of a white/black list), system admins will need the audit log produced
> by
> >>> security_enclave_load().
> >>>
> >>> I'm confused.  Things like MRSIGNER aren't known until the SIGSTRUCT shows
> >>> up.  Also, security_enclave_load() provides no protection against loading a
> >>> mishmash of two different enclave files.  I see security_enclave_init() as
> >>> "verify this SIGSTRUCT against your policy on who may sign enclaves and/or
> >>> grant EXECMOD depending on SIGSTRUCT" and security_enclave_load() as
> >>> "implement your EXECMOD / EXECUTE / WRITE / whatever policy and possibly
> >>> check enclave files for some label."
> >>
> >> Sorry for the confusion. I was saying the same thing except that the decision
> >> of security_enclave_load() doesn't have to depend on SIGSTRUCT. Given your
> >> prototype of security_enclave_load(), I think we are on the same page. I made
> >> the above comment to object to the idea of "require that the sigstruct be
> >> supplied before any EADD operations so that the maxperm decisions can depend
> >> on the sigstruct".
> >
> > Except that having the sigstruct allows using the sigstruct as the proxy
> > for the enclave.  I think the last big disconnect is that Andy and I want
> > to tie everything to an enclave-specific file, i.e. sigstruct, while you
> > are proposing labeling /dev/sgx/enclave.  If someone wants to cram several
> > sigstructs into a single file, so be it, but using /dev/sgx/enclave means
> > users can't do per-enclave permissions, period.
> >
> > What is your objection to working on the sigstruct?
> >
> >>>>>> Passing both would allow tying EXECMOD to /dev/sgx/enclave as
> >>>>>> Cedric wanted (without having to play games and pass
> >>>>>> /dev/sgx/enclave to security_enclave_load()), but I don't think
> >>>>>> there's anything fundamentally broken with using .sigstruct for
> >>>>>> EXECMOD.  It requires more verbose labeling, but that's not a bad thing.
> >>>>>
> >>>>> The benefit of putting it on .sigstruct is that it can be per-enclave.
> >>>>>
> >>>>> As I understand it from Fedora packaging, the way this works on
> >>>>> distros is generally that a package will include some files and
> >>>>> their associated labels, and, if the package needs EXECMOD, then the
> >>>>> files are labeled with EXECMOD and the author of the relevant code might get a dirty
> >>> look.
> >>>>>
> >>>>> This could translate to the author of an exclave that needs RWX
> >>>>> regions getting a dirty look without leaking this permission into other enclaves.
> >>>>>
> >>>>> (In my opinion, the dirty looks are actually the best security
> >>>>> benefit of the entire concept of LSMs making RWX difficult.  A
> >>>>> sufficiently creative attacker can almost always bypass W^X
> >>>>> restrictions once they’ve pwned you, but W^X makes it harder to pwn
> >>>>> you in the first place, and SELinux makes it really obvious when
> >>>>> packaging a program that doesn’t respect W^X.  The upshot is that a
> >>>>> lot of programs got fixed.)
> >>>>
> >>>> I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX,
> i.e.
> >>> FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM.
> >>>
> >>> Hmm.  If we want to make this distinction, we need something a big richer
> >>> than my proposed callbacks.  A check of the actual mprotect() / mmap()
> >>> permissions would also be needed.  Specifically, allowing MAXPERM=RWX
> >>> wouldn't imply that PROT_WRITE | PROT_EXEC is allowed.
> >
> > Actually, I think we do have everything we need from an LSM perspective.
> > LSMs just need to understand that sgx_enclave_load() with a NULL vma
> > implies a transition from RW.  For example, SELinux would interpret
> > sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.
> >
> > As Cedric mentioned earlier, the host process doesn't necessarily know
> > which pages will end up RW vs RX, i.e. sgx_enclave_load(NULL, RX)
> > already has to be invoked at runtime, and when that happens, the kernel
> > can take the opportunity to change the VMAs from MAY_RW to MAY_RX.
> >
> > For simplicity in the kernel and clarity in userspace, it makes sense to
> > require an explicit ioctl() to add the to-be-EAUG'd range.  That just
> > leaves us wanting an ioctl() to set the post-EACCEPT{COPY} permissions.
> >
> > E.g.:
> >
> >      ioctl(<prefix>_ADD_REGION, { NULL }) /* NULL == EAUG, MAY_RW */
> >
> >      mprotect(addr, size, RW);
> >      ...
> >
> >      EACCEPTCOPY -> EAUG /* page fault handler */
> >
> >      ioctl(<prefix>_ACTIVATE_REGION, { addr, size, RX}) /* MAY_RX */
> >
> >      mprotect(addr, size, RX);
> >
> >      ...
> >
> > And making ACTIVATE_REGION a single-shot per page eliminates the need for
> > the MAXPERMS concept (see below).
> >
> >> If we keep only one MAXPERM, wouldn't this be the current behavior of
> >> mmap()/mprotect()?
> >>
> >> To be a bit more clear, system admin sets MAXPERM upper bound in the form of
> >> FILE__{READ|WRITE|EXECUTE|EXECMOD} of /dev/sgx/enclave. Then for a
> >> process/enclave, if what it requires falls below what's allowed on
> >> /dev/sgx/enclave, then everything will just work. Otherwise, it fails in the
> >> form of -EPERM returned from mmap()/mprotect(). Please note that MAXPERM here
> >> applies to "runtime" permissions, while "initial" permissions are taken care
> >> of by security_enclave_{load|init}. "initial" permissions could be more
> >> permissive than "runtime" permissions, e.g., RX is still required for initial
> >> code pages even though system admins could disable dynamically loaded code
> >> pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial"
> >> mapping would still have to be done by the driver (to bypass LSM), either via
> >> a new ioctl or as part of IOC_EINIT.
> >
> > Aha!
> >
> > Starting with Cedric's assertion that initial permissions can be taken
> > directly from SECINFO:
> >
> >    - Initial permissions for *EADD* pages are explicitly handled via
> >      sgx_enclave_load() with the exact SECINFO permissions.
> >
> >    - Initial permissions for *EAUG* are unconditionally RW.  EACCEPTCOPY
> >      requires the target EPC page to be RW, and EACCEPT with RO is useless.
> >
> >    - Runtime permissions break down as follows:
> >        R   - N/A, subset of RW (EAUG)
> >        W   - N/A, subset of RW (EAUG) and x86 paging can't do W
> >        X   - N/A, subset of RX (x86 paging can't do XO)
> >        RW  - Handled by EAUG LSM hook (uses RW unconditionally)
> >        WX  - N/A, subset of RWX (x86 paging can't do WX)
> >        RX  - Handled by ACTIVATE_REGION
> >        RWX - Handled by ACTIVATE_REGION
> >
> > In other words, if we define the SGX -> LSM calls as follows (minus the
> > file pointer and other params for brevity):
> >
> >    - <prefix>_ACTIVATE_REGION(vma, perms) -> sgx_enclave_load(NULL, perms)
> >
> >    - <prefix>_ADD_REGION(vma) -> sgx_enclave_load(vma, SECINFO.perms)
> >
> >    - <prefix>_ADD_REGION(NULL) -> sgx_enclave_load(NULL, RW)
> >
> > then SGX and LSMs have all the information and hooks needed.  The catch
> > is that the LSM semantics of sgx_enclave_load(..., RW) would need to be
> > different than normal shared memory, e.g. FILE__WRITE should *not* be
> > required, but that's ok since it's an SGX specific hook.  And if for some
> > reason an LSM wanted to gate access to EAUG *without* FILE__EXECMOD, it'd
> > have the necessary information to do so.
> 
> Assuming that sgx_enclave_load() is a LSM hook (probably named
> security_enclave_load() instead), then:
> 
> a) Does the sigstruct file get passed to this hook in every case, even
> when vma is NULL?  I think the answer is yes, just want to confirm.

I'm confused. 

In the case of EADD (non-NULL vma), are we passing both vma and sigstruct file? If so, which file dictates allowed permissions, vma->vm_file or sigstruct, or both???

In the case of EAUG (NULL vma), all other parameters are constant for any given enclave. Then why do we call this same hook for every region added, assuming the hook will return the same value everytime anyway?  

And it looks like ACTIVATE_REGION is needed only because the proposed security_enclave_load() would base its decision on the sigstruct file. An alternative is to base that decision on /dev/sgx/enclave. Of course the former has finer granularity but is that really necessary? From security perspective, only the weakest link matters. FILE__EXECMOD on a regular shared object could allow exploits of all bugs throughout the host process because code within that shared object is modifiable by not only itself but also any code within that same process. In contrast, FILE__EXECMOD on /dev/sgx/enclave only allows enclaves to modify themselves. They cannot modify each other, neither can "untrusted" code outside of enclaves modify any of them. So it doesn't look like a weaker link to me. Moreover, requiring FILE__EXECMOD on sigstruct means it could be used as a target buffer for code injection attacks. IMHO that *lowers* the security of the whole process.

> 
> b) Should we use a different hook for ACTIVATE_REGION than for
> ADD_REGION or is the distinction between them irrelevant/unnecessary
> from an access control point of view? At present LSM/SELinux won't be
> able to distinguish ACTIVATE_REGION(vma, RW) from ADD_REGION(NULL) above
> since they will both invoke the same hook with the same arguments IIUC.
> Does it matter?  It's ok if the answer is no, just want to confirm.
> 
> c) Is there still also a separate security_enclave_init() hook that will
> be called, and if so, how does it differ and when is it called relative
> to security_enclave_load()?

I think security_enclave_init() will always be useful, as it offers a way for LSM to implement whitelisting/blacklisting. Of course an LSM module like SELinux can look into the backing inode too. I think the hook should have a signature like:

int security_enclave_init(struct sgx_sigstruct __user *sigstruct);

An LSM that cares about the backing file could look into vm_file of the VMA covering the buffer, while an LSM that cares the sigstruct itself (e.g. signing key) could just look into the buffer. 

> 
> d) What checks were you envisioning each of these calls making?
> 
> With the separate security_enclave_*() hooks, we could define and use
> new ENCLAVE__* permissions, e.g. ENCLAVE__LOAD, ENCLAVE__INIT,
> ENCLAVE__EXECUTE, ENCLAVE__EXECMEM, ENCLAVE__EXECMOD, if we want to
> distinguish these operations from regular file mmap/mprotect operations.

I'm not sure if these ENCLAVE__* flags are an overkill, unless we want to enforce an enclave file cannot be loaded as a regular shared object or vice versa.

> 
> >
> > The userspace changes are fairly minimal:
> >
> >    - For SGX1, use PROT_NONE for the initial mmap() and refactor ADD_PAGE
> >      to ADD_REGION.
> >
> >    - For SGX2, do an explicit ADD_REGION on the ranges to be EAUG'd, and an
> >      ACTIVATE_REGION to make a region RX or R (no extra ioctl() required to
> >      keep RW permissions).
> >
> > Because ACTIVATE_REGION can only be done once per page, to do *abitrary*
> > mprotect() transitions, userspace would need to set the added/activated
> > permissions to be a superset of the transitions, e.g. RW -> RX would
> > require RWX, but that's a non-issue.
> >
> >    - For SGX1 it's a nop since it's impossible to change the EPCM
> >      permissions, i.e. the page would need to be RWX regardless.
> >
> >    - For SGX2, userspace can suck it up and request RWX to do completely
> >      arbitrary transitions (working as intended), or the kernel can support
> >      trimming (removing) pages from an enclave, which would allow userspace
> >      to do "arbitrary" transitions by first removing the page.
> >


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30  6:12                                                                                                                           ` Xing, Cedric
@ 2019-05-30 14:22                                                                                                                             ` Stephen Smalley
  2019-05-30 14:31                                                                                                                               ` Andy Lutomirski
  0 siblings, 1 reply; 318+ messages in thread
From: Stephen Smalley @ 2019-05-30 14:22 UTC (permalink / raw)
  To: Xing, Cedric, Christopherson, Sean J, William Roberts
  Cc: Andy Lutomirski, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 5/30/19 2:12 AM, Xing, Cedric wrote:
>> From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-owner@vger.kernel.org] On Behalf
>> Of Stephen Smalley
>> Sent: Wednesday, May 29, 2019 7:08 AM
>>
>> On 5/28/19 4:24 PM, Sean Christopherson wrote:
>>> On Sat, May 25, 2019 at 11:09:38PM -0700, Xing, Cedric wrote:
>>>>> From: Andy Lutomirski [mailto:luto@kernel.org]
>>>>> Sent: Saturday, May 25, 2019 5:58 PM
>>>>>
>>>>> On Sat, May 25, 2019 at 3:40 PM Xing, Cedric <cedric.xing@intel.com> wrote:
>>>>>>
>>>>>> If we think of EADD as a way of mmap()'ing an enclave file into memory,
>>>>>> would this
>>>>> security_enclave_load() be the same as
>>>>> security_mmap_file(source_vma->vm_file, maxperm, MAP_PRIVATE), except that
>>>>> the target is now EPC instead of regular pages?
>>>>>
>>>>> Hmm, that's clever.  Although it seems plausible that an LSM would want to
>>>>> allow RX or RWX of a given file page but only in the context of an approved
>>>>> enclave, so I think it should still be its own hook.
>>>>
>>>> What do you mean by "in the context of an approved enclave"? EPC pages are
>>>> *inaccessible* to any software until after EINIT. So it would never be a
>>>> security concern to EADD a page with wrong permissions as long as the enclave
>>>> would be denied eventually by LSM at EINIT.
>>>>
>>>> But I acknowledge the difference between loading a page into regular memory
>>>> vs. into EPC. So it's beneficial to have a separate hook, which if not
>>>> hooked, would pass through to security_mmap_file() by default?
>>>
>>> Mapping the enclave will still go through security_mmap_file(), the extra
>>> security_enclave_load() hook allows the mmap() to use PROT_NONE.
>>>
>>>>> If it's going to be in an arbitrary file, then I think the signature needs to be more
>> like:
>>>>>
>>>>> int security_enclave_init(struct vm_area_struct *sigstruct_vma, loff_t
>> sigstruct_offset,
>>>>> const sgx_sigstruct *sigstruct);
>>>>>
>>>>> So that the LSM still has the opportunity to base its decision on the contents of the
>>>>> SIGSTRUCT.  Actually, we need that change regardless.
>>>>
>>>> Wouldn't the pair of { sigstruct_vma, sigstruct_offset } be the same as just
>>>> a pointer, because the VMA could be looked up using the pointer and the
>>>> offset would then be (pointer - vma->vm_start)?
>>>
>>> VMA has vm_file, e.g. the .sigstruct file labeled by LSMs.  That being
>>> said, why does the LSM need the VMA?  E.g. why not this?
>>>
>>>     int security_enclave_init(struct file *file, struct sgx_sigstruct *sigstruct);
>>>
>>>>>> Loosely speaking, an enclave (including initial contents of all of its pages and
>> their
>>>>> permissions) and its MRENCLAVE are a 1-to-1 correspondence (given the collision
>> resistant
>>>>> property of SHA-2). So only one is needed for a decision, and either one would lead to
>> the
>>>>> same decision. So I don't see anything making any sense here.
>>>>>>
>>>>>> Theoretically speaking, if LSM can make a decision at EINIT by means of
>>>>> security_enclave_load(), then security_enclave_load() is never needed.
>>>>>>
>>>>>> In practice, I support keeping both because security_enclave_load() can only approve
>> an
>>>>> enumerable set while security_enclave_load() can approve a non-enumerable set of
>> enclaves.
>>>>> Moreover, in order to determine the validity of a MRENCLAVE (as in development of a
>> policy
>>>>> or in creation of a white/black list), system admins will need the audit log produced
>> by
>>>>> security_enclave_load().
>>>>>
>>>>> I'm confused.  Things like MRSIGNER aren't known until the SIGSTRUCT shows
>>>>> up.  Also, security_enclave_load() provides no protection against loading a
>>>>> mishmash of two different enclave files.  I see security_enclave_init() as
>>>>> "verify this SIGSTRUCT against your policy on who may sign enclaves and/or
>>>>> grant EXECMOD depending on SIGSTRUCT" and security_enclave_load() as
>>>>> "implement your EXECMOD / EXECUTE / WRITE / whatever policy and possibly
>>>>> check enclave files for some label."
>>>>
>>>> Sorry for the confusion. I was saying the same thing except that the decision
>>>> of security_enclave_load() doesn't have to depend on SIGSTRUCT. Given your
>>>> prototype of security_enclave_load(), I think we are on the same page. I made
>>>> the above comment to object to the idea of "require that the sigstruct be
>>>> supplied before any EADD operations so that the maxperm decisions can depend
>>>> on the sigstruct".
>>>
>>> Except that having the sigstruct allows using the sigstruct as the proxy
>>> for the enclave.  I think the last big disconnect is that Andy and I want
>>> to tie everything to an enclave-specific file, i.e. sigstruct, while you
>>> are proposing labeling /dev/sgx/enclave.  If someone wants to cram several
>>> sigstructs into a single file, so be it, but using /dev/sgx/enclave means
>>> users can't do per-enclave permissions, period.
>>>
>>> What is your objection to working on the sigstruct?
>>>
>>>>>>>> Passing both would allow tying EXECMOD to /dev/sgx/enclave as
>>>>>>>> Cedric wanted (without having to play games and pass
>>>>>>>> /dev/sgx/enclave to security_enclave_load()), but I don't think
>>>>>>>> there's anything fundamentally broken with using .sigstruct for
>>>>>>>> EXECMOD.  It requires more verbose labeling, but that's not a bad thing.
>>>>>>>
>>>>>>> The benefit of putting it on .sigstruct is that it can be per-enclave.
>>>>>>>
>>>>>>> As I understand it from Fedora packaging, the way this works on
>>>>>>> distros is generally that a package will include some files and
>>>>>>> their associated labels, and, if the package needs EXECMOD, then the
>>>>>>> files are labeled with EXECMOD and the author of the relevant code might get a dirty
>>>>> look.
>>>>>>>
>>>>>>> This could translate to the author of an exclave that needs RWX
>>>>>>> regions getting a dirty look without leaking this permission into other enclaves.
>>>>>>>
>>>>>>> (In my opinion, the dirty looks are actually the best security
>>>>>>> benefit of the entire concept of LSMs making RWX difficult.  A
>>>>>>> sufficiently creative attacker can almost always bypass W^X
>>>>>>> restrictions once they’ve pwned you, but W^X makes it harder to pwn
>>>>>>> you in the first place, and SELinux makes it really obvious when
>>>>>>> packaging a program that doesn’t respect W^X.  The upshot is that a
>>>>>>> lot of programs got fixed.)
>>>>>>
>>>>>> I'm lost here. Dynamically linked enclaves, if running on SGX2, would need RW->RX,
>> i.e.
>>>>> FILE__EXECMOD on /dev/sgx/enclave. But they never need RWX, i.e. PROCESS__EXECMEM.
>>>>>
>>>>> Hmm.  If we want to make this distinction, we need something a big richer
>>>>> than my proposed callbacks.  A check of the actual mprotect() / mmap()
>>>>> permissions would also be needed.  Specifically, allowing MAXPERM=RWX
>>>>> wouldn't imply that PROT_WRITE | PROT_EXEC is allowed.
>>>
>>> Actually, I think we do have everything we need from an LSM perspective.
>>> LSMs just need to understand that sgx_enclave_load() with a NULL vma
>>> implies a transition from RW.  For example, SELinux would interpret
>>> sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.
>>>
>>> As Cedric mentioned earlier, the host process doesn't necessarily know
>>> which pages will end up RW vs RX, i.e. sgx_enclave_load(NULL, RX)
>>> already has to be invoked at runtime, and when that happens, the kernel
>>> can take the opportunity to change the VMAs from MAY_RW to MAY_RX.
>>>
>>> For simplicity in the kernel and clarity in userspace, it makes sense to
>>> require an explicit ioctl() to add the to-be-EAUG'd range.  That just
>>> leaves us wanting an ioctl() to set the post-EACCEPT{COPY} permissions.
>>>
>>> E.g.:
>>>
>>>       ioctl(<prefix>_ADD_REGION, { NULL }) /* NULL == EAUG, MAY_RW */
>>>
>>>       mprotect(addr, size, RW);
>>>       ...
>>>
>>>       EACCEPTCOPY -> EAUG /* page fault handler */
>>>
>>>       ioctl(<prefix>_ACTIVATE_REGION, { addr, size, RX}) /* MAY_RX */
>>>
>>>       mprotect(addr, size, RX);
>>>
>>>       ...
>>>
>>> And making ACTIVATE_REGION a single-shot per page eliminates the need for
>>> the MAXPERMS concept (see below).
>>>
>>>> If we keep only one MAXPERM, wouldn't this be the current behavior of
>>>> mmap()/mprotect()?
>>>>
>>>> To be a bit more clear, system admin sets MAXPERM upper bound in the form of
>>>> FILE__{READ|WRITE|EXECUTE|EXECMOD} of /dev/sgx/enclave. Then for a
>>>> process/enclave, if what it requires falls below what's allowed on
>>>> /dev/sgx/enclave, then everything will just work. Otherwise, it fails in the
>>>> form of -EPERM returned from mmap()/mprotect(). Please note that MAXPERM here
>>>> applies to "runtime" permissions, while "initial" permissions are taken care
>>>> of by security_enclave_{load|init}. "initial" permissions could be more
>>>> permissive than "runtime" permissions, e.g., RX is still required for initial
>>>> code pages even though system admins could disable dynamically loaded code
>>>> pages by *not* giving FILE__{EXECUTE|EXECMOD}. Therefore, the "initial"
>>>> mapping would still have to be done by the driver (to bypass LSM), either via
>>>> a new ioctl or as part of IOC_EINIT.
>>>
>>> Aha!
>>>
>>> Starting with Cedric's assertion that initial permissions can be taken
>>> directly from SECINFO:
>>>
>>>     - Initial permissions for *EADD* pages are explicitly handled via
>>>       sgx_enclave_load() with the exact SECINFO permissions.
>>>
>>>     - Initial permissions for *EAUG* are unconditionally RW.  EACCEPTCOPY
>>>       requires the target EPC page to be RW, and EACCEPT with RO is useless.
>>>
>>>     - Runtime permissions break down as follows:
>>>         R   - N/A, subset of RW (EAUG)
>>>         W   - N/A, subset of RW (EAUG) and x86 paging can't do W
>>>         X   - N/A, subset of RX (x86 paging can't do XO)
>>>         RW  - Handled by EAUG LSM hook (uses RW unconditionally)
>>>         WX  - N/A, subset of RWX (x86 paging can't do WX)
>>>         RX  - Handled by ACTIVATE_REGION
>>>         RWX - Handled by ACTIVATE_REGION
>>>
>>> In other words, if we define the SGX -> LSM calls as follows (minus the
>>> file pointer and other params for brevity):
>>>
>>>     - <prefix>_ACTIVATE_REGION(vma, perms) -> sgx_enclave_load(NULL, perms)
>>>
>>>     - <prefix>_ADD_REGION(vma) -> sgx_enclave_load(vma, SECINFO.perms)
>>>
>>>     - <prefix>_ADD_REGION(NULL) -> sgx_enclave_load(NULL, RW)
>>>
>>> then SGX and LSMs have all the information and hooks needed.  The catch
>>> is that the LSM semantics of sgx_enclave_load(..., RW) would need to be
>>> different than normal shared memory, e.g. FILE__WRITE should *not* be
>>> required, but that's ok since it's an SGX specific hook.  And if for some
>>> reason an LSM wanted to gate access to EAUG *without* FILE__EXECMOD, it'd
>>> have the necessary information to do so.
>>
>> Assuming that sgx_enclave_load() is a LSM hook (probably named
>> security_enclave_load() instead), then:
>>
>> a) Does the sigstruct file get passed to this hook in every case, even
>> when vma is NULL?  I think the answer is yes, just want to confirm.
> 
> I'm confused.

I'm finding it difficult to follow as well, so my questions are just an 
attempt to understand the latest model.

> In the case of EADD (non-NULL vma), are we passing both vma and sigstruct file? If so, which file dictates allowed permissions, vma->vm_file or sigstruct, or both???

My impression was that they were going to pass both, but the sigstruct 
file is the target of permission checks.  The vma if non-NULL would be 
used to determine whether PROT_EXEC is being added or was already 
present and whether EXECMOD needs to be checked (i.e. copy-on-write has 
occurred and PROT_EXEC is being added).

> In the case of EAUG (NULL vma), all other parameters are constant for any given enclave. Then why do we call this same hook for every region added, assuming the hook will return the same value everytime anyway?

Yes, I was wondering about that as well.

> And it looks like ACTIVATE_REGION is needed only because the proposed security_enclave_load() would base its decision on the sigstruct file. An alternative is to base that decision on /dev/sgx/enclave. Of course the former has finer granularity but is that really necessary? From security perspective, only the weakest link matters. FILE__EXECMOD on a regular shared object could allow exploits of all bugs throughout the host process because code within that shared object is modifiable by not only itself but also any code within that same process. In contrast, FILE__EXECMOD on /dev/sgx/enclave only allows enclaves to modify themselves. They cannot modify each other, neither can "untrusted" code outside of enclaves modify any of them. So it doesn't look like a weaker link to me. Moreover, requiring FILE__EXECMOD on sigstruct means it could be used as a target buffer for code injection attacks. IMHO that *lowers* the security of the whole process.

This is partly why I suggested separate ENCLAVE__EXECMOD and other 
checks below, so we can distinguish between FILE__EXECMOD versus 
ENCLAVE__EXECMOD on the sigstruct file.  If using /dev/sgx/enclave as 
the target, then we don't need a separate permission per se but we lose 
the per-sigstruct granularity.

> 
>>
>> b) Should we use a different hook for ACTIVATE_REGION than for
>> ADD_REGION or is the distinction between them irrelevant/unnecessary
>> from an access control point of view? At present LSM/SELinux won't be
>> able to distinguish ACTIVATE_REGION(vma, RW) from ADD_REGION(NULL) above
>> since they will both invoke the same hook with the same arguments IIUC.
>> Does it matter?  It's ok if the answer is no, just want to confirm.
>>
>> c) Is there still also a separate security_enclave_init() hook that will
>> be called, and if so, how does it differ and when is it called relative
>> to security_enclave_load()?
> 
> I think security_enclave_init() will always be useful, as it offers a way for LSM to implement whitelisting/blacklisting. Of course an LSM module like SELinux can look into the backing inode too. I think the hook should have a signature like:
> 
> int security_enclave_init(struct sgx_sigstruct __user *sigstruct);
> 
> An LSM that cares about the backing file could look into vm_file of the VMA covering the buffer, while an LSM that cares the sigstruct itself (e.g. signing key) could just look into the buffer.

I'm not a fan of passing __user pointers to LSM hooks.  And it certainly 
shouldn't be looking at the buffer since it could change between the 
time of check and time of use.

> 
>>
>> d) What checks were you envisioning each of these calls making?
>>
>> With the separate security_enclave_*() hooks, we could define and use
>> new ENCLAVE__* permissions, e.g. ENCLAVE__LOAD, ENCLAVE__INIT,
>> ENCLAVE__EXECUTE, ENCLAVE__EXECMEM, ENCLAVE__EXECMOD, if we want to
>> distinguish these operations from regular file mmap/mprotect operations.
> 
> I'm not sure if these ENCLAVE__* flags are an overkill, unless we want to enforce an enclave file cannot be loaded as a regular shared object or vice versa.

ENCLAVE__LOAD and/or ENCLAVE__INIT would be to support whitelisting of 
what enclaves can be loaded/initialized by the process.  That's separate 
from the W^X discussion.  Those permissions would be between the process 
and either the sigstruct file or the enclave file (the consensus seemed 
to be the sigstruct file as the stronger/more complete binding of the 
enclave).  We probably only need one of those two permission checks not 
both.

ENCLAVE__EXECUTE, ENCLAVE__EXECMEM, ENCLAVE__EXECMOD would allow 
distinctions between host process mmap/mprotect PROT_EXEC operations 
(which would continue to apply FILE__EXECUTE, PROCESS__EXECMEM, and 
FILE__EXECMOD checks if appropriate) and the driver's setting of initial 
and runtime permissions (which would apply ENCLAVE__EXECUTE, 
ENCLAVE__EXECMEM, and ENCLAVE__EXECMOD checks if appropriate). That's 
particularly helpful if we are using the sigstruct or enclave file as 
the target of all checks instead of /dev/sgx/enclave, so that we don't 
have to allow FILE__EXECUTE or FILE__EXECMOD to the sigstruct file by 
the host process.

> 
>>
>>>
>>> The userspace changes are fairly minimal:
>>>
>>>     - For SGX1, use PROT_NONE for the initial mmap() and refactor ADD_PAGE
>>>       to ADD_REGION.
>>>
>>>     - For SGX2, do an explicit ADD_REGION on the ranges to be EAUG'd, and an
>>>       ACTIVATE_REGION to make a region RX or R (no extra ioctl() required to
>>>       keep RW permissions).
>>>
>>> Because ACTIVATE_REGION can only be done once per page, to do *abitrary*
>>> mprotect() transitions, userspace would need to set the added/activated
>>> permissions to be a superset of the transitions, e.g. RW -> RX would
>>> require RWX, but that's a non-issue.
>>>
>>>     - For SGX1 it's a nop since it's impossible to change the EPCM
>>>       permissions, i.e. the page would need to be RWX regardless.
>>>
>>>     - For SGX2, userspace can suck it up and request RWX to do completely
>>>       arbitrary transitions (working as intended), or the kernel can support
>>>       trimming (removing) pages from an enclave, which would allow userspace
>>>       to do "arbitrary" transitions by first removing the page.
>>>
> 


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 14:22                                                                                                                             ` Stephen Smalley
@ 2019-05-30 14:31                                                                                                                               ` Andy Lutomirski
  2019-05-30 15:04                                                                                                                                 ` Stephen Smalley
  2019-06-03 20:43                                                                                                                                 ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-30 14:31 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Xing, Cedric, Christopherson, Sean J, William Roberts,
	Andy Lutomirski, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

Hi all-

After an offline discussion with Sean yesterday, here are some updates
to the user API parts of my proposal.

Unfortunately, Sean convinced me that MAXPERM doesn't work the way I
described it because, for SGX2, the enclave loader won't know at load
time whether a given EAUG-ed page will ever be executed.  So here's an
update.

First, here are the requrements as I see them, where EXECUTE, EXECMOD,
and EXECMEM could be substituted with other rules at the LSM's
discretion:

 - You can create a WX or RWX mapping if and only if you have EXECMEM.

 - To create an X mapping of an enclave page that has ever been W, you
need EXECMOD.

 - To create an X mapping of an enclave page that came from EADD, you
need EXECUTE on the source file.  Optionally, we could also permit
this if you have EXECMOD.

And I have two design proposals.  One is static and one is dynamic.
To implement either one, we will probably need a new .may_mprotect vm
operation, and that operation can call an LSM hook.  Or we can give
LSMs a way to detect that a given vm_area_struct is an enclave.  As I
see it, this is an implementation detail that is certainly solveable.


Static proposal:


EADD takes an execute_intent flag.  It calls a new hook:

  int security_enclave_load(struct vm_area_struct *source, bool execute_intent);

This hook will fail if execute_intent==true and the caller has neither
EXECUTE, EXECMOD, nor EXECMEM.

EAUG sets execute_intent = false.

EINIT takes a sigstruct pointer.  SGX can (when initially upstreamed
or later on once there's demand) call a new hook:

  security_enclave_init(struct sigstruct *sigstruct, struct
vm_area_struct *source);

mmap() and mprotect() will require EXECMEM to create WX or RWX
mappings.  They will require EXECMOD to create RX or X mappings of an
execute_intent==false page.  They require no permissions in the other
cases.


Dynamic proposal:


EADD does not take any special flags.  It does something like this internally:

  bool execute_intent = true;
  int security_enclave_load(struct vm_area_struct *source, bool
*execute_intent);

The implementation of security_enclave_load() may set *execute_intent to false.
The driver records execute_intent after the LSM is done.

mmap() and mprotect() will require EXECMEM to create WX or RWX
mappings.  They will require EXECMOD to create RX or X mappings of an
execute_intent==false page.  They require no permissions in the other
cases.



A benefit of the static proposal is that audit failures due to a lack
of EXECUTE permission are easy to implement and to understand in the
lods.  With the dynamic model, we can only really audit the lack of
EXECMOD or EXECMEM.  A benefit of the dynamic model is that we hide
what is arguably a decently large wart from the API.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 14:31                                                                                                                               ` Andy Lutomirski
@ 2019-05-30 15:04                                                                                                                                 ` Stephen Smalley
  2019-05-30 16:14                                                                                                                                   ` Andy Lutomirski
  2019-06-03 20:47                                                                                                                                   ` Jarkko Sakkinen
  2019-06-03 20:43                                                                                                                                 ` Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Stephen Smalley @ 2019-05-30 15:04 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Xing, Cedric, Christopherson, Sean J, William Roberts,
	Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On 5/30/19 10:31 AM, Andy Lutomirski wrote:
> Hi all-
> 
> After an offline discussion with Sean yesterday, here are some updates
> to the user API parts of my proposal.
> 
> Unfortunately, Sean convinced me that MAXPERM doesn't work the way I
> described it because, for SGX2, the enclave loader won't know at load
> time whether a given EAUG-ed page will ever be executed.  So here's an
> update.
> 
> First, here are the requrements as I see them, where EXECUTE, EXECMOD,
> and EXECMEM could be substituted with other rules at the LSM's
> discretion:
> 
>   - You can create a WX or RWX mapping if and only if you have EXECMEM.
> 
>   - To create an X mapping of an enclave page that has ever been W, you
> need EXECMOD.

EXECMOD to what file? The enclave file from which the page's content 
originated, the sigstruct file, or /dev/sgx/enclave?

>   - To create an X mapping of an enclave page that came from EADD, you
> need EXECUTE on the source file.  Optionally, we could also permit
> this if you have EXECMOD.

What is the "source file" i.e. the target of the check?  Enclave file, 
sigstruct file, or /dev/sgx/enclave?

> 
> And I have two design proposals.  One is static and one is dynamic.
> To implement either one, we will probably need a new .may_mprotect vm
> operation, and that operation can call an LSM hook.  Or we can give
> LSMs a way to detect that a given vm_area_struct is an enclave.  As I
> see it, this is an implementation detail that is certainly solveable.
> 
> 
> Static proposal:
> 
> 
> EADD takes an execute_intent flag.  It calls a new hook:
> 
>    int security_enclave_load(struct vm_area_struct *source, bool execute_intent);
> 
> This hook will fail if execute_intent==true and the caller has neither
> EXECUTE, EXECMOD, nor EXECMEM.

EADD execute_intent flag is originally provided by whom (userspace or 
driver) on what basis? Which file is referenced by source->vm_file? Why 
trigger all three checks up front versus only checking if needed?  Won't 
this trigger a lot of unnecessary EXECMOD and EXECMEM denials that will 
need to be dontaudit'd? What if there is a mismatch between 
execute_intent and the initial permissions?

> 
> EAUG sets execute_intent = false.
> 
> EINIT takes a sigstruct pointer.  SGX can (when initially upstreamed
> or later on once there's demand) call a new hook:
> 
>    security_enclave_init(struct sigstruct *sigstruct, struct
> vm_area_struct *source);

Is struct sigstruct the same as struct sgx_sigstruct in the current 
patches (i.e. just the sigstruct data, no file)?  What file is 
referenced by source->vm_file (the sigstruct or the enclave or 
/dev/sgx/enclave)?  Is this hook only for enforcing a whitelist on what 
enclaves can be loaded?  What is the target of the check?

> mmap() and mprotect() will require EXECMEM to create WX or RWX
> mappings.  They will require EXECMOD to create RX or X mappings of an
> execute_intent==false page.  They require no permissions in the other
> cases.

Does this occur for both setting initial permissions and runtime 
permissions or just runtime? Both userspace- and driver-initiated 
mmap/mprotect operations or just userspace-initiated ones?  Does the 
driver use interfaces that call the mmap/mprotect hooks or lower level 
functions?

> 
> 
> Dynamic proposal:
> 
> 
> EADD does not take any special flags.  It does something like this internally:
> 
>    bool execute_intent = true;
>    int security_enclave_load(struct vm_area_struct *source, bool
> *execute_intent);
> 
> The implementation of security_enclave_load() may set *execute_intent to false.
> The driver records execute_intent after the LSM is done.

On what basis does LSM decide whether to set *execute_intent?  If the 
process lacks all three permissions? What if there is a mismatch with 
the initial permissions?

> 
> mmap() and mprotect() will require EXECMEM to create WX or RWX
> mappings.  They will require EXECMOD to create RX or X mappings of an
> execute_intent==false page.  They require no permissions in the other
> cases.
> 
> 
> 
> A benefit of the static proposal is that audit failures due to a lack
> of EXECUTE permission are easy to implement and to understand in the
> lods.  With the dynamic model, we can only really audit the lack of
> EXECMOD or EXECMEM.  A benefit of the dynamic model is that we hide
> what is arguably a decently large wart from the API.
> 


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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 15:04                                                                                                                                 ` Stephen Smalley
@ 2019-05-30 16:14                                                                                                                                   ` Andy Lutomirski
  2019-05-30 18:01                                                                                                                                     ` Sean Christopherson
  2019-06-03 20:54                                                                                                                                     ` Jarkko Sakkinen
  2019-06-03 20:47                                                                                                                                   ` Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-30 16:14 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Andy Lutomirski, Xing, Cedric, Christopherson, Sean J,
	William Roberts, Jarkko Sakkinen, James Morris, Serge E. Hallyn,
	LSM List, Paul Moore, Eric Paris, selinux, Jethro Beekman,
	Hansen, Dave, Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML,
	X86 ML, linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun,
	Serge, Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn,
	Kai, Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 8:04 AM Stephen Smalley <sds@tycho.nsa.gov> wrote:
>
> On 5/30/19 10:31 AM, Andy Lutomirski wrote:
> > Hi all-
> >
> > After an offline discussion with Sean yesterday, here are some updates
> > to the user API parts of my proposal.
> >
> > Unfortunately, Sean convinced me that MAXPERM doesn't work the way I
> > described it because, for SGX2, the enclave loader won't know at load
> > time whether a given EAUG-ed page will ever be executed.  So here's an
> > update.
> >
> > First, here are the requrements as I see them, where EXECUTE, EXECMOD,
> > and EXECMEM could be substituted with other rules at the LSM's
> > discretion:
> >
> >   - You can create a WX or RWX mapping if and only if you have EXECMEM.
> >
> >   - To create an X mapping of an enclave page that has ever been W, you
> > need EXECMOD.
>
> EXECMOD to what file? The enclave file from which the page's content
> originated, the sigstruct file, or /dev/sgx/enclave?

I leave that decision to you :)  The user should need permission to do
an execmod thing on an enclave, however that wants to be encoded.

>
> >   - To create an X mapping of an enclave page that came from EADD, you
> > need EXECUTE on the source file.  Optionally, we could also permit
> > this if you have EXECMOD.
>
> What is the "source file" i.e. the target of the check?  Enclave file,
> sigstruct file, or /dev/sgx/enclave?

Enclave file -- that is, the file backing the vma from which the data is loaded.

>
> >
> > And I have two design proposals.  One is static and one is dynamic.
> > To implement either one, we will probably need a new .may_mprotect vm
> > operation, and that operation can call an LSM hook.  Or we can give
> > LSMs a way to detect that a given vm_area_struct is an enclave.  As I
> > see it, this is an implementation detail that is certainly solveable.
> >
> >
> > Static proposal:
> >
> >
> > EADD takes an execute_intent flag.  It calls a new hook:
> >
> >    int security_enclave_load(struct vm_area_struct *source, bool execute_intent);
> >
> > This hook will fail if execute_intent==true and the caller has neither
> > EXECUTE, EXECMOD, nor EXECMEM.
>
> EADD execute_intent flag is originally provided by whom (userspace or
> driver) on what basis? Which file is referenced by source->vm_file? Why
> trigger all three checks up front versus only checking if needed?  Won't
> this trigger a lot of unnecessary EXECMOD and EXECMEM denials that will
> need to be dontaudit'd? What if there is a mismatch between
> execute_intent and the initial permissions?

It's provided by userspace based on whether it thinks the data in
question is enclave code.  source->vm_file is the file from which the
code is being loaded.  I'm assuming that the user code will only set
excute_intent ==true if it actually wants to execute the code, so, if
there's a denial, it will be fatal.  The normal case will be that the
request will be granted on the basis of EXECUTE.

>
> >
> > EAUG sets execute_intent = false.
> >
> > EINIT takes a sigstruct pointer.  SGX can (when initially upstreamed
> > or later on once there's demand) call a new hook:
> >
> >    security_enclave_init(struct sigstruct *sigstruct, struct
> > vm_area_struct *source);
>
> Is struct sigstruct the same as struct sgx_sigstruct in the current
> patches (i.e. just the sigstruct data, no file)?  What file is
> referenced by source->vm_file (the sigstruct or the enclave or
> /dev/sgx/enclave)?  Is this hook only for enforcing a whitelist on what
> enclaves can be loaded?  What is the target of the check?

sigstruct is just the data.  source->vm_file is the file from which
the sigstruct came, which could be a .sigstruct file or could be the
main executable or a DSO that contains an embedded enclave.  The
sigstruct data is there so that an LSM (not necessarily SELinux) could
check MRENCLAVE or MRSIGNER, and the source is there so that the
file's label can be checked.

>
> > mmap() and mprotect() will require EXECMEM to create WX or RWX
> > mappings.  They will require EXECMOD to create RX or X mappings of an
> > execute_intent==false page.  They require no permissions in the other
> > cases.
>
> Does this occur for both setting initial permissions and runtime
> permissions or just runtime? Both userspace- and driver-initiated
> mmap/mprotect operations or just userspace-initiated ones?  Does the
> driver use interfaces that call the mmap/mprotect hooks or lower level
> functions?

These would occur for any mmap(), mprotect(), or ioctl() that changes
VMA permissions.  Actually arranging for the hooks to be called is an
implementation detail that might require a new .mprotect vm_operation.
As an alternative, security_enclave_init() or similar could supply
may_execmod and may_execmem flags to the driver, and the driver could
do these checks on its own when mmap() and mprotect() happen without a
new LSM callback.

>
> >
> >
> > Dynamic proposal:
> >
> >
> > EADD does not take any special flags.  It does something like this internally:
> >
> >    bool execute_intent = true;
> >    int security_enclave_load(struct vm_area_struct *source, bool
> > *execute_intent);
> >
> > The implementation of security_enclave_load() may set *execute_intent to false.
> > The driver records execute_intent after the LSM is done.
>
> On what basis does LSM decide whether to set *execute_intent?  If the
> process lacks all three permissions? What if there is a mismatch with
> the initial permissions?
>

I think it would set *execute_intent=false if the process lacks
EXECUTE on source->vm_file.  I'm not sure any more complexity is
required.  If the enclave has EXECMOD, then it will still work on the
basis of the mmap/mprotect rules.

> >
> > mmap() and mprotect() will require EXECMEM to create WX or RWX
> > mappings.  They will require EXECMOD to create RX or X mappings of an
> > execute_intent==false page.  They require no permissions in the other
> > cases.
> >
> >
> >
> > A benefit of the static proposal is that audit failures due to a lack
> > of EXECUTE permission are easy to implement and to understand in the
> > lods.  With the dynamic model, we can only really audit the lack of
> > EXECMOD or EXECMEM.  A benefit of the dynamic model is that we hide
> > what is arguably a decently large wart from the API.
> >
>

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30  5:38                                                                                                                             ` Xing, Cedric
@ 2019-05-30 17:21                                                                                                                               ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-30 17:21 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, Stephen Smalley, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Wed, May 29, 2019 at 10:38:06PM -0700, Xing, Cedric wrote:
> > From: Christopherson, Sean J
> > Sent: Tuesday, May 28, 2019 2:41 PM
> > 
> > On Tue, May 28, 2019 at 01:48:02PM -0700, Andy Lutomirski wrote:
> > > On Tue, May 28, 2019 at 1:24 PM Sean Christopherson
> > > <sean.j.christopherson@intel.com> wrote:
> > > >
> > > > Actually, I think we do have everything we need from an LSM perspective.
> > > > LSMs just need to understand that sgx_enclave_load() with a NULL vma
> > > > implies a transition from RW.  For example, SELinux would interpret
> > > > sgx_enclave_load(NULL, RX) as requiring FILE__EXECMOD.
> > >
> > > You lost me here.  What operation triggers this callback?  And
> > > wouldn't sgx_enclave_load(NULL, RX) sometimes be a transition from RO
> > > or just some fresh executable zero bytes?
> > 
> > An explicit ioctl() after EACCEPTCOPY to update the allowed permissions.
> > For all intents and purposes, the EAUG'd page must start RW.  Maybe a better way to phrase
> > it is that at some point the page must be writable to have any value whatsover.
> > EACCEPTCOPY explicitly requires the page to be at least RW.  EACCEPT technically doesn't
> > require RW, but a RO or RX zero page is useless.  Userspace could still EACCEPT with RO or
> > RX, but SGX would assume a minimum of RW for the purposes of the LSM check.
> 
> Why is an explicit ioctl() necessary after EACCEPTCOPY? Or why is mprotect() not sufficient?

Ignore this, I was trying to avoid having to add a vm_ops mprotect(),
which Andy pointed out was silly.

> > In theory, it's still your MAXPERM model, but with the unnecessary states removed and the
> > others enforced/handled by the natural SGX transitions instead of explictly in ioctls.
> > Underneath the hood the SGX driver would still need to track the MAXPERM.
> 
> What are the "unnecessary states" removed? 

Andy proposed taking full RWX in MAXPERMs, but really we only need "can
writes ever happen to this page", as that allows the SGX driver to avoid
having to track if a page has been mapped PROT_WRITE by any VMA in any
process.

> I'm not sure understand the proposal fully. The whole thing looks to me like
> the driver is undertaking things that should/would otherwise be done by
> mmap()/mprotect() syscalls. It also imposes unnecessary restrictions on user
> mode code, such as mmap(PROT_NONE), ACTIVATE_REGION can be called only once,
> etc. What'd happen if ACTIVATE_REGION is called with a range spanning
> multiple/partial VMAs? What'd happen if an enclave was unmapped than mapped
> again? I'd say the proposal is unintuitive at least.
> 
> In theory, if the driver can keep track of MAXPERM for all pages within an
> enclave, then it could fail mmap() if the requested prot conflicts with any
> page's MAXPERM within that range. Otherwise, MAXPERM could be copied into
> VM_MAY* flags then mprotect() will just follow through. Wouldn't that be a
> much simpler and more intuitive approach?

Ignore all this, again I was trying to avoid hooking mprotect().

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 16:14                                                                                                                                   ` Andy Lutomirski
@ 2019-05-30 18:01                                                                                                                                     ` Sean Christopherson
  2019-05-30 19:20                                                                                                                                       ` Andy Lutomirski
  2019-06-03 21:05                                                                                                                                       ` Jarkko Sakkinen
  2019-06-03 20:54                                                                                                                                     ` Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-30 18:01 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Xing, Cedric, William Roberts, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> On Thu, May 30, 2019 at 8:04 AM Stephen Smalley <sds@tycho.nsa.gov> wrote:
> >
> > On 5/30/19 10:31 AM, Andy Lutomirski wrote:
> > > Hi all-
> > >
> > > After an offline discussion with Sean yesterday, here are some updates
> > > to the user API parts of my proposal.
> > >
> > > Unfortunately, Sean convinced me that MAXPERM doesn't work the way I
> > > described it because, for SGX2, the enclave loader won't know at load
> > > time whether a given EAUG-ed page will ever be executed.  So here's an
> > > update.
> > >
> > > First, here are the requrements as I see them, where EXECUTE, EXECMOD,
> > > and EXECMEM could be substituted with other rules at the LSM's
> > > discretion:
> > >
> > >   - You can create a WX or RWX mapping if and only if you have EXECMEM.
> > >
> > >   - To create an X mapping of an enclave page that has ever been W, you
> > > need EXECMOD.
> >
> > EXECMOD to what file? The enclave file from which the page's content
> > originated, the sigstruct file, or /dev/sgx/enclave?
> 
> I leave that decision to you :)  The user should need permission to do
> an execmod thing on an enclave, however that wants to be encoded.

But that decision dictates how the SGX API handles sigstruct.  If LSMs
want to associate EXECMOD with sigstruct, then SGX needs to take sigstruct
early and hold a reference to the file for the lifetime of the enclave.
And if we're going to do that, the whole approach of inheriting
permissions from source VMAs becomes unnecessary complexity.

> >
> > >   - To create an X mapping of an enclave page that came from EADD, you
> > > need EXECUTE on the source file.  Optionally, we could also permit
> > > this if you have EXECMOD.
> >
> > What is the "source file" i.e. the target of the check?  Enclave file,
> > sigstruct file, or /dev/sgx/enclave?
> 
> Enclave file -- that is, the file backing the vma from which the data is loaded.

It wasn't explicitly called out in Andy's proposal(s), but the idea is
that the SGX driver would effectively inherit permissions from the source
VMA (EADD needs a source for the initial value of the encave page).

I have two gripes with that approach:

  - Requires enclave builder to mark enclave pages executable in the
    non-enclave VMAs, which may unnecessarily require EXECMOD on the
    source file, or even worse, EXECMEM, and potentially increases the
    attack surface since the file must be executable.

  - Is completely unnecessary if the enclave holds a reference to the
    sigstruct file, as LSMs can easily apply labels to the sigstruct,
    e.g. EXECUTE on the sigstruct instead of EXECUTE on the source file.


After the bajillion mails we've generated, AIUI we've come up with two
concepts that are viable: inheriting permissions from the source VMA
vs. using sigstruct as a proxy for the enclave.  Andy's proposals rely on
the inheritance concept.  The proposal below is based on the sigstruct
proxy concept.

For those not familiar with SGX details, sigstruct can be used as a proxy
because hardware enforces that the measurement stored in the sigstruct
exactly matches the measurement generated by the enclave build process,
e.g. adding a page as RX instead of R will change the measurement.

Core Concepts:
  - FILE_{READ,WRITE,EXEC} on /dev/sgx/enclave effectively gates access to
    EPC.  All real world enclaves will need all three permissions.
  - sigstruct is the proxy for enclave from an LSM perspective, e.g.
    SELinux can define ENCLAVE__EXECUTE and ENCLAVE__EXECMOD and apply
    them to the sigstruct file.
  - Take sigstruct at ECREATE so that ADD_REGION immediately followed by
    mprotect() works as expected (because SGX.mprotect() needs sigstruct
    to pass to security_enclave_mprotect(), see below).
  - SGX driver takes a reference to the backing sigstruct file if it
    exists so that the file can be provided to LSMs during mprotect().
  - Optional: SGX driver *requires* sigstruct to be backed by file, purely
    to enforce userspace infrastructure is in place for LSM support.

W^X handling:
  - mmap() to /dev/sgx/enclave only allowed with PROT_NONE, i.e. force
    userspace through mprotect() to simplify the kernel implementation.
  - Add vm_ops mprotect() ops hook (I'll refer to SGX's implementation
    as SGX.mprotect())
  - Take explicit ALLOW_WRITE at ADD_REGION, a.k.a. EADD
  - ADD_REGION also used to describe EAUG region (tentatively for SGX2).
  - Track "can be written at some point in time (past or future)" as
    ALLOW_WRITE (to avoid confusiong with MAY_WRITE).  A priori knowledge
    of writability avoids having to track/coordinate PROT_WRITE across
    VMAs and MMs.
  - SGX.mprotect() returns -EPERM if PROT_WRITE && !ALLOW_WRITE.
  - Add security_enclave_mprotect() LSM hook, called by SGX.mprotect(),
    e.g. int security_enclave_mprotect(struct file *sigstruct,
                                       unsigned long prot,
                                       bool allow_write)
  - Intention is that EXECMOD is required if PROT_EXEC and ALLOW_WRITE.

Enclave {white,black}listing:
  - Optional/Future: add security_enclave_create(), invoked during
    SGX ECREATE ioctl(), e.g.
       int security_enclave_create(struct vm_area_struct *sigstruct)

  - If this LSM hook is implemented, having sigstruct at ECREATE
    allows LSMs to determine whether or not the enclave is allowed to
    execute before allocating EPC for the enclave, e.g. unwanted enclaves
    can't DoS wanted enclaves.

LSM implementation possibilities:

  - Define ENCLAVE__EXECUTE and ENCLAVE__EXECMOD, require them on the
    process.  Does not require sigstruct to be backed by file, but cannot
    achieve per-enclave granularity.  

  - Define ENCLAVE__EXECUTE and ENCLAVE__EXECMOD, require them on the
    sigstruct, i.e. force sigstruct to reside in filesystem.  Allows
    per-enclave granularity.

  - Reuse FILE__EXECUTE and FILE__EXECMOD on sigstruct.  Likely has
    implications that may or may not be concerning, e.g. the sigstruct
    file itself is weirdly executable.

  - Adding ENCLAVE__EXECUTE and ENCLAVE__EXECMOD means the sigstruct,
    which may be emdedded in the same file as the enclave, does *not*
    require FILE__EXECUTE or FILE__EXECMOD, e.g. can be read-only.

  - LSMs can (will?) require ENCLAVE__EXECUTE and ENCLAVE__EXECMOD to
    effectively map an enclave, even if the process acquired the enclave
    via SCM_RIGHTS (enclaves are tracked by fds).  This is good or bad
    depending on your perspective.

Userspace changes:

  - EADD ioctl adds flags param to take ALLOW_WRITE

  - ECREATE ioctl takes sigstruct instead of EINIT

  - Initial mmap() must be PROT_NONE.

  - sigstruct likely needs to reside in a file (this may not affect
    some userspace implementations).

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 18:01                                                                                                                                     ` Sean Christopherson
@ 2019-05-30 19:20                                                                                                                                       ` Andy Lutomirski
  2019-05-30 21:16                                                                                                                                         ` Sean Christopherson
  2019-05-30 21:48                                                                                                                                         ` Xing, Cedric
  2019-06-03 21:05                                                                                                                                       ` Jarkko Sakkinen
  1 sibling, 2 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-30 19:20 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, William Roberts,
	Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 11:01 AM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > On Thu, May 30, 2019 at 8:04 AM Stephen Smalley <sds@tycho.nsa.gov> wrote:
> > >
> > > On 5/30/19 10:31 AM, Andy Lutomirski wrote:
> > > > Hi all-
> > > >
> > > > After an offline discussion with Sean yesterday, here are some updates
> > > > to the user API parts of my proposal.
> > > >
> > > > Unfortunately, Sean convinced me that MAXPERM doesn't work the way I
> > > > described it because, for SGX2, the enclave loader won't know at load
> > > > time whether a given EAUG-ed page will ever be executed.  So here's an
> > > > update.
> > > >
> > > > First, here are the requrements as I see them, where EXECUTE, EXECMOD,
> > > > and EXECMEM could be substituted with other rules at the LSM's
> > > > discretion:
> > > >
> > > >   - You can create a WX or RWX mapping if and only if you have EXECMEM.
> > > >
> > > >   - To create an X mapping of an enclave page that has ever been W, you
> > > > need EXECMOD.
> > >
> > > EXECMOD to what file? The enclave file from which the page's content
> > > originated, the sigstruct file, or /dev/sgx/enclave?
> >
> > I leave that decision to you :)  The user should need permission to do
> > an execmod thing on an enclave, however that wants to be encoded.
>
> But that decision dictates how the SGX API handles sigstruct.  If LSMs
> want to associate EXECMOD with sigstruct, then SGX needs to take sigstruct
> early and hold a reference to the file for the lifetime of the enclave.
> And if we're going to do that, the whole approach of inheriting
> permissions from source VMAs becomes unnecessary complexity.
>
> > >
> > > >   - To create an X mapping of an enclave page that came from EADD, you
> > > > need EXECUTE on the source file.  Optionally, we could also permit
> > > > this if you have EXECMOD.
> > >
> > > What is the "source file" i.e. the target of the check?  Enclave file,
> > > sigstruct file, or /dev/sgx/enclave?
> >
> > Enclave file -- that is, the file backing the vma from which the data is loaded.
>
> It wasn't explicitly called out in Andy's proposal(s), but the idea is
> that the SGX driver would effectively inherit permissions from the source
> VMA (EADD needs a source for the initial value of the encave page).

I actually meant for it to *not* work like this.  I don't want the
source VMA to have to be VM_EXEC.  I think the LSM should just check
permissions on ->vm_file.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 19:20                                                                                                                                       ` Andy Lutomirski
@ 2019-05-30 21:16                                                                                                                                         ` Sean Christopherson
  2019-05-30 21:23                                                                                                                                           ` Andy Lutomirski
  2019-05-30 21:48                                                                                                                                         ` Xing, Cedric
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-05-30 21:16 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Xing, Cedric, William Roberts, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 12:20:45PM -0700, Andy Lutomirski wrote:
> On Thu, May 30, 2019 at 11:01 AM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > > Enclave file -- that is, the file backing the vma from which the data is loaded.
> >
> > It wasn't explicitly called out in Andy's proposal(s), but the idea is
> > that the SGX driver would effectively inherit permissions from the source
> > VMA (EADD needs a source for the initial value of the encave page).
> 
> I actually meant for it to *not* work like this.  I don't want the
> source VMA to have to be VM_EXEC.  I think the LSM should just check
> permissions on ->vm_file.

But if ->vm_file is NULL, i.e. the enclave is not backed by a file,
then PROCESS__EXECMEM is required (or more likely, ENCLAVE__EXECMEM).

In practice, it's the same net effect of using sigstruct as a proxy,
i.e. *something* has to get to the file system to avoid EXECMEM.  But
putting the entire enclave to the filesystem seems like a heaver lift
than dumping the sigstruct.

And if sigstruct needs to be in the file system for
security_enclave_create/init()...

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 21:16                                                                                                                                         ` Sean Christopherson
@ 2019-05-30 21:23                                                                                                                                           ` Andy Lutomirski
  2019-05-30 21:36                                                                                                                                             ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Andy Lutomirski @ 2019-05-30 21:23 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, William Roberts,
	Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 2:16 PM Sean Christopherson
<sean.j.christopherson@intel.com> wrote:
>
> On Thu, May 30, 2019 at 12:20:45PM -0700, Andy Lutomirski wrote:
> > On Thu, May 30, 2019 at 11:01 AM Sean Christopherson
> > <sean.j.christopherson@intel.com> wrote:
> > >
> > > On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > > > Enclave file -- that is, the file backing the vma from which the data is loaded.
> > >
> > > It wasn't explicitly called out in Andy's proposal(s), but the idea is
> > > that the SGX driver would effectively inherit permissions from the source
> > > VMA (EADD needs a source for the initial value of the encave page).
> >
> > I actually meant for it to *not* work like this.  I don't want the
> > source VMA to have to be VM_EXEC.  I think the LSM should just check
> > permissions on ->vm_file.
>
> But if ->vm_file is NULL, i.e. the enclave is not backed by a file,
> then PROCESS__EXECMEM is required (or more likely, ENCLAVE__EXECMEM).
>

If ->vm_file is NULL, then I think some privilege is needed.  I
suppose the policy could have a new lesser permission EXECUNTRUSTED
which is like EXECMOD but you can't modify it.  I'm not convinced this
is particular important.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 21:23                                                                                                                                           ` Andy Lutomirski
@ 2019-05-30 21:36                                                                                                                                             ` Sean Christopherson
  2019-06-03  9:12                                                                                                                                               ` Dr. Greg
  2019-06-03 21:08                                                                                                                                               ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-30 21:36 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Xing, Cedric, William Roberts, Jarkko Sakkinen,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 02:23:07PM -0700, Andy Lutomirski wrote:
> On Thu, May 30, 2019 at 2:16 PM Sean Christopherson
> <sean.j.christopherson@intel.com> wrote:
> >
> > On Thu, May 30, 2019 at 12:20:45PM -0700, Andy Lutomirski wrote:
> > > On Thu, May 30, 2019 at 11:01 AM Sean Christopherson
> > > <sean.j.christopherson@intel.com> wrote:
> > > >
> > > > On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > > > > Enclave file -- that is, the file backing the vma from which the data is loaded.
> > > >
> > > > It wasn't explicitly called out in Andy's proposal(s), but the idea is
> > > > that the SGX driver would effectively inherit permissions from the source
> > > > VMA (EADD needs a source for the initial value of the encave page).
> > >
> > > I actually meant for it to *not* work like this.  I don't want the
> > > source VMA to have to be VM_EXEC.  I think the LSM should just check
> > > permissions on ->vm_file.
> >
> > But if ->vm_file is NULL, i.e. the enclave is not backed by a file,
> > then PROCESS__EXECMEM is required (or more likely, ENCLAVE__EXECMEM).
> >
> 
> If ->vm_file is NULL, then I think some privilege is needed.  I
> suppose the policy could have a new lesser permission EXECUNTRUSTED
> which is like EXECMOD but you can't modify it.  I'm not convinced this
> is particular important.

Assuming MRENCLAVE generated by Graphene or any other hosting scheme are
stable[1], then avoiding EXEC<whatever> means the user can effectively
whitelist what enclaves are runnable by Graphene, even if the kernel
doesn't implement security_enclave_create/init().

I agree that it probably isn't all that important, it's more of a "why
not" argument, i.e. what is gained by not using sigstruct as a proxy?

[1] What in the world is being attested if MRENCLAVE isn't stable?

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

* RE: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 19:20                                                                                                                                       ` Andy Lutomirski
  2019-05-30 21:16                                                                                                                                         ` Sean Christopherson
@ 2019-05-30 21:48                                                                                                                                         ` Xing, Cedric
  2019-05-30 22:24                                                                                                                                           ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-05-30 21:48 UTC (permalink / raw)
  To: Andy Lutomirski, Christopherson, Sean J
  Cc: Stephen Smalley, William Roberts, Jarkko Sakkinen, James Morris,
	Serge E. Hallyn, LSM List, Paul Moore, Eric Paris, selinux,
	Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

Hi Andy,

I'm just curious how Sean convinced you that "MAXPERM doesn't work". More specifically, I'm objecting to the statement of "the enclave loader won't know at load time whether a given EAUG-ed page will ever be executed".

I'm still new to LSM so my understanding may not be correct. But I think LSM policy defines a boundary that "loosely" restricts what a process can do. By "loosely", I mean it is usually more permissive than a process needs. For example, FILE__EXECMOD basically says there are self-modifying code in a file, but it isn't specific on which pages contain self-modifying code, hence *all* pages are allowed mprotect(RW->RX) even though only a (small) subset actually need it. LSM policies are static too, as FILE__EXECMOD is given by a system admin to be associated with the disk file, instead of being requested/programmed by any processes loading/mapping that file.

So I think the same rationale applies to enclaves. Your original idea of MAXPERM is the policy set forth by system admin and shall *never* change at runtime. If an enclave is dynamically linked and needs to bring in code pages at runtime, the admin needs to enable it by setting, say ENCLAVE__EXECMOD, in the sigstruct file. Then all EAUG'ed pages will receive RWX as MAXPERM. The process would then mprotect() selective pages to be RX but which exact set of pages doesn't concern LSM usually.

> From: Andy Lutomirski [mailto:luto@kernel.org]
> Sent: Thursday, May 30, 2019 12:21 PM
> 
> On Thu, May 30, 2019 at 11:01 AM Sean Christopherson <sean.j.christopherson@intel.com>
> wrote:
> >
> > On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > > On Thu, May 30, 2019 at 8:04 AM Stephen Smalley <sds@tycho.nsa.gov> wrote:
> > > >
> > > > On 5/30/19 10:31 AM, Andy Lutomirski wrote:
> > > > > Hi all-
> > > > >
> > > > > After an offline discussion with Sean yesterday, here are some
> > > > > updates to the user API parts of my proposal.
> > > > >
> > > > > Unfortunately, Sean convinced me that MAXPERM doesn't work the
> > > > > way I described it because, for SGX2, the enclave loader won't
> > > > > know at load time whether a given EAUG-ed page will ever be
> > > > > executed.  So here's an update.
> > > > >
> > > > > First, here are the requrements as I see them, where EXECUTE,
> > > > > EXECMOD, and EXECMEM could be substituted with other rules at
> > > > > the LSM's
> > > > > discretion:
> > > > >
> > > > >   - You can create a WX or RWX mapping if and only if you have EXECMEM.
> > > > >
> > > > >   - To create an X mapping of an enclave page that has ever been
> > > > > W, you need EXECMOD.
> > > >
> > > > EXECMOD to what file? The enclave file from which the page's
> > > > content originated, the sigstruct file, or /dev/sgx/enclave?
> > >
> > > I leave that decision to you :)  The user should need permission to
> > > do an execmod thing on an enclave, however that wants to be encoded.
> >
> > But that decision dictates how the SGX API handles sigstruct.  If LSMs
> > want to associate EXECMOD with sigstruct, then SGX needs to take
> > sigstruct early and hold a reference to the file for the lifetime of the enclave.
> > And if we're going to do that, the whole approach of inheriting
> > permissions from source VMAs becomes unnecessary complexity.
> >
> > > >
> > > > >   - To create an X mapping of an enclave page that came from
> > > > > EADD, you need EXECUTE on the source file.  Optionally, we could
> > > > > also permit this if you have EXECMOD.
> > > >
> > > > What is the "source file" i.e. the target of the check?  Enclave
> > > > file, sigstruct file, or /dev/sgx/enclave?
> > >
> > > Enclave file -- that is, the file backing the vma from which the data is loaded.
> >
> > It wasn't explicitly called out in Andy's proposal(s), but the idea is
> > that the SGX driver would effectively inherit permissions from the
> > source VMA (EADD needs a source for the initial value of the encave page).
> 
> I actually meant for it to *not* work like this.  I don't want the source VMA to have to
> be VM_EXEC.  I think the LSM should just check permissions on ->vm_file.

-Cedric

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 21:48                                                                                                                                         ` Xing, Cedric
@ 2019-05-30 22:24                                                                                                                                           ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-05-30 22:24 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Andy Lutomirski, Stephen Smalley, William Roberts,
	Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 02:48:43PM -0700, Xing, Cedric wrote:
> So I think the same rationale applies to enclaves. Your original idea of
> MAXPERM is the policy set forth by system admin and shall *never* change at
> runtime. If an enclave is dynamically linked and needs to bring in code pages
> at runtime, the admin needs to enable it by setting, say ENCLAVE__EXECMOD, in
> the sigstruct file. Then all EAUG'ed pages will receive RWX as MAXPERM. The
> process would then mprotect() selective pages to be RX but which exact set of
> pages doesn't concern LSM usually.

Because passing RWX means the enclave "requires" EXECMOD even if it never
actually does a RW->RX transition.  It's not broken per se, but at the
very least it's decidedly odd.

Dynamically detecting the EXECMOD case is not difficult and has the
advantage of simplifying userspace loaders, e.g. all EAUG pages are tagged
ALLOW_WRITE and the kernel takes care of the rest.

I *think* auditing/learning is also messed up with a MAXPERMS approach, as
mprotect() would fail (due to MAXPERMS clearing MAY_{READ,WRITE,EXEC})
before it calls security_file_mprotect().  Hooking mprotect() is the
obvious workaround, but then it's looking a lot like the new proposals.

In other words, the new proposals are rooted in the MAXPERMS concept, e.g.
MAXPERM is effectively "I want EXECMOD", which gets distilled down to
ALLOW_WRITE (or ALLOW_EXEC in Andy's proposal).

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 21:36                                                                                                                                             ` Sean Christopherson
@ 2019-06-03  9:12                                                                                                                                               ` Dr. Greg
  2019-06-03 21:08                                                                                                                                               ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Dr. Greg @ 2019-06-03  9:12 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, William Roberts,
	Jarkko Sakkinen, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Linus Torvalds, LKML, X86 ML, linux-sgx,
	Andrew Morton, nhorman, npmccallum, Ayoun, Serge, Katz-zamir,
	Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 02:36:01PM -0700, Sean Christopherson wrote:

Good morning, I hope everyone had a pleasant weekend.

> Assuming MRENCLAVE generated by Graphene or any other hosting scheme
> are stable[1], then avoiding EXEC<whatever> means the user can
> effectively whitelist what enclaves are runnable by Graphene, even
> if the kernel doesn't implement security_enclave_create/init().
>
> I agree that it probably isn't all that important, it's more of a
> "why not" argument, i.e. what is gained by not using sigstruct as a
> proxy?
>
> [1] What in the world is being attested if MRENCLAVE isn't stable?

The cryptographic identity of the entity that signed the enclave and
generated the SIGSTRUCT.

At the risk of being the monotone in the choir, any relevant SGX
security controls require verifying the identity of whoever signed the
identity characteristics (SIGSTRUCT) of the image that initiates the
execution of an SGX TEE.  Other then verifying the initial execution
image, the MRENCLAVE value isn't all that relevant.

This issue is further evidenced by the fact that sealing data to an
enclave uses the MRSIGNER variant of ENCLU[EGETKEY] key derivation.

The current work on LSM controls seems to focus on the identity of the
entity that is requesting the image to be loaded rather then who
actually signed, and presumably authored, the code.  As I have
previously noted, with SGX2/EDMM, a platform owner may not even have
any visibility into the code that an SGX TEE may ultimately load and
execute.

Any security relevant LSM control in this space has to focus on
providing the platform owner the ability to take action based on the
contents of the SIGSTRUCT of the initiating image.  In addition to the
identity of who is requesting the image to be loaded.

Have a good 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
FAX: 701-281-3949           EMAIL: greg@enjellic.com
------------------------------------------------------------------------------
"Experience is something you don't get until just after you need it."
                                -- Olivier

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 14:31                                                                                                                               ` Andy Lutomirski
  2019-05-30 15:04                                                                                                                                 ` Stephen Smalley
@ 2019-06-03 20:43                                                                                                                                 ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-03 20:43 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Xing, Cedric, Christopherson, Sean J,
	William Roberts, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 07:31:14AM -0700, Andy Lutomirski wrote:
>  - To create an X mapping of an enclave page that came from EADD, you
> need EXECUTE on the source file.  Optionally, we could also permit
> this if you have EXECMOD.

Source file? EADD ioctl takes memory buffer in right now.

> And I have two design proposals.  One is static and one is dynamic.
> To implement either one, we will probably need a new .may_mprotect vm
> operation, and that operation can call an LSM hook.  Or we can give
> LSMs a way to detect that a given vm_area_struct is an enclave.  As I
> see it, this is an implementation detail that is certainly solveable.

Why VM operation and not file operation?

> EADD takes an execute_intent flag.  It calls a new hook:
> 
>   int security_enclave_load(struct vm_area_struct *source, bool execute_intent);
> 
> This hook will fail if execute_intent==true and the caller has neither
> EXECUTE, EXECMOD, nor EXECMEM.
> 
> EAUG sets execute_intent = false.
> 
> EINIT takes a sigstruct pointer.  SGX can (when initially upstreamed
> or later on once there's demand) call a new hook:
> 
>   security_enclave_init(struct sigstruct *sigstruct, struct
> vm_area_struct *source);

What is the source VMA in these callbacks? Why is @execute_intent
needed anyway as a ioctl arugment and not deduced from SECINFO?

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 15:04                                                                                                                                 ` Stephen Smalley
  2019-05-30 16:14                                                                                                                                   ` Andy Lutomirski
@ 2019-06-03 20:47                                                                                                                                   ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-03 20:47 UTC (permalink / raw)
  To: Stephen Smalley
  Cc: Andy Lutomirski, Xing, Cedric, Christopherson, Sean J,
	William Roberts, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 11:04:24AM -0400, Stephen Smalley wrote:
> Does this occur for both setting initial permissions and runtime permissions
> or just runtime? Both userspace- and driver-initiated mmap/mprotect
> operations or just userspace-initiated ones?  Does the driver use interfaces
> that call the mmap/mprotect hooks or lower level functions?

The driver never initiates mmap() or mprotect().

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 16:14                                                                                                                                   ` Andy Lutomirski
  2019-05-30 18:01                                                                                                                                     ` Sean Christopherson
@ 2019-06-03 20:54                                                                                                                                     ` Jarkko Sakkinen
  2019-06-03 21:23                                                                                                                                       ` Sean Christopherson
  2019-06-03 21:37                                                                                                                                       ` Andy Lutomirski
  1 sibling, 2 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-03 20:54 UTC (permalink / raw)
  To: Andy Lutomirski
  Cc: Stephen Smalley, Xing, Cedric, Christopherson, Sean J,
	William Roberts, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > What is the "source file" i.e. the target of the check?  Enclave file,
> > sigstruct file, or /dev/sgx/enclave?
> 
> Enclave file -- that is, the file backing the vma from which the data
> is loaded.

Wonder why KVM gets away without having this given that enclaves are
lot alike VMs.

> It's provided by userspace based on whether it thinks the data in
> question is enclave code.  source->vm_file is the file from which the
> code is being loaded.  I'm assuming that the user code will only set
> excute_intent ==true if it actually wants to execute the code, so, if
> there's a denial, it will be fatal.  The normal case will be that the
> request will be granted on the basis of EXECUTE.

AFAIK user spaces tells that already with the SECINFO flags. I don't
get why we need a duplicate parameter.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 18:01                                                                                                                                     ` Sean Christopherson
  2019-05-30 19:20                                                                                                                                       ` Andy Lutomirski
@ 2019-06-03 21:05                                                                                                                                       ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-03 21:05 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, William Roberts,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 11:01:10AM -0700, Sean Christopherson wrote:
>   - Requires enclave builder to mark enclave pages executable in the
>     non-enclave VMAs, which may unnecessarily require EXECMOD on the
>     source file, or even worse, EXECMEM, and potentially increases the
>     attack surface since the file must be executable.

Enclave builder marks *non-enclave pages*? Not following.

> W^X handling:
>   - mmap() to /dev/sgx/enclave only allowed with PROT_NONE, i.e. force
>     userspace through mprotect() to simplify the kernel implementation.
>   - Add vm_ops mprotect() ops hook (I'll refer to SGX's implementation
>     as SGX.mprotect())
>   - Take explicit ALLOW_WRITE at ADD_REGION, a.k.a. EADD
>   - ADD_REGION also used to describe EAUG region (tentatively for SGX2).
>   - Track "can be written at some point in time (past or future)" as
>     ALLOW_WRITE (to avoid confusiong with MAY_WRITE).  A priori knowledge
>     of writability avoids having to track/coordinate PROT_WRITE across
>     VMAs and MMs.

Still not sure why you want to use vm_ops instead of file_operations.

The approach I've been proposing earlier in this email thread before
these new proposals can be summarized from hook perspective as:

- Allow mmap() only before ECREATE and require it to be size
  of the ELRANGE (ECREATE ioctl would check this). This would
  be with PROT_NONE.
- Disallow mprotect() before EINIT. Requires a new callback
  to file_operations like mmap() has.
- After EINIT check for each mprotect() that it matches the
  permissions of underlying enclave pages. Disallow mmap()
  after EINIT.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-05-30 21:36                                                                                                                                             ` Sean Christopherson
  2019-06-03  9:12                                                                                                                                               ` Dr. Greg
@ 2019-06-03 21:08                                                                                                                                               ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-03 21:08 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, William Roberts,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Thu, May 30, 2019 at 02:36:01PM -0700, Sean Christopherson wrote:
> Assuming MRENCLAVE generated by Graphene or any other hosting scheme are
> stable[1], then avoiding EXEC<whatever> means the user can effectively
> whitelist what enclaves are runnable by Graphene, even if the kernel
> doesn't implement security_enclave_create/init().
> 
> I agree that it probably isn't all that important, it's more of a "why
> not" argument, i.e. what is gained by not using sigstruct as a proxy?
> 
> [1] What in the world is being attested if MRENCLAVE isn't stable?

If I've understood correctly, Graphene uses a single loader enclave
that loads the executable in.

/Jarkko

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-06-03 20:54                                                                                                                                     ` Jarkko Sakkinen
@ 2019-06-03 21:23                                                                                                                                       ` Sean Christopherson
  2019-06-04 11:39                                                                                                                                         ` Jarkko Sakkinen
  2019-06-03 21:37                                                                                                                                       ` Andy Lutomirski
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-06-03 21:23 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, William Roberts,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Mon, Jun 03, 2019 at 11:54:05PM +0300, Jarkko Sakkinen wrote:
> On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > > What is the "source file" i.e. the target of the check?  Enclave file,
> > > sigstruct file, or /dev/sgx/enclave?
> > 
> > Enclave file -- that is, the file backing the vma from which the data
> > is loaded.
> 
> Wonder why KVM gets away without having this given that enclaves are
> lot alike VMs.

From a memory management perspective, VMs are not at all like enclaves.
An enclave is an extension of its host, i.e. runs in the same address.
This isn't strictly necessary, e.g. an enclave could run in a sandbox
process, but even then the enclave will be running with the kernel's
standard page tables.

A VM is a essentially an opaque blob of data that gets loaded into memory.
KVM builds a completely different set of page tables for the VM, the VM
has it's own file system (or perhaps doesn't have a file system at all),
etc...  Ignoring Spectre and L1TF, the VM is contained to its own world.

There are a lot of ways for a userspace VMM to expose things beyond raw
memory, but doing so requires the appropriate permissions.

And practically speaking, all traditional VMs will effectively need RWX
memory, i.e. Qemu (or any other userspace VMM) would be required to have
EXECMEM permissions, which would be a net negative for security.

> > It's provided by userspace based on whether it thinks the data in
> > question is enclave code.  source->vm_file is the file from which the
> > code is being loaded.  I'm assuming that the user code will only set
> > excute_intent ==true if it actually wants to execute the code, so, if
> > there's a denial, it will be fatal.  The normal case will be that the
> > request will be granted on the basis of EXECUTE.
> 
> AFAIK user spaces tells that already with the SECINFO flags. I don't
> get why we need a duplicate parameter.

Please read through the RFC, I think it address a lot of your questions.
Hopefully that will help us avoid some thrash.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-06-03 20:54                                                                                                                                     ` Jarkko Sakkinen
  2019-06-03 21:23                                                                                                                                       ` Sean Christopherson
@ 2019-06-03 21:37                                                                                                                                       ` Andy Lutomirski
  1 sibling, 0 replies; 318+ messages in thread
From: Andy Lutomirski @ 2019-06-03 21:37 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, Christopherson,
	Sean J, William Roberts, James Morris, Serge E. Hallyn, LSM List,
	Paul Moore, Eric Paris, selinux, Jethro Beekman, Hansen, Dave,
	Thomas Gleixner, Dr. Greg, Linus Torvalds, LKML, X86 ML,
	linux-sgx, Andrew Morton, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, Andy Shevchenko, Svahn, Kai,
	Borislav Petkov, Josh Triplett, Huang, Kai, David Rientjes

On Mon, Jun 3, 2019 at 1:54 PM Jarkko Sakkinen
<jarkko.sakkinen@linux.intel.com> wrote:
>
> On Thu, May 30, 2019 at 09:14:10AM -0700, Andy Lutomirski wrote:
> > > What is the "source file" i.e. the target of the check?  Enclave file,
> > > sigstruct file, or /dev/sgx/enclave?
> >
> > Enclave file -- that is, the file backing the vma from which the data
> > is loaded.
>
> Wonder why KVM gets away without having this given that enclaves are
> lot alike VMs.
>

I would argue it's because access to /dev/kvm means you can execute
whatever you code you want in a VM.  I don't see how this is
avoidable. On the other hand, it would be nice for SGX to not imply
this same sort of "execute anything" right, especially since, unlike
KVM, SGX is not a sandbox.

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

* Re: SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support)
  2019-06-03 21:23                                                                                                                                       ` Sean Christopherson
@ 2019-06-04 11:39                                                                                                                                         ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-04 11:39 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Andy Lutomirski, Stephen Smalley, Xing, Cedric, William Roberts,
	James Morris, Serge E. Hallyn, LSM List, Paul Moore, Eric Paris,
	selinux, Jethro Beekman, Hansen, Dave, Thomas Gleixner, Dr. Greg,
	Linus Torvalds, LKML, X86 ML, linux-sgx, Andrew Morton, nhorman,
	npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang, Haitao,
	Andy Shevchenko, Svahn, Kai, Borislav Petkov, Josh Triplett,
	Huang, Kai, David Rientjes

On Mon, Jun 03, 2019 at 02:23:36PM -0700, Sean Christopherson wrote:
> Please read through the RFC, I think it address a lot of your questions.
> Hopefully that will help us avoid some thrash.

I promise to read it through with detail albeit I just said that as a
patch set it is broken :-) Internals still need documentation tho...

/Jarkko

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-04-24  0:26       ` Sean Christopherson
  2019-04-24  1:04         ` Jethro Beekman
@ 2019-06-04 20:12         ` Sean Christopherson
  2019-06-05 14:29           ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-06-04 20:12 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Jethro Beekman, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	nhorman, npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

On Tue, Apr 23, 2019 at 05:26:53PM -0700, Sean Christopherson wrote:
> On Tue, Apr 23, 2019 at 11:29:24PM +0000, Jethro Beekman wrote:
> > On 2019-04-22 14:58, Sean Christopherson wrote:
> > >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.
> 
> > >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...

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

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-06-04 20:12         ` Sean Christopherson
@ 2019-06-05 14:29           ` Jarkko Sakkinen
  2019-06-05 14:52             ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-05 14:29 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Jethro Beekman, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	nhorman, npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

On Tue, Jun 04, 2019 at 01:12:32PM -0700, Sean Christopherson wrote:
> On Tue, Apr 23, 2019 at 05:26:53PM -0700, Sean Christopherson wrote:
> > On Tue, Apr 23, 2019 at 11:29:24PM +0000, Jethro Beekman wrote:
> > > On 2019-04-22 14:58, Sean Christopherson wrote:
> > > >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.
> > 
> > > >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...
> 
> 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

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-06-05 14:29           ` Jarkko Sakkinen
@ 2019-06-05 14:52             ` Sean Christopherson
  2019-06-05 21:25               ` Dr. Greg
  2019-06-06 15:32               ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-06-05 14:52 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Jethro Beekman, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	nhorman, npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

On Wed, Jun 05, 2019 at 05:29:08PM +0300, Jarkko Sakkinen wrote:
> On Tue, Jun 04, 2019 at 01:12:32PM -0700, Sean Christopherson wrote:
> > On Tue, Apr 23, 2019 at 05:26:53PM -0700, Sean Christopherson wrote:
> > > On Tue, Apr 23, 2019 at 11:29:24PM +0000, Jethro Beekman wrote:
> > > > On 2019-04-22 14:58, Sean Christopherson wrote:
> > > > >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.
> > > 
> > > > >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...
> > 
> > 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.

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-06-05 14:52             ` Sean Christopherson
@ 2019-06-05 21:25               ` Dr. Greg
  2019-06-05 22:20                 ` Sean Christopherson
  2019-06-06 15:32               ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Dr. Greg @ 2019-06-05 21:25 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Jarkko Sakkinen, Jethro Beekman, linux-kernel, x86, linux-sgx,
	akpm, dave.hansen, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

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

Good afternoon to everyone.

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

>   - 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: greg@enjellic.com
------------------------------------------------------------------------------
"System Administration is a few hours of boredom followed by several
 moments of intense fear."
                                -- Tom ONeil

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-06-05 21:25               ` Dr. Greg
@ 2019-06-05 22:20                 ` Sean Christopherson
  0 siblings, 0 replies; 318+ messages in thread
From: Sean Christopherson @ 2019-06-05 22:20 UTC (permalink / raw)
  To: Dr. Greg
  Cc: Jarkko Sakkinen, Jethro Beekman, linux-kernel, x86, linux-sgx,
	akpm, dave.hansen, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes

On Wed, Jun 05, 2019 at 04:25:37PM -0500, Dr. Greg wrote:
> On Wed, Jun 05, 2019 at 07:52:19AM -0700, Sean Christopherson wrote:
> 
> Good afternoon to everyone.
> 
> > 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.

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".

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

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

* Re: [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver
  2019-06-05 14:52             ` Sean Christopherson
  2019-06-05 21:25               ` Dr. Greg
@ 2019-06-06 15:32               ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-06 15:32 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Jethro Beekman, linux-kernel, x86, linux-sgx, akpm, dave.hansen,
	nhorman, npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes

On Wed, Jun 05, 2019 at 07:52:19AM -0700, Sean Christopherson wrote:
> 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.

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

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

* Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling
  2019-04-17 10:39 ` [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions " Jarkko Sakkinen
@ 2019-06-25 15:43   ` Jarkko Sakkinen
  2019-06-27 20:32     ` Xing, Cedric
  2019-07-11 15:56     ` Sean Christopherson
  0 siblings, 2 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-06-25 15:43 UTC (permalink / raw)
  To: linux-kernel, x86, linux-sgx, sean.j.christopherson
  Cc: akpm, dave.hansen, nhorman, npmccallum, serge.ayoun,
	shay.katz-zamir, haitao.huang, andriy.shevchenko, tglx,
	kai.svahn, bp, josh, luto, kai.huang, rientjes, Andy Lutomirski,
	Dave Hansen

On Wed, Apr 17, 2019 at 01:39:32PM +0300, Jarkko Sakkinen wrote:
> From: Sean Christopherson <sean.j.christopherson@intel.com>
> 
> 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.
> 
> Suggested-by: Andy Lutomirski <luto@amacapital.net>
> Cc: Andy Lutomirski <luto@amacapital.net>
> Cc: Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
> Cc: Dave Hansen <dave.hansen@linux.intel.com>
> Cc: Josh Triplett <josh@joshtriplett.org>
> Signed-off-by: Sean Christopherson <sean.j.christopherson@intel.com>

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

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

* RE: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling
  2019-06-25 15:43   ` Jarkko Sakkinen
@ 2019-06-27 20:32     ` Xing, Cedric
  2019-07-11 15:54       ` Sean Christopherson
  2019-07-11 15:56     ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-06-27 20:32 UTC (permalink / raw)
  To: Jarkko Sakkinen, linux-kernel, x86, linux-sgx, Christopherson, Sean J
  Cc: akpm, Hansen, Dave, nhorman, npmccallum, Ayoun, Serge,
	Katz-zamir, Shay, Huang, Haitao, andriy.shevchenko, tglx, Svahn,
	Kai, bp, josh, luto, Huang, Kai, rientjes, Andy Lutomirski,
	Dave Hansen

> From: linux-sgx-owner@vger.kernel.org [mailto:linux-sgx-
> owner@vger.kernel.org] 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. 

> 
> 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

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
@ 2019-07-10 11:17     ` Jarkko Sakkinen
  2019-07-10 18:08       ` Xing, Cedric
  2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
                       ` (3 subsequent siblings)
  4 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-10 11:17 UTC (permalink / raw)
  To: Cedric Xing
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Tue, Apr 23, 2019 at 11:26:20PM -0700, Cedric Xing wrote:
> The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
> %rsp, which prohibits enclaves from allocating space on the untrusted stack.
> However, there are existing enclaves (e.g. those built with current Intel SGX
> SDK libraries) relying on the untrusted stack for passing parameters to
> untrusted functions (aka. o-calls), which requires allocating space on the
> untrusted stack by enclaves. And given its simplicity and convenience, it could
> be desired by future SGX applications as well.  
> 
> This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its
> stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto
> the untrusted stack by decrementing the untrusted %rsp. Additionally, this new
> __vdso_sgx_enter_enclave() will take one more parameter - a callback function,
> to be invoked upon all enclave exits (both AEX and normal exits). The callback
> function will be given the value of %rsp left off by the enclave, so that data
> "pushed" by the enclave (if any) could be addressed/accessed.  Please note that
> the callback function is optional, and if not supplied (i.e. null),
> __vdso_sgx_enter_enclave() will just return (i.e. behave the same as the
> current implementation) after the enclave exits (or AEX due to exceptions).
> 
> The SGX selftest is augmented by two new tests. One exercises the new callback
> interface, and serves as a simple example to showcase how to use it; while the
> other validates the hand-crafted CFI directives in __vdso_sgx_enter_enclave()
> by single-stepping through it and unwinding call stack at every instruction.

Why does the SDK anyway use real enclaves when step debugging? I don't
think kernel needs to scale to that. For me it looks more like a bad
architectural choice in the SDK implementation than anything else.

You should design SDK in a way that it doesn't run the code inside real
enclave at first. It is just the sanest development model to use. The
current SDK has an unacceptable requirement that the workstation used to
develop code destined to run inside enclave must possess an appropriate
hardware. I don't think that is acceptable no matter what kind of API
kernel provides to invoke enclaves.

I think "real" debug enclaves are only good for production testing when
you have more or less ready to release/deploy something but still want
to be able to get a memory dump of the enclave on occassion.

With these conclusions I think the current vDSO API is sufficient for
Linux.

/Jarkko

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-10 11:17     ` Jarkko Sakkinen
@ 2019-07-10 18:08       ` Xing, Cedric
  2019-07-10 22:46         ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-07-10 18:08 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/10/2019 4:17 AM, Jarkko Sakkinen wrote:
> On Tue, Apr 23, 2019 at 11:26:20PM -0700, Cedric Xing wrote:
>> The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
>> %rsp, which prohibits enclaves from allocating space on the untrusted stack.
>> However, there are existing enclaves (e.g. those built with current Intel SGX
>> SDK libraries) relying on the untrusted stack for passing parameters to
>> untrusted functions (aka. o-calls), which requires allocating space on the
>> untrusted stack by enclaves. And given its simplicity and convenience, it could
>> be desired by future SGX applications as well.
>>
>> This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its
>> stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto
>> the untrusted stack by decrementing the untrusted %rsp. Additionally, this new
>> __vdso_sgx_enter_enclave() will take one more parameter - a callback function,
>> to be invoked upon all enclave exits (both AEX and normal exits). The callback
>> function will be given the value of %rsp left off by the enclave, so that data
>> "pushed" by the enclave (if any) could be addressed/accessed.  Please note that
>> the callback function is optional, and if not supplied (i.e. null),
>> __vdso_sgx_enter_enclave() will just return (i.e. behave the same as the
>> current implementation) after the enclave exits (or AEX due to exceptions).
>>
>> The SGX selftest is augmented by two new tests. One exercises the new callback
>> interface, and serves as a simple example to showcase how to use it; while the
>> other validates the hand-crafted CFI directives in __vdso_sgx_enter_enclave()
>> by single-stepping through it and unwinding call stack at every instruction.
> 
> Why does the SDK anyway use real enclaves when step debugging? I don't
> think kernel needs to scale to that. For me it looks more like a bad
> architectural choice in the SDK implementation than anything else.

Intel's SGX SDK *does* support simulation mode for debugging enclaves 
outside of SGX mode, or even on non-SGX platforms. But nothing can 
replace the real SGX environment, hence SGX ISA supports debugging real 
enclaves.

> You should design SDK in a way that it doesn't run the code inside real
> enclave at first. It is just the sanest development model to use. The
> current SDK has an unacceptable requirement that the workstation used to
> develop code destined to run inside enclave must possess an appropriate
> hardware. I don't think that is acceptable no matter what kind of API
> kernel provides to invoke enclaves.

SDK supports simulation on non-SGX platforms.

> I think "real" debug enclaves are only good for production testing when
> you have more or less ready to release/deploy something but still want
> to be able to get a memory dump of the enclave on occassion.

That's true.

> With these conclusions I think the current vDSO API is sufficient for
> Linux.

The new vDSO API is to support data exchange on stack. It has nothing to 
do with debugging. BTW, the community has closed on this.

The CFI directives are for stack unwinding. They don't affect what the 
code does so you can just treat them as NOPs if you don't understand 
what they do. However, they are useful to not only debuggers but also 
exception handling code. libunwind also has a setjmp()/longjmp() 
implementation based on CFI directives.

> /Jarkko
> 

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-10 18:08       ` Xing, Cedric
@ 2019-07-10 22:46         ` Jarkko Sakkinen
  2019-07-10 22:54           ` Xing, Cedric
  2019-07-10 23:15           ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-10 22:46 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
> > With these conclusions I think the current vDSO API is sufficient for
> > Linux.
> 
> The new vDSO API is to support data exchange on stack. It has nothing to do
> with debugging. BTW, the community has closed on this.

And how that is useful?

> The CFI directives are for stack unwinding. They don't affect what the code
> does so you can just treat them as NOPs if you don't understand what they
> do. However, they are useful to not only debuggers but also exception
> handling code. libunwind also has a setjmp()/longjmp() implementation based
> on CFI directives.

Of course I won't merge code of which usefulness I don't understand.

/Jarkko

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-10 22:46         ` Jarkko Sakkinen
@ 2019-07-10 22:54           ` Xing, Cedric
  2019-07-11  9:36             ` Jarkko Sakkinen
  2019-07-10 23:15           ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-07-10 22:54 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/10/2019 3:46 PM, Jarkko Sakkinen wrote:
> On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
>>> With these conclusions I think the current vDSO API is sufficient for
>>> Linux.
>>
>> The new vDSO API is to support data exchange on stack. It has nothing to do
>> with debugging. BTW, the community has closed on this.
> 
> And how that is useful?

There is a lengthy discussion on its usefulness so I don't want to 
repeat. In short, it allows using untrusted stack as a convenient method 
to exchange data with the enclave. It is currently being used by Intel's 
SGX SDK for e/o-calls parameters.

>> The CFI directives are for stack unwinding. They don't affect what the code
>> does so you can just treat them as NOPs if you don't understand what they
>> do. However, they are useful to not only debuggers but also exception
>> handling code. libunwind also has a setjmp()/longjmp() implementation based
>> on CFI directives.
> 
> Of course I won't merge code of which usefulness I don't understand.

Sure.

Any other questions I can help with?

> /Jarkko
> 

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-10 22:46         ` Jarkko Sakkinen
  2019-07-10 22:54           ` Xing, Cedric
@ 2019-07-10 23:15           ` Jarkko Sakkinen
  2019-07-10 23:37             ` Xing, Cedric
  1 sibling, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-10 23:15 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Thu, Jul 11, 2019 at 01:46:28AM +0300, Jarkko Sakkinen wrote:
> On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
> > > With these conclusions I think the current vDSO API is sufficient for
> > > Linux.
> > 
> > The new vDSO API is to support data exchange on stack. It has nothing to do
> > with debugging. BTW, the community has closed on this.
> 
> And how that is useful?
> 
> > The CFI directives are for stack unwinding. They don't affect what the code
> > does so you can just treat them as NOPs if you don't understand what they
> > do. However, they are useful to not only debuggers but also exception
> > handling code. libunwind also has a setjmp()/longjmp() implementation based
> > on CFI directives.
> 
> Of course I won't merge code of which usefulness I don't understand.

I re-read the cover letter [1] because it usually is the place
to "pitch" a feature.

It fails to address two things:

1. How and in what circumstances is an untrusted stack is a better
   vessel for handling exceptions than the register based approach
   that we already have?
2. How is it simpler approach? There is a strong claim of simplicity
   and convenience without anything backing it.
3. Why we need both register and stack based approach co-exist? I'd go
   with one approach for a new API without any legacy whatsoever.

This really needs a better pitch before we can consider doing anything
to it.

Also, in [2] there is talk about the next revision. Maybe the way go
forward is to address the three issues I found in the cover letter
and fix whatever needed to be fixed in the actual patches?

[1] https://lkml.org/lkml/2019/4/24/84
[2] https://lkml.org/lkml/2019/4/25/1170

/Jarkko

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-10 23:15           ` Jarkko Sakkinen
@ 2019-07-10 23:37             ` Xing, Cedric
  2019-07-11  9:38               ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-07-10 23:37 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/10/2019 4:15 PM, Jarkko Sakkinen wrote:
> On Thu, Jul 11, 2019 at 01:46:28AM +0300, Jarkko Sakkinen wrote:
>> On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
>>>> With these conclusions I think the current vDSO API is sufficient for
>>>> Linux.
>>>
>>> The new vDSO API is to support data exchange on stack. It has nothing to do
>>> with debugging. BTW, the community has closed on this.
>>
>> And how that is useful?
>>
>>> The CFI directives are for stack unwinding. They don't affect what the code
>>> does so you can just treat them as NOPs if you don't understand what they
>>> do. However, they are useful to not only debuggers but also exception
>>> handling code. libunwind also has a setjmp()/longjmp() implementation based
>>> on CFI directives.
>>
>> Of course I won't merge code of which usefulness I don't understand.
> 
> I re-read the cover letter [1] because it usually is the place
> to "pitch" a feature.
> 
> It fails to address two things:
> 
> 1. How and in what circumstances is an untrusted stack is a better
>     vessel for handling exceptions than the register based approach
>     that we already have?

We are not judging which vessel is better (or the best) among all 
possible vessels. We are trying to enable more vessels. Every vessel has 
its pros and cons so there's *no* single best vessel.

> 2. How is it simpler approach? There is a strong claim of simplicity
>     and convenience without anything backing it.

The major benefits in terms of simplicity realize in user mode 
applications. It's always a trade-off. This vDSO API takes 10-20 more 
lines than the original one but would save hundreds or even thousands in 
user applications.

Again, I don't want to repeat everything as you can look back at the 
lengthy discussion to dig out the details.

> 3. Why we need both register and stack based approach co-exist? I'd go
>     with one approach for a new API without any legacy whatsoever.

Neither is a legacy to the other. Supporting both approaches is by 
design. Again, the goal is to enable more vessels because there's *no* 
single best vessel.

> This really needs a better pitch before we can consider doing anything
> to it.
> 
> Also, in [2] there is talk about the next revision. Maybe the way go
> forward is to address the three issues I found in the cover letter
> and fix whatever needed to be fixed in the actual patches?
> 
> [1] https://lkml.org/lkml/2019/4/24/84
> [2] https://lkml.org/lkml/2019/4/25/1170

Let me update the commit message for the vDSO API and send you a patch.

> /Jarkko
> 

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

* [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on untrusted stack
  2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
  2019-07-10 11:17     ` Jarkko Sakkinen
@ 2019-07-11  4:21     ` Cedric Xing
  2019-07-12  3:28       ` Jarkko Sakkinen
                         ` (4 more replies)
  2019-07-11  4:21     ` [RFC PATCH v3 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
                       ` (2 subsequent siblings)
  4 siblings, 5 replies; 318+ messages in thread
From: Cedric Xing @ 2019-07-11  4:21 UTC (permalink / raw)
  To: linux-sgx
  Cc: Cedric Xing, luto, jethro, greg, jarkko.sakkinen, sean.j.christopherson

This patchset is based upon, and can be applied cleanly on SGX1 patch v20
(https://lkml.org/lkml/2019/4/17/344) by Jarkko Sakkinen.

The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
%rsp, which prohibits enclaves from allocating space on the untrusted stack.
However, there are existing enclaves (e.g. those built with current Intel SGX
SDK libraries) relying on the untrusted stack for passing parameters to
untrusted functions (aka. o-calls), which requires allocating space on the
untrusted stack by enclaves. After all, passing data via untrusted stack is
very easy to implement (by enclaves), with essentially no overhead, therefore
is very suitable for exchanging data in small amounts, so could be desirable by
future SGX applications as well.  

This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its
stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto
the untrusted stack by decrementing the untrusted %rsp. And in order to service
o-calls and to preserve the untrusted stack upon exceptions, the new vDSO API
takes one more optional parameter - "callback", which if supplied, will be
invoked on all enclave exits (including normal and asynchronous exits). Ample
details regarding the new ABI have been documented as comments inside the
source code located in arch/x86/entry/vsgx_enter_enclave.S

Please note that there was a lengthy discussion on what is the "best" approach
for passing parameters for trusted/untrusted calls. Unfortunately there's no
single "best" approach that fits all use cases, hence this new ABI has been
designed intentionally to accommodate varieties. Therefore, to those not
interested in using the untrusted stack, whatever worked with the old ABI
proposed by Sean will continue to work with this new ABI.

The SGX selftest has been augmented by two new tests. One exercises the new
callback interface, and serves as a simple example to showcase how to use it;
while the other validates the hand-crafted CFI directives in
__vdso_sgx_enter_enclave() by single-stepping through it and unwinding call
stack at every instruction. Please note that the selftest CANNOT run to
completion yet, as it depends on the vDSO fixup code to signal the process upon
#DB/#BP inside enclaves (rather than the current behavior of branching to the
handler in vDSO).

Changelog:
  · This is version 3 of this patch series with the following changes.
    - Per Andy Lutomirski and Sean Christopherson, revised comments and their
      format in arch/x86/entry/vsgx_enter_enclave.S
    - Per Jarkko Sakkinen, revised the cover letter to articulate motivation
      and objective of this patchset.
  · v2 - https://patchwork.kernel.org/cover/10914161/
  · v1 - https://patchwork.kernel.org/cover/10911615/

Cedric Xing (3):
  selftests/x86: Fixed Makefile for SGX selftest
  x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing
    on untrusted stack
  selftests/x86: Augment SGX selftest to test new
    __vdso_sgx_enter_enclave() and its callback interface

 arch/x86/entry/vdso/vsgx_enter_enclave.S   | 214 ++++++++++----
 arch/x86/include/uapi/asm/sgx.h            |  14 +-
 tools/testing/selftests/x86/Makefile       |  12 +-
 tools/testing/selftests/x86/sgx/Makefile   |  49 ++--
 tools/testing/selftests/x86/sgx/main.c     | 323 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
 6 files changed, 500 insertions(+), 152 deletions(-)

-- 
2.17.1


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

* [RFC PATCH v3 1/3] selftests/x86: Fixed Makefile for SGX selftest
  2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
  2019-07-10 11:17     ` Jarkko Sakkinen
  2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
@ 2019-07-11  4:21     ` Cedric Xing
  2019-07-11  4:21     ` [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
  2019-07-11  4:21     ` [RFC PATCH v3 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
  4 siblings, 0 replies; 318+ messages in thread
From: Cedric Xing @ 2019-07-11  4:21 UTC (permalink / raw)
  To: linux-sgx
  Cc: Cedric Xing, luto, jethro, greg, jarkko.sakkinen, sean.j.christopherson

The original x86/sgx/Makefile doesn't work when 'x86/sgx' is specified as the
test target. This patch fixes that problem, along with minor changes to the
dependencies between 'x86' and 'x86/sgx' in selftests/x86/Makefile.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/Makefile     | 12 +++----
 tools/testing/selftests/x86/sgx/Makefile | 45 +++++++++---------------
 2 files changed, 22 insertions(+), 35 deletions(-)

diff --git a/tools/testing/selftests/x86/Makefile b/tools/testing/selftests/x86/Makefile
index 4fc9a42f56ea..1294c5f5b6ca 100644
--- a/tools/testing/selftests/x86/Makefile
+++ b/tools/testing/selftests/x86/Makefile
@@ -70,11 +70,11 @@ 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 $@;	\
+all_64: | $(SUBDIRS_64)
+	@for DIR in $|; do					\
+		BUILD_TARGET=$(OUTPUT)/$$DIR;			\
+		mkdir $$BUILD_TARGET  -p;			\
+		$(MAKE) OUTPUT=$$BUILD_TARGET -C $$DIR $@;	\
 	done
 
 EXTRA_CLEAN := $(BINARIES_32) $(BINARIES_64)
@@ -90,7 +90,7 @@ ifeq ($(CAN_BUILD_I386)$(CAN_BUILD_X86_64),01)
 all: warn_32bit_failure
 
 warn_32bit_failure:
-	@echo "Warning: you seem to have a broken 32-bit build" 2>&1; 	\
+	@echo "Warning: you seem to have a broken 32-bit build" 2>&1;	\
 	echo "environment.  This will reduce test coverage of 64-bit" 2>&1; \
 	echo "kernels.  If you are using a Debian-like distribution," 2>&1; \
 	echo "try:"; 2>&1; \
diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 1fd6f2708e81..3af15d7c8644 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -2,47 +2,34 @@ top_srcdir = ../../../../..
 
 include ../../lib.mk
 
-HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
-ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
+ifeq ($(shell $(CC) -dumpmachine | cut --delimiter=- -f1),x86_64)
+all: all_64
+endif
+
+HOST_CFLAGS := -Wall -Werror -g $(INCLUDES)
+ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIE \
 	       -fno-stack-protector -mrdrnd $(INCLUDES)
 
 TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
-$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
-		      $(OUTPUT)/encl_piggy.o
+$(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
 	$(CC) $(HOST_CFLAGS) -o $@ $^
 
-$(OUTPUT)/main.o: main.c
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/sgx_call.o: sgx_call.S
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
-	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
+$(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
-$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
+$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
 	objcopy --remove-section=.got.plt -O binary $< $@
 
-$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
-	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
+$(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
 
-$(OUTPUT)/encl.o: encl.c
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
-	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+$(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
+	$^ $@
 
 $(OUTPUT)/sgxsign: sgxsign.c
 	$(CC) -o $@ $< -lcrypto
 
-EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
-	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
-	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
-	       $(OUTPUT)/sgxsign
-
-.PHONY: clean
+EXTRA_CLEAN := $(TEST_CUSTOM_PROGS) $(addprefix $(OUTPUT)/,	\
+		encl.elf encl.bin encl.ss encl_piggy.o sgxsign)
-- 
2.17.1


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

* [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
                       ` (2 preceding siblings ...)
  2019-07-11  4:21     ` [RFC PATCH v3 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
@ 2019-07-11  4:21     ` Cedric Xing
  2019-07-11  9:50       ` Jarkko Sakkinen
  2019-07-11  9:53       ` Jarkko Sakkinen
  2019-07-11  4:21     ` [RFC PATCH v3 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
  4 siblings, 2 replies; 318+ messages in thread
From: Cedric Xing @ 2019-07-11  4:21 UTC (permalink / raw)
  To: linux-sgx
  Cc: Cedric Xing, luto, jethro, greg, jarkko.sakkinen, sean.j.christopherson

The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
which prohibits enclaves from allocating and passing parameters for
untrusted function calls (aka. o-calls) on the untrusted stack.

This patch addresses the problem above by introducing a new ABI that preserves
%rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
using %rbp so that enclaves are allowed to allocate space on the untrusted
stack by decrementing %rsp. Please note that the stack space allocated in such
way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
__vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
been revised to take a callback function as an optional parameter, which if
supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
eXit) and normal exits), with the value of %rsp left off by the enclave as a
parameter to the callback.

Here's the summary of API/ABI changes in this patch. More details could be
found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
  * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
    because it is filled upon both AEX (i.e. exceptions) and normal enclave
    exits.
  * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
    the previous implementation).
  * __vdso_sgx_enter_enclave() takes one more parameter - a callback function
    to be invoked upon enclave exits. This callback is optional, and if not
    supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave
    exits (same behavior as previous implementation).
  * The callback function is given as a parameter the value of %rsp at enclave
    exit to address data "pushed" by the enclave. A positive value returned by
    the callback will be treated as an ENCLU leaf for re-entering the enclave,
    while a zero or negative value will be passed through as the return
    value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
    leave callback by longjmp() or by throwing a C++ exception.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 arch/x86/entry/vdso/vsgx_enter_enclave.S | 214 ++++++++++++++++-------
 arch/x86/include/uapi/asm/sgx.h          |  14 +-
 2 files changed, 157 insertions(+), 71 deletions(-)

diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
index fe0bf6671d6d..62f28c01b3c8 100644
--- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
+++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
@@ -14,88 +14,174 @@
 .code64
 .section .text, "ax"
 
-#ifdef SGX_KERNEL_DOC
 /**
  * __vdso_sgx_enter_enclave() - Enter an SGX enclave
  *
- * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
- * @tcs:	**IN \%rbx** - TCS, must be non-NULL
- * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
+ * Parameters:
+ *	@leaf, passed in %eax, must be either EENTER(2) or ERESUME(3)
+ *	@tcs, passed on stack at 8(%rsp), is the linear address of TCS
+ *	@exinfo, passed on stack at 0x10(%rsp), is optional, and if non-NULL,
+ *	shall point to an sgx_enclave_exinfo structure to receive information
+ *	about the enclave exit
+ *	@callback, passed on stack at 0x18(%rsp), is optiona, and if non-NULL,
+ *	points to a callback function that will be invoked after the enclave
+ *	exits
  *
- * Return:
- *  **OUT \%eax** -
- *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
- *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
+ * Returns:
+ *	$0 (zero) on a clean exit from the enclave
+ *	$-EINVAL will be returned if leaf isn't either EENTER or ERESUME
+ *	Other negative values could also be returned as the return value from
+ *	the callback function
  *
- * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
- * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
- * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
- * the return value passed via ``%eax``.  All registers except ``%rsp`` must
- * be treated as volatile from the caller's perspective, including but not
- * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
- * being run **must** preserve the untrusted ``%rsp`` and stack.
+ * IMPORTANT! This API is **not** compliant with x86-64 ABI but adopts a
+ * proprietary calling convention, described below:
+ *   · As noted above, input parameters are passed via %eax and the stack.
+ *   · The return value is passed via %eax.
+ *   · %rbx and %rcx must be treated as volatile as they are modified as part
+ *     of enclaves transitions and are used as scratch regs.
+ *   · %rdx, %rdi, %rsi and %r8-%r15 are passed as is and may be freely
+ *     modified by the enclave. Values left in those registers will not be
+ *     altered either, so will be visiable to the callback or the caller (if no
+ *     callback is specified).
+ *   · %rsp is saved/restored across __vdso_sgx_enter_enclave().
+ *
+ * A callback function, if supplied, shall have the following signature:
+ *
+ *	int callback(long rdi, long rsi, long rdx,
+ *		     struct sgx_enclave_exinfo *exinfo, long r8, long r9,
+ *		     void *tcs, long ursp);
+ *
+ * Callback functions shall comply to x86_64 ABI.
+ *   · All registers left off by the enclave are passed as is except %rax, %rbx
+ *     and %rcx. %rdi, %rsi, %r8 and %9 could be accessed as function
+ *     parameters, while other registers could be access in assembly code if
+ *     needed.
+ *   · Positive return values from the callback will be interpreted as ENCLU
+ *     leafs to re-enter the enclave. Currently only EENTER(2) and ERESUME(3)
+ *     are supported, while all other positive return values will result in
+ *     $-EINVAL returned to the caller of __vdso_sgx_enter_enclave().
+ *   · $0 (zero) or negative return values will be passed back to the caller of
+ *     __vdso_sgx_enter_enclave() as is.
+ *
+ * Pseudo-code:
+ *
+ * typedef int (*sgx_callback)(long rdi, long rsi, long rdx,
+ *			       struct sgx_enclave_exinfo *exinfo, long r8,
+ *			       long r9, void *tcs, long ursp);
+ *
+ * int __vdso_sgx_enter_enclave(int leaf, void *tcs,
+ *				struct sgx_enclave_exinfo *exinfo,
+ *				sgx_callback callback)
+ * {
+ *	while (leaf == EENTER || leaf == ERESUME) {
+ *		int rc;
+ *		try {
+ *			ENCLU[leaf];
+ *			rc = 0;
+ *			if (exinfo)
+ *				exinfo->leaf = EEXIT;
+ *		} catch (exception) {
+ *			rc = -EFAULT;
+ *			if (exinfo)
+ *				*exinfo = exception;
+ *		}
+ *
+ *		leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
+ *						   r8, r9, tcs, ursp);
+ *	}
+ *
+ *	return leaf > 0 ? -EINVAL : leaf;
+ * }
  */
-__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
-			 struct sgx_enclave_exception *ex_info)
-{
-	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
-		return -EINVAL;
-
-	if (!tcs)
-		return -EINVAL;
-
-	try {
-		ENCLU[leaf];
-	} catch (exception) {
-		if (e)
-			*e = exception;
-		return -EFAULT;
-	}
-
-	return 0;
-}
-#endif
 ENTRY(__vdso_sgx_enter_enclave)
-	/* EENTER <= leaf <= ERESUME */
+	/* Prolog */
+	.cfi_startproc
+	push	%rbp
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbp, 0
+	mov	%rsp, %rbp
+	.cfi_def_cfa_register	%rbp
+
+1:	/* EENTER <= leaf <= ERESUME */
 	cmp	$0x2, %eax
-	jb	bad_input
-
+	jb	6f
 	cmp	$0x3, %eax
-	ja	bad_input
+	ja	6f
 
-	/* TCS must be non-NULL */
-	test	%rbx, %rbx
-	je	bad_input
+	/* Load TCS and AEP */
+	mov	0x10(%rbp), %rbx
+	lea	2f(%rip), %rcx
 
-	/* Save @exception_info */
-	push	%rcx
+	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
+2:	enclu
 
-	/* Load AEP for ENCLU */
-	lea	1f(%rip),  %rcx
-1:	enclu
+	/* EEXIT path */
+	xor	%ebx, %ebx
+3:	mov	0x18(%rbp), %rcx
+	jrcxz	4f
+	mov	%eax, EX_LEAF(%rcx)
+	jnc	4f
+	mov	%di, EX_TRAPNR(%rcx)
+	mov	%si, EX_ERROR_CODE(%rcx)
+	mov	%rdx, EX_ADDRESS(%rcx)
 
-	add	$0x8, %rsp
-	xor	%eax, %eax
+4:	/* Call *callback if supplied */
+	mov	0x20(%rbp), %rax
+	test	%rax, %rax
+	/*
+	 * At this point, %ebx holds the effective return value, which shall be
+	 * returned if no callback is specified
+	 */
+	cmovz	%rbx, %rax
+	jz	7f
+	/*
+	 * Align stack per x86_64 ABI. The original %rsp is saved in %rbx to be
+	 * restored after *callback returns.
+	 */
+	mov	%rsp, %rbx
+	and	$-0x10, %rsp
+	/* Clear RFLAGS.DF per x86_64 ABI */
+	cld
+	/* Parameters for *callback */
+	push	%rbx
+	push	0x10(%rbp)
+	/* Call *%rax via retpoline */
+	call	40f
+	/*
+	 * Restore %rsp to its original value left off by the enclave from last
+	 * exit
+	 */
+	mov	%rbx, %rsp
+	/*
+	 * Positive return value from *callback will be interpreted as an ENCLU
+	 * leaf, while a non-positive value will be interpreted as the return
+	 * value to be passed back to the caller.
+	 */
+	jmp	1b
+40:	/* retpoline */
+	call	42f
+41:	pause
+	lfence
+	jmp	41b
+42:	mov	%rax, (%rsp)
 	ret
 
-bad_input:
-	mov     $(-EINVAL), %rax
-	ret
+5:	/* Exception path */
+	mov	$-EFAULT, %ebx
+	stc
+	jmp	3b
 
-.pushsection .fixup, "ax"
-	/* Re-load @exception_info and fill it (if it's non-NULL) */
-2:	pop	%rcx
-	test    %rcx, %rcx
-	je      3f
+6:	/* Unsupported ENCLU leaf */
+	cmp	$0, %eax
+	jle	7f
+	mov	$-EINVAL, %eax
 
-	mov	%eax, EX_LEAF(%rcx)
-	mov	%di,  EX_TRAPNR(%rcx)
-	mov	%si,  EX_ERROR_CODE(%rcx)
-	mov	%rdx, EX_ADDRESS(%rcx)
-3:	mov	$(-EFAULT), %rax
+7:	/* Epilog */
+	leave
+	.cfi_def_cfa		%rsp, 8
 	ret
-.popsection
+	.cfi_endproc
 
-_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
+_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
 
 ENDPROC(__vdso_sgx_enter_enclave)
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 9ed690a38c70..50d2b5143e5e 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -24,7 +24,7 @@
 
 /**
  * struct sgx_enclave_create - parameter structure for the
- *                             %SGX_IOC_ENCLAVE_CREATE ioctl
+ *			       %SGX_IOC_ENCLAVE_CREATE ioctl
  * @src:	address for the SECS page data
  */
 struct sgx_enclave_create  {
@@ -33,7 +33,7 @@ struct sgx_enclave_create  {
 
 /**
  * struct sgx_enclave_add_page - parameter structure for the
- *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
+ *				 %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
  * @addr:	address within the ELRANGE
  * @src:	address for the page data
  * @secinfo:	address for the SECINFO data
@@ -49,7 +49,7 @@ struct sgx_enclave_add_page {
 
 /**
  * struct sgx_enclave_init - parameter structure for the
- *                           %SGX_IOC_ENCLAVE_INIT ioctl
+ *			     %SGX_IOC_ENCLAVE_INIT ioctl
  * @sigstruct:	address for the SIGSTRUCT data
  */
 struct sgx_enclave_init {
@@ -66,16 +66,16 @@ struct sgx_enclave_set_attribute {
 };
 
 /**
- * struct sgx_enclave_exception - structure to report exceptions encountered in
- *				  __vdso_sgx_enter_enclave()
+ * struct sgx_enclave_exinfo - structure to report exceptions encountered in
+ *			       __vdso_sgx_enter_enclave()
  *
- * @leaf:	ENCLU leaf from \%eax at time of exception
+ * @leaf:	ENCLU leaf from \%eax at time of exception/exit
  * @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 {
+struct sgx_enclave_exinfo {
 	__u32 leaf;
 	__u16 trapnr;
 	__u16 error_code;
-- 
2.17.1


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

* [RFC PATCH v3 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
                       ` (3 preceding siblings ...)
  2019-07-11  4:21     ` [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-07-11  4:21     ` Cedric Xing
  4 siblings, 0 replies; 318+ messages in thread
From: Cedric Xing @ 2019-07-11  4:21 UTC (permalink / raw)
  To: linux-sgx
  Cc: Cedric Xing, luto, jethro, greg, jarkko.sakkinen, sean.j.christopherson

This patch augments SGX selftest with two new tests.

The first test exercises the newly added callback interface, by marking the
whole enclave range as PROT_READ, then calling mprotect() upon #PFs to add
necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.
This test also serves as an example to demonstrate the callback interface.

The second test single-steps through __vdso_sgx_enter_enclave() to make sure
the call stack can be unwound at every instruction within that vDSO API. Its
purpose is to validate the hand-crafted CFI directives in the assembly.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/sgx/Makefile   |   6 +-
 tools/testing/selftests/x86/sgx/main.c     | 323 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
 3 files changed, 322 insertions(+), 47 deletions(-)

diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 3af15d7c8644..31f937e220c4 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -14,16 +14,16 @@ TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
 $(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
-	$(CC) $(HOST_CFLAGS) -o $@ $^
+	$(CC) $(HOST_CFLAGS) -o $@ $^ -lunwind -ldl -Wl,--defsym,__image_base=0 -pie
 
 $(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
 	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
 $(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
-	objcopy --remove-section=.got.plt -O binary $< $@
+	objcopy -O binary $< $@
 
 $(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@ -Wl,--build-id=none
 
 $(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
 	$^ $@
diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
index e2265f841fb0..d3e53c71306d 100644
--- a/tools/testing/selftests/x86/sgx/main.c
+++ b/tools/testing/selftests/x86/sgx/main.c
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
 // Copyright(c) 2016-18 Intel Corporation.
 
+#define _GNU_SOURCE
 #include <elf.h>
 #include <fcntl.h>
 #include <stdbool.h>
@@ -9,16 +10,31 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <errno.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
-#include <sys/time.h>
+#include <sys/auxv.h>
+#include <signal.h>
+#include <sys/ucontext.h>
+
+#define UNW_LOCAL_ONLY
+#include <libunwind.h>
+
 #include "encl_piggy.h"
 #include "defines.h"
 #include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
 #include "../../../../../arch/x86/include/uapi/asm/sgx.h"
 
-static const uint64_t MAGIC = 0x1122334455667788ULL;
+#define _Q(x)	__Q(x)
+#define __Q(x)	#x
+#define ERRLN	"Line " _Q(__LINE__)
+
+#define X86_EFLAGS_TF	(1ul << 8)
+
+extern char __image_base[];
+size_t eenter;
+static size_t vdso_base;
 
 struct vdso_symtab {
 	Elf64_Sym *elf_symtab;
@@ -26,20 +42,11 @@ struct vdso_symtab {
 	Elf64_Word *elf_hashtab;
 };
 
-static void *vdso_get_base_addr(char *envp[])
+static void vdso_init(void)
 {
-	Elf64_auxv_t *auxv;
-	int i;
-
-	for (i = 0; envp[i]; i++);
-	auxv = (Elf64_auxv_t *)&envp[i + 1];
-
-	for (i = 0; auxv[i].a_type != AT_NULL; i++) {
-		if (auxv[i].a_type == AT_SYSINFO_EHDR)
-			return (void *)auxv[i].a_un.a_val;
-	}
-
-	return NULL;
+	vdso_base = getauxval(AT_SYSINFO_EHDR);
+	if (!vdso_base)
+		exit(1);
 }
 
 static Elf64_Dyn *vdso_get_dyntab(void *addr)
@@ -66,8 +73,9 @@ static void *vdso_get_dyn(void *addr, Elf64_Dyn *dyntab, Elf64_Sxword tag)
 	return NULL;
 }
 
-static bool vdso_get_symtab(void *addr, struct vdso_symtab *symtab)
+static bool vdso_get_symtab(struct vdso_symtab *symtab)
 {
+	void *addr = (void *)vdso_base;
 	Elf64_Dyn *dyntab = vdso_get_dyntab(addr);
 
 	symtab->elf_symtab = vdso_get_dyn(addr, dyntab, DT_SYMTAB);
@@ -138,7 +146,7 @@ static bool encl_create(int dev_fd, unsigned long bin_size,
 	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
 		    MAP_SHARED, dev_fd, 0);
 	if (base == MAP_FAILED) {
-		perror("mmap");
+		perror(ERRLN);
 		return false;
 	}
 
@@ -224,35 +232,271 @@ static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
 	return false;
 }
 
-void sgx_call(void *rdi, void *rsi, void *tcs,
-	      struct sgx_enclave_exception *exception,
-	      void *eenter);
+int sgx_call(void *rdi, void *rsi, long rdx, void *rcx, void *r8, void *r9,
+	     void *tcs, struct sgx_enclave_exinfo *ei, void *cb);
+
+static void show_enclave_exinfo(const struct sgx_enclave_exinfo *exinfop,
+				const char *header)
+{
+	static const char * const enclu_leaves[] = {
+		"EREPORT",
+		"EGETKEY",
+		"EENTER",
+		"ERESUME",
+		"EEXIT"
+	};
+	static const char * const exception_names[] = {
+		"#DE",
+		"#DB",
+		"NMI",
+		"#BP",
+		"#OF",
+		"#BR",
+		"#UD",
+		"#NM",
+		"#DF",
+		"CSO",
+		"#TS",
+		"#NP",
+		"#SS",
+		"#GP",
+		"#PF",
+		"Unknown",
+		"#MF",
+		"#AC",
+		"#MC",
+		"#XM",
+		"#VE",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown"
+	};
+
+	printf("%s: leaf:%s(%d)", header,
+		enclu_leaves[exinfop->leaf], exinfop->leaf);
+	if (exinfop->leaf != 4)
+		printf(" trap:%s(%d) ec:%d addr:0x%llx\n",
+			exception_names[exinfop->trapnr], exinfop->trapnr,
+			exinfop->error_code, exinfop->address);
+	else
+		printf("\n");
+}
+
+static const uint64_t MAGIC = 0x1122334455667788ULL;
 
-int main(int argc, char *argv[], char *envp[])
+static void test1(struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[1] Entering the enclave without callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, NULL);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Null TCS\n Expect: #PF at EENTER\n");
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 NULL, &exinfo, NULL);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 2 /*EENTER*/ || exinfo.trapnr != 14 /*#PF*/)
+		exit(1);
+}
+
+static int test2_callback(long rdi, long rsi, long rdx,
+			  struct sgx_enclave_exinfo *ei, long r8, long r9,
+			  void *tcs, long ursp)
+{
+	show_enclave_exinfo(ei, "  callback");
+
+	switch (ei->leaf) {
+	case 4:
+		return 0;
+	case 3:
+	case 2:
+		switch (ei->trapnr) {
+		case 1:	/*#DB*/
+			break;
+		case 14:/*#PF*/
+			if ((ei->error_code & 1) == 0) {
+				fprintf(stderr, ERRLN
+					": Unexpected #PF error code\n");
+				exit(1);
+			}
+			if (mprotect((void *)(ei->address & -0x1000), 0x1000,
+				     ((ei->error_code & 2) ? PROT_WRITE : 0) |
+				     ((ei->error_code & 0x10) ? PROT_EXEC : 0) |
+				     PROT_READ)) {
+				perror(ERRLN);
+				exit(1);
+			}
+			break;
+		default:
+			fprintf(stderr, ERRLN ": Unexpected exception\n");
+			exit(1);
+		}
+		return ei->leaf == 2 ? -EAGAIN : ei->leaf;
+	}
+	return -EINVAL;
+}
+
+static void test2(struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[2] Entering the enclave with callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, test2_callback);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Read-only enclave (0x%lx-0x%lx)\n"
+	       " Expect: #PFs to be fixed by callback\n",
+	       secs->base, secs->base + (encl_bin_end - encl_bin) - 1);
+	if (mprotect((void *)secs->base, encl_bin_end - encl_bin, PROT_READ)) {
+		perror(ERRLN);
+		exit(1);
+	}
+	while (sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+			(void *)secs->base, &exinfo, test2_callback) == -EAGAIN)
+		;
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 4 /*EEXIT*/)
+		exit(1);
+}
+
+static struct test3_proc_context {
+	unw_word_t	ip, bx, sp, bp, r12, r13, r14, r15;
+} test3_ctx;
+
+static unw_word_t test3_getcontext(unw_cursor_t *cursor,
+				   struct test3_proc_context *ctxp)
+{
+	unw_get_reg(cursor, UNW_REG_IP, &ctxp->ip);
+	unw_get_reg(cursor, UNW_REG_SP, &ctxp->sp);
+	unw_get_reg(cursor, UNW_X86_64_RBX, &ctxp->bx);
+	unw_get_reg(cursor, UNW_X86_64_RBP, &ctxp->bp);
+	unw_get_reg(cursor, UNW_X86_64_R12, &ctxp->r12);
+	unw_get_reg(cursor, UNW_X86_64_R13, &ctxp->r13);
+	unw_get_reg(cursor, UNW_X86_64_R14, &ctxp->r14);
+	unw_get_reg(cursor, UNW_X86_64_R15, &ctxp->r15);
+	return ctxp->ip;
+}
+
+static void test3_sigtrap(int sig, siginfo_t *info, ucontext_t *ctxp)
+{
+	static int in_vdso_eenter;
+	static size_t caller;
+
+	unw_cursor_t cursor;
+	unw_context_t uc;
+	struct test3_proc_context pc;
+
+	if (ctxp->uc_mcontext.gregs[REG_RIP] == eenter) {
+		in_vdso_eenter = 1;
+		caller = *(size_t *)(ctxp->uc_mcontext.gregs[REG_RSP]);
+		printf("  trace started at ip:%llx (vdso:0x%llx)\n",
+			ctxp->uc_mcontext.gregs[REG_RIP],
+			ctxp->uc_mcontext.gregs[REG_RIP] - vdso_base);
+	}
+
+	if (!in_vdso_eenter)
+		return;
+
+	if (ctxp->uc_mcontext.gregs[REG_RIP] == caller) {
+		in_vdso_eenter = 0;
+		ctxp->uc_mcontext.gregs[REG_EFL] &= ~X86_EFLAGS_TF;
+		printf("  trace ended successfully at ip:%llx (executable:0x%llx)\n",
+			ctxp->uc_mcontext.gregs[REG_RIP],
+			ctxp->uc_mcontext.gregs[REG_RIP] -
+				(size_t)__image_base);
+		return;
+	}
+
+	unw_getcontext(&uc);
+	unw_init_local(&cursor, &uc);
+	while (unw_step(&cursor) > 0 &&
+	       test3_getcontext(&cursor, &pc) != test3_ctx.ip)
+		;
+
+	if (memcmp(&pc, &test3_ctx, sizeof(pc))) {
+		fprintf(stderr, ERRLN ": Error unwinding\n");
+		exit(1);
+	}
+}
+
+static void test3_set_tf(void)
+{
+	__asm__ ("pushfq; orl %0, (%%rsp); popfq" : : "i"(X86_EFLAGS_TF));
+}
+
+static void test3(struct sgx_secs *secs)
+{
+	unw_cursor_t cursor;
+	unw_context_t uc;
+	struct sigaction sa = {
+		.sa_sigaction = (void (*)(int, siginfo_t*, void*))test3_sigtrap,
+		.sa_flags = SA_SIGINFO,
+	};
+
+	unw_getcontext(&uc);
+	unw_init_local(&cursor, &uc);
+	if (unw_step(&cursor) > 0)
+		test3_getcontext(&cursor, &test3_ctx);
+	else {
+		fprintf(stderr, ERRLN ": error initializing unwind context\n");
+		exit(1);
+	}
+
+	if (sigaction(SIGTRAP, &sa, NULL) < 0) {
+		perror(ERRLN);
+		exit(1);
+	}
+
+	test3_set_tf();
+	test1(secs);
+
+	test3_set_tf();
+	test2(secs);
+}
+
+int main(void)
 {
 	unsigned long bin_size = encl_bin_end - encl_bin;
 	unsigned long ss_size = encl_ss_end - encl_ss;
-	struct sgx_enclave_exception exception;
 	Elf64_Sym *eenter_sym;
 	struct vdso_symtab symtab;
 	struct sgx_secs secs;
-	uint64_t result = 0;
-	void *eenter;
-	void *addr;
-
-	memset(&exception, 0, sizeof(exception));
 
-	addr = vdso_get_base_addr(envp);
-	if (!addr)
-		exit(1);
+	vdso_init();
 
-	if (!vdso_get_symtab(addr, &symtab))
+	if (!vdso_get_symtab(&symtab))
 		exit(1);
 
 	eenter_sym = vdso_symtab_get(&symtab, "__vdso_sgx_enter_enclave");
 	if (!eenter_sym)
 		exit(1);
-	eenter = addr + eenter_sym->st_value;
+	eenter = vdso_base + eenter_sym->st_value;
 
 	printf("Binary size %lu (0x%lx), SIGSTRUCT size %lu\n", bin_size,
 	       bin_size, ss_size);
@@ -266,14 +510,11 @@ int main(int argc, char *argv[], char *envp[])
 	if (!encl_load(&secs, bin_size))
 		exit(1);
 
-	printf("Input: 0x%lx\n", MAGIC);
-	sgx_call((void *)&MAGIC, &result, (void *)secs.base, &exception,
-		 eenter);
-	if (result != MAGIC) {
-		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
-		exit(1);
-	}
+	printf("--- Functional Tests ---\n");
+	test1(&secs);
+	test2(&secs);
 
-	printf("Output: 0x%lx\n", result);
-	exit(0);
+	printf("--- Unwind Tests ---\n");
+	test3(&secs);
+	return 0;
 }
diff --git a/tools/testing/selftests/x86/sgx/sgx_call.S b/tools/testing/selftests/x86/sgx/sgx_call.S
index 14bd0a044199..ca2c0c947758 100644
--- a/tools/testing/selftests/x86/sgx/sgx_call.S
+++ b/tools/testing/selftests/x86/sgx/sgx_call.S
@@ -7,9 +7,43 @@
 
 	.global sgx_call
 sgx_call:
+	.cfi_startproc
+	push	%r15
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r15, 0
+	push	%r14
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r14, 0
+	push	%r13
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r13, 0
+	push	%r12
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r12, 0
 	push	%rbx
-	mov	$0x02, %rax
-	mov	%rdx, %rbx
-	call	*%r8
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbx, 0
+	push	$0
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	mov	$2, %eax
+	call	*eenter(%rip)
+	add	$0x20, %rsp
+	.cfi_adjust_cfa_offset	-0x20
 	pop	%rbx
+	.cfi_adjust_cfa_offset	-8
+	pop	%r12
+	.cfi_adjust_cfa_offset	-8
+	pop	%r13
+	.cfi_adjust_cfa_offset	-8
+	pop	%r14
+	.cfi_adjust_cfa_offset	-8
+	pop	%r15
+	.cfi_adjust_cfa_offset	-8
 	ret
+	.cfi_endproc
-- 
2.17.1


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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-10 22:54           ` Xing, Cedric
@ 2019-07-11  9:36             ` Jarkko Sakkinen
  2019-07-11 19:49               ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-11  9:36 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Wed, Jul 10, 2019 at 03:54:20PM -0700, Xing, Cedric wrote:
> On 7/10/2019 3:46 PM, Jarkko Sakkinen wrote:
> > On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
> > > > With these conclusions I think the current vDSO API is sufficient for
> > > > Linux.
> > > 
> > > The new vDSO API is to support data exchange on stack. It has nothing to do
> > > with debugging. BTW, the community has closed on this.
> > 
> > And how that is useful?
> 
> There is a lengthy discussion on its usefulness so I don't want to repeat.
> In short, it allows using untrusted stack as a convenient method to exchange
> data with the enclave. It is currently being used by Intel's SGX SDK for
> e/o-calls parameters.
> 
> > > The CFI directives are for stack unwinding. They don't affect what the code
> > > does so you can just treat them as NOPs if you don't understand what they
> > > do. However, they are useful to not only debuggers but also exception
> > > handling code. libunwind also has a setjmp()/longjmp() implementation based
> > > on CFI directives.
> > 
> > Of course I won't merge code of which usefulness I don't understand.
> 
> Sure.
> 
> Any other questions I can help with?

I dissected my concerns in other email. We can merge this feature after
v21 if it makes sense.

/Jarkko

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-10 23:37             ` Xing, Cedric
@ 2019-07-11  9:38               ` Jarkko Sakkinen
  2019-07-11 15:50                 ` Sean Christopherson
  2019-07-11 19:51                 ` Xing, Cedric
  0 siblings, 2 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-11  9:38 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Wed, Jul 10, 2019 at 04:37:41PM -0700, Xing, Cedric wrote:
> On 7/10/2019 4:15 PM, Jarkko Sakkinen wrote:
> > On Thu, Jul 11, 2019 at 01:46:28AM +0300, Jarkko Sakkinen wrote:
> > > On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
> > > > > With these conclusions I think the current vDSO API is sufficient for
> > > > > Linux.
> > > > 
> > > > The new vDSO API is to support data exchange on stack. It has nothing to do
> > > > with debugging. BTW, the community has closed on this.
> > > 
> > > And how that is useful?
> > > 
> > > > The CFI directives are for stack unwinding. They don't affect what the code
> > > > does so you can just treat them as NOPs if you don't understand what they
> > > > do. However, they are useful to not only debuggers but also exception
> > > > handling code. libunwind also has a setjmp()/longjmp() implementation based
> > > > on CFI directives.
> > > 
> > > Of course I won't merge code of which usefulness I don't understand.
> > 
> > I re-read the cover letter [1] because it usually is the place
> > to "pitch" a feature.
> > 
> > It fails to address two things:
> > 
> > 1. How and in what circumstances is an untrusted stack is a better
> >     vessel for handling exceptions than the register based approach
> >     that we already have?
> 
> We are not judging which vessel is better (or the best) among all possible
> vessels. We are trying to enable more vessels. Every vessel has its pros and
> cons so there's *no* single best vessel.

I think reasonable metric is actually the coverage of the Intel SDK
based enclaves. How widely are they in the wild? If the user base is
large, it should be reasonable to support this just based on that.

/Jarkko

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

* Re: [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-11  4:21     ` [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-07-11  9:50       ` Jarkko Sakkinen
  2019-07-11  9:53       ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-11  9:50 UTC (permalink / raw)
  To: Cedric Xing; +Cc: linux-sgx, luto, jethro, greg, sean.j.christopherson

On Wed, Jul 10, 2019 at 09:21:32PM -0700, Cedric Xing wrote:
> The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
> which prohibits enclaves from allocating and passing parameters for
> untrusted function calls (aka. o-calls) on the untrusted stack.
> 
> This patch addresses the problem above by introducing a new ABI that preserves
> %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
> using %rbp so that enclaves are allowed to allocate space on the untrusted
> stack by decrementing %rsp. Please note that the stack space allocated in such
> way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
> __vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
> been revised to take a callback function as an optional parameter, which if
> supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
> eXit) and normal exits), with the value of %rsp left off by the enclave as a
> parameter to the callback.
> 
> Here's the summary of API/ABI changes in this patch. More details could be
> found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
>   * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
>     because it is filled upon both AEX (i.e. exceptions) and normal enclave
>     exits.
>   * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
>     the previous implementation).
>   * __vdso_sgx_enter_enclave() takes one more parameter - a callback function
>     to be invoked upon enclave exits. This callback is optional, and if not
>     supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave
>     exits (same behavior as previous implementation).
>   * The callback function is given as a parameter the value of %rsp at enclave
>     exit to address data "pushed" by the enclave. A positive value returned by
>     the callback will be treated as an ENCLU leaf for re-entering the enclave,
>     while a zero or negative value will be passed through as the return
>     value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
>     leave callback by longjmp() or by throwing a C++ exception.
> 
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---
>  arch/x86/entry/vdso/vsgx_enter_enclave.S | 214 ++++++++++++++++-------
>  arch/x86/include/uapi/asm/sgx.h          |  14 +-
>  2 files changed, 157 insertions(+), 71 deletions(-)
> 
> diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> index fe0bf6671d6d..62f28c01b3c8 100644
> --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> @@ -14,88 +14,174 @@
>  .code64
>  .section .text, "ax"
>  
> -#ifdef SGX_KERNEL_DOC
>  /**
>   * __vdso_sgx_enter_enclave() - Enter an SGX enclave
>   *

This was already there but here should not be empty line.

> - * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
> - * @tcs:	**IN \%rbx** - TCS, must be non-NULL
> - * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer

Does not align with kdoc standards.

* @leaf:	ENCLU leaf, must be EENTER or ERESUME
* @tcs:		TCS, must be non-NULL
* @ex_info:	Optional 'struct sgx_enclave_exception' pointer



> + * Parameters:
> + *	@leaf, passed in %eax, must be either EENTER(2) or ERESUME(3)
> + *	@tcs, passed on stack at 8(%rsp), is the linear address of TCS
> + *	@exinfo, passed on stack at 0x10(%rsp), is optional, and if non-NULL,
> + *	shall point to an sgx_enclave_exinfo structure to receive information
> + *	about the enclave exit
> + *	@callback, passed on stack at 0x18(%rsp), is optiona, and if non-NULL,
> + *	points to a callback function that will be invoked after the enclave
> + *	exits
>   *
> - * Return:
> - *  **OUT \%eax** -
> - *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
> - *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
> + * Returns:
> + *	$0 (zero) on a clean exit from the enclave
> + *	$-EINVAL will be returned if leaf isn't either EENTER or ERESUME
> + *	Other negative values could also be returned as the return value from
> + *	the callback function
>   *
> - * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
> - * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
> - * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
> - * the return value passed via ``%eax``.  All registers except ``%rsp`` must
> - * be treated as volatile from the caller's perspective, including but not
> - * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
> - * being run **must** preserve the untrusted ``%rsp`` and stack.
> + * IMPORTANT! This API is **not** compliant with x86-64 ABI but adopts a
> + * proprietary calling convention, described below:
> + *   · As noted above, input parameters are passed via %eax and the stack.
> + *   · The return value is passed via %eax.
> + *   · %rbx and %rcx must be treated as volatile as they are modified as part
> + *     of enclaves transitions and are used as scratch regs.
> + *   · %rdx, %rdi, %rsi and %r8-%r15 are passed as is and may be freely
> + *     modified by the enclave. Values left in those registers will not be
> + *     altered either, so will be visiable to the callback or the caller (if no
> + *     callback is specified).
> + *   · %rsp is saved/restored across __vdso_sgx_enter_enclave().
> + *
> + * A callback function, if supplied, shall have the following signature:
> + *
> + *	int callback(long rdi, long rsi, long rdx,
> + *		     struct sgx_enclave_exinfo *exinfo, long r8, long r9,
> + *		     void *tcs, long ursp);
> + *
> + * Callback functions shall comply to x86_64 ABI.
> + *   · All registers left off by the enclave are passed as is except %rax, %rbx
> + *     and %rcx. %rdi, %rsi, %r8 and %9 could be accessed as function
> + *     parameters, while other registers could be access in assembly code if
> + *     needed.
> + *   · Positive return values from the callback will be interpreted as ENCLU
> + *     leafs to re-enter the enclave. Currently only EENTER(2) and ERESUME(3)
> + *     are supported, while all other positive return values will result in
> + *     $-EINVAL returned to the caller of __vdso_sgx_enter_enclave().
> + *   · $0 (zero) or negative return values will be passed back to the caller of
> + *     __vdso_sgx_enter_enclave() as is.
> + *
> + * Pseudo-code:
> + *
> + * typedef int (*sgx_callback)(long rdi, long rsi, long rdx,
> + *			       struct sgx_enclave_exinfo *exinfo, long r8,
> + *			       long r9, void *tcs, long ursp);
> + *
> + * int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> + *				struct sgx_enclave_exinfo *exinfo,
> + *				sgx_callback callback)
> + * {
> + *	while (leaf == EENTER || leaf == ERESUME) {
> + *		int rc;
> + *		try {
> + *			ENCLU[leaf];
> + *			rc = 0;
> + *			if (exinfo)
> + *				exinfo->leaf = EEXIT;
> + *		} catch (exception) {
> + *			rc = -EFAULT;
> + *			if (exinfo)
> + *				*exinfo = exception;
> + *		}
> + *
> + *		leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
> + *						   r8, r9, tcs, ursp);
> + *	}
> + *
> + *	return leaf > 0 ? -EINVAL : leaf;
> + * }
>   */

Please remove all of this documentation  or write more punctual
documentation and follow the standard:

https://www.kernel.org/doc/Documentation/kernel-doc-nano-HOWTO.txt

Not going to maintain the above. Rather do not add documentation
at all than the above.

> -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> -			 struct sgx_enclave_exception *ex_info)
> -{
> -	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> -		return -EINVAL;
> -
> -	if (!tcs)
> -		return -EINVAL;
> -
> -	try {
> -		ENCLU[leaf];
> -	} catch (exception) {
> -		if (e)
> -			*e = exception;
> -		return -EFAULT;
> -	}
> -
> -	return 0;
> -}
> -#endif
>  ENTRY(__vdso_sgx_enter_enclave)
> -	/* EENTER <= leaf <= ERESUME */
> +	/* Prolog */
> +	.cfi_startproc
> +	push	%rbp
> +	.cfi_adjust_cfa_offset	8
> +	.cfi_rel_offset		%rbp, 0
> +	mov	%rsp, %rbp
> +	.cfi_def_cfa_register	%rbp
> +
> +1:	/* EENTER <= leaf <= ERESUME */
>  	cmp	$0x2, %eax
> -	jb	bad_input
> -
> +	jb	6f
>  	cmp	$0x3, %eax
> -	ja	bad_input
> +	ja	6f
>  
> -	/* TCS must be non-NULL */
> -	test	%rbx, %rbx
> -	je	bad_input
> +	/* Load TCS and AEP */
> +	mov	0x10(%rbp), %rbx
> +	lea	2f(%rip), %rcx
>  
> -	/* Save @exception_info */
> -	push	%rcx
> +	/* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> +2:	enclu
>  
> -	/* Load AEP for ENCLU */
> -	lea	1f(%rip),  %rcx
> -1:	enclu
> +	/* EEXIT path */
> +	xor	%ebx, %ebx
> +3:	mov	0x18(%rbp), %rcx
> +	jrcxz	4f
> +	mov	%eax, EX_LEAF(%rcx)
> +	jnc	4f
> +	mov	%di, EX_TRAPNR(%rcx)
> +	mov	%si, EX_ERROR_CODE(%rcx)
> +	mov	%rdx, EX_ADDRESS(%rcx)
>  
> -	add	$0x8, %rsp
> -	xor	%eax, %eax
> +4:	/* Call *callback if supplied */
> +	mov	0x20(%rbp), %rax
> +	test	%rax, %rax
> +	/*
> +	 * At this point, %ebx holds the effective return value, which shall be
> +	 * returned if no callback is specified
> +	 */
> +	cmovz	%rbx, %rax
> +	jz	7f
> +	/*
> +	 * Align stack per x86_64 ABI. The original %rsp is saved in %rbx to be
> +	 * restored after *callback returns.
> +	 */
> +	mov	%rsp, %rbx
> +	and	$-0x10, %rsp
> +	/* Clear RFLAGS.DF per x86_64 ABI */
> +	cld
> +	/* Parameters for *callback */
> +	push	%rbx
> +	push	0x10(%rbp)
> +	/* Call *%rax via retpoline */
> +	call	40f
> +	/*
> +	 * Restore %rsp to its original value left off by the enclave from last
> +	 * exit
> +	 */
> +	mov	%rbx, %rsp
> +	/*
> +	 * Positive return value from *callback will be interpreted as an ENCLU
> +	 * leaf, while a non-positive value will be interpreted as the return
> +	 * value to be passed back to the caller.
> +	 */
> +	jmp	1b
> +40:	/* retpoline */
> +	call	42f
> +41:	pause
> +	lfence
> +	jmp	41b
> +42:	mov	%rax, (%rsp)
>  	ret
>  
> -bad_input:
> -	mov     $(-EINVAL), %rax
> -	ret
> +5:	/* Exception path */
> +	mov	$-EFAULT, %ebx
> +	stc
> +	jmp	3b
>  
> -.pushsection .fixup, "ax"
> -	/* Re-load @exception_info and fill it (if it's non-NULL) */
> -2:	pop	%rcx
> -	test    %rcx, %rcx
> -	je      3f
> +6:	/* Unsupported ENCLU leaf */
> +	cmp	$0, %eax
> +	jle	7f
> +	mov	$-EINVAL, %eax
>  
> -	mov	%eax, EX_LEAF(%rcx)
> -	mov	%di,  EX_TRAPNR(%rcx)
> -	mov	%si,  EX_ERROR_CODE(%rcx)
> -	mov	%rdx, EX_ADDRESS(%rcx)
> -3:	mov	$(-EFAULT), %rax
> +7:	/* Epilog */
> +	leave
> +	.cfi_def_cfa		%rsp, 8
>  	ret
> -.popsection
> +	.cfi_endproc
>  
> -_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
> +_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
>  
>  ENDPROC(__vdso_sgx_enter_enclave)
> diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
> index 9ed690a38c70..50d2b5143e5e 100644
> --- a/arch/x86/include/uapi/asm/sgx.h
> +++ b/arch/x86/include/uapi/asm/sgx.h
> @@ -24,7 +24,7 @@
>  
>  /**
>   * struct sgx_enclave_create - parameter structure for the
> - *                             %SGX_IOC_ENCLAVE_CREATE ioctl
> + *			       %SGX_IOC_ENCLAVE_CREATE ioctl

You have bunch of these clutter diff's in your patch. Please get rid of
them.

>   * @src:	address for the SECS page data
>   */
>  struct sgx_enclave_create  {
> @@ -33,7 +33,7 @@ struct sgx_enclave_create  {
>  
>  /**
>   * struct sgx_enclave_add_page - parameter structure for the
> - *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
> + *				 %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
>   * @addr:	address within the ELRANGE
>   * @src:	address for the page data
>   * @secinfo:	address for the SECINFO data
> @@ -49,7 +49,7 @@ struct sgx_enclave_add_page {
>  
>  /**
>   * struct sgx_enclave_init - parameter structure for the
> - *                           %SGX_IOC_ENCLAVE_INIT ioctl
> + *			     %SGX_IOC_ENCLAVE_INIT ioctl
>   * @sigstruct:	address for the SIGSTRUCT data
>   */
>  struct sgx_enclave_init {
> @@ -66,16 +66,16 @@ struct sgx_enclave_set_attribute {
>  };
>  
>  /**
> - * struct sgx_enclave_exception - structure to report exceptions encountered in
> - *				  __vdso_sgx_enter_enclave()
> + * struct sgx_enclave_exinfo - structure to report exceptions encountered in
> + *			       __vdso_sgx_enter_enclave()

If you want to rename a struct it should be its own commit. Anyway, I'd
say that this unnecessary.

>   *
> - * @leaf:	ENCLU leaf from \%eax at time of exception
> + * @leaf:	ENCLU leaf from \%eax at time of exception/exit
>   * @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 {
> +struct sgx_enclave_exinfo {
>  	__u32 leaf;
>  	__u16 trapnr;
>  	__u16 error_code;
> -- 
> 2.17.1
> 

Summary: I can live with the general idea but the patch itself is
somewhat half-finished still.

/Jarkko

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

* Re: [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-11  4:21     ` [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
  2019-07-11  9:50       ` Jarkko Sakkinen
@ 2019-07-11  9:53       ` Jarkko Sakkinen
  2019-07-11 15:42         ` Sean Christopherson
  1 sibling, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-11  9:53 UTC (permalink / raw)
  To: Cedric Xing; +Cc: linux-sgx, luto, jethro, greg, sean.j.christopherson

On Wed, Jul 10, 2019 at 09:21:32PM -0700, Cedric Xing wrote:
> -#ifdef SGX_KERNEL_DOC

Why is this removed?

> + * int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> + *				struct sgx_enclave_exinfo *exinfo,
> + *				sgx_callback callback)
> + * {
> + *	while (leaf == EENTER || leaf == ERESUME) {
> + *		int rc;
> + *		try {
> + *			ENCLU[leaf];
> + *			rc = 0;
> + *			if (exinfo)
> + *				exinfo->leaf = EEXIT;
> + *		} catch (exception) {
> + *			rc = -EFAULT;
> + *			if (exinfo)
> + *				*exinfo = exception;
> + *		}
> + *
> + *		leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
> + *						   r8, r9, tcs, ursp);
> + *	}
> + *
> + *	return leaf > 0 ? -EINVAL : leaf;
> + * }
>   */

What is this? C++ and anyway there is already a source code. No need
to duplicate with pseudo-code. Only adds maintenance burde. Please get
rid of this.

/Jarkko

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

* Re: [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-11  9:53       ` Jarkko Sakkinen
@ 2019-07-11 15:42         ` Sean Christopherson
  2019-07-11 17:55           ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-07-11 15:42 UTC (permalink / raw)
  To: Jarkko Sakkinen; +Cc: Cedric Xing, linux-sgx, luto, jethro, greg

On Thu, Jul 11, 2019 at 12:53:17PM +0300, Jarkko Sakkinen wrote:
> On Wed, Jul 10, 2019 at 09:21:32PM -0700, Cedric Xing wrote:
> > -#ifdef SGX_KERNEL_DOC
> 
> Why is this removed?
> 
> > + * int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> > + *				struct sgx_enclave_exinfo *exinfo,
> > + *				sgx_callback callback)
> > + * {
> > + *	while (leaf == EENTER || leaf == ERESUME) {
> > + *		int rc;
> > + *		try {
> > + *			ENCLU[leaf];
> > + *			rc = 0;
> > + *			if (exinfo)
> > + *				exinfo->leaf = EEXIT;
> > + *		} catch (exception) {
> > + *			rc = -EFAULT;
> > + *			if (exinfo)
> > + *				*exinfo = exception;
> > + *		}
> > + *
> > + *		leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
> > + *						   r8, r9, tcs, ursp);
> > + *	}
> > + *
> > + *	return leaf > 0 ? -EINVAL : leaf;
> > + * }
> >   */
> 
> What is this? C++ and anyway there is already a source code. No need
> to duplicate with pseudo-code. Only adds maintenance burde. Please get
> rid of this.

Adding C pseudo-code was my idea, e.g. it already exists in v20.  Declaring
a psuedo-C function coerces kernel-doc into generating documentation for
the asm routine.  IIRC, fully defining the function is not required for
docs, but IMO it's significantly easier to gain an understanding of a blob
of asm if there is higher level pseudocode.

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-11  9:38               ` Jarkko Sakkinen
@ 2019-07-11 15:50                 ` Sean Christopherson
  2019-07-11 17:59                   ` Jarkko Sakkinen
  2019-07-11 19:51                 ` Xing, Cedric
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-07-11 15:50 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: Xing, Cedric, linux-kernel, linux-sgx, akpm, dave.hansen,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Thu, Jul 11, 2019 at 12:38:09PM +0300, Jarkko Sakkinen wrote:
> On Wed, Jul 10, 2019 at 04:37:41PM -0700, Xing, Cedric wrote:
> > We are not judging which vessel is better (or the best) among all possible
> > vessels. We are trying to enable more vessels. Every vessel has its pros and
> > cons so there's *no* single best vessel.
> 
> I think reasonable metric is actually the coverage of the Intel SDK
> based enclaves. How widely are they in the wild? If the user base is
> large, it should be reasonable to support this just based on that.

Large enough that Andy agreed to take the vDSO code with the optional
callback, despite his personal opinion being that mucking with uR{B,S}P
from within the enclave is poor form.

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

* Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling
  2019-06-27 20:32     ` Xing, Cedric
@ 2019-07-11 15:54       ` Sean Christopherson
  2019-07-11 22:12         ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-07-11 15:54 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: Jarkko Sakkinen, linux-kernel, x86, linux-sgx, akpm, Hansen,
	Dave, nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, andriy.shevchenko, tglx, Svahn, Kai, bp, josh, luto,
	Huang, Kai, rientjes, Andy Lutomirski, Dave Hansen

On Thu, Jun 27, 2019 at 01:32:58PM -0700, Xing, Cedric wrote:
> 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.

On Tue, Apr 23, 2019 at 11:59:37AM -0700, Sean Christopherson wrote:
> On Mon, Apr 22, 2019 at 06:29:06PM -0700, Andy Lutomirski wrote:
> > 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...


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

* Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling
  2019-06-25 15:43   ` Jarkko Sakkinen
  2019-06-27 20:32     ` Xing, Cedric
@ 2019-07-11 15:56     ` Sean Christopherson
  2019-07-11 17:52       ` Jarkko Sakkinen
  1 sibling, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-07-11 15:56 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, x86, linux-sgx, akpm, dave.hansen, nhorman,
	npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes, Andy Lutomirski, Dave Hansen

On Tue, Jun 25, 2019 at 06:43:41PM +0300, Jarkko Sakkinen wrote:
> 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.

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

* Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling
  2019-07-11 15:56     ` Sean Christopherson
@ 2019-07-11 17:52       ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-11 17:52 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: linux-kernel, x86, linux-sgx, akpm, dave.hansen, nhorman,
	npmccallum, serge.ayoun, shay.katz-zamir, haitao.huang,
	andriy.shevchenko, tglx, kai.svahn, bp, josh, luto, kai.huang,
	rientjes, Andy Lutomirski, Dave Hansen

On Thu, Jul 11, 2019 at 08:56:46AM -0700, Sean Christopherson wrote:
> On Tue, Jun 25, 2019 at 06:43:41PM +0300, Jarkko Sakkinen wrote:
> > 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

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

* Re: [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-11 15:42         ` Sean Christopherson
@ 2019-07-11 17:55           ` Jarkko Sakkinen
  2019-07-11 17:58             ` Sean Christopherson
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-11 17:55 UTC (permalink / raw)
  To: Sean Christopherson; +Cc: Cedric Xing, linux-sgx, luto, jethro, greg

On Thu, Jul 11, 2019 at 08:42:31AM -0700, Sean Christopherson wrote:
> On Thu, Jul 11, 2019 at 12:53:17PM +0300, Jarkko Sakkinen wrote:
> > On Wed, Jul 10, 2019 at 09:21:32PM -0700, Cedric Xing wrote:
> > > -#ifdef SGX_KERNEL_DOC
> > 
> > Why is this removed?
> > 
> > > + * int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> > > + *				struct sgx_enclave_exinfo *exinfo,
> > > + *				sgx_callback callback)
> > > + * {
> > > + *	while (leaf == EENTER || leaf == ERESUME) {
> > > + *		int rc;
> > > + *		try {
> > > + *			ENCLU[leaf];
> > > + *			rc = 0;
> > > + *			if (exinfo)
> > > + *				exinfo->leaf = EEXIT;
> > > + *		} catch (exception) {
> > > + *			rc = -EFAULT;
> > > + *			if (exinfo)
> > > + *				*exinfo = exception;
> > > + *		}
> > > + *
> > > + *		leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
> > > + *						   r8, r9, tcs, ursp);
> > > + *	}
> > > + *
> > > + *	return leaf > 0 ? -EINVAL : leaf;
> > > + * }
> > >   */
> > 
> > What is this? C++ and anyway there is already a source code. No need
> > to duplicate with pseudo-code. Only adds maintenance burde. Please get
> > rid of this.
> 
> Adding C pseudo-code was my idea, e.g. it already exists in v20.  Declaring
> a psuedo-C function coerces kernel-doc into generating documentation for
> the asm routine.  IIRC, fully defining the function is not required for
> docs, but IMO it's significantly easier to gain an understanding of a blob
> of asm if there is higher level pseudocode.

The way to do this right would be to write a documentation block before
kdoc's for the functions. It is described in the last section of

https://www.kernel.org/doc/Documentation/kernel-doc-nano-HOWTO.txt0

I.e. organize the file as

1. Documentation block describing the theory of operation.
2. Functions and their associated documentations.

/Jarkko

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

* Re: [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-11 17:55           ` Jarkko Sakkinen
@ 2019-07-11 17:58             ` Sean Christopherson
  2019-07-12  3:16               ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Sean Christopherson @ 2019-07-11 17:58 UTC (permalink / raw)
  To: Jarkko Sakkinen; +Cc: Cedric Xing, linux-sgx, luto, jethro, greg

On Thu, Jul 11, 2019 at 08:55:50PM +0300, Jarkko Sakkinen wrote:
> On Thu, Jul 11, 2019 at 08:42:31AM -0700, Sean Christopherson wrote:
> > On Thu, Jul 11, 2019 at 12:53:17PM +0300, Jarkko Sakkinen wrote:
> > > On Wed, Jul 10, 2019 at 09:21:32PM -0700, Cedric Xing wrote:
> > > > -#ifdef SGX_KERNEL_DOC
> > > 
> > > Why is this removed?
> > > 
> > > > + * int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> > > > + *				struct sgx_enclave_exinfo *exinfo,
> > > > + *				sgx_callback callback)
> > > > + * {
> > > > + *	while (leaf == EENTER || leaf == ERESUME) {
> > > > + *		int rc;
> > > > + *		try {
> > > > + *			ENCLU[leaf];
> > > > + *			rc = 0;
> > > > + *			if (exinfo)
> > > > + *				exinfo->leaf = EEXIT;
> > > > + *		} catch (exception) {
> > > > + *			rc = -EFAULT;
> > > > + *			if (exinfo)
> > > > + *				*exinfo = exception;
> > > > + *		}
> > > > + *
> > > > + *		leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
> > > > + *						   r8, r9, tcs, ursp);
> > > > + *	}
> > > > + *
> > > > + *	return leaf > 0 ? -EINVAL : leaf;
> > > > + * }
> > > >   */
> > > 
> > > What is this? C++ and anyway there is already a source code. No need
> > > to duplicate with pseudo-code. Only adds maintenance burde. Please get
> > > rid of this.
> > 
> > Adding C pseudo-code was my idea, e.g. it already exists in v20.  Declaring
> > a psuedo-C function coerces kernel-doc into generating documentation for
> > the asm routine.  IIRC, fully defining the function is not required for
> > docs, but IMO it's significantly easier to gain an understanding of a blob
> > of asm if there is higher level pseudocode.
> 
> The way to do this right would be to write a documentation block before
> kdoc's for the functions. It is described in the last section of
> 
> https://www.kernel.org/doc/Documentation/kernel-doc-nano-HOWTO.txt0
> 
> I.e. organize the file as
> 
> 1. Documentation block describing the theory of operation.
> 2. Functions and their associated documentations.

The kernel doc parser straight up doesn't work on asm functions, hence the
shenanigans to coerce it into thinking it's parsing a normal C function.

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-11 15:50                 ` Sean Christopherson
@ 2019-07-11 17:59                   ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-11 17:59 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Xing, Cedric, linux-kernel, linux-sgx, akpm, dave.hansen,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Thu, Jul 11, 2019 at 08:50:37AM -0700, Sean Christopherson wrote:
> On Thu, Jul 11, 2019 at 12:38:09PM +0300, Jarkko Sakkinen wrote:
> > On Wed, Jul 10, 2019 at 04:37:41PM -0700, Xing, Cedric wrote:
> > > We are not judging which vessel is better (or the best) among all possible
> > > vessels. We are trying to enable more vessels. Every vessel has its pros and
> > > cons so there's *no* single best vessel.
> > 
> > I think reasonable metric is actually the coverage of the Intel SDK
> > based enclaves. How widely are they in the wild? If the user base is
> > large, it should be reasonable to support this just based on that.
> 
> Large enough that Andy agreed to take the vDSO code with the optional
> callback, despite his personal opinion being that mucking with uR{B,S}P
> from within the enclave is poor form.

OK, the cover letter empahasized things that did not make sense to me,
which made me to do my initial conclusions. I don't recall even reading
the word "coverage" from it.

Anyways, I'm sure we can land this after v21 has been published now that
the rationale is clear.

/Jarkko

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-11  9:36             ` Jarkko Sakkinen
@ 2019-07-11 19:49               ` Xing, Cedric
  0 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-11 19:49 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/11/2019 2:36 AM, Jarkko Sakkinen wrote:
> On Wed, Jul 10, 2019 at 03:54:20PM -0700, Xing, Cedric wrote:
>> On 7/10/2019 3:46 PM, Jarkko Sakkinen wrote:
>>> On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
>>>>> With these conclusions I think the current vDSO API is sufficient for
>>>>> Linux.
>>>>
>>>> The new vDSO API is to support data exchange on stack. It has nothing to do
>>>> with debugging. BTW, the community has closed on this.
>>>
>>> And how that is useful?
>>
>> There is a lengthy discussion on its usefulness so I don't want to repeat.
>> In short, it allows using untrusted stack as a convenient method to exchange
>> data with the enclave. It is currently being used by Intel's SGX SDK for
>> e/o-calls parameters.
>>
>>>> The CFI directives are for stack unwinding. They don't affect what the code
>>>> does so you can just treat them as NOPs if you don't understand what they
>>>> do. However, they are useful to not only debuggers but also exception
>>>> handling code. libunwind also has a setjmp()/longjmp() implementation based
>>>> on CFI directives.
>>>
>>> Of course I won't merge code of which usefulness I don't understand.
>>
>> Sure.
>>
>> Any other questions I can help with?
> 
> I dissected my concerns in other email. We can merge this feature after
> v21 if it makes sense.

Sent out v3 of vDSO changes last night. I hope your concerns have been 
properly addressed.

The new vDSO API is a community consensus. I can help on whatever 
technical problems you may have but I don't see a reason you should 
reject it.

> /Jarkko
> 

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

* Re: [RFC PATCH v2 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack
  2019-07-11  9:38               ` Jarkko Sakkinen
  2019-07-11 15:50                 ` Sean Christopherson
@ 2019-07-11 19:51                 ` Xing, Cedric
  1 sibling, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-11 19:51 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/11/2019 2:38 AM, Jarkko Sakkinen wrote:
> On Wed, Jul 10, 2019 at 04:37:41PM -0700, Xing, Cedric wrote:
>> On 7/10/2019 4:15 PM, Jarkko Sakkinen wrote:
>>> On Thu, Jul 11, 2019 at 01:46:28AM +0300, Jarkko Sakkinen wrote:
>>>> On Wed, Jul 10, 2019 at 11:08:37AM -0700, Xing, Cedric wrote:
>>>>>> With these conclusions I think the current vDSO API is sufficient for
>>>>>> Linux.
>>>>>
>>>>> The new vDSO API is to support data exchange on stack. It has nothing to do
>>>>> with debugging. BTW, the community has closed on this.
>>>>
>>>> And how that is useful?
>>>>
>>>>> The CFI directives are for stack unwinding. They don't affect what the code
>>>>> does so you can just treat them as NOPs if you don't understand what they
>>>>> do. However, they are useful to not only debuggers but also exception
>>>>> handling code. libunwind also has a setjmp()/longjmp() implementation based
>>>>> on CFI directives.
>>>>
>>>> Of course I won't merge code of which usefulness I don't understand.
>>>
>>> I re-read the cover letter [1] because it usually is the place
>>> to "pitch" a feature.
>>>
>>> It fails to address two things:
>>>
>>> 1. How and in what circumstances is an untrusted stack is a better
>>>      vessel for handling exceptions than the register based approach
>>>      that we already have?
>>
>> We are not judging which vessel is better (or the best) among all possible
>> vessels. We are trying to enable more vessels. Every vessel has its pros and
>> cons so there's *no* single best vessel.
> 
> I think reasonable metric is actually the coverage of the Intel SDK
> based enclaves. How widely are they in the wild? If the user base is
> large, it should be reasonable to support this just based on that.

I don't know how many existing enclaves out there, but definitely larger 
than 0 (zero), while user base for the old API is definitely 0. What are 
you worrying, really?

> /Jarkko
> 

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

* Re: [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions in vDSO before signaling
  2019-07-11 15:54       ` Sean Christopherson
@ 2019-07-11 22:12         ` Xing, Cedric
  0 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-11 22:12 UTC (permalink / raw)
  To: Sean Christopherson
  Cc: Jarkko Sakkinen, linux-kernel, x86, linux-sgx, akpm, Hansen,
	Dave, nhorman, npmccallum, Ayoun, Serge, Katz-zamir, Shay, Huang,
	Haitao, andriy.shevchenko, tglx, Svahn, Kai, bp, josh, luto,
	Huang, Kai, rientjes, Andy Lutomirski, Dave Hansen

On 7/11/2019 8:54 AM, Sean Christopherson wrote:
> On Thu, Jun 27, 2019 at 01:32:58PM -0700, Xing, Cedric wrote:
>> 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.

> On Tue, Apr 23, 2019 at 11:59:37AM -0700, Sean Christopherson wrote:
>> On Mon, Apr 22, 2019 at 06:29:06PM -0700, Andy Lutomirski wrote:
>>> 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...

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

* Re: [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-11 17:58             ` Sean Christopherson
@ 2019-07-12  3:16               ` Jarkko Sakkinen
  2019-07-13  7:00                 ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-12  3:16 UTC (permalink / raw)
  To: Sean Christopherson; +Cc: Cedric Xing, linux-sgx, luto, jethro, greg

On Thu, Jul 11, 2019 at 10:58:13AM -0700, Sean Christopherson wrote:
> > The way to do this right would be to write a documentation block before
> > kdoc's for the functions. It is described in the last section of
> > 
> > https://www.kernel.org/doc/Documentation/kernel-doc-nano-HOWTO.txt0
> > 
> > I.e. organize the file as
> > 
> > 1. Documentation block describing the theory of operation.
> > 2. Functions and their associated documentations.
> 
> The kernel doc parser straight up doesn't work on asm functions, hence the
> shenanigans to coerce it into thinking it's parsing a normal C function.

Aah. I think I was too hazy with my comment. Looked it from patchwork and
the documentation is mostly just fine.

For this patch this cruft nees to be removed:

- *                           %SGX_IOC_ENCLAVE_INIT ioctl
+ *			     %SGX_IOC_ENCLAVE_INIT ioctl

These make squashing the patch properly nasty.

Also there is one unwanted rename. Did not find anything else obviously
wrong.

/Jarkko

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

* Re: [RFC PATCH v2 1/3] selftests/x86: Fixed Makefile for SGX selftest
  2019-04-24  6:26   ` [RFC PATCH v2 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
@ 2019-07-12  3:19     ` Jarkko Sakkinen
  2019-07-13  6:58       ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-12  3:19 UTC (permalink / raw)
  To: Cedric Xing
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Tue, Apr 23, 2019 at 11:26:21PM -0700, Cedric Xing wrote:
> The original x86/sgx/Makefile doesn't work when 'x86/sgx' is specified as the
> test target. This patch fixes that problem, along with minor changes to the
> dependencies between 'x86' and 'x86/sgx' in selftests/x86/Makefile.
> 
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---
>  tools/testing/selftests/x86/Makefile     | 12 +++----
>  tools/testing/selftests/x86/sgx/Makefile | 45 +++++++++---------------
>  2 files changed, 22 insertions(+), 35 deletions(-)
> 
> diff --git a/tools/testing/selftests/x86/Makefile b/tools/testing/selftests/x86/Makefile
> index 4fc9a42f56ea..1294c5f5b6ca 100644
> --- a/tools/testing/selftests/x86/Makefile
> +++ b/tools/testing/selftests/x86/Makefile
> @@ -70,11 +70,11 @@ 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 $@;	\
> +all_64: | $(SUBDIRS_64)
> +	@for DIR in $|; do					\
> +		BUILD_TARGET=$(OUTPUT)/$$DIR;			\
> +		mkdir $$BUILD_TARGET  -p;			\
> +		$(MAKE) OUTPUT=$$BUILD_TARGET -C $$DIR $@;	\

This is not fix for anything. It is change in semantics. This diff
should be isolated to its own commit as you are changing something
outside of SGX scope.

>  	done
>  
>  EXTRA_CLEAN := $(BINARIES_32) $(BINARIES_64)
> @@ -90,7 +90,7 @@ ifeq ($(CAN_BUILD_I386)$(CAN_BUILD_X86_64),01)
>  all: warn_32bit_failure
>  
>  warn_32bit_failure:
> -	@echo "Warning: you seem to have a broken 32-bit build" 2>&1; 	\
> +	@echo "Warning: you seem to have a broken 32-bit build" 2>&1;	\

Please clean this up.

>  	echo "environment.  This will reduce test coverage of 64-bit" 2>&1; \
>  	echo "kernels.  If you are using a Debian-like distribution," 2>&1; \
>  	echo "try:"; 2>&1; \
> diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
> index 1fd6f2708e81..3af15d7c8644 100644
> --- a/tools/testing/selftests/x86/sgx/Makefile
> +++ b/tools/testing/selftests/x86/sgx/Makefile
> @@ -2,47 +2,34 @@ top_srcdir = ../../../../..
>  
>  include ../../lib.mk
>  
> -HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
> -ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
> +ifeq ($(shell $(CC) -dumpmachine | cut --delimiter=- -f1),x86_64)
> +all: all_64
> +endif
> +
> +HOST_CFLAGS := -Wall -Werror -g $(INCLUDES)
> +ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIE \
>  	       -fno-stack-protector -mrdrnd $(INCLUDES)
>  
>  TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
>  all_64: $(TEST_CUSTOM_PROGS)
>  
> -$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
> -		      $(OUTPUT)/encl_piggy.o
> +$(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
>  	$(CC) $(HOST_CFLAGS) -o $@ $^
>  
> -$(OUTPUT)/main.o: main.c
> -	$(CC) $(HOST_CFLAGS) -c $< -o $@
> -
> -$(OUTPUT)/sgx_call.o: sgx_call.S
> -	$(CC) $(HOST_CFLAGS) -c $< -o $@
> -
> -$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
> -	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
> +$(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
> +	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
>  
> -$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
> +$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
>  	objcopy --remove-section=.got.plt -O binary $< $@
>  
> -$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
> -	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
> +$(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
> +	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
>  
> -$(OUTPUT)/encl.o: encl.c
> -	$(CC) $(ENCL_CFLAGS) -c $< -o $@
> -
> -$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
> -	$(CC) $(ENCL_CFLAGS) -c $< -o $@
> -
> -$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
> -	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
> +$(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
> +	$^ $@
>  
>  $(OUTPUT)/sgxsign: sgxsign.c
>  	$(CC) -o $@ $< -lcrypto
>  
> -EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
> -	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
> -	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
> -	       $(OUTPUT)/sgxsign
> -
> -.PHONY: clean
> +EXTRA_CLEAN := $(TEST_CUSTOM_PROGS) $(addprefix $(OUTPUT)/,	\
> +		encl.elf encl.bin encl.ss encl_piggy.o sgxsign)
> -- 
> 2.17.1
> 

What are all these changes to the makefile? I don't see mention of them
in the commit message.

/Jarkko

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

* Re: [RFC PATCH v2 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-04-24  6:26   ` [RFC PATCH v2 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
@ 2019-07-12  3:25     ` Jarkko Sakkinen
  2019-07-13  7:03       ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-12  3:25 UTC (permalink / raw)
  To: Cedric Xing
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Tue, Apr 23, 2019 at 11:26:23PM -0700, Cedric Xing wrote:
> This patch augments SGX selftest with two new tests.
> 
> The first test exercises the newly added callback interface, by marking the
> whole enclave range as PROT_READ, then calling mprotect() upon #PFs to add
> necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.
> This test also serves as an example to demonstrate the callback interface.
> 
> The second test single-steps through __vdso_sgx_enter_enclave() to make sure
> the call stack can be unwound at every instruction within that vDSO API. Its
> purpose is to validate the hand-crafted CFI directives in the assembly.
> 
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---
>  tools/testing/selftests/x86/sgx/Makefile   |   6 +-
>  tools/testing/selftests/x86/sgx/main.c     | 323 ++++++++++++++++++---
>  tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
>  3 files changed, 322 insertions(+), 47 deletions(-)
> 
> diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
> index 3af15d7c8644..31f937e220c4 100644
> --- a/tools/testing/selftests/x86/sgx/Makefile
> +++ b/tools/testing/selftests/x86/sgx/Makefile
> @@ -14,16 +14,16 @@ TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
>  all_64: $(TEST_CUSTOM_PROGS)
>  
>  $(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
> -	$(CC) $(HOST_CFLAGS) -o $@ $^
> +	$(CC) $(HOST_CFLAGS) -o $@ $^ -lunwind -ldl -Wl,--defsym,__image_base=0 -pie
>  
>  $(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
>  	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
>  
>  $(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
> -	objcopy --remove-section=.got.plt -O binary $< $@
> +	objcopy -O binary $< $@
>  
>  $(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
> -	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
> +	$(CC) $(ENCL_CFLAGS) -T $^ -o $@ -Wl,--build-id=none
>  
>  $(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
>  	$^ $@
> diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
> index e2265f841fb0..d3e53c71306d 100644
> --- a/tools/testing/selftests/x86/sgx/main.c
> +++ b/tools/testing/selftests/x86/sgx/main.c
> @@ -1,6 +1,7 @@
>  // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
>  // Copyright(c) 2016-18 Intel Corporation.
>  
> +#define _GNU_SOURCE
>  #include <elf.h>
>  #include <fcntl.h>
>  #include <stdbool.h>
> @@ -9,16 +10,31 @@
>  #include <stdlib.h>
>  #include <string.h>
>  #include <unistd.h>
> +#include <errno.h>
>  #include <sys/ioctl.h>
>  #include <sys/mman.h>
>  #include <sys/stat.h>
> -#include <sys/time.h>
> +#include <sys/auxv.h>
> +#include <signal.h>
> +#include <sys/ucontext.h>
> +
> +#define UNW_LOCAL_ONLY
> +#include <libunwind.h>
> +
>  #include "encl_piggy.h"
>  #include "defines.h"
>  #include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
>  #include "../../../../../arch/x86/include/uapi/asm/sgx.h"
>  
> -static const uint64_t MAGIC = 0x1122334455667788ULL;
> +#define _Q(x)	__Q(x)
> +#define __Q(x)	#x
> +#define ERRLN	"Line " _Q(__LINE__)
> +
> +#define X86_EFLAGS_TF	(1ul << 8)
> +
> +extern char __image_base[];
> +size_t eenter;
> +static size_t vdso_base;
>  
>  struct vdso_symtab {
>  	Elf64_Sym *elf_symtab;
> @@ -26,20 +42,11 @@ struct vdso_symtab {
>  	Elf64_Word *elf_hashtab;
>  };
>  
> -static void *vdso_get_base_addr(char *envp[])
> +static void vdso_init(void)
>  {
> -	Elf64_auxv_t *auxv;
> -	int i;
> -
> -	for (i = 0; envp[i]; i++);
> -	auxv = (Elf64_auxv_t *)&envp[i + 1];
> -
> -	for (i = 0; auxv[i].a_type != AT_NULL; i++) {
> -		if (auxv[i].a_type == AT_SYSINFO_EHDR)
> -			return (void *)auxv[i].a_un.a_val;
> -	}
> -
> -	return NULL;
> +	vdso_base = getauxval(AT_SYSINFO_EHDR);
> +	if (!vdso_base)
> +		exit(1);
>  }

The clean up makes sense but should be a separate patch i.e. one
logical change per patch. Right now the patch does other mods
than the ones explcitly stated in the commit message.

I'd suggest open coding vdso_init() to the call site in that
patch.

Please try to always minimize for diff's.

>  
>  static Elf64_Dyn *vdso_get_dyntab(void *addr)
> @@ -66,8 +73,9 @@ static void *vdso_get_dyn(void *addr, Elf64_Dyn *dyntab, Elf64_Sxword tag)
>  	return NULL;
>  }
>  
> -static bool vdso_get_symtab(void *addr, struct vdso_symtab *symtab)
> +static bool vdso_get_symtab(struct vdso_symtab *symtab)
>  {
> +	void *addr = (void *)vdso_base;
>  	Elf64_Dyn *dyntab = vdso_get_dyntab(addr);
>  
>  	symtab->elf_symtab = vdso_get_dyn(addr, dyntab, DT_SYMTAB);
> @@ -138,7 +146,7 @@ static bool encl_create(int dev_fd, unsigned long bin_size,
>  	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
>  		    MAP_SHARED, dev_fd, 0);
>  	if (base == MAP_FAILED) {
> -		perror("mmap");
> +		perror(ERRLN);
>  		return false;
>  	}
>  
> @@ -224,35 +232,271 @@ static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
>  	return false;
>  }
>  
> -void sgx_call(void *rdi, void *rsi, void *tcs,
> -	      struct sgx_enclave_exception *exception,
> -	      void *eenter);
> +int sgx_call(void *rdi, void *rsi, long rdx, void *rcx, void *r8, void *r9,
> +	     void *tcs, struct sgx_enclave_exinfo *ei, void *cb);
> +
> +static void show_enclave_exinfo(const struct sgx_enclave_exinfo *exinfop,
> +				const char *header)
> +{
> +	static const char * const enclu_leaves[] = {
> +		"EREPORT",
> +		"EGETKEY",
> +		"EENTER",
> +		"ERESUME",
> +		"EEXIT"
> +	};
> +	static const char * const exception_names[] = {
> +		"#DE",
> +		"#DB",
> +		"NMI",
> +		"#BP",
> +		"#OF",
> +		"#BR",
> +		"#UD",
> +		"#NM",
> +		"#DF",
> +		"CSO",
> +		"#TS",
> +		"#NP",
> +		"#SS",
> +		"#GP",
> +		"#PF",
> +		"Unknown",
> +		"#MF",
> +		"#AC",
> +		"#MC",
> +		"#XM",
> +		"#VE",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown",
> +		"Unknown"
> +	};
> +
> +	printf("%s: leaf:%s(%d)", header,
> +		enclu_leaves[exinfop->leaf], exinfop->leaf);
> +	if (exinfop->leaf != 4)
> +		printf(" trap:%s(%d) ec:%d addr:0x%llx\n",
> +			exception_names[exinfop->trapnr], exinfop->trapnr,
> +			exinfop->error_code, exinfop->address);
> +	else
> +		printf("\n");
> +}
> +
> +static const uint64_t MAGIC = 0x1122334455667788ULL;
>  
> -int main(int argc, char *argv[], char *envp[])
> +static void test1(struct sgx_secs *secs)

test1, test2 and test3 are not too descriptive names. Every patch should
make the code base cleaner, not messier.

/Jarkko

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

* Re: [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on untrusted stack
  2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
@ 2019-07-12  3:28       ` Jarkko Sakkinen
  2019-07-13  6:51       ` [RFC PATCH v4 " Cedric Xing
                         ` (3 subsequent siblings)
  4 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-12  3:28 UTC (permalink / raw)
  To: Cedric Xing; +Cc: linux-sgx, luto, jethro, greg, sean.j.christopherson

On Wed, Jul 10, 2019 at 09:21:30PM -0700, Cedric Xing wrote:
> This patchset is based upon, and can be applied cleanly on SGX1 patch v20
> (https://lkml.org/lkml/2019/4/17/344) by Jarkko Sakkinen.
> 
> The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
> %rsp, which prohibits enclaves from allocating space on the untrusted stack.
> However, there are existing enclaves (e.g. those built with current Intel SGX
> SDK libraries) relying on the untrusted stack for passing parameters to
> untrusted functions (aka. o-calls), which requires allocating space on the
> untrusted stack by enclaves. After all, passing data via untrusted stack is
> very easy to implement (by enclaves), with essentially no overhead, therefore
> is very suitable for exchanging data in small amounts, so could be desirable by
> future SGX applications as well.  
> 
> This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its
> stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto
> the untrusted stack by decrementing the untrusted %rsp. And in order to service
> o-calls and to preserve the untrusted stack upon exceptions, the new vDSO API
> takes one more optional parameter - "callback", which if supplied, will be
> invoked on all enclave exits (including normal and asynchronous exits). Ample
> details regarding the new ABI have been documented as comments inside the
> source code located in arch/x86/entry/vsgx_enter_enclave.S
> 
> Please note that there was a lengthy discussion on what is the "best" approach
> for passing parameters for trusted/untrusted calls. Unfortunately there's no
> single "best" approach that fits all use cases, hence this new ABI has been
> designed intentionally to accommodate varieties. Therefore, to those not
> interested in using the untrusted stack, whatever worked with the old ABI
> proposed by Sean will continue to work with this new ABI.
> 
> The SGX selftest has been augmented by two new tests. One exercises the new
> callback interface, and serves as a simple example to showcase how to use it;
> while the other validates the hand-crafted CFI directives in
> __vdso_sgx_enter_enclave() by single-stepping through it and unwinding call
> stack at every instruction. Please note that the selftest CANNOT run to
> completion yet, as it depends on the vDSO fixup code to signal the process upon
> #DB/#BP inside enclaves (rather than the current behavior of branching to the
> handler in vDSO).
> 
> Changelog:
>   · This is version 3 of this patch series with the following changes.
>     - Per Andy Lutomirski and Sean Christopherson, revised comments and their
>       format in arch/x86/entry/vsgx_enter_enclave.S
>     - Per Jarkko Sakkinen, revised the cover letter to articulate motivation
>       and objective of this patchset.
>   · v2 - https://patchwork.kernel.org/cover/10914161/
>   · v1 - https://patchwork.kernel.org/cover/10911615/

1. I agree with the high level idea.
2. The patches do changes out of scope.

Generally, when doing kernel patches, even for a running patch set,
please do not do anything extra.

It is also stated in the kernel process;

https://www.kernel.org/doc/html/v4.17/process/submitting-patches.html#separate-your-changes

Once these are fully cleaned up we can merge them.

/Jarkko

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

* [RFC PATCH v4 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on untrusted stack
  2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
  2019-07-12  3:28       ` Jarkko Sakkinen
@ 2019-07-13  6:51       ` Cedric Xing
  2019-07-13  6:51       ` [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest Cedric Xing
                         ` (2 subsequent siblings)
  4 siblings, 0 replies; 318+ messages in thread
From: Cedric Xing @ 2019-07-13  6:51 UTC (permalink / raw)
  To: linux-kernel, linux-sgx, jarkko.sakkinen
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

This patchset is based upon, and can be applied cleanly on SGX1 patch v20
(https://lkml.org/lkml/2019/4/17/344) by Jarkko Sakkinen.

The current proposed __vdso_sgx_enter_enclave() requires enclaves to preserve
%rsp, which prohibits enclaves from allocating space on the untrusted stack.
However, there are existing enclaves (e.g. those built with current Intel SGX
SDK libraries) relying on the untrusted stack for passing parameters to
untrusted functions (aka. o-calls), which requires allocating space on the
untrusted stack by enclaves. After all, passing data via untrusted stack is
very easy to implement (by enclaves), with essentially no overhead, therefore
is very suitable for exchanging data in small amounts, so could be desirable by
future SGX applications as well.

This patchset introduces a new ABI for __vdso_sgx_enter_enclave() to anchor its
stack frame on %rbp (instead of %rsp), so as to allow enclaves to "push" onto
the untrusted stack by decrementing the untrusted %rsp. And in order to service
o-calls and to preserve the untrusted stack upon exceptions, the new vDSO API
takes one more optional parameter - "callback", which if supplied, will be
invoked on all enclave exits (including normal and asynchronous exits). Ample
details regarding the new ABI have been documented as comments inside the
source code located in arch/x86/entry/vsgx_enter_enclave.S

Please note that there was a lengthy discussion on what is the "best" approach
for passing parameters for trusted/untrusted calls. Unfortunately there's no
single "best" approach that fits all use cases, hence this new ABI has been
designed intentionally to accommodate varieties. Therefore, to those not
interested in using the untrusted stack, whatever worked with the old ABI
proposed by Sean will continue to work with this new ABI.

The SGX selftest has been augmented by two new tests. One exercises the new
callback interface, and serves as a simple example to showcase how to use it;
while the other validates the hand-crafted CFI directives in
__vdso_sgx_enter_enclave() by single-stepping through it and unwinding call
stack at every instruction.

Changelog:
  · This is version 4 of this patch series with the following changes.
    - Removed unrelated cosmetic changes.
    - Rewrote and reformatted comments in
      arch/x86/entry/vdso/vsgx_enter_enclave.S to follow kernel-doc
      conventions. New comments now can be converted to nice looking man pages.
    - Fixed minor issues in the unwinding selftest and now it can run to
      completion successfully with Sean's fix in vDSO fixup code
      (https://patchwork.kernel.org/patch/11040801/). Comments have also been
      added to describe the tests done.
  · v3 - https://patchwork.kernel.org/cover/11039263/
  · v2 - https://patchwork.kernel.org/cover/10914161/
  · v1 - https://patchwork.kernel.org/cover/10911615/

Cedric Xing (3):
  selftests/x86/sgx: Fix Makefile for SGX selftest
  x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing
    on untrusted stack
  selftests/x86/sgx: Augment SGX selftest to test vDSO API

 arch/x86/entry/vdso/vsgx_enter_enclave.S   | 310 ++++++++++++++-----
 arch/x86/include/uapi/asm/sgx.h            |  14 +-
 tools/testing/selftests/x86/sgx/Makefile   |  49 ++-
 tools/testing/selftests/x86/sgx/main.c     | 344 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
 5 files changed, 600 insertions(+), 157 deletions(-)

-- 
2.17.1


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

* [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest
  2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
  2019-07-12  3:28       ` Jarkko Sakkinen
  2019-07-13  6:51       ` [RFC PATCH v4 " Cedric Xing
@ 2019-07-13  6:51       ` Cedric Xing
  2019-07-13 15:10         ` Jarkko Sakkinen
  2019-07-13  6:51       ` [RFC PATCH v4 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
  2019-07-13  6:51       ` [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API Cedric Xing
  4 siblings, 1 reply; 318+ messages in thread
From: Cedric Xing @ 2019-07-13  6:51 UTC (permalink / raw)
  To: linux-kernel, linux-sgx, jarkko.sakkinen
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

The original x86/sgx/Makefile didn't work when "x86/sgx" was specified as the
test target, nor did it work with "run_tests" as the make target. Yet another
problem was that it breaks 32-bit only build. This patch fixes those problems,
along with adjustments to compiler/linker options and simplifications to the
build rules.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/sgx/Makefile | 45 +++++++++---------------
 1 file changed, 16 insertions(+), 29 deletions(-)

diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 1fd6f2708e81..3af15d7c8644 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -2,47 +2,34 @@ top_srcdir = ../../../../..
 
 include ../../lib.mk
 
-HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
-ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
+ifeq ($(shell $(CC) -dumpmachine | cut --delimiter=- -f1),x86_64)
+all: all_64
+endif
+
+HOST_CFLAGS := -Wall -Werror -g $(INCLUDES)
+ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIE \
 	       -fno-stack-protector -mrdrnd $(INCLUDES)
 
 TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
-$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
-		      $(OUTPUT)/encl_piggy.o
+$(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
 	$(CC) $(HOST_CFLAGS) -o $@ $^
 
-$(OUTPUT)/main.o: main.c
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/sgx_call.o: sgx_call.S
-	$(CC) $(HOST_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
-	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
+$(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
-$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
+$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
 	objcopy --remove-section=.got.plt -O binary $< $@
 
-$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
-	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
+$(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
 
-$(OUTPUT)/encl.o: encl.c
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -c $< -o $@
-
-$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
-	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
+$(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
+	$^ $@
 
 $(OUTPUT)/sgxsign: sgxsign.c
 	$(CC) -o $@ $< -lcrypto
 
-EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
-	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
-	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
-	       $(OUTPUT)/sgxsign
-
-.PHONY: clean
+EXTRA_CLEAN := $(TEST_CUSTOM_PROGS) $(addprefix $(OUTPUT)/,	\
+		encl.elf encl.bin encl.ss encl_piggy.o sgxsign)
-- 
2.17.1


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

* [RFC PATCH v4 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
                         ` (2 preceding siblings ...)
  2019-07-13  6:51       ` [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest Cedric Xing
@ 2019-07-13  6:51       ` Cedric Xing
  2019-07-13 15:04         ` Jarkko Sakkinen
  2019-07-13  6:51       ` [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API Cedric Xing
  4 siblings, 1 reply; 318+ messages in thread
From: Cedric Xing @ 2019-07-13  6:51 UTC (permalink / raw)
  To: linux-kernel, linux-sgx, jarkko.sakkinen
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
which prohibits enclaves from allocating and passing parameters for
untrusted function calls (aka. o-calls) on the untrusted stack.

This patch addresses the problem above by introducing a new ABI that preserves
%rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
using %rbp so that enclaves are allowed to allocate space on the untrusted
stack by decrementing %rsp. Please note that the stack space allocated in such
way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
__vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
been revised to take a callback function as an optional parameter, which if
supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
eXit) and normal exits), with the value of %rsp left off by the enclave as a
parameter to the callback.

Here's the summary of API/ABI changes in this patch. More details could be
found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
  * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
    because it is filled upon both AEX (i.e. exceptions) and normal enclave
    exits.
  * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
    the previous implementation).
  * __vdso_sgx_enter_enclave() takes one more parameter - a callback function
    to be invoked upon enclave exits. This callback is optional, and if not
    supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave
    exits (same behavior as previous implementation).
  * The callback function is given as a parameter the value of %rsp at enclave
    exit to address data "pushed" by the enclave. A positive value returned by
    the callback will be treated as an ENCLU leaf for re-entering the enclave,
    while a zero or negative value will be passed through as the return
    value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
    leave callback by longjmp() or by throwing a C++ exception.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 arch/x86/entry/vdso/vsgx_enter_enclave.S | 310 +++++++++++++++++------
 arch/x86/include/uapi/asm/sgx.h          |  14 +-
 2 files changed, 242 insertions(+), 82 deletions(-)

diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
index fe0bf6671d6d..a96542ba6945 100644
--- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
+++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
@@ -6,96 +6,256 @@
 
 #include "extable.h"
 
-#define EX_LEAF		0*8
-#define EX_TRAPNR	0*8+4
-#define EX_ERROR_CODE	0*8+6
-#define EX_ADDRESS	1*8
+#define EX_LEAF     0*8
+#define EX_TRAPNR   0*8+4
+#define EX_ERROR_CODE   0*8+6
+#define EX_ADDRESS  1*8
 
 .code64
 .section .text, "ax"
 
 #ifdef SGX_KERNEL_DOC
 /**
- * __vdso_sgx_enter_enclave() - Enter an SGX enclave
+ * typedef sgx_ex_callback - Callback function for __vdso_sgx_enter_enclave()
  *
- * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
- * @tcs:	**IN \%rbx** - TCS, must be non-NULL
- * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
+ * @rdi:    value of %%rdi register at enclave exit
+ * @rsi:    value of %%rsi register at enclave exit
+ * @rdx:    value of %%rdx register at enclave exit
+ * @exinfo: pointer to a sgx_enclave_exinfo structure, which was passed to
+ *      __vdso_sgx_enter_enclave() as input
+ * @r8:     value of %%r8 register at enclave exit
+ * @r9:     value of %%r9 register at enclave exit
+ * @tcs:    TCS used by __vdso_sgx_enter_enclave() to enter the enclave,
+ *      could be used to re-enter the
+ *      enclave
+ * @ursp:   value of %%rsp register at enclave exit
+ *
+ * This is the callback function to be invoked upon enclave exits, including
+ * normal exits (as result of EEXIT), and asynchronous exits (AEX) due to
+ * exceptions occurred at EENTER or within the enclave.
+ *
+ * This callback is expected to follow x86_64 ABI.
  *
  * Return:
- *  **OUT \%eax** -
- *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
- *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
- *
- * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
- * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
- * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
- * the return value passed via ``%eax``.  All registers except ``%rsp`` must
- * be treated as volatile from the caller's perspective, including but not
- * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
- * being run **must** preserve the untrusted ``%rsp`` and stack.
+ *
+ * EENTER(2) - causes __vdso_sgx_enter_enclave() to issue ENCLU[EENTER] on the
+ * same TCS. All GPRs left off by this callback function will be passed through
+ * back to the enclave, except %%rax, %%rbx and %%rcx, which are clobbered by
+ * ENCLU[EENTER] instruction.
+ *
+ * ERESUME(3) - causes __vdso_sgx_enter_enclave() to issue ENCLU[ERESUME] on
+ * the same TCS.
+ *
+ * 0 (zero) or negative returned values will be returned back to
+ * __vdso_sgx_enter_enclave()'s caller as is.
+ *
+ * All other values will cause -EINVAL to be returned to
+ * __vdso_sgx_enter_enclave()'s caller.
+ *
+ * Note: All general purpose registers (GPRs) left off by the enclave are
+ * passed through to this function, except %%rax, %%rbx and %%rcx, which are
+ * used internally by __vdso_sgx_enter_enclave(). Some of those registers are
+ * accessible as function parameters (i.e. @rdi, @rsi, @rdx, @r8, @r9 and
+ * @ursp), while others can be accessed only from assembly code.
  */
-__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
-			 struct sgx_enclave_exception *ex_info)
-{
-	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
-		return -EINVAL;
+typedef int sgx_ex_callback(long rdi, long rsi, long rdx,
+                struct sgx_enclave_exinfo *exinfo,
+                long r8, long r9, void *tcs, long ursp);
 
-	if (!tcs)
-		return -EINVAL;
+/**
+ * __vdso_sgx_enter_enclave() - Enter an SGX enclave and capture exceptions
+ *
+ * @leaf:
+ *  passed in %%eax, must be either EENTER(2) or ERESUME(3)
+ * @tcs:
+ *  passed on stack at 8(%%rsp), is the linear address of TCS
+ * @exinfo:
+ *  passed on stack at 0x10(%%rsp), optional, and if non-NULL, shall point
+ *  to an sgx_enclave_exinfo structure to receive information about the
+ *  enclave exit
+ * @callback:
+ *  passed on stack at 0x18(%%rsp), optional, and if non-NULL, points to a
+ *  callback function to be invoked at enclave exits
+ *
+ * __vdso_sgx_enter_enclave() issues either ENCLU[EENTER] or ENCLU[ERESUME] on
+ * @tcs depending on @leaf.
+ *
+ * IMPORTANT! This API is not compliant with x86-64 ABI but adopts a
+ * proprietary calling convention. Please see NOTES section below for details.
+ *
+ * On an enclave exit, @exinfo->leaf will be set to the ENCLU leaf at exit, if
+ * @exinfo is not NULL. That is, @exinfo->leaf may be one of the following:
+ *
+ *   * EEXIT:   Normal exit due to ENCLU[EEXIT] within the enclave. All other
+ *      members will remain intact.
+ *
+ *   * ERESUME: Asynchronous exit due to exceptions within the enclave.
+ *      @exinfo->trapnr, @exinfo->error_code and @exinfo->address are
+ *      set to the trap number, error code and fault address,
+ *      respectively.
+ *
+ *   * EENTER:  Exception occurred when trying to enter the enclave.
+ *      @exinfo->trapnr, @exinfo->error_code and @exinfo->address are
+ *      set to the trap number, error code and fault address,
+ *      accordingly.
+ *
+ * If @callback is NULL, 0 (zero) is returned if the enclave has been entered
+ * and exited normally, or -EFAULT if any exception has occurred, or -EINVAL if
+ * @leaf on input is neither EENTER or ERESUME.
+ *
+ * If @callback is not NULL, it is invoked at enclave exit, and then actions
+ * will be taken depending on its return value - i.e. positive value will be
+ * treated as ENCLU leaf to re-enter the enclave, while 0 (zero) or negative
+ * values will be returned back to the caller as is. Unrecognized leaf values
+ * will cause -EINVAL to be returned.
+ *
+ * Return:
+ *
+ * 0 (zero) is returned on a successful entry and normal exit from the enclave.
+ *
+ * -EINVAL is returned if @leaf is neither EENTER nor ERESUME, or if @callback
+ * is not NULL and returns a positive value that is neither EENTER nor ERESUME
+ * after the enclave exits.
+ *
+ * -EFAULT is returned if an exception has occurred at EENTER or during
+ * execution of the enclave and @callback is NULL, or if @callback is not NULL
+ * and it returns -EFAULT after the enclave exits.
+ *
+ * Other values may be returned as the return value from @callback if it is not
+ * NULL.
+ *
+ * Note: __vdso_sgx_enter_enclave() adopts a proprietary calling convention,
+ * described below:
+ *
+ *    * As noted above, input parameters are passed via %%eax and the stack.
+ *
+ *    * %%rbx and %%rcx must be treated as volatile as they are modified as part
+ *  of enclaves transitions and are used as scratch regs.
+ *
+ *    * %%rdx, %%rdi, %%rsi and %%r8-%%r15 are passed as is and may be freely
+ *  modified by the enclave. Values left in those registers will not be
+ *  altered either, so will be visiable to the callback or the caller (if no
+ *  callback is specified).
+ *
+ *    * %%rsp could be decremented by the enclave to allocate temporary space on
+ *      the untrusted stack. Temporary space allocated this way is retained in
+ *      the context of @callback, and will be freed (i.e. %%rsp will be
+ *      restored) before __vdso_sgx_enter_enclave() returns.
+ */
+int __vdso_sgx_enter_enclave(int leaf, void *tcs,
+                 struct sgx_enclave_exinfo *exinfo,
+                 sgx_ex_callback *callback);
+{
+     while (leaf == EENTER || leaf == ERESUME) {
+    int rc;
+    try {
+        ENCLU[leaf];
+        rc = 0;
+        if (exinfo)
+            exinfo->leaf = EEXIT;
+    } catch (exception) {
+        rc = -EFAULT;
+        if (exinfo)
+            *exinfo = exception;
+    }
 
-	try {
-		ENCLU[leaf];
-	} catch (exception) {
-		if (e)
-			*e = exception;
-		return -EFAULT;
-	}
+    leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
+                       r8, r9, tcs, ursp);
+     }
 
-	return 0;
+     return leaf > 0 ? -EINVAL : leaf;
 }
 #endif
+
 ENTRY(__vdso_sgx_enter_enclave)
-	/* EENTER <= leaf <= ERESUME */
-	cmp	$0x2, %eax
-	jb	bad_input
-
-	cmp	$0x3, %eax
-	ja	bad_input
-
-	/* TCS must be non-NULL */
-	test	%rbx, %rbx
-	je	bad_input
-
-	/* Save @exception_info */
-	push	%rcx
-
-	/* Load AEP for ENCLU */
-	lea	1f(%rip),  %rcx
-1:	enclu
-
-	add	$0x8, %rsp
-	xor	%eax, %eax
-	ret
-
-bad_input:
-	mov     $(-EINVAL), %rax
-	ret
-
-.pushsection .fixup, "ax"
-	/* Re-load @exception_info and fill it (if it's non-NULL) */
-2:	pop	%rcx
-	test    %rcx, %rcx
-	je      3f
-
-	mov	%eax, EX_LEAF(%rcx)
-	mov	%di,  EX_TRAPNR(%rcx)
-	mov	%si,  EX_ERROR_CODE(%rcx)
-	mov	%rdx, EX_ADDRESS(%rcx)
-3:	mov	$(-EFAULT), %rax
-	ret
-.popsection
-
-_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
+    /* Prolog */
+    .cfi_startproc
+    push    %rbp
+    .cfi_adjust_cfa_offset  8
+    .cfi_rel_offset     %rbp, 0
+    mov %rsp, %rbp
+    .cfi_def_cfa_register   %rbp
+
+1:  /* EENTER <= leaf <= ERESUME */
+    cmp $0x2, %eax
+    jb  6f
+    cmp $0x3, %eax
+    ja  6f
+
+    /* Load TCS and AEP */
+    mov 0x10(%rbp), %rbx
+    lea 2f(%rip), %rcx
+
+    /* Single ENCLU serving as both EENTER and AEP (ERESUME) */
+2:  enclu
+
+    /* EEXIT path */
+    xor %ebx, %ebx
+3:  mov 0x18(%rbp), %rcx
+    jrcxz   4f
+    mov %eax, EX_LEAF(%rcx)
+    jnc 4f
+    mov %di, EX_TRAPNR(%rcx)
+    mov %si, EX_ERROR_CODE(%rcx)
+    mov %rdx, EX_ADDRESS(%rcx)
+
+4:  /* Call *callback if supplied */
+    mov 0x20(%rbp), %rax
+    test    %rax, %rax
+    /*
+     * At this point, %ebx holds the effective return value, which shall be
+     * returned if no callback is specified
+     */
+    cmovz   %rbx, %rax
+    jz  7f
+    /*
+     * Align stack per x86_64 ABI. The original %rsp is saved in %rbx to be
+     * restored after *callback returns.
+     */
+    mov %rsp, %rbx
+    and $-0x10, %rsp
+    /* Clear RFLAGS.DF per x86_64 ABI */
+    cld
+    /* Parameters for *callback */
+    push    %rbx
+    push    0x10(%rbp)
+    /* Call *%rax via retpoline */
+    call    40f
+    /*
+     * Restore %rsp to its original value left off by the enclave from last
+     * exit
+     */
+    mov %rbx, %rsp
+    /*
+     * Positive return value from *callback will be interpreted as an ENCLU
+     * leaf, while a non-positive value will be interpreted as the return
+     * value to be passed back to the caller.
+     */
+    jmp 1b
+40: /* retpoline */
+    call    42f
+41: pause
+    lfence
+    jmp 41b
+42: mov %rax, (%rsp)
+    ret
+
+5:  /* Exception path */
+    mov $-EFAULT, %ebx
+    stc
+    jmp 3b
+
+6:  /* Unsupported ENCLU leaf */
+    cmp $0, %eax
+    jle 7f
+    mov $-EINVAL, %eax
+
+7:  /* Epilog */
+    leave
+    .cfi_def_cfa        %rsp, 8
+    ret
+    .cfi_endproc
+
+_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
 
 ENDPROC(__vdso_sgx_enter_enclave)
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 9ed690a38c70..50d2b5143e5e 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -24,7 +24,7 @@
 
 /**
  * struct sgx_enclave_create - parameter structure for the
- *                             %SGX_IOC_ENCLAVE_CREATE ioctl
+ *			       %SGX_IOC_ENCLAVE_CREATE ioctl
  * @src:	address for the SECS page data
  */
 struct sgx_enclave_create  {
@@ -33,7 +33,7 @@ struct sgx_enclave_create  {
 
 /**
  * struct sgx_enclave_add_page - parameter structure for the
- *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
+ *				 %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
  * @addr:	address within the ELRANGE
  * @src:	address for the page data
  * @secinfo:	address for the SECINFO data
@@ -49,7 +49,7 @@ struct sgx_enclave_add_page {
 
 /**
  * struct sgx_enclave_init - parameter structure for the
- *                           %SGX_IOC_ENCLAVE_INIT ioctl
+ *			     %SGX_IOC_ENCLAVE_INIT ioctl
  * @sigstruct:	address for the SIGSTRUCT data
  */
 struct sgx_enclave_init {
@@ -66,16 +66,16 @@ struct sgx_enclave_set_attribute {
 };
 
 /**
- * struct sgx_enclave_exception - structure to report exceptions encountered in
- *				  __vdso_sgx_enter_enclave()
+ * struct sgx_enclave_exinfo - structure to report exceptions encountered in
+ *			       __vdso_sgx_enter_enclave()
  *
- * @leaf:	ENCLU leaf from \%eax at time of exception
+ * @leaf:	ENCLU leaf from \%eax at time of exception/exit
  * @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 {
+struct sgx_enclave_exinfo {
 	__u32 leaf;
 	__u16 trapnr;
 	__u16 error_code;
-- 
2.17.1


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

* [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API
  2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
                         ` (3 preceding siblings ...)
  2019-07-13  6:51       ` [RFC PATCH v4 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-07-13  6:51       ` Cedric Xing
  2019-07-13 15:21         ` Jarkko Sakkinen
  4 siblings, 1 reply; 318+ messages in thread
From: Cedric Xing @ 2019-07-13  6:51 UTC (permalink / raw)
  To: linux-kernel, linux-sgx, jarkko.sakkinen
  Cc: cedric.xing, akpm, dave.hansen, sean.j.christopherson,
	serge.ayoun, shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

This patch augments SGX selftest with two new tests.

The first test exercises the newly added callback interface, by marking the
whole enclave range as PROT_READ, then calling mprotect() upon #PFs to add
necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.
This test also serves as an example to demonstrate the callback interface.

The second test single-steps through __vdso_sgx_enter_enclave() to make sure
the call stack can be unwound at every instruction within that vDSO API. Its
purpose is to validate the hand-crafted CFI directives in the assembly.

Besides the new tests, this patch also fixes minor problems in the Makefile,
such as:
  * appended "--build-id=none" to ld command line to suppress the
    ".note.gnu.build-id section discarded" linker warning.
  * removed "--remove-section=.got.plt" from objcopy command line as that
    section would never exist in statically linked (enclave) images.

Signed-off-by: Cedric Xing <cedric.xing@intel.com>
---
 tools/testing/selftests/x86/sgx/Makefile   |   6 +-
 tools/testing/selftests/x86/sgx/main.c     | 344 ++++++++++++++++++---
 tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
 3 files changed, 343 insertions(+), 47 deletions(-)

diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
index 3af15d7c8644..31f937e220c4 100644
--- a/tools/testing/selftests/x86/sgx/Makefile
+++ b/tools/testing/selftests/x86/sgx/Makefile
@@ -14,16 +14,16 @@ TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
 all_64: $(TEST_CUSTOM_PROGS)
 
 $(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
-	$(CC) $(HOST_CFLAGS) -o $@ $^
+	$(CC) $(HOST_CFLAGS) -o $@ $^ -lunwind -ldl -Wl,--defsym,__image_base=0 -pie
 
 $(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
 	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
 
 $(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
-	objcopy --remove-section=.got.plt -O binary $< $@
+	objcopy -O binary $< $@
 
 $(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
-	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
+	$(CC) $(ENCL_CFLAGS) -T $^ -o $@ -Wl,--build-id=none
 
 $(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
 	$^ $@
diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
index e2265f841fb0..e47d6c32623f 100644
--- a/tools/testing/selftests/x86/sgx/main.c
+++ b/tools/testing/selftests/x86/sgx/main.c
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
 // Copyright(c) 2016-18 Intel Corporation.
 
+#define _GNU_SOURCE
 #include <elf.h>
 #include <fcntl.h>
 #include <stdbool.h>
@@ -9,16 +10,31 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <errno.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/stat.h>
-#include <sys/time.h>
+#include <sys/auxv.h>
+#include <signal.h>
+#include <sys/ucontext.h>
+
+#define UNW_LOCAL_ONLY
+#include <libunwind.h>
+
 #include "encl_piggy.h"
 #include "defines.h"
 #include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
 #include "../../../../../arch/x86/include/uapi/asm/sgx.h"
 
-static const uint64_t MAGIC = 0x1122334455667788ULL;
+#define _Q(x)	__Q(x)
+#define __Q(x)	#x
+#define ERRLN	"Line " _Q(__LINE__)
+
+#define X86_EFLAGS_TF	(1ul << 8)
+
+extern char __image_base[];
+size_t eenter;
+static size_t vdso_base;
 
 struct vdso_symtab {
 	Elf64_Sym *elf_symtab;
@@ -26,20 +42,11 @@ struct vdso_symtab {
 	Elf64_Word *elf_hashtab;
 };
 
-static void *vdso_get_base_addr(char *envp[])
+static void vdso_init(void)
 {
-	Elf64_auxv_t *auxv;
-	int i;
-
-	for (i = 0; envp[i]; i++);
-	auxv = (Elf64_auxv_t *)&envp[i + 1];
-
-	for (i = 0; auxv[i].a_type != AT_NULL; i++) {
-		if (auxv[i].a_type == AT_SYSINFO_EHDR)
-			return (void *)auxv[i].a_un.a_val;
-	}
-
-	return NULL;
+	vdso_base = getauxval(AT_SYSINFO_EHDR);
+	if (!vdso_base)
+		exit(1);
 }
 
 static Elf64_Dyn *vdso_get_dyntab(void *addr)
@@ -66,8 +73,9 @@ static void *vdso_get_dyn(void *addr, Elf64_Dyn *dyntab, Elf64_Sxword tag)
 	return NULL;
 }
 
-static bool vdso_get_symtab(void *addr, struct vdso_symtab *symtab)
+static bool vdso_get_symtab(struct vdso_symtab *symtab)
 {
+	void *addr = (void *)vdso_base;
 	Elf64_Dyn *dyntab = vdso_get_dyntab(addr);
 
 	symtab->elf_symtab = vdso_get_dyn(addr, dyntab, DT_SYMTAB);
@@ -138,7 +146,7 @@ static bool encl_create(int dev_fd, unsigned long bin_size,
 	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
 		    MAP_SHARED, dev_fd, 0);
 	if (base == MAP_FAILED) {
-		perror("mmap");
+		perror(ERRLN);
 		return false;
 	}
 
@@ -224,35 +232,292 @@ static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
 	return false;
 }
 
-void sgx_call(void *rdi, void *rsi, void *tcs,
-	      struct sgx_enclave_exception *exception,
-	      void *eenter);
+int sgx_call(void *rdi, void *rsi, long rdx, void *rcx, void *r8, void *r9,
+	     void *tcs, struct sgx_enclave_exinfo *ei, void *cb);
+
+static void show_enclave_exinfo(const struct sgx_enclave_exinfo *exinfop,
+				const char *header)
+{
+	static const char * const enclu_leaves[] = {
+		"EREPORT",
+		"EGETKEY",
+		"EENTER",
+		"ERESUME",
+		"EEXIT"
+	};
+	static const char * const exception_names[] = {
+		"#DE",
+		"#DB",
+		"NMI",
+		"#BP",
+		"#OF",
+		"#BR",
+		"#UD",
+		"#NM",
+		"#DF",
+		"CSO",
+		"#TS",
+		"#NP",
+		"#SS",
+		"#GP",
+		"#PF",
+		"Unknown",
+		"#MF",
+		"#AC",
+		"#MC",
+		"#XM",
+		"#VE",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown",
+		"Unknown"
+	};
+
+	printf("%s: leaf:%s(%d)", header,
+		enclu_leaves[exinfop->leaf], exinfop->leaf);
+	if (exinfop->leaf != 4)
+		printf(" trap:%s(%d) ec:%d addr:0x%llx\n",
+			exception_names[exinfop->trapnr], exinfop->trapnr,
+			exinfop->error_code, exinfop->address);
+	else
+		printf("\n");
+}
+
+static const uint64_t MAGIC = 0x1122334455667788ULL;
+
+/*
+ * test1() tests vDSO API (i.e. __vdso_sgx_enter_enclave) without supplying a
+ * callback function.  It loads a very simple enclave that copies a 64-bit
+ * value from source buffer to the destination. Then it invokes the enclave
+ * twice. At the first time it provides all valid inputs and verifies the
+ * output buffer contains the same value as the source buffer. At the second
+ * time, it provides NULL as the TCS address to exercise the exception flow.
+ */
+static void test1(struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[1] Entering the enclave without callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, NULL);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Null TCS\n Expect: #PF at EENTER\n");
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 NULL, &exinfo, NULL);
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 2 /*EENTER*/ || exinfo.trapnr != 14 /*#PF*/)
+		exit(1);
+}
+
+static int test2_callback(long rdi, long rsi, long rdx,
+			  struct sgx_enclave_exinfo *ei, long r8, long r9,
+			  void *tcs, long ursp)
+{
+	show_enclave_exinfo(ei, "  callback");
+
+	switch (ei->leaf) {
+	case 4:
+		return 0;
+	case 3:
+	case 2:
+		switch (ei->trapnr) {
+		case 1:	/*#DB*/
+			break;
+		case 14:/*#PF*/
+			if ((ei->error_code & 1) == 0) {
+				fprintf(stderr, ERRLN
+					": Unexpected #PF error code\n");
+				exit(1);
+			}
+			if (mprotect((void *)(ei->address & -0x1000), 0x1000,
+				     ((ei->error_code & 2) ? PROT_WRITE : 0) |
+				     ((ei->error_code & 0x10) ? PROT_EXEC : 0) |
+				     PROT_READ)) {
+				perror(ERRLN);
+				exit(1);
+			}
+			break;
+		default:
+			fprintf(stderr, ERRLN ": Unexpected exception\n");
+			exit(1);
+		}
+		return ei->leaf == 2 ? -EAGAIN : ei->leaf;
+	}
+	return -EINVAL;
+}
+
+/*
+ * test2() tests the exception/callback mechanism of the vDSO API with a
+ * callback function. Firstly, it supplies all valid inputs along with a
+ * callback function, and verifies that exinfo contains the expected values.
+ * Secondly, it marks the whole enclave virtual range as read-only, and let the
+ * callback fixes the PTE permissions by calling mprotect() along the way. The
+ * callback in this test also serves an example to show how to use the callback
+ * interface.
+ */
+static void test2(struct sgx_secs *secs)
+{
+	uint64_t result = 0;
+	struct sgx_enclave_exinfo exinfo;
+
+	printf("[2] Entering the enclave with callback.\n");
+
+	printf("Input: 0x%lx\n Expect: Same as input\n", MAGIC);
+	sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+		 (void *)secs->base, &exinfo, test2_callback);
+	if (result != MAGIC) {
+		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
+		exit(1);
+	}
+	printf(" Output: 0x%lx\n", result);
+
+	printf("Input: Read-only enclave (0x%lx-0x%lx)\n"
+	       " Expect: #PFs to be fixed by callback\n",
+	       secs->base, secs->base + (encl_bin_end - encl_bin) - 1);
+	if (mprotect((void *)secs->base, encl_bin_end - encl_bin, PROT_READ)) {
+		perror(ERRLN);
+		exit(1);
+	}
+	while (sgx_call((void *)&MAGIC, &result, 0, NULL, NULL, NULL,
+			(void *)secs->base, &exinfo, test2_callback) == -EAGAIN)
+		;
+	show_enclave_exinfo(&exinfo, " Exit");
+	if (exinfo.leaf != 4 /*EEXIT*/)
+		exit(1);
+}
+
+static void *test3_caller;
+static struct test3_proc_context {
+	unw_word_t	ip, bx, sp, bp, r12, r13, r14, r15;
+} test3_ctx;
 
-int main(int argc, char *argv[], char *envp[])
+static unw_word_t test3_getcontext(unw_cursor_t *cursor,
+				   struct test3_proc_context *ctxp)
+{
+	unw_get_reg(cursor, UNW_REG_IP, &ctxp->ip);
+	unw_get_reg(cursor, UNW_REG_SP, &ctxp->sp);
+	unw_get_reg(cursor, UNW_X86_64_RBX, &ctxp->bx);
+	unw_get_reg(cursor, UNW_X86_64_RBP, &ctxp->bp);
+	unw_get_reg(cursor, UNW_X86_64_R12, &ctxp->r12);
+	unw_get_reg(cursor, UNW_X86_64_R13, &ctxp->r13);
+	unw_get_reg(cursor, UNW_X86_64_R14, &ctxp->r14);
+	unw_get_reg(cursor, UNW_X86_64_R15, &ctxp->r15);
+	return ctxp->ip;
+}
+
+static void test3_sigtrap(int sig, siginfo_t *info, ucontext_t *ctxp)
+{
+	static int in_vdso_eenter;
+
+	unw_cursor_t cursor;
+	unw_context_t uc;
+	struct test3_proc_context pc;
+
+	if (ctxp->uc_mcontext.gregs[REG_RIP] == eenter) {
+		in_vdso_eenter = 1;
+		printf("  trace started at ip:%llx (vdso:0x%llx)\n",
+			ctxp->uc_mcontext.gregs[REG_RIP],
+			ctxp->uc_mcontext.gregs[REG_RIP] - vdso_base);
+	}
+
+	if (!in_vdso_eenter)
+		return;
+
+	if ((void *)ctxp->uc_mcontext.gregs[REG_RIP] == test3_caller) {
+		in_vdso_eenter = 0;
+		ctxp->uc_mcontext.gregs[REG_EFL] &= ~X86_EFLAGS_TF;
+		printf("  trace ended successfully at ip:%llx (executable:0x%llx)\n",
+			ctxp->uc_mcontext.gregs[REG_RIP],
+			ctxp->uc_mcontext.gregs[REG_RIP] -
+				(size_t)__image_base);
+		return;
+	}
+
+	unw_getcontext(&uc);
+	unw_init_local(&cursor, &uc);
+	while (unw_step(&cursor) > 0 &&
+	       test3_getcontext(&cursor, &pc) != test3_ctx.ip)
+		;
+
+	if (memcmp(&pc, &test3_ctx, sizeof(pc))) {
+		fprintf(stderr, ERRLN ": Error unwinding\n");
+		exit(1);
+	}
+}
+
+__attribute__((noinline))
+static void test3_test_unwind(void (*f)(struct sgx_secs *),
+			      struct sgx_secs *secs)
+{
+	test3_caller = __builtin_return_address(0);
+	__asm__ ("pushfq; orl %0, (%%rsp); popfq" : : "i"(X86_EFLAGS_TF));
+	f(secs);
+}
+
+/*
+ * test3() single-steps through the vDSO API to test out CFI directives inside
+ * the API.
+ */
+static void test3(struct sgx_secs *secs)
+{
+	unw_cursor_t cursor;
+	unw_context_t uc;
+	struct sigaction sa = {
+		.sa_sigaction = (void (*)(int, siginfo_t*, void*))test3_sigtrap,
+		.sa_flags = SA_SIGINFO,
+	};
+
+	unw_getcontext(&uc);
+	unw_init_local(&cursor, &uc);
+	if (unw_step(&cursor) > 0)
+		test3_getcontext(&cursor, &test3_ctx);
+	else {
+		fprintf(stderr, ERRLN ": error initializing unwind context\n");
+		exit(1);
+	}
+
+	if (sigaction(SIGTRAP, &sa, NULL) < 0) {
+		perror(ERRLN);
+		exit(1);
+	}
+
+	test3_test_unwind(test1, secs);
+	test3_test_unwind(test2, secs);
+}
+
+int main(void)
 {
 	unsigned long bin_size = encl_bin_end - encl_bin;
 	unsigned long ss_size = encl_ss_end - encl_ss;
-	struct sgx_enclave_exception exception;
 	Elf64_Sym *eenter_sym;
 	struct vdso_symtab symtab;
 	struct sgx_secs secs;
-	uint64_t result = 0;
-	void *eenter;
-	void *addr;
-
-	memset(&exception, 0, sizeof(exception));
 
-	addr = vdso_get_base_addr(envp);
-	if (!addr)
-		exit(1);
+	vdso_init();
 
-	if (!vdso_get_symtab(addr, &symtab))
+	if (!vdso_get_symtab(&symtab))
 		exit(1);
 
 	eenter_sym = vdso_symtab_get(&symtab, "__vdso_sgx_enter_enclave");
 	if (!eenter_sym)
 		exit(1);
-	eenter = addr + eenter_sym->st_value;
+	eenter = vdso_base + eenter_sym->st_value;
 
 	printf("Binary size %lu (0x%lx), SIGSTRUCT size %lu\n", bin_size,
 	       bin_size, ss_size);
@@ -266,14 +531,11 @@ int main(int argc, char *argv[], char *envp[])
 	if (!encl_load(&secs, bin_size))
 		exit(1);
 
-	printf("Input: 0x%lx\n", MAGIC);
-	sgx_call((void *)&MAGIC, &result, (void *)secs.base, &exception,
-		 eenter);
-	if (result != MAGIC) {
-		fprintf(stderr, "0x%lx != 0x%lx\n", result, MAGIC);
-		exit(1);
-	}
+	printf("--- Functional Tests ---\n");
+	test1(&secs);
+	test2(&secs);
 
-	printf("Output: 0x%lx\n", result);
-	exit(0);
+	printf("--- Unwind Tests ---\n");
+	test3(&secs);
+	return 0;
 }
diff --git a/tools/testing/selftests/x86/sgx/sgx_call.S b/tools/testing/selftests/x86/sgx/sgx_call.S
index 14bd0a044199..ca2c0c947758 100644
--- a/tools/testing/selftests/x86/sgx/sgx_call.S
+++ b/tools/testing/selftests/x86/sgx/sgx_call.S
@@ -7,9 +7,43 @@
 
 	.global sgx_call
 sgx_call:
+	.cfi_startproc
+	push	%r15
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r15, 0
+	push	%r14
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r14, 0
+	push	%r13
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r13, 0
+	push	%r12
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%r12, 0
 	push	%rbx
-	mov	$0x02, %rax
-	mov	%rdx, %rbx
-	call	*%r8
+	.cfi_adjust_cfa_offset	8
+	.cfi_rel_offset		%rbx, 0
+	push	$0
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	push	0x48(%rsp)
+	.cfi_adjust_cfa_offset	8
+	mov	$2, %eax
+	call	*eenter(%rip)
+	add	$0x20, %rsp
+	.cfi_adjust_cfa_offset	-0x20
 	pop	%rbx
+	.cfi_adjust_cfa_offset	-8
+	pop	%r12
+	.cfi_adjust_cfa_offset	-8
+	pop	%r13
+	.cfi_adjust_cfa_offset	-8
+	pop	%r14
+	.cfi_adjust_cfa_offset	-8
+	pop	%r15
+	.cfi_adjust_cfa_offset	-8
 	ret
+	.cfi_endproc
-- 
2.17.1


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

* Re: [RFC PATCH v2 1/3] selftests/x86: Fixed Makefile for SGX selftest
  2019-07-12  3:19     ` Jarkko Sakkinen
@ 2019-07-13  6:58       ` Xing, Cedric
  0 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-13  6:58 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/11/2019 8:19 PM, Jarkko Sakkinen wrote:
> On Tue, Apr 23, 2019 at 11:26:21PM -0700, Cedric Xing wrote:
>> The original x86/sgx/Makefile doesn't work when 'x86/sgx' is specified as the
>> test target. This patch fixes that problem, along with minor changes to the
>> dependencies between 'x86' and 'x86/sgx' in selftests/x86/Makefile.
>>
>> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
>> ---
>>   tools/testing/selftests/x86/Makefile     | 12 +++----
>>   tools/testing/selftests/x86/sgx/Makefile | 45 +++++++++---------------
>>   2 files changed, 22 insertions(+), 35 deletions(-)
>>
>> diff --git a/tools/testing/selftests/x86/Makefile b/tools/testing/selftests/x86/Makefile
>> index 4fc9a42f56ea..1294c5f5b6ca 100644
>> --- a/tools/testing/selftests/x86/Makefile
>> +++ b/tools/testing/selftests/x86/Makefile
>> @@ -70,11 +70,11 @@ 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 $@;	\
>> +all_64: | $(SUBDIRS_64)
>> +	@for DIR in $|; do					\
>> +		BUILD_TARGET=$(OUTPUT)/$$DIR;			\
>> +		mkdir $$BUILD_TARGET  -p;			\
>> +		$(MAKE) OUTPUT=$$BUILD_TARGET -C $$DIR $@;	\
> 
> This is not fix for anything. It is change in semantics. This diff
> should be isolated to its own commit as you are changing something
> outside of SGX scope.

I have removed all changes to x86/Makefile from v4.

The current x86/Makefile only builds but cannot run sgx selftest. I 
don't see it as an urgent issue though.

>>   	done
>>   
>>   EXTRA_CLEAN := $(BINARIES_32) $(BINARIES_64)
>> @@ -90,7 +90,7 @@ ifeq ($(CAN_BUILD_I386)$(CAN_BUILD_X86_64),01)
>>   all: warn_32bit_failure
>>   
>>   warn_32bit_failure:
>> -	@echo "Warning: you seem to have a broken 32-bit build" 2>&1; 	\
>> +	@echo "Warning: you seem to have a broken 32-bit build" 2>&1;	\
> 
> Please clean this up.
> 
>>   	echo "environment.  This will reduce test coverage of 64-bit" 2>&1; \
>>   	echo "kernels.  If you are using a Debian-like distribution," 2>&1; \
>>   	echo "try:"; 2>&1; \
>> diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
>> index 1fd6f2708e81..3af15d7c8644 100644
>> --- a/tools/testing/selftests/x86/sgx/Makefile
>> +++ b/tools/testing/selftests/x86/sgx/Makefile
>> @@ -2,47 +2,34 @@ top_srcdir = ../../../../..
>>   
>>   include ../../lib.mk
>>   
>> -HOST_CFLAGS := -Wall -Werror -g $(INCLUDES) -fPIC
>> -ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIC \
>> +ifeq ($(shell $(CC) -dumpmachine | cut --delimiter=- -f1),x86_64)
>> +all: all_64
>> +endif
>> +
>> +HOST_CFLAGS := -Wall -Werror -g $(INCLUDES)
>> +ENCL_CFLAGS := -Wall -Werror -static -nostdlib -nostartfiles -fPIE \
>>   	       -fno-stack-protector -mrdrnd $(INCLUDES)
>>   
>>   TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
>>   all_64: $(TEST_CUSTOM_PROGS)
>>   
>> -$(TEST_CUSTOM_PROGS): $(OUTPUT)/main.o $(OUTPUT)/sgx_call.o \
>> -		      $(OUTPUT)/encl_piggy.o
>> +$(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
>>   	$(CC) $(HOST_CFLAGS) -o $@ $^
>>   
>> -$(OUTPUT)/main.o: main.c
>> -	$(CC) $(HOST_CFLAGS) -c $< -o $@
>> -
>> -$(OUTPUT)/sgx_call.o: sgx_call.S
>> -	$(CC) $(HOST_CFLAGS) -c $< -o $@
>> -
>> -$(OUTPUT)/encl_piggy.o: $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
>> -	$(CC) $(HOST_CFLAGS) -c encl_piggy.S -o $@
>> +$(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
>> +	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
>>   
>> -$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf $(OUTPUT)/sgxsign
>> +$(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
>>   	objcopy --remove-section=.got.plt -O binary $< $@
>>   
>> -$(OUTPUT)/encl.elf: $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o
>> -	$(CC) $(ENCL_CFLAGS) -T encl.lds -o $@ $^
>> +$(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
>> +	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
>>   
>> -$(OUTPUT)/encl.o: encl.c
>> -	$(CC) $(ENCL_CFLAGS) -c $< -o $@
>> -
>> -$(OUTPUT)/encl_bootstrap.o: encl_bootstrap.S
>> -	$(CC) $(ENCL_CFLAGS) -c $< -o $@
>> -
>> -$(OUTPUT)/encl.ss: $(OUTPUT)/encl.bin  $(OUTPUT)/sgxsign
>> -	$(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
>> +$(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
>> +	$^ $@
>>   
>>   $(OUTPUT)/sgxsign: sgxsign.c
>>   	$(CC) -o $@ $< -lcrypto
>>   
>> -EXTRA_CLEAN := $(OUTPUT)/sgx-selftest $(OUTPUT)/sgx-selftest.o \
>> -	       $(OUTPUT)/sgx_call.o $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss \
>> -	       $(OUTPUT)/encl.elf $(OUTPUT)/encl.o $(OUTPUT)/encl_bootstrap.o \
>> -	       $(OUTPUT)/sgxsign
>> -
>> -.PHONY: clean
>> +EXTRA_CLEAN := $(TEST_CUSTOM_PROGS) $(addprefix $(OUTPUT)/,	\
>> +		encl.elf encl.bin encl.ss encl_piggy.o sgxsign)
>> -- 
>> 2.17.1
>>
> 
> What are all these changes to the makefile? I don't see mention of them
> in the commit message.

Added description to the commit message in v4.

> /Jarkko
> 

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

* Re: [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-12  3:16               ` Jarkko Sakkinen
@ 2019-07-13  7:00                 ` Xing, Cedric
  0 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-13  7:00 UTC (permalink / raw)
  To: Jarkko Sakkinen, Sean Christopherson; +Cc: linux-sgx, luto, jethro, greg

On 7/11/2019 8:16 PM, Jarkko Sakkinen wrote:
> On Thu, Jul 11, 2019 at 10:58:13AM -0700, Sean Christopherson wrote:
>>> The way to do this right would be to write a documentation block before
>>> kdoc's for the functions. It is described in the last section of
>>>
>>> https://www.kernel.org/doc/Documentation/kernel-doc-nano-HOWTO.txt0
>>>
>>> I.e. organize the file as
>>>
>>> 1. Documentation block describing the theory of operation.
>>> 2. Functions and their associated documentations.
>>
>> The kernel doc parser straight up doesn't work on asm functions, hence the
>> shenanigans to coerce it into thinking it's parsing a normal C function.
> 
> Aah. I think I was too hazy with my comment. Looked it from patchwork and
> the documentation is mostly just fine.
> 
> For this patch this cruft nees to be removed:
> 
> - *                           %SGX_IOC_ENCLAVE_INIT ioctl
> + *			     %SGX_IOC_ENCLAVE_INIT ioctl
> 
> These make squashing the patch properly nasty.
> 
> Also there is one unwanted rename. Did not find anything else obviously
> wrong.

Reformatted the comments. Tested with kernel-doc. Now v4 could be 
converted and displayed nicely as man pages.

> /Jarkko
> 

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

* Re: [RFC PATCH v2 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface
  2019-07-12  3:25     ` Jarkko Sakkinen
@ 2019-07-13  7:03       ` Xing, Cedric
  0 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-13  7:03 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/11/2019 8:25 PM, Jarkko Sakkinen wrote:
> On Tue, Apr 23, 2019 at 11:26:23PM -0700, Cedric Xing wrote:
>> This patch augments SGX selftest with two new tests.
>>
>> The first test exercises the newly added callback interface, by marking the
>> whole enclave range as PROT_READ, then calling mprotect() upon #PFs to add
>> necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.
>> This test also serves as an example to demonstrate the callback interface.
>>
>> The second test single-steps through __vdso_sgx_enter_enclave() to make sure
>> the call stack can be unwound at every instruction within that vDSO API. Its
>> purpose is to validate the hand-crafted CFI directives in the assembly.
>>
>> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
>> ---
>>   tools/testing/selftests/x86/sgx/Makefile   |   6 +-
>>   tools/testing/selftests/x86/sgx/main.c     | 323 ++++++++++++++++++---
>>   tools/testing/selftests/x86/sgx/sgx_call.S |  40 ++-
>>   3 files changed, 322 insertions(+), 47 deletions(-)
>>
>> diff --git a/tools/testing/selftests/x86/sgx/Makefile b/tools/testing/selftests/x86/sgx/Makefile
>> index 3af15d7c8644..31f937e220c4 100644
>> --- a/tools/testing/selftests/x86/sgx/Makefile
>> +++ b/tools/testing/selftests/x86/sgx/Makefile
>> @@ -14,16 +14,16 @@ TEST_CUSTOM_PROGS := $(OUTPUT)/test_sgx
>>   all_64: $(TEST_CUSTOM_PROGS)
>>   
>>   $(TEST_CUSTOM_PROGS): main.c sgx_call.S $(OUTPUT)/encl_piggy.o
>> -	$(CC) $(HOST_CFLAGS) -o $@ $^
>> +	$(CC) $(HOST_CFLAGS) -o $@ $^ -lunwind -ldl -Wl,--defsym,__image_base=0 -pie
>>   
>>   $(OUTPUT)/encl_piggy.o: encl_piggy.S $(OUTPUT)/encl.bin $(OUTPUT)/encl.ss
>>   	$(CC) $(HOST_CFLAGS) -I$(OUTPUT) -c $< -o $@
>>   
>>   $(OUTPUT)/encl.bin: $(OUTPUT)/encl.elf
>> -	objcopy --remove-section=.got.plt -O binary $< $@
>> +	objcopy -O binary $< $@
>>   
>>   $(OUTPUT)/encl.elf: encl.lds encl.c encl_bootstrap.S
>> -	$(CC) $(ENCL_CFLAGS) -T $^ -o $@
>> +	$(CC) $(ENCL_CFLAGS) -T $^ -o $@ -Wl,--build-id=none
>>   
>>   $(OUTPUT)/encl.ss: $(OUTPUT)/sgxsign signing_key.pem $(OUTPUT)/encl.bin
>>   	$^ $@
>> diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c
>> index e2265f841fb0..d3e53c71306d 100644
>> --- a/tools/testing/selftests/x86/sgx/main.c
>> +++ b/tools/testing/selftests/x86/sgx/main.c
>> @@ -1,6 +1,7 @@
>>   // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
>>   // Copyright(c) 2016-18 Intel Corporation.
>>   
>> +#define _GNU_SOURCE
>>   #include <elf.h>
>>   #include <fcntl.h>
>>   #include <stdbool.h>
>> @@ -9,16 +10,31 @@
>>   #include <stdlib.h>
>>   #include <string.h>
>>   #include <unistd.h>
>> +#include <errno.h>
>>   #include <sys/ioctl.h>
>>   #include <sys/mman.h>
>>   #include <sys/stat.h>
>> -#include <sys/time.h>
>> +#include <sys/auxv.h>
>> +#include <signal.h>
>> +#include <sys/ucontext.h>
>> +
>> +#define UNW_LOCAL_ONLY
>> +#include <libunwind.h>
>> +
>>   #include "encl_piggy.h"
>>   #include "defines.h"
>>   #include "../../../../../arch/x86/kernel/cpu/sgx/arch.h"
>>   #include "../../../../../arch/x86/include/uapi/asm/sgx.h"
>>   
>> -static const uint64_t MAGIC = 0x1122334455667788ULL;
>> +#define _Q(x)	__Q(x)
>> +#define __Q(x)	#x
>> +#define ERRLN	"Line " _Q(__LINE__)
>> +
>> +#define X86_EFLAGS_TF	(1ul << 8)
>> +
>> +extern char __image_base[];
>> +size_t eenter;
>> +static size_t vdso_base;
>>   
>>   struct vdso_symtab {
>>   	Elf64_Sym *elf_symtab;
>> @@ -26,20 +42,11 @@ struct vdso_symtab {
>>   	Elf64_Word *elf_hashtab;
>>   };
>>   
>> -static void *vdso_get_base_addr(char *envp[])
>> +static void vdso_init(void)
>>   {
>> -	Elf64_auxv_t *auxv;
>> -	int i;
>> -
>> -	for (i = 0; envp[i]; i++);
>> -	auxv = (Elf64_auxv_t *)&envp[i + 1];
>> -
>> -	for (i = 0; auxv[i].a_type != AT_NULL; i++) {
>> -		if (auxv[i].a_type == AT_SYSINFO_EHDR)
>> -			return (void *)auxv[i].a_un.a_val;
>> -	}
>> -
>> -	return NULL;
>> +	vdso_base = getauxval(AT_SYSINFO_EHDR);
>> +	if (!vdso_base)
>> +		exit(1);
>>   }
> 
> The clean up makes sense but should be a separate patch i.e. one
> logical change per patch. Right now the patch does other mods
> than the ones explcitly stated in the commit message.
> 
> I'd suggest open coding vdso_init() to the call site in that
> patch.
> 
> Please try to always minimize for diff's.
> 
>>   
>>   static Elf64_Dyn *vdso_get_dyntab(void *addr)
>> @@ -66,8 +73,9 @@ static void *vdso_get_dyn(void *addr, Elf64_Dyn *dyntab, Elf64_Sxword tag)
>>   	return NULL;
>>   }
>>   
>> -static bool vdso_get_symtab(void *addr, struct vdso_symtab *symtab)
>> +static bool vdso_get_symtab(struct vdso_symtab *symtab)
>>   {
>> +	void *addr = (void *)vdso_base;
>>   	Elf64_Dyn *dyntab = vdso_get_dyntab(addr);
>>   
>>   	symtab->elf_symtab = vdso_get_dyn(addr, dyntab, DT_SYMTAB);
>> @@ -138,7 +146,7 @@ static bool encl_create(int dev_fd, unsigned long bin_size,
>>   	base = mmap(NULL, secs->size, PROT_READ | PROT_WRITE | PROT_EXEC,
>>   		    MAP_SHARED, dev_fd, 0);
>>   	if (base == MAP_FAILED) {
>> -		perror("mmap");
>> +		perror(ERRLN);
>>   		return false;
>>   	}
>>   
>> @@ -224,35 +232,271 @@ static bool encl_load(struct sgx_secs *secs, unsigned long bin_size)
>>   	return false;
>>   }
>>   
>> -void sgx_call(void *rdi, void *rsi, void *tcs,
>> -	      struct sgx_enclave_exception *exception,
>> -	      void *eenter);
>> +int sgx_call(void *rdi, void *rsi, long rdx, void *rcx, void *r8, void *r9,
>> +	     void *tcs, struct sgx_enclave_exinfo *ei, void *cb);
>> +
>> +static void show_enclave_exinfo(const struct sgx_enclave_exinfo *exinfop,
>> +				const char *header)
>> +{
>> +	static const char * const enclu_leaves[] = {
>> +		"EREPORT",
>> +		"EGETKEY",
>> +		"EENTER",
>> +		"ERESUME",
>> +		"EEXIT"
>> +	};
>> +	static const char * const exception_names[] = {
>> +		"#DE",
>> +		"#DB",
>> +		"NMI",
>> +		"#BP",
>> +		"#OF",
>> +		"#BR",
>> +		"#UD",
>> +		"#NM",
>> +		"#DF",
>> +		"CSO",
>> +		"#TS",
>> +		"#NP",
>> +		"#SS",
>> +		"#GP",
>> +		"#PF",
>> +		"Unknown",
>> +		"#MF",
>> +		"#AC",
>> +		"#MC",
>> +		"#XM",
>> +		"#VE",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown",
>> +		"Unknown"
>> +	};
>> +
>> +	printf("%s: leaf:%s(%d)", header,
>> +		enclu_leaves[exinfop->leaf], exinfop->leaf);
>> +	if (exinfop->leaf != 4)
>> +		printf(" trap:%s(%d) ec:%d addr:0x%llx\n",
>> +			exception_names[exinfop->trapnr], exinfop->trapnr,
>> +			exinfop->error_code, exinfop->address);
>> +	else
>> +		printf("\n");
>> +}
>> +
>> +static const uint64_t MAGIC = 0x1122334455667788ULL;
>>   
>> -int main(int argc, char *argv[], char *envp[])
>> +static void test1(struct sgx_secs *secs)
> 
> test1, test2 and test3 are not too descriptive names. Every patch should
> make the code base cleaner, not messier.

I don't think it that important, as there are many test## occurrences in 
existing selftests. Anyway, I've added comments to those test functions 
to brief what is done. Hope you'll find them helpful.

> /Jarkko
> 

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

* Re: [RFC PATCH v4 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-13  6:51       ` [RFC PATCH v4 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
@ 2019-07-13 15:04         ` Jarkko Sakkinen
  2019-07-13 15:06           ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-13 15:04 UTC (permalink / raw)
  To: Cedric Xing, linux-kernel, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Fri, 2019-07-12 at 23:51 -0700, Cedric Xing wrote:
> The previous __vdso_sgx_enter_enclave() requires enclaves to preserve %rsp,
> which prohibits enclaves from allocating and passing parameters for
> untrusted function calls (aka. o-calls) on the untrusted stack.
> 
> This patch addresses the problem above by introducing a new ABI that preserves
> %rbp instead of %rsp. Then __vdso_sgx_enter_enclave() can anchor its frame
> using %rbp so that enclaves are allowed to allocate space on the untrusted
> stack by decrementing %rsp. Please note that the stack space allocated in such
> way will be part of __vdso_sgx_enter_enclave()'s frame so will be freed after
> __vdso_sgx_enter_enclave() returns. Therefore, __vdso_sgx_enter_enclave() has
> been revised to take a callback function as an optional parameter, which if
> supplied, will be invoked upon enclave exits (both AEX (Asynchronous Enclave
> eXit) and normal exits), with the value of %rsp left off by the enclave as a
> parameter to the callback.
> 
> Here's the summary of API/ABI changes in this patch. More details could be
> found in arch/x86/entry/vdso/vsgx_enter_enclave.S.
>   * 'struct sgx_enclave_exception' is renamed to 'struct sgx_enclave_exinfo'
>     because it is filled upon both AEX (i.e. exceptions) and normal enclave
>     exits.
>   * __vdso_sgx_enter_enclave() anchors its frame using %rbp (instead of %rsp in
>     the previous implementation).
>   * __vdso_sgx_enter_enclave() takes one more parameter - a callback function
>     to be invoked upon enclave exits. This callback is optional, and if not
>     supplied, will cause __vdso_sgx_enter_enclave() to return upon enclave
>     exits (same behavior as previous implementation).
>   * The callback function is given as a parameter the value of %rsp at enclave
>     exit to address data "pushed" by the enclave. A positive value returned by
>     the callback will be treated as an ENCLU leaf for re-entering the enclave,
>     while a zero or negative value will be passed through as the return
>     value of __vdso_sgx_enter_enclave() to its caller. It's also safe to
>     leave callback by longjmp() or by throwing a C++ exception.
> 
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> ---
>  arch/x86/entry/vdso/vsgx_enter_enclave.S | 310 +++++++++++++++++------
>  arch/x86/include/uapi/asm/sgx.h          |  14 +-
>  2 files changed, 242 insertions(+), 82 deletions(-)
> 
> diff --git a/arch/x86/entry/vdso/vsgx_enter_enclave.S b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> index fe0bf6671d6d..a96542ba6945 100644
> --- a/arch/x86/entry/vdso/vsgx_enter_enclave.S
> +++ b/arch/x86/entry/vdso/vsgx_enter_enclave.S
> @@ -6,96 +6,256 @@
>  
>  #include "extable.h"
>  
> -#define EX_LEAF		0*8
> -#define EX_TRAPNR	0*8+4
> -#define EX_ERROR_CODE	0*8+6
> -#define EX_ADDRESS	1*8
> +#define EX_LEAF     0*8
> +#define EX_TRAPNR   0*8+4
> +#define EX_ERROR_CODE   0*8+6
> +#define EX_ADDRESS  1*8

A completely new diff that should not exist in this version.

>  
>  .code64
>  .section .text, "ax"
>  
>  #ifdef SGX_KERNEL_DOC
>  /**
> - * __vdso_sgx_enter_enclave() - Enter an SGX enclave
> + * typedef sgx_ex_callback - Callback function for __vdso_sgx_enter_enclave()
>   *
> - * @leaf:	**IN \%eax** - ENCLU leaf, must be EENTER or ERESUME
> - * @tcs:	**IN \%rbx** - TCS, must be non-NULL
> - * @ex_info:	**IN \%rcx** - Optional 'struct sgx_enclave_exception' pointer
> + * @rdi:    value of %%rdi register at enclave exit
> + * @rsi:    value of %%rsi register at enclave exit
> + * @rdx:    value of %%rdx register at enclave exit
> + * @exinfo: pointer to a sgx_enclave_exinfo structure, which was passed to
> + *      __vdso_sgx_enter_enclave() as input
> + * @r8:     value of %%r8 register at enclave exit
> + * @r9:     value of %%r9 register at enclave exit
> + * @tcs:    TCS used by __vdso_sgx_enter_enclave() to enter the enclave,
> + *      could be used to re-enter the
> + *      enclave
> + * @ursp:   value of %%rsp register at enclave exit
> + *
> + * This is the callback function to be invoked upon enclave exits, including
> + * normal exits (as result of EEXIT), and asynchronous exits (AEX) due to
> + * exceptions occurred at EENTER or within the enclave.
> + *
> + * This callback is expected to follow x86_64 ABI.
>   *
>   * Return:
> - *  **OUT \%eax** -
> - *  %0 on a clean entry/exit to/from the enclave, %-EINVAL if ENCLU leaf is
> - *  not allowed or if TCS is NULL, %-EFAULT if ENCLU or the enclave faults
> - *
> - * **Important!**  __vdso_sgx_enter_enclave() is **NOT** compliant with the
> - * x86-64 ABI, i.e. cannot be called from standard C code.   As noted above,
> - * input parameters must be passed via ``%eax``, ``%rbx`` and ``%rcx``, with
> - * the return value passed via ``%eax``.  All registers except ``%rsp`` must
> - * be treated as volatile from the caller's perspective, including but not
> - * limited to GPRs, EFLAGS.DF, MXCSR, FCW, etc...  Conversely, the enclave
> - * being run **must** preserve the untrusted ``%rsp`` and stack.
> + *
> + * EENTER(2) - causes __vdso_sgx_enter_enclave() to issue ENCLU[EENTER] on the
> + * same TCS. All GPRs left off by this callback function will be passed through
> + * back to the enclave, except %%rax, %%rbx and %%rcx, which are clobbered by
> + * ENCLU[EENTER] instruction.
> + *
> + * ERESUME(3) - causes __vdso_sgx_enter_enclave() to issue ENCLU[ERESUME] on
> + * the same TCS.
> + *
> + * 0 (zero) or negative returned values will be returned back to
> + * __vdso_sgx_enter_enclave()'s caller as is.
> + *
> + * All other values will cause -EINVAL to be returned to
> + * __vdso_sgx_enter_enclave()'s caller.
> + *
> + * Note: All general purpose registers (GPRs) left off by the enclave are
> + * passed through to this function, except %%rax, %%rbx and %%rcx, which are
> + * used internally by __vdso_sgx_enter_enclave(). Some of those registers are
> + * accessible as function parameters (i.e. @rdi, @rsi, @rdx, @r8, @r9 and
> + * @ursp), while others can be accessed only from assembly code.
>   */
> -__vdso_sgx_enter_enclave(u32 leaf, void *tcs,
> -			 struct sgx_enclave_exception *ex_info)
> -{
> -	if (leaf != SGX_EENTER && leaf != SGX_ERESUME)
> -		return -EINVAL;
> +typedef int sgx_ex_callback(long rdi, long rsi, long rdx,
> +                struct sgx_enclave_exinfo *exinfo,
> +                long r8, long r9, void *tcs, long ursp);
>  
> -	if (!tcs)
> -		return -EINVAL;
> +/**
> + * __vdso_sgx_enter_enclave() - Enter an SGX enclave and capture exceptions
> + *
> + * @leaf:
> + *  passed in %%eax, must be either EENTER(2) or ERESUME(3)
> + * @tcs:
> + *  passed on stack at 8(%%rsp), is the linear address of TCS
> + * @exinfo:
> + *  passed on stack at 0x10(%%rsp), optional, and if non-NULL, shall point
> + *  to an sgx_enclave_exinfo structure to receive information about the
> + *  enclave exit
> + * @callback:
> + *  passed on stack at 0x18(%%rsp), optional, and if non-NULL, points to a
> + *  callback function to be invoked at enclave exits
> + *
> + * __vdso_sgx_enter_enclave() issues either ENCLU[EENTER] or ENCLU[ERESUME] on
> + * @tcs depending on @leaf.
> + *
> + * IMPORTANT! This API is not compliant with x86-64 ABI but adopts a
> + * proprietary calling convention. Please see NOTES section below for details.
> + *
> + * On an enclave exit, @exinfo->leaf will be set to the ENCLU leaf at exit, if
> + * @exinfo is not NULL. That is, @exinfo->leaf may be one of the following:
> + *
> + *   * EEXIT:   Normal exit due to ENCLU[EEXIT] within the enclave. All other
> + *      members will remain intact.
> + *
> + *   * ERESUME: Asynchronous exit due to exceptions within the enclave.
> + *      @exinfo->trapnr, @exinfo->error_code and @exinfo->address are
> + *      set to the trap number, error code and fault address,
> + *      respectively.
> + *
> + *   * EENTER:  Exception occurred when trying to enter the enclave.
> + *      @exinfo->trapnr, @exinfo->error_code and @exinfo->address are
> + *      set to the trap number, error code and fault address,
> + *      accordingly.
> + *
> + * If @callback is NULL, 0 (zero) is returned if the enclave has been entered
> + * and exited normally, or -EFAULT if any exception has occurred, or -EINVAL if
> + * @leaf on input is neither EENTER or ERESUME.
> + *
> + * If @callback is not NULL, it is invoked at enclave exit, and then actions
> + * will be taken depending on its return value - i.e. positive value will be
> + * treated as ENCLU leaf to re-enter the enclave, while 0 (zero) or negative
> + * values will be returned back to the caller as is. Unrecognized leaf values
> + * will cause -EINVAL to be returned.
> + *
> + * Return:
> + *
> + * 0 (zero) is returned on a successful entry and normal exit from the enclave.
> + *
> + * -EINVAL is returned if @leaf is neither EENTER nor ERESUME, or if @callback
> + * is not NULL and returns a positive value that is neither EENTER nor ERESUME
> + * after the enclave exits.
> + *
> + * -EFAULT is returned if an exception has occurred at EENTER or during
> + * execution of the enclave and @callback is NULL, or if @callback is not NULL
> + * and it returns -EFAULT after the enclave exits.
> + *
> + * Other values may be returned as the return value from @callback if it is not
> + * NULL.
> + *
> + * Note: __vdso_sgx_enter_enclave() adopts a proprietary calling convention,
> + * described below:
> + *
> + *    * As noted above, input parameters are passed via %%eax and the stack.
> + *
> + *    * %%rbx and %%rcx must be treated as volatile as they are modified as part
> + *  of enclaves transitions and are used as scratch regs.
> + *
> + *    * %%rdx, %%rdi, %%rsi and %%r8-%%r15 are passed as is and may be freely
> + *  modified by the enclave. Values left in those registers will not be
> + *  altered either, so will be visiable to the callback or the caller (if no
> + *  callback is specified).
> + *
> + *    * %%rsp could be decremented by the enclave to allocate temporary space on
> + *      the untrusted stack. Temporary space allocated this way is retained in
> + *      the context of @callback, and will be freed (i.e. %%rsp will be
> + *      restored) before __vdso_sgx_enter_enclave() returns.
> + */
> +int __vdso_sgx_enter_enclave(int leaf, void *tcs,
> +                 struct sgx_enclave_exinfo *exinfo,
> +                 sgx_ex_callback *callback);
> +{
> +     while (leaf == EENTER || leaf == ERESUME) {
> +    int rc;
> +    try {
> +        ENCLU[leaf];
> +        rc = 0;
> +        if (exinfo)
> +            exinfo->leaf = EEXIT;
> +    } catch (exception) {
> +        rc = -EFAULT;
> +        if (exinfo)
> +            *exinfo = exception;
> +    }
>  
> -	try {
> -		ENCLU[leaf];
> -	} catch (exception) {
> -		if (e)
> -			*e = exception;
> -		return -EFAULT;
> -	}
> +    leaf = !callback ? rc: (*callback)(rdi, rsi, rdx, exinfo,
> +                       r8, r9, tcs, ursp);
> +     }
>  
> -	return 0;
> +     return leaf > 0 ? -EINVAL : leaf;
>  }
>  #endif
> +
>  ENTRY(__vdso_sgx_enter_enclave)
> -	/* EENTER <= leaf <= ERESUME */
> -	cmp	$0x2, %eax
> -	jb	bad_input
> -
> -	cmp	$0x3, %eax
> -	ja	bad_input
> -
> -	/* TCS must be non-NULL */
> -	test	%rbx, %rbx
> -	je	bad_input
> -
> -	/* Save @exception_info */
> -	push	%rcx
> -
> -	/* Load AEP for ENCLU */
> -	lea	1f(%rip),  %rcx
> -1:	enclu
> -
> -	add	$0x8, %rsp
> -	xor	%eax, %eax
> -	ret
> -
> -bad_input:
> -	mov     $(-EINVAL), %rax
> -	ret
> -
> -.pushsection .fixup, "ax"
> -	/* Re-load @exception_info and fill it (if it's non-NULL) */
> -2:	pop	%rcx
> -	test    %rcx, %rcx
> -	je      3f
> -
> -	mov	%eax, EX_LEAF(%rcx)
> -	mov	%di,  EX_TRAPNR(%rcx)
> -	mov	%si,  EX_ERROR_CODE(%rcx)
> -	mov	%rdx, EX_ADDRESS(%rcx)
> -3:	mov	$(-EFAULT), %rax
> -	ret
> -.popsection
> -
> -_ASM_VDSO_EXTABLE_HANDLE(1b, 2b)
> +    /* Prolog */
> +    .cfi_startproc
> +    push    %rbp
> +    .cfi_adjust_cfa_offset  8
> +    .cfi_rel_offset     %rbp, 0
> +    mov %rsp, %rbp
> +    .cfi_def_cfa_register   %rbp
> +
> +1:  /* EENTER <= leaf <= ERESUME */
> +    cmp $0x2, %eax
> +    jb  6f
> +    cmp $0x3, %eax
> +    ja  6f
> +
> +    /* Load TCS and AEP */
> +    mov 0x10(%rbp), %rbx
> +    lea 2f(%rip), %rcx
> +
> +    /* Single ENCLU serving as both EENTER and AEP (ERESUME) */
> +2:  enclu
> +
> +    /* EEXIT path */
> +    xor %ebx, %ebx
> +3:  mov 0x18(%rbp), %rcx
> +    jrcxz   4f
> +    mov %eax, EX_LEAF(%rcx)
> +    jnc 4f
> +    mov %di, EX_TRAPNR(%rcx)
> +    mov %si, EX_ERROR_CODE(%rcx)
> +    mov %rdx, EX_ADDRESS(%rcx)
> +
> +4:  /* Call *callback if supplied */
> +    mov 0x20(%rbp), %rax
> +    test    %rax, %rax
> +    /*
> +     * At this point, %ebx holds the effective return value, which shall be
> +     * returned if no callback is specified
> +     */
> +    cmovz   %rbx, %rax
> +    jz  7f
> +    /*
> +     * Align stack per x86_64 ABI. The original %rsp is saved in %rbx to be
> +     * restored after *callback returns.
> +     */
> +    mov %rsp, %rbx
> +    and $-0x10, %rsp
> +    /* Clear RFLAGS.DF per x86_64 ABI */
> +    cld
> +    /* Parameters for *callback */
> +    push    %rbx
> +    push    0x10(%rbp)
> +    /* Call *%rax via retpoline */
> +    call    40f
> +    /*
> +     * Restore %rsp to its original value left off by the enclave from last
> +     * exit
> +     */
> +    mov %rbx, %rsp
> +    /*
> +     * Positive return value from *callback will be interpreted as an ENCLU
> +     * leaf, while a non-positive value will be interpreted as the return
> +     * value to be passed back to the caller.
> +     */
> +    jmp 1b
> +40: /* retpoline */
> +    call    42f
> +41: pause
> +    lfence
> +    jmp 41b
> +42: mov %rax, (%rsp)
> +    ret
> +
> +5:  /* Exception path */
> +    mov $-EFAULT, %ebx
> +    stc
> +    jmp 3b
> +
> +6:  /* Unsupported ENCLU leaf */
> +    cmp $0, %eax
> +    jle 7f
> +    mov $-EINVAL, %eax
> +
> +7:  /* Epilog */
> +    leave
> +    .cfi_def_cfa        %rsp, 8
> +    ret
> +    .cfi_endproc
> +
> +_ASM_VDSO_EXTABLE_HANDLE(2b, 5b)
>  
>  ENDPROC(__vdso_sgx_enter_enclave)
> diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
> index 9ed690a38c70..50d2b5143e5e 100644
> --- a/arch/x86/include/uapi/asm/sgx.h
> +++ b/arch/x86/include/uapi/asm/sgx.h
> @@ -24,7 +24,7 @@
>  
>  /**
>   * struct sgx_enclave_create - parameter structure for the
> - *                             %SGX_IOC_ENCLAVE_CREATE ioctl
> + *			       %SGX_IOC_ENCLAVE_CREATE ioctl

Cruft. Please do not change files if there is:

1. No reason to do it (holds for this).
2. No relation to the patch (also holds for this).

If only (2) holds, create a patch with its own commit message etc.

This is also explained in the kernel process guide. I earlier linked
that.

>   * @src:	address for the SECS page data
>   */
>  struct sgx_enclave_create  {
> @@ -33,7 +33,7 @@ struct sgx_enclave_create  {
>  
>  /**
>   * struct sgx_enclave_add_page - parameter structure for the
> - *                               %SGX_IOC_ENCLAVE_ADD_PAGE ioctl
> + *				 %SGX_IOC_ENCLAVE_ADD_PAGE ioctl

Ditto.

>   * @addr:	address within the ELRANGE
>   * @src:	address for the page data
>   * @secinfo:	address for the SECINFO data
> @@ -49,7 +49,7 @@ struct sgx_enclave_add_page {
>  
>  /**
>   * struct sgx_enclave_init - parameter structure for the
> - *                           %SGX_IOC_ENCLAVE_INIT ioctl
> + *			     %SGX_IOC_ENCLAVE_INIT ioctl

Ditto.

>   * @sigstruct:	address for the SIGSTRUCT data
>   */
>  struct sgx_enclave_init {
> @@ -66,16 +66,16 @@ struct sgx_enclave_set_attribute {
>  };
>  
>  /**
> - * struct sgx_enclave_exception - structure to report exceptions encountered in
> - *				  __vdso_sgx_enter_enclave()
> + * struct sgx_enclave_exinfo - structure to report exceptions encountered in
> + *			       __vdso_sgx_enter_enclave()
>   *
> - * @leaf:	ENCLU leaf from \%eax at time of exception
> + * @leaf:	ENCLU leaf from \%eax at time of exception/exit
>   * @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 {
> +struct sgx_enclave_exinfo {

Ditto.

>  	__u32 leaf;
>  	__u16 trapnr;
>  	__u16 error_code;

I already manually removed those changes already from previous version.

/Jarkko


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

* Re: [RFC PATCH v4 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack
  2019-07-13 15:04         ` Jarkko Sakkinen
@ 2019-07-13 15:06           ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-13 15:06 UTC (permalink / raw)
  To: Cedric Xing, linux-kernel, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Sat, 2019-07-13 at 18:04 +0300, Jarkko Sakkinen wrote:
> I already manually removed those changes already from previous version.

I wonder why this was posted anyway given that there was no
improvement. Anyway, I'll use the previous version.

/Jarkko 


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

* Re: [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest
  2019-07-13  6:51       ` [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest Cedric Xing
@ 2019-07-13 15:10         ` Jarkko Sakkinen
  2019-07-13 15:15           ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-13 15:10 UTC (permalink / raw)
  To: Cedric Xing, linux-kernel, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Fri, 2019-07-12 at 23:51 -0700, Cedric Xing wrote:
> The original x86/sgx/Makefile didn't work when "x86/sgx" was specified as the
> test target, nor did it work with "run_tests" as the make target. Yet another
> problem was that it breaks 32-bit only build. This patch fixes those problems,
> along with adjustments to compiler/linker options and simplifications to the
> build rules.
> 
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>

You must split this in quite a few separate patches:

1. One for each fix.
2. At least one patch for each change in compiler and linker options with a
   commit message clearly expalaining why the change was made.
3. One for each simplification.

We don't support 32-bit build:

config INTEL_SGX
	bool "Intel SGX core functionality"
	depends on X86_64 && CPU_SUP_INTEL
	
/Jarkko


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

* Re: [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest
  2019-07-13 15:10         ` Jarkko Sakkinen
@ 2019-07-13 15:15           ` Jarkko Sakkinen
  2019-07-13 17:29             ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-13 15:15 UTC (permalink / raw)
  To: Cedric Xing, linux-kernel, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Sat, 2019-07-13 at 18:10 +0300, Jarkko Sakkinen wrote:
> On Fri, 2019-07-12 at 23:51 -0700, Cedric Xing wrote:
> > The original x86/sgx/Makefile didn't work when "x86/sgx" was specified as the
> > test target, nor did it work with "run_tests" as the make target. Yet another
> > problem was that it breaks 32-bit only build. This patch fixes those problems,
> > along with adjustments to compiler/linker options and simplifications to the
> > build rules.
> > 
> > Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> 
> You must split this in quite a few separate patches:
> 
> 1. One for each fix.
> 2. At least one patch for each change in compiler and linker options with a
>    commit message clearly expalaining why the change was made.
> 3. One for each simplification.
> 
> We don't support 32-bit build:
> 
> config INTEL_SGX
> 	bool "Intel SGX core functionality"
> 	depends on X86_64 && CPU_SUP_INTEL

This is not to say that changes suck. This just in "unreviewable" state as far
as the kernel processes go...

/Jarkko


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

* Re: [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API
  2019-07-13  6:51       ` [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API Cedric Xing
@ 2019-07-13 15:21         ` Jarkko Sakkinen
  2019-07-13 17:20           ` Xing, Cedric
  0 siblings, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-13 15:21 UTC (permalink / raw)
  To: Cedric Xing, linux-sgx
  Cc: dave.hansen, sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Fri, 2019-07-12 at 23:51 -0700, Cedric Xing wrote:
> This patch augments SGX selftest with two new tests.
> 
> The first test exercises the newly added callback interface, by marking the
> whole enclave range as PROT_READ, then calling mprotect() upon #PFs to add
> necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.
> This test also serves as an example to demonstrate the callback interface.
> 
> The second test single-steps through __vdso_sgx_enter_enclave() to make sure
> the call stack can be unwound at every instruction within that vDSO API. Its
> purpose is to validate the hand-crafted CFI directives in the assembly.
> 
> Besides the new tests, this patch also fixes minor problems in the Makefile,
> such as:
>   * appended "--build-id=none" to ld command line to suppress the
>     ".note.gnu.build-id section discarded" linker warning.
>   * removed "--remove-section=.got.plt" from objcopy command line as that
>     section would never exist in statically linked (enclave) images.
> 
> Signed-off-by: Cedric Xing <cedric.xing@intel.com>

This is also in "unreviewable" state. And you ignored the comment about the
function names.

All I asked was patch that just changes the calling convention to send v21
and include the vDSO change. How hard can that be?

Also do not add the main LKML (linux-kernel@vger.kernel.org) to these patches
that are not directly against the mainline. That is only causing unnecessary
saturation and noise.

Thank you.

/Jarkko


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

* Re: [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API
  2019-07-13 15:21         ` Jarkko Sakkinen
@ 2019-07-13 17:20           ` Xing, Cedric
  2019-07-14 14:40             ` Jarkko Sakkinen
  2019-07-14 14:47             ` Jarkko Sakkinen
  0 siblings, 2 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-13 17:20 UTC (permalink / raw)
  To: Jarkko Sakkinen, linux-sgx
  Cc: dave.hansen, sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On 7/13/2019 8:21 AM, Jarkko Sakkinen wrote:
> On Fri, 2019-07-12 at 23:51 -0700, Cedric Xing wrote:
>> This patch augments SGX selftest with two new tests.
>>
>> The first test exercises the newly added callback interface, by marking the
>> whole enclave range as PROT_READ, then calling mprotect() upon #PFs to add
>> necessary PTE permissions per PFEC (#PF Error Code) until the enclave finishes.
>> This test also serves as an example to demonstrate the callback interface.
>>
>> The second test single-steps through __vdso_sgx_enter_enclave() to make sure
>> the call stack can be unwound at every instruction within that vDSO API. Its
>> purpose is to validate the hand-crafted CFI directives in the assembly.
>>
>> Besides the new tests, this patch also fixes minor problems in the Makefile,
>> such as:
>>    * appended "--build-id=none" to ld command line to suppress the
>>      ".note.gnu.build-id section discarded" linker warning.
>>    * removed "--remove-section=.got.plt" from objcopy command line as that
>>      section would never exist in statically linked (enclave) images.
>>
>> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
> 
> This is also in "unreviewable" state. And you ignored the comment about the
> function names.

Like I said, there are plenty of test### functions in the selftests. And 
your original version didn't have even a name - everything was inside 
main() without any comments. How was your original version "reviewable"?

> All I asked was patch that just changes the calling convention to send v21
> and include the vDSO change. How hard can that be?

Your selftest Makefile was broken. You had to run the test manually. It 
broke the build on 32-bit platforms.

> Also do not add the main LKML (linux-kernel@vger.kernel.org) to these patches
> that are not directly against the mainline. That is only causing unnecessary
> saturation and noise.

My apology for that. I'll take note.

> Thank you.
> 
> /Jarkko
> 

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

* Re: [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest
  2019-07-13 15:15           ` Jarkko Sakkinen
@ 2019-07-13 17:29             ` Xing, Cedric
  2019-07-14 14:53               ` Jarkko Sakkinen
  0 siblings, 1 reply; 318+ messages in thread
From: Xing, Cedric @ 2019-07-13 17:29 UTC (permalink / raw)
  To: Jarkko Sakkinen, linux-kernel, linux-sgx
  Cc: akpm, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On 7/13/2019 8:15 AM, Jarkko Sakkinen wrote:
> On Sat, 2019-07-13 at 18:10 +0300, Jarkko Sakkinen wrote:
>> On Fri, 2019-07-12 at 23:51 -0700, Cedric Xing wrote:
>>> The original x86/sgx/Makefile didn't work when "x86/sgx" was specified as the
>>> test target, nor did it work with "run_tests" as the make target. Yet another
>>> problem was that it breaks 32-bit only build. This patch fixes those problems,
>>> along with adjustments to compiler/linker options and simplifications to the
>>> build rules.
>>>
>>> Signed-off-by: Cedric Xing <cedric.xing@intel.com>
>>
>> You must split this in quite a few separate patches:
>>
>> 1. One for each fix.
>> 2. At least one patch for each change in compiler and linker options with a
>>     commit message clearly expalaining why the change was made.
>> 3. One for each simplification.
>>
>> We don't support 32-bit build:
>>
>> config INTEL_SGX
>> 	bool "Intel SGX core functionality"
>> 	depends on X86_64 && CPU_SUP_INTEL
> 
> This is not to say that changes suck. This just in "unreviewable" state as far
> as the kernel processes go...

Please note that your patchset hasn't been upstreamed yet. Your Makefile 
is problematic to begin with. Technically it's your job to make it work 
before sending out any patches. You didn't explain what's done for each 
line of Makefile in your commit message either.

Not saying documentation is unimportant, but the purposes for those 
changes are obvious and easy to understand for anyone having reasonable 
knowledge on how Makefile works.

I'm totally fine not fixing the Makefile. You can just leave them out.

> /Jarkko
> 

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

* Re: [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API
  2019-07-13 17:20           ` Xing, Cedric
@ 2019-07-14 14:40             ` Jarkko Sakkinen
  2019-07-14 14:47             ` Jarkko Sakkinen
  1 sibling, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-14 14:40 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-sgx, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Sat, Jul 13, 2019 at 10:20:58AM -0700, Xing, Cedric wrote:
> > All I asked was patch that just changes the calling convention to send v21
> > and include the vDSO change. How hard can that be?
> 
> Your selftest Makefile was broken. You had to run the test manually. It
> broke the build on 32-bit platforms.

1. We don't support 32-bit.
2. All changes should be in their own commits.

/Jarkko

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

* Re: [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API
  2019-07-13 17:20           ` Xing, Cedric
  2019-07-14 14:40             ` Jarkko Sakkinen
@ 2019-07-14 14:47             ` Jarkko Sakkinen
  2019-07-17 21:57               ` Xing, Cedric
  1 sibling, 1 reply; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-14 14:47 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-sgx, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On Sat, Jul 13, 2019 at 10:20:58AM -0700, Xing, Cedric wrote:
> Like I said, there are plenty of test### functions in the selftests. And
> your original version didn't have even a name - everything was inside main()
> without any comments. How was your original version "reviewable"?

I don't care. We can do better than that.

If you have a specific thing that needs a comment in my selftest, please
remark and I can add it.

As for your last question, I neither care about metaphysics. Please,
stick to the content.

/Jarkko

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

* Re: [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest
  2019-07-13 17:29             ` Xing, Cedric
@ 2019-07-14 14:53               ` Jarkko Sakkinen
  0 siblings, 0 replies; 318+ messages in thread
From: Jarkko Sakkinen @ 2019-07-14 14:53 UTC (permalink / raw)
  To: Xing, Cedric
  Cc: linux-kernel, linux-sgx, akpm, dave.hansen,
	sean.j.christopherson, serge.ayoun, shay.katz-zamir,
	haitao.huang, kai.svahn, kai.huang

On Sat, Jul 13, 2019 at 10:29:12AM -0700, Xing, Cedric wrote:
> Please note that your patchset hasn't been upstreamed yet. Your Makefile is
> problematic to begin with. Technically it's your job to make it work before
> sending out any patches. You didn't explain what's done for each line of
> Makefile in your commit message either.

Yes, it is different case to do the initial version of the whole thing
that suggest fixes to it. The latter needs to have more granularity.
Bug fixes in any type of software development should be isolated to
separate change sets. It is just a sane QA practice.

> Not saying documentation is unimportant, but the purposes for those changes
> are obvious and easy to understand for anyone having reasonable knowledge on
> how Makefile works.
>
> I'm totally fine not fixing the Makefile. You can just leave them out.

/Jarkko

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

* Re: [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API
  2019-07-14 14:47             ` Jarkko Sakkinen
@ 2019-07-17 21:57               ` Xing, Cedric
  0 siblings, 0 replies; 318+ messages in thread
From: Xing, Cedric @ 2019-07-17 21:57 UTC (permalink / raw)
  To: Jarkko Sakkinen
  Cc: linux-sgx, dave.hansen, sean.j.christopherson, serge.ayoun,
	shay.katz-zamir, haitao.huang, kai.svahn, kai.huang

On 7/14/2019 7:47 AM, Jarkko Sakkinen wrote:
> On Sat, Jul 13, 2019 at 10:20:58AM -0700, Xing, Cedric wrote:
>> Like I said, there are plenty of test### functions in the selftests. And
>> your original version didn't have even a name - everything was inside main()
>> without any comments. How was your original version "reviewable"?
> 
> I don't care. We can do better than that.

Not that they did a poor job. You probably don't understand the 
intention here. Naming tests with numbers helps users correlate test 
outputs with test functions.

> If you have a specific thing that needs a comment in my selftest, please
> remark and I can add it.

You should have enclosed your test code in a function to be separated 
from the initialization code (e.g. finding vDSO in memory, locating API, 
etc.). My patch actually did that for you.

> As for your last question, I neither care about metaphysics. Please,
> stick to the content.

I tried to point out you are implementing a double standard here. Please 
do not misinterpret it.

> /Jarkko
> 

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

end of thread, other threads:[~2019-07-17 21:57 UTC | newest]

Thread overview: 318+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2019-04-17 10:39 [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 01/28] x86/cpufeatures: Add Intel-defined SGX feature bit Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 02/28] x86/cpufeatures: Add SGX sub-features (as Linux-defined bits) Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 03/28] x86/msr: Add IA32_FEATURE_CONTROL.SGX_ENABLE definition Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 04/28] x86/cpufeatures: Add Intel-defined SGX_LC feature bit Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 05/28] x86/msr: Add SGX Launch Control MSR definitions Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 06/28] x86/mm: x86/sgx: Add new 'PF_SGX' page fault error code bit Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 07/28] x86/mm: x86/sgx: Signal SIGSEGV for userspace #PFs w/ PF_SGX Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 08/28] x86/cpu/intel: Detect SGX support and update caps appropriately Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 09/28] x86/sgx: Add ENCLS architectural error codes Jarkko Sakkinen
2019-04-22 21:35   ` Sean Christopherson
2019-04-17 10:39 ` [PATCH v20 10/28] x86/sgx: Add SGX1 and SGX2 architectural data structures Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 11/28] x86/sgx: Add wrappers for ENCLS leaf functions Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 12/28] x86/sgx: Enumerate and track EPC sections Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 13/28] x86/sgx: Add functions to allocate and free EPC pages Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 14/28] x86/sgx: Add sgx_einit() for initializing enclaves Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 15/28] x86/sgx: Add the Linux SGX Enclave Driver Jarkko Sakkinen
2019-04-22 21:58   ` Sean Christopherson
2019-04-23 23:29     ` Jethro Beekman
2019-04-24  0:26       ` Sean Christopherson
2019-04-24  1:04         ` Jethro Beekman
2019-04-29 19:08           ` Sean Christopherson
2019-06-04 20:12         ` Sean Christopherson
2019-06-05 14:29           ` Jarkko Sakkinen
2019-06-05 14:52             ` Sean Christopherson
2019-06-05 21:25               ` Dr. Greg
2019-06-05 22:20                 ` Sean Christopherson
2019-06-06 15:32               ` Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 16/28] x86/sgx: Add provisioning Jarkko Sakkinen
2019-04-19  3:06   ` Huang, Kai
2019-04-23 14:33     ` Jarkko Sakkinen
2019-04-24  1:34   ` Jethro Beekman
2019-05-02  8:27     ` Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 17/28] x86/sgx: Add swapping code to the core and SGX driver Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 18/28] x86/sgx: ptrace() support for the " Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 19/28] x86/vdso: Add support for exception fixup in vDSO functions Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 20/28] x86/fault: Add helper function to sanitize error code Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 21/28] x86/fault: Attempt to fixup unhandled #PF in vDSO before signaling Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 22/28] x86/traps: Attempt to fixup exceptions " Jarkko Sakkinen
2019-06-25 15:43   ` Jarkko Sakkinen
2019-06-27 20:32     ` Xing, Cedric
2019-07-11 15:54       ` Sean Christopherson
2019-07-11 22:12         ` Xing, Cedric
2019-07-11 15:56     ` Sean Christopherson
2019-07-11 17:52       ` Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 23/28] x86/vdso: Add __vdso_sgx_enter_enclave() to wrap SGX enclave transitions Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 24/28] selftests/x86: Add a selftest for SGX Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 25/28] x86/sgx: Update MAINTAINERS Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 26/28] docs: x86/sgx: Add Architecture documentation Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 27/28] docs: x86/sgx: Document kernel internals Jarkko Sakkinen
2019-04-17 10:39 ` [PATCH v20 28/28] docs: x86/sgx: Document the enclave API Jarkko Sakkinen
2019-04-18 17:10 ` [PATCH v20 00/28] Intel SGX1 support Dr. Greg
2019-04-18 17:24   ` Dave Hansen
2019-04-19 16:24     ` Dr. Greg
2019-04-19 16:39       ` Dave Hansen
2019-04-18 18:01   ` Dave Hansen
2019-04-19 14:17     ` Dr. Greg
2019-04-19 14:25       ` Dave Hansen
2019-04-19 15:27       ` Andy Lutomirski
2019-04-19 19:38         ` Jethro Beekman
2019-04-19 20:39           ` Thomas Gleixner
2019-04-19 20:46             ` Jethro Beekman
2019-04-19 20:50               ` Thomas Gleixner
2019-04-19 20:54                 ` Jethro Beekman
2019-04-19 21:15                   ` Andy Lutomirski
2019-04-19 21:19                     ` Jethro Beekman
2019-04-19 21:31                       ` Andy Lutomirski
2019-04-19 21:35                         ` Jethro Beekman
2019-04-19 21:38                           ` Thomas Gleixner
2019-04-19 21:56                             ` Jethro Beekman
2019-04-20  5:42                               ` Thomas Gleixner
2019-04-20 16:02                                 ` Dr. Greg
2019-04-22 15:01                                   ` Sean Christopherson
2019-04-22 16:24                                     ` Dr. Greg
2019-04-22 16:48                                       ` Sean Christopherson
2019-04-22 16:55                                         ` Linus Torvalds
2019-04-22 17:17                                           ` Sean Christopherson
2019-04-23  9:11                                             ` Dr. Greg
2019-04-22 16:26                               ` Andy Lutomirski
2019-04-23 21:15                                 ` Jethro Beekman
2019-05-10 17:23                                 ` Xing, Cedric
2019-05-10 17:37                                   ` Jethro Beekman
2019-05-10 17:54                                     ` Dave Hansen
2019-05-10 18:04                                       ` Jethro Beekman
2019-05-10 18:56                                         ` Xing, Cedric
2019-05-10 19:04                                           ` Jethro Beekman
2019-05-10 19:22                                             ` Andy Lutomirski
2019-05-11  1:06                                               ` Xing, Cedric
2019-05-14 15:08                                                 ` Andy Lutomirski
2019-05-15  8:31                                                   ` Jarkko Sakkinen
     [not found]                                               ` <20190513102926.GD8743@linux.intel.com>
2019-05-14 10:43                                                 ` Jarkko Sakkinen
2019-05-14 15:13                                                   ` Andy Lutomirski
2019-05-14 20:45                                                     ` Sean Christopherson
2019-05-14 21:27                                                       ` Andy Lutomirski
2019-05-14 22:28                                                         ` Xing, Cedric
2019-05-15  1:30                                                         ` Sean Christopherson
2019-05-15 18:27                                                           ` SGX vs LSM (Re: [PATCH v20 00/28] Intel SGX1 support) Andy Lutomirski
2019-05-15 19:58                                                             ` James Morris
2019-05-15 20:35                                                               ` Andy Lutomirski
2019-05-15 22:46                                                                 ` James Morris
2019-05-15 23:13                                                                   ` Andy Lutomirski
2019-05-16  3:03                                                                     ` Xing, Cedric
2019-05-16  4:40                                                                       ` Andy Lutomirski
2019-05-16 22:23                                                                         ` Xing, Cedric
2019-05-17  0:35                                                                           ` Andy Lutomirski
2019-05-17  1:06                                                                             ` Xing, Cedric
2019-05-17  1:21                                                                               ` Andy Lutomirski
2019-05-17 16:05                                                                             ` Sean Christopherson
2019-05-17 13:53                                                                           ` Stephen Smalley
2019-05-17 15:09                                                                             ` Sean Christopherson
2019-05-17 16:20                                                                               ` Stephen Smalley
2019-05-17 16:24                                                                                 ` Andy Lutomirski
2019-05-17 16:37                                                                                 ` Stephen Smalley
2019-05-17 17:12                                                                                   ` Andy Lutomirski
2019-05-17 18:05                                                                                     ` Stephen Smalley
2019-05-17 19:20                                                                                       ` Stephen Smalley
2019-05-17 19:28                                                                                       ` Sean Christopherson
2019-05-17 20:09                                                                                         ` Stephen Smalley
2019-05-17 20:14                                                                                           ` Andy Lutomirski
2019-05-17 20:34                                                                                             ` Stephen Smalley
2019-05-17 21:36                                                                                           ` Sean Christopherson
2019-05-17 17:29                                                                                   ` Sean Christopherson
2019-05-17 17:42                                                                                     ` Stephen Smalley
2019-05-17 17:50                                                                                       ` Sean Christopherson
2019-05-17 18:16                                                                                         ` Stephen Smalley
2019-05-17 17:43                                                                                     ` Andy Lutomirski
2019-05-17 17:55                                                                                       ` Sean Christopherson
2019-05-17 18:04                                                                                         ` Linus Torvalds
2019-05-17 18:21                                                                                           ` Sean Christopherson
2019-05-17 18:33                                                                                             ` Linus Torvalds
2019-05-17 18:52                                                                                               ` Sean Christopherson
2019-05-17 18:53                                                                                             ` Andy Lutomirski
2019-05-16  7:24                                                                     ` James Morris
2019-05-16 21:00                                                                       ` Andy Lutomirski
2019-05-20  9:38                                                                       ` Dr. Greg
2019-05-15 21:38                                                             ` Sean Christopherson
2019-05-16  1:19                                                               ` Haitao Huang
2019-05-16  5:16                                                             ` Jarkko Sakkinen
2019-05-16 21:02                                                               ` Andy Lutomirski
2019-05-16 22:45                                                                 ` Sean Christopherson
2019-05-16 23:29                                                                   ` Xing, Cedric
2019-05-20 11:29                                                                   ` Jarkko Sakkinen
2019-05-20 11:33                                                                 ` Jarkko Sakkinen
2019-05-17  0:03                                                             ` Sean Christopherson
2019-05-17  0:26                                                               ` Andy Lutomirski
2019-05-17 15:41                                                                 ` Sean Christopherson
2019-05-20 11:42                                                                   ` Jarkko Sakkinen
2019-05-20 11:41                                                                 ` Jarkko Sakkinen
2019-05-21 15:19                                                                   ` Jarkko Sakkinen
2019-05-21 15:24                                                                     ` Jethro Beekman
2019-05-22 13:10                                                                       ` Jarkko Sakkinen
2019-05-21 15:51                                                                     ` Sean Christopherson
2019-05-22 13:20                                                                       ` Jarkko Sakkinen
2019-05-22 13:22                                                                         ` Jarkko Sakkinen
2019-05-22 13:56                                                                           ` Stephen Smalley
2019-05-22 15:38                                                                             ` Sean Christopherson
2019-05-22 22:42                                                                               ` Andy Lutomirski
2019-05-23  2:35                                                                                 ` Sean Christopherson
2019-05-23 10:26                                                                                   ` Jarkko Sakkinen
2019-05-23 14:17                                                                                     ` Sean Christopherson
2019-05-23 15:38                                                                                       ` Andy Lutomirski
2019-05-23 23:40                                                                                         ` Sean Christopherson
2019-05-24  1:17                                                                                           ` Andy Lutomirski
2019-05-24  7:24                                                                                             ` Xing, Cedric
2019-05-24 15:41                                                                                               ` Stephen Smalley
2019-05-24 16:57                                                                                                 ` Xing, Cedric
2019-05-24 17:42                                                                                                 ` Sean Christopherson
2019-05-24 17:54                                                                                                   ` Andy Lutomirski
2019-05-24 17:56                                                                                                     ` Sean Christopherson
2019-05-24 17:54                                                                                                   ` Sean Christopherson
2019-05-24 18:34                                                                                                     ` Xing, Cedric
2019-05-24 19:13                                                                                                       ` Sean Christopherson
2019-05-24 19:30                                                                                                         ` Andy Lutomirski
2019-05-24 20:42                                                                                                         ` Xing, Cedric
2019-05-24 21:11                                                                                                           ` Sean Christopherson
2019-05-24 19:37                                                                                                       ` Andy Lutomirski
2019-05-24 20:03                                                                                                         ` Sean Christopherson
2019-05-24 20:58                                                                                                           ` Xing, Cedric
2019-05-24 21:27                                                                                                           ` Andy Lutomirski
2019-05-24 22:41                                                                                                             ` Sean Christopherson
2019-05-24 23:42                                                                                                               ` Andy Lutomirski
2019-05-25 22:40                                                                                                                 ` Xing, Cedric
2019-05-26  0:57                                                                                                                   ` Andy Lutomirski
2019-05-26  6:09                                                                                                                     ` Xing, Cedric
2019-05-28 20:24                                                                                                                       ` Sean Christopherson
2019-05-28 20:48                                                                                                                         ` Andy Lutomirski
2019-05-28 21:41                                                                                                                           ` Sean Christopherson
2019-05-30  5:38                                                                                                                             ` Xing, Cedric
2019-05-30 17:21                                                                                                                               ` Sean Christopherson
2019-05-29 14:08                                                                                                                         ` Stephen Smalley
2019-05-30  6:12                                                                                                                           ` Xing, Cedric
2019-05-30 14:22                                                                                                                             ` Stephen Smalley
2019-05-30 14:31                                                                                                                               ` Andy Lutomirski
2019-05-30 15:04                                                                                                                                 ` Stephen Smalley
2019-05-30 16:14                                                                                                                                   ` Andy Lutomirski
2019-05-30 18:01                                                                                                                                     ` Sean Christopherson
2019-05-30 19:20                                                                                                                                       ` Andy Lutomirski
2019-05-30 21:16                                                                                                                                         ` Sean Christopherson
2019-05-30 21:23                                                                                                                                           ` Andy Lutomirski
2019-05-30 21:36                                                                                                                                             ` Sean Christopherson
2019-06-03  9:12                                                                                                                                               ` Dr. Greg
2019-06-03 21:08                                                                                                                                               ` Jarkko Sakkinen
2019-05-30 21:48                                                                                                                                         ` Xing, Cedric
2019-05-30 22:24                                                                                                                                           ` Sean Christopherson
2019-06-03 21:05                                                                                                                                       ` Jarkko Sakkinen
2019-06-03 20:54                                                                                                                                     ` Jarkko Sakkinen
2019-06-03 21:23                                                                                                                                       ` Sean Christopherson
2019-06-04 11:39                                                                                                                                         ` Jarkko Sakkinen
2019-06-03 21:37                                                                                                                                       ` Andy Lutomirski
2019-06-03 20:47                                                                                                                                   ` Jarkko Sakkinen
2019-06-03 20:43                                                                                                                                 ` Jarkko Sakkinen
2019-05-25 17:31                                                                                                           ` Dr. Greg
2019-05-24 16:43                                                                                               ` Andy Lutomirski
2019-05-24 17:07                                                                                                 ` Sean Christopherson
2019-05-24 17:51                                                                                                   ` Andy Lutomirski
2019-05-24 14:44                                                                                         ` Stephen Smalley
2019-05-27 13:48                                                                                         ` Jarkko Sakkinen
2019-05-23 19:58                                                                                       ` Sean Christopherson
2019-05-27 13:34                                                                                       ` Jarkko Sakkinen
2019-05-27 13:38                                                                                         ` Jarkko Sakkinen
2019-05-23  8:10                                                                                 ` Jarkko Sakkinen
2019-05-23  8:23                                                                                   ` Jarkko Sakkinen
2019-05-20 11:36                                                               ` Jarkko Sakkinen
2019-05-15 10:35                                                       ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
2019-05-15 11:00                                                         ` Jarkko Sakkinen
2019-05-15 14:27                                                           ` Andy Lutomirski
2019-05-16  5:07                                                             ` Jarkko Sakkinen
2019-05-16  6:51                                                               ` Jarkko Sakkinen
2019-05-16  7:02                                                                 ` Jarkko Sakkinen
2019-05-15 13:21                                                         ` Sean Christopherson
2019-05-16  5:01                                                           ` Jarkko Sakkinen
2019-05-15  8:49                                                     ` Jarkko Sakkinen
2019-05-15  9:58                                                       ` Jarkko Sakkinen
2019-05-14 14:33                                               ` Haitao Huang
2019-05-14 15:17                                                 ` Andy Lutomirski
2019-05-14 15:30                                                   ` Haitao Huang
2019-05-14 20:45                                                     ` Andy Lutomirski
2019-05-14 21:08                                                       ` Haitao Huang
2019-05-14 21:58                                                       ` Xing, Cedric
2019-05-15  5:15                                                         ` Haitao Huang
2019-05-10 18:44                                       ` Xing, Cedric
2019-04-19 21:34                       ` Thomas Gleixner
2019-04-19 21:05               ` Jethro Beekman
2019-04-18 18:07   ` Andy Lutomirski
2019-04-22 20:42 ` [RFC PATCH v1 0/3] An alternative __vdso_sgx_enter_enclave() to allow enclave/host parameter passing using untrusted stack Cedric Xing
2019-04-22 22:05   ` Sean Christopherson
2019-04-23  0:37   ` Cedric Xing
2019-04-24  6:26   ` [RFC PATCH v2 " Cedric Xing
2019-07-10 11:17     ` Jarkko Sakkinen
2019-07-10 18:08       ` Xing, Cedric
2019-07-10 22:46         ` Jarkko Sakkinen
2019-07-10 22:54           ` Xing, Cedric
2019-07-11  9:36             ` Jarkko Sakkinen
2019-07-11 19:49               ` Xing, Cedric
2019-07-10 23:15           ` Jarkko Sakkinen
2019-07-10 23:37             ` Xing, Cedric
2019-07-11  9:38               ` Jarkko Sakkinen
2019-07-11 15:50                 ` Sean Christopherson
2019-07-11 17:59                   ` Jarkko Sakkinen
2019-07-11 19:51                 ` Xing, Cedric
2019-07-11  4:21     ` [RFC PATCH v3 0/3] x86/sgx: Amend vDSO API to allow enclave/host parameter passing on " Cedric Xing
2019-07-12  3:28       ` Jarkko Sakkinen
2019-07-13  6:51       ` [RFC PATCH v4 " Cedric Xing
2019-07-13  6:51       ` [RFC PATCH v4 1/3] selftests/x86/sgx: Fix Makefile for SGX selftest Cedric Xing
2019-07-13 15:10         ` Jarkko Sakkinen
2019-07-13 15:15           ` Jarkko Sakkinen
2019-07-13 17:29             ` Xing, Cedric
2019-07-14 14:53               ` Jarkko Sakkinen
2019-07-13  6:51       ` [RFC PATCH v4 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
2019-07-13 15:04         ` Jarkko Sakkinen
2019-07-13 15:06           ` Jarkko Sakkinen
2019-07-13  6:51       ` [RFC PATCH v4 3/3] selftests/x86/sgx: Augment SGX selftest to test vDSO API Cedric Xing
2019-07-13 15:21         ` Jarkko Sakkinen
2019-07-13 17:20           ` Xing, Cedric
2019-07-14 14:40             ` Jarkko Sakkinen
2019-07-14 14:47             ` Jarkko Sakkinen
2019-07-17 21:57               ` Xing, Cedric
2019-07-11  4:21     ` [RFC PATCH v3 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
2019-07-11  4:21     ` [RFC PATCH v3 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
2019-07-11  9:50       ` Jarkko Sakkinen
2019-07-11  9:53       ` Jarkko Sakkinen
2019-07-11 15:42         ` Sean Christopherson
2019-07-11 17:55           ` Jarkko Sakkinen
2019-07-11 17:58             ` Sean Christopherson
2019-07-12  3:16               ` Jarkko Sakkinen
2019-07-13  7:00                 ` Xing, Cedric
2019-07-11  4:21     ` [RFC PATCH v3 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
2019-04-24  6:26   ` [RFC PATCH v2 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
2019-07-12  3:19     ` Jarkko Sakkinen
2019-07-13  6:58       ` Xing, Cedric
2019-04-24  6:26   ` [RFC PATCH v2 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
2019-04-24 19:04     ` Sean Christopherson
2019-04-25 23:31       ` Xing, Cedric
2019-04-26 21:00         ` Sean Christopherson
2019-05-02  8:28           ` Jarkko Sakkinen
2019-04-24  6:26   ` [RFC PATCH v2 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
2019-07-12  3:25     ` Jarkko Sakkinen
2019-07-13  7:03       ` Xing, Cedric
2019-04-22 20:42 ` [RFC PATCH v1 1/3] selftests/x86: Fixed Makefile for SGX selftest Cedric Xing
2019-04-23  0:37   ` Cedric Xing
2019-04-22 20:42 ` [RFC PATCH v1 2/3] x86/vdso: Modify __vdso_sgx_enter_enclave() to allow parameter passing on untrusted stack Cedric Xing
2019-04-22 22:26   ` Sean Christopherson
2019-04-23  0:37   ` Cedric Xing
2019-04-23  1:25   ` Andy Lutomirski
2019-04-24 17:56     ` Xing, Cedric
2019-04-23 19:26   ` Sean Christopherson
2019-04-23 19:44     ` Andy Lutomirski
2019-04-22 20:42 ` [RFC PATCH v1 3/3] selftests/x86: Augment SGX selftest to test new __vdso_sgx_enter_enclave() and its callback interface Cedric Xing
2019-04-23  0:37   ` Cedric Xing
2019-04-23  1:29   ` Andy Lutomirski
2019-04-23  1:48     ` Sean Christopherson
2019-04-23 18:59     ` Sean Christopherson
2019-04-23 19:07       ` Andy Lutomirski
2019-04-23 20:11         ` Sean Christopherson
2019-04-23 11:56 ` [PATCH v20 00/28] Intel SGX1 support Jarkko Sakkinen
2019-04-23 16:52   ` Andy Lutomirski
2019-04-24 12:17     ` Jarkko Sakkinen
2019-05-08 13:45       ` Jarkko Sakkinen

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