mbox series

[v40,00/24] Intel SGX foundations

Message ID 20201104145430.300542-1-jarkko.sakkinen@linux.intel.com (mailing list archive)
Headers show
Series Intel SGX foundations | expand

Message

Jarkko Sakkinen Nov. 4, 2020, 2:54 p.m. UTC
Overview
========

Intel(R) SGX is new hardware functionality that can be used by
applications to populate protected regions of user code and data called
enclaves. Once activated, the new hardware protects enclave code and
data from outside access and modification.

SGX implementations have existed on desktop processors for several
years.  The upcoming 3rd Generation Intel Xeon Scalable Platform,
code-named “Ice Lake” will also support SGX[1].

Use Cases
=========

Enclaves provide a place to store secrets and process data with those
secrets.  SGX has been used, for example, to decrypt video without
exposing the decryption keys to nosy debuggers that might be used to
subvert DRM.  Software has generally been rewritten specifically to run
in enclaves, but there are also projects that try to run limited
unmodified software in enclaves[2].

SGX hardware is available in public clouds today.  But, anyone wishing
to use it must use a modified distribution or side-load SGX support[3].

Hardware Implementation
=======================

New memory controller hardware encrypts data transparently before
leaving the processor package.  The randomly-generated encryption key
has a lifetime of exactly one power cycle.  This mitigates attacks
originating outside the processor, like snooping DIMM traffic.

Important Kernel Touch Points
=============================

Although statically carved out of normal DRAM, enclave memory can not be
accessed or managed directly by the kernel and is marked by the firmware
as “Reserved”.  As a result, SGX support contains simple but analogous
functionality to the core mm such as a page allocator and reclaim.

Entering and exiting enclaves is tricky business.  Enclaves are
restricted from making system calls or taking interrupts directly.  The
enclave will exit out to userspace before things like this can happen.
A new vDSO exception mechanism is introduced to help smooth over some of
the architectural rough edges and make the job of userspace easier.

This implementation is picky and will decline to work on hardware which
is locked to Intel’s root of trust.

1. https://newsroom.intel.com/news-releases/intel-xeon-scalable-platform-built-most-sensitive-workloads/
2. https://grapheneproject.io/
3. https://docs.microsoft.com/en-us/azure/confidential-computing/quick-create-portal

v40 (2020-10-20):
* Change copyright years to 2016-2020 in the all files added.
  https://lore.kernel.org/linux-sgx/20201003143925.GB800720@kroah.com/
* Remove dual licensing and use GPL 2.0 unconditionally.
  https://lore.kernel.org/linux-sgx/20201003143925.GB800720@kroah.com/
* Remove platform capabilities checks from sgx_validate_secs(), as they are
  validated together with the SIGSTRUCT capabilities in
  sgx_ioc_enclave_init().
  https://lore.kernel.org/linux-sgx/20201005020819.124724-1-jarkko.sakkinen@linux.intel.com/
* During the migration from radix_tree to xarray, the locks went missing
  from sgx_encl_may_map(). Fix this by iterating with the enclave lock and
  xarray lock held.
  https://lore.kernel.org/linux-sgx/20201003195440.GD20115@casper.infradead.org/
* Verify in the #PF handler that the faulted page has equal or higher build
  time permissions than the VMA permissions (i.e. the subset of {VM_READ,
  VM_WRITE, VM_EXECUTE} in vma->vm_flags). Trigger a bus error, if this not
  the case. By doing this, mmap() and mprotect() can be allowed to map an
  address range, which has unpopulated pages, because the required
  invariant will be checked before new pages are inserted to the process
  address space.
* In the vDSO, do not save RBX before validating the reserved area of the
  struct sgx_enclave_run.
  https://lore.kernel.org/linux-sgx/20201006025703.GG15803@linux.intel.com/
* Increase the reserved area to 256 bytes in struct sgx_enclave_run as
  there needs to be some space for expansion given the evolution of
  microarchitectures, the fact that there can be only one vDSO and possible
  future extensions.
  https://lore.kernel.org/linux-sgx/20201006213927.GA117517@linux.intel.com/
* Change Copyright comments from '//' to '/* ... */'.
  https://lore.kernel.org/linux-sgx/20201005084554.GA3403@infradead.org/
* Fix the error fallback path in the SGX vDSO. RAX was not popped in the
  error path.
  https://lore.kernel.org/linux-sgx/20201017210204.GA64894@linux.intel.com/
* Move mm list management, backing storage and refcounting code  to
  “x86/sgx: Add a page reclaimer”, as they are only needed by the page
  reclaimer. Finally, change the patch position to be the very last after
  the kselftest, so that the whole patch set can be tested easily with and
  without the reclaimer.
* Move sgx_xsave_size_tbl code from “x86/sgx: Add SGX enclave driver” to
  “x86/sgx: Add SGX_IOC_ENCLAVE_CREATE”. Comment the code and use
  XFEATURE_YMM and XFEATURE_MAX as limits for the features.
* Fix bug sgx_sanitize_section() that pages left dirty were not returned
  back, which could lead to a memory leak. Rename unsanitized_page_list as
  more intuitive and shorter laundry_list and document the function itself
  and the call site.
* Use vmalloc() to allocate an array of struct sgx_epc_page’s for struct
  sgx_epc_section, in effect removing the need to store addresses inside
  the page structures. This removes the artificial limit of 8 sections. The
  section array is still statically allocated but now it is trivial to
  increase its size later on.
* Rest of the changes are documented in patch change logs as this is
  preferred way for the x86 tree.

v39 (2020-10-03):
* A new GIT tree location.
  git://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-sgx.git
* Return -ERESTARTSYS instead of -EINTR in SGX_IOC_ENCLAVE_ADD_PAGES.
  https://lore.kernel.org/linux-sgx/20200917160322.GG8530@linux.intel.com/T/#u
* Do not initialize 'encl_size' in sgx_encl_create before
  sgx_validate_secs() is called.
  https://lore.kernel.org/linux-sgx/20200921100356.GB5901@zn.tnic/
* Revert 'count' back to struct sgx_enclave_add_pages, move the check of
  -EIO to sgx_ioc_enclave_pages() instead of being buried in subfunctions.
  https://lore.kernel.org/linux-sgx/20200921195822.GA58176@linux.intel.com/
* Fix documentation for the 'encl' parameter in sgx_ioc_enclave_create(),
  sgx_ioc_enclave_init() and sgx_ioc_enclave_provision().
  https://lore.kernel.org/linux-sgx/20200921100356.GB5901@zn.tnic/
* Refine sgx_ioc_enclave_create() kdoc to better describe the meaning and
  purpose of SECS validation done by sgx_validate_secs().
  https://lore.kernel.org/linux-sgx/20200921135107.GG5901@zn.tnic/
* Improve documentation sgx_ioc_enclave_add_pages() on IO failures.
  https://lore.kernel.org/linux-sgx/20200921194419.GA56547@linux.intel.com/
* Fix a bug in __sgx_encl_add_page(). When get_user_pages() fails, we must
  return -EFAULT instead of mistakenly returning the page count.
  Reported by Haitao Huang.
* Rewrite the commit message for vm_ops->mprotect() (courtesy of Dave Hansen)
  https://lore.kernel.org/linux-sgx/32fc9df4-d4aa-6768-aa06-0035427b7535@intel.com/
* Fix ptrace support coding style issues.
  https://lore.kernel.org/linux-sgx/20200922154424.GL22660@zn.tnic/
* Fix the documentation.
  https://lore.kernel.org/linux-sgx/20200915112842.897265-24-jarkko.sakkinen@linux.intel.com/
* Always write MSRs for the public key before EINIT.
  https://lore.kernel.org/linux-sgx/20200921173514.GI5901@zn.tnic/
* Categorically disabled enclaves from noexec partitions.
  https://lore.kernel.org/linux-sgx/20200923135056.GD5160@linux.intel.com/
* Properly document the EWB flow, i.e. why there is three trials for EWB.
  https://lore.kernel.org/linux-sgx/20200922104538.GE22660@zn.tnic/
* Add kdoc about batch processing to sgx_reclaim_pages().
  https://lore.kernel.org/linux-sgx/20200922104538.GE22660@zn.tnic/
  https://lore.kernel.org/linux-mm/20200929011438.GA31167@linux.intel.com/
* Documentation fixes.
  https://lore.kernel.org/linux-sgx/20200915112842.897265-1-jarkko.sakkinen@linux.intel.com/T/#me637011aba9f45698eba88ff195452c0491c07fe
* SGX vDSO clean ups.
  https://lore.kernel.org/linux-sgx/20200915112842.897265-1-jarkko.sakkinen@linux.intel.com/T/#ma2204bba8d8e8a09bf9164fc1bb5c55813997b4a
* Add the commit message from "x86/vdso: Add support for exception fixup in vDSO functions" to Documentation/x86/sgx.rst
  https://lore.kernel.org/linux-sgx/20200923220712.GU28545@zn.tnic/
* Update correct attributes variable when allowing provisioning.
  https://lore.kernel.org/linux-sgx/20201001220824.GA24069@linux.intel.com/T/#t
* Remove sgx_exception and put its fields to sgx_exception.
  https://lore.kernel.org/linux-sgx/20201002211212.620059-1-jarkko.sakkinen@linux.intel.com/T/#u
* Remove 'exit_reason' and put EEXIT to 'self' field of sgx_enclave_run.
  https://lore.kernel.org/linux-sgx/20201002211212.620059-1-jarkko.sakkinen@linux.intel.com/T/#u
* Refine clarity of the field names in struct sgx_enclave_run and vsgx.S, and rewrite kdoc.
  https://lore.kernel.org/linux-sgx/20201002211212.620059-1-jarkko.sakkinen@linux.intel.com/T/#u
* Fix memory validation in vsgx.S. The reserved areas was not zero validated,
  which causes unnecessary risk for memory corruption bugs. In effect, 'flags'
  field can be  removed from struct sgx_enclave_run.
  https://lore.kernel.org/linux-sgx/20201002211212.620059-1-jarkko.sakkinen@linux.intel.com/T/#u
* Reduce the size of sgx_enclave_run from 256 bytes to 64 bytes, i.e. size of
  a cache line. This leave 24 bytes of free space to waste in future.
  https://lore.kernel.org/linux-sgx/20201002211212.620059-1-jarkko.sakkinen@linux.intel.com/T/#u
* Verify atttributes, miscsselect and xfrm also in EINIT against SIGSTRUCT set
  limits.
  https://lore.kernel.org/linux-sgx/op.0rvxzr02wjvjmi@mqcpg7oapc828.gar.corp.intel.com/
* Use plain lfence instead of retpoline in the vDSO because retpoline has
  the potential to cause forward compatibility issues with the future
  microarchitecture features. One such in already sight is CET-SS.
  https://lore.kernel.org/linux-sgx/20200930163822.GA55565@linux.intel.com/T/#ma65748158e2b967dbc1d9ac3b214a1415066d61c

v38:
* Fast iteration because I had email server issues with v37. Using
  temporary SMTP for this (mail.kapsi.fi).
* Return -EINTR when no data is processed, just like read().
  https://patchwork.kernel.org/patch/11773941/
* Remove cruft from SGX_IOC_ENCLAVE_ADD_PAGES and fix the return value.
  https://lore.kernel.org/linux-sgx/20200915095450.GH3612@linux.intel.com/T/#mc643ef2ab477f5f7aa5d463d883d1308eb44d6f1

v37:
* Remove MODULE_*().
  https://lore.kernel.org/linux-sgx/20200825164412.GF12107@zn.tnic/
* Fix mmap() type check.
  https://lore.kernel.org/linux-sgx/20200827152051.GB22351@sjchrist-ice/
* Fix ioctl-number.txt.
  https://lore.kernel.org/linux-sgx/20200826145239.GC22390@zn.tnic/
* Fix SPDX identifier in arch/x86/include/uapi/asm/sgx.h
  https://lore.kernel.org/linux-sgx/20200826145239.GC22390@zn.tnic/
* Consistently document "@encl: an enclave pointer".
  https://lore.kernel.org/linux-sgx/20200826145239.GC22390@zn.tnic/
* Renamed SGX_IOC_ENCLAVE_SET_ATTRIBUTE as SGX_IOC_ENCLAVE_PROVISION and
  cleaned up associated code. Also fixed issues of code introduced too
  early that were caused by the split. Now it should be more streamlined.
  https://lore.kernel.org/linux-sgx/20200826145239.GC22390@zn.tnic/
* Fixed signed integer shift overflow:
  https://github.com/intel/linux-sgx-driver/pull/16/commits d27ca6071b2b28e2e789d265eda796dd9fc65a64
* Fixed off-by-one error in a size calculation:
  https://github.com/intel/SGXDataCenterAttestationPrimitives/commit/e44cc238becf584cc079aef40b557c6af9a03f38
* Rework vDSO API with a context structure for IO data.
  https://lore.kernel.org/linux-sgx/20200904104437.29555-1-sean.j.christopherson@intel.com/
* Refined commentary about retry-loop with ENCLS[EINIT] based on Sean's response.
  https://lore.kernel.org/linux-sgx/20200629152718.GA12312@linux.intel.com/
* Return positive number from SGX_IOC_ENCLAVE_ADD_PAGES indicating the
  number of pages processed and set a fixed 1MB limit for length. In addition,
  on interrupt, return 0 and number of processed pages instead of -EINTR.
  https://lore.kernel.org/linux-sgx/20200626153400.GE27151@zn.tnic/

v36:
* Make a self-contained mprotect() handler.
* Move from radix_tree to xarray, which is more modern and robust data
  structure for managing large sparse arrays. Rename encl->page_tree as
  encl->page_array.

v35:
* Add missing SGX_ENCL_DEAD check to sgx_ioctl().

v34:
* Remove SGX_ENCL_DEAD checks from ioctl.c, as the file is open while
  executing an ioctl.
* Split driver patch into base patch and one patch for each ioctl.
* Move encl->flags check to the beginning of each ioctl. Return
  consistently -EINVAL if they don't match the expected values. Before,
  sometimes -EFAULT was returned instead of -EINVAL.
* Rename vm_ops->may_mprotect as vm_ops->mprotect() and move the call
  right before call to mprotect_fixup().

v33:
* Rebased to v5.8-rc1. Given the core changes (mmap_lock and #DB
  handling), it made sense to update the series.
* Refined documentation about how remote attestation is done in SGX.

v32:
* v31 contained not fully cleaned up main.c after merger of main.c and
  reclaim.c. Fixed in this version.
* Rebased to v5.7. Forgot to do this for v31.

v31:
* Unset SGX_ENCL_IOCTL in the error path of checking encl->flags in order
  to prevent leaving it set and thus block any further ioctl calls.
* Added missing cleanup_srcu_struct() call to sgx_encl_release().
* Take encl->lock in sgx_encl_add_page() in order to prevent races with
  the page reclaimer.
* Fix a use-after-free bug from the page reclaimer. Call kref_put() for
  encl->refcount only after putting enclave page back to the active page
  list because it could be the last ref to the enclave.
* Filter any CPU disallowed values from sigstruct->vendor
  SGX_IOC_ENCLAVE_INIT.
* Use bits 0-7 of page descriptor for the EPC section index. This
  should be enough for long term needs.
* Refined naming for functions that allocate and free EPC pages to
  be more sound and consistent.
* Merge main.c and reclaim.c into one.

v30:
Bunch of tags added. No actual code changes.

v29:
* The selftest has been moved to selftests/sgx. Because SGX is an execution
  environment of its own, it really isn't a great fit with more "standard"
  x86 tests.

  The RSA key is now generated on fly and the whole signing process has
  been made as part of the enclave loader instead of signing the enclave
  during the compilation time.

  Finally, the enclave loader loads now the test enclave directly from its
  ELF file, which means that ELF file does not need to be coverted as raw
  binary during the build process.
* Version the mm_list instead of using on synchronize_mm() when adding new
  entries. We hold the write lock for the mm_struct, and dup_mm() can thus
  deadlock with the page reclaimer, which could hold the lock for the old
  mm_struct.
* Disallow mmap(PROT_NONE) from /dev/sgx. Any mapping (e.g. anonymous) can
  be used to reserve the address range. Now /dev/sgx supports only opaque
  mappings to the (initialized) enclave data.
* Make the vDSO callable directly from C by preserving RBX and taking leaf
  from RCX.

v28:
* Documented to Documentation/x86/sgx.rst how the kernel manages the
  enclave ownership.
* Removed non-LC flow from sgx_einit().
* Removed struct sgx_einittoken since only the size of the corresponding
  microarchitectural structure is used in the series ATM.

v27:
* Disallow RIE processes to use enclaves as there could a permission
  conflict between VMA and enclave permissions.
* In the documentation, replace "grep /proc/cpuinfo" with
  "grep sgx /proc/cpuinfo".

v26:
* Fixed the commit author in "x86/sgx: Linux Enclave Driver", which was
  changed in v25 by mistake.
* Addressed a bunch of grammar mistakes in sgx.rst (thanks Randy once
  again for such a detailed feedback).
* Added back the MAINTAINERS update commit, which was mistakenly removed
  in v25.
* EREMOVE's for SECS cannot be done while sanitizing an EPC section. The
  CPU does not allow to remove a SECS page before all of its children have
  been removed, and a child page can be in some other section than the one
  currently being processed. Thus, removed special SECS processing from
  sgx_sanitize_page() and instead put sections through it twice. In the
  2nd round the lists should only contain SECS pages.

v25:
* Fix a double-free issue when SGX_IOC_ENCLAVE_ADD_PAGES
  fails on executing ENCLS[EADD]. The rollback path executed
  radix_tree_delete() on the same address twice when this happened.
* Return -EINTR instead of -ERESTARTSYS in SGX_IOC_ENCLAVE_ADD_PAGES when
  a signal is pending.
* As requested by Borislav, move the CPUID 0x12 features to their own word
  in cpufeatures.
* Sean fixed a bug from sgx_reclaimer_write() where sgx_encl_put_backing()
  was called with an uninitialized pointer when sgx_encl_get_backing()
  fails.
* Migrated /dev/sgx/* to misc. This is future-proof as struct miscdevice
  has 'groups' for setting up sysfs attributes for the device.
* Use device_initcall instead of subsys_initcall so that misc_class is
  initialized before SGX is initialized.
* Return -EACCES in SGX_IOC_ENCLAVE_INIT when caller tries to select
  enclave attributes that we the kernel does not allow it to set instead
  of -EINVAL.
* Unless SGX public key MSRs are writable always deny the feature from
  Linux. Previously this was only denied from driver. How VMs should be
  supported is not really part of initial patch set, which makes this
  an obvious choice.
* Cleaned up and refined documentation to be more approachable.

v24:
* Reclaim unmeasured and TCS pages (regression in v23).
* Replace usages of GFP_HIGHUSER with GFP_KERNEL.
* Return -EIO on when EADD or EEXTEND fails in %SGX_IOC_ENCLAVE_ADD_PAGES
  and use the same rollback (destroy enclave). This can happen when host
  suspends itself unknowingly to a VM running enclaves. From -EIO the user
  space can deduce what happened.
* Have a separate @count in struct sgx_enclave_add_pages to output number
  of bytes processed instead of overwriting the input parameters for
  clarity and more importantly that the API provides means for partial
  processing (@count could be less than @length in success case).

v23:
* Replace SGX_ENCLAVE_ADD_PAGE with SGX_ENCLAVE_ADD_PAGES. Replace @mrmask
  with %SGX_PAGE_MEASURE flag.
* Return -EIO instead of -ECANCELED when ptrace() fails to read a TCS page.
* In the reclaimer, pin page before ENCLS[EBLOCK] because pinning can fail
  (because of OOM) even in legit behaviour and after EBLOCK the reclaiming
  flow can be only reverted by killing the whole enclave.
* Fixed SGX_ATTR_RESERVED_MASK. Bit 7 was marked as reserved while in fact
  it should have been bit 6 (Table 37-3 in the SDM).
* Return -EPERM from SGX_IOC_ENCLAVE_INIT when ENCLS[EINIT] returns an SGX
  error code.

v22:
* Refined bunch commit messages and added associated SDM references as
  many of them were too exhausting and some outdated.
* Alignment checks have been removed from mmap() because it does not define
  the ELRANGE. VMAs only act as windows to the enclave. The semantics
  compare somewhat how mmap() works with regular files.
* We now require user space addresses given to SGX_IOC_ENCLAVE_ADD_PAGE to be
  page aligned so that we can pass the page directly to EADD and do not have
  to do an extra copy. This was made effectively possible by removing the
  worker thread for adding pages.
* The selftest build files have been refined throughout of various glitches
  and work properly in a cross compilation environment such as BuildRoot.
  In addition, libcalls fail the build with an assertion in the linker
  script, if they end up to the enclave binary.
* CONFIG_INTEL_SGX_DRIVER has been removed because you cannot use SGX core
  for anything without having the driver. This could change when KVM support
  is added.
* We require zero permissions in SECINFO for TCS pages because the CPU
  overwrites SECINFO flags with zero permissions and measures the page
  only after that. Allowing to pass TCS with non-zero permissions would
  cause mismatching measurement between the one provided in SIGSTRUCT and
  the one computed by the CPU.
* Obviously lots of small fixes and clean ups (does make sense to
  document them all).

v21:
* Check on mmap() that the VMA does cover an area that does not have
  enclave pages. Only mapping with PROT_NONE can do that to reserve
  initial address space for an enclave.
* Check om mmap() and mprotect() that the VMA permissions do not
  surpass the enclave permissions.
* Remove two refcounts from vma_close(): mm_list and encl->refcount.
  Enclave refcount is only need for swapper/enclave sync and we can
  remove mm_list refcount by destroying mm_struct when the process
  is closed. By not having vm_close() the Linux MM can merge VMAs.
* Do not naturally align MAP_FIXED address.
* Numerous small fixes and clean ups.
* Use SRCU for synchronizing the list of mm_struct's.
* Move to stack based call convention in the vDSO.

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 (14):
  x86/sgx: Add SGX architectural data structures
  x86/sgx: Add wrappers for ENCLS functions
  x86/cpu/intel: Add nosgx kernel parameter
  x86/sgx: Add SGX page allocator functions
  x86/sgx: Add SGX misc driver interface
  x86/sgx: Add SGX_IOC_ENCLAVE_CREATE
  x86/sgx: Add SGX_IOC_ENCLAVE_ADD_PAGES
  x86/sgx: Add SGX_IOC_ENCLAVE_INIT
  x86/sgx: Add SGX_IOC_ENCLAVE_PROVISION
  selftests/x86: Add a selftest for SGX
  x86/sgx: Add a page reclaimer
  x86/sgx: Add ptrace() support for the SGX driver
  docs: x86/sgx: Document SGX kernel architecture
  x86/sgx: Update MAINTAINERS

Sean Christopherson (10):
  x86/sgx: Initialize metadata for Enclave Page Cache (EPC) sections
  x86/cpufeatures: x86/msr: Add Intel SGX hardware bits
  x86/cpufeatures: x86/msr: Add Intel SGX Launch Control hardware bits
  x86/mm: x86/sgx: Signal SIGSEGV with PF_SGX
  x86/cpu/intel: Detect SGX support
  mm: Add 'mprotect' hook to struct vm_operations_struct
  x86/vdso: Add support for exception fixup in vDSO functions
  x86/fault: Add helper function to sanitize error code
  x86/traps: Attempt to fixup exceptions in vDSO before signaling
  x86/vdso: Implement a vDSO for Intel SGX enclave call

 .../admin-guide/kernel-parameters.txt         |   2 +
 .../userspace-api/ioctl/ioctl-number.rst      |   1 +
 Documentation/x86/index.rst                   |   1 +
 Documentation/x86/sgx.rst                     | 211 +++++
 MAINTAINERS                                   |  13 +
 arch/x86/Kconfig                              |  17 +
 arch/x86/entry/vdso/Makefile                  |   8 +-
 arch/x86/entry/vdso/extable.c                 |  46 ++
 arch/x86/entry/vdso/extable.h                 |  28 +
 arch/x86/entry/vdso/vdso-layout.lds.S         |   9 +-
 arch/x86/entry/vdso/vdso.lds.S                |   1 +
 arch/x86/entry/vdso/vdso2c.h                  |  50 +-
 arch/x86/entry/vdso/vsgx.S                    | 151 ++++
 arch/x86/include/asm/cpufeatures.h            |   2 +
 arch/x86/include/asm/disabled-features.h      |   8 +-
 arch/x86/include/asm/enclu.h                  |   9 +
 arch/x86/include/asm/msr-index.h              |   8 +
 arch/x86/include/asm/trap_pf.h                |   1 +
 arch/x86/include/asm/vdso.h                   |   5 +
 arch/x86/include/uapi/asm/sgx.h               | 168 ++++
 arch/x86/kernel/cpu/Makefile                  |   1 +
 arch/x86/kernel/cpu/feat_ctl.c                |  38 +-
 arch/x86/kernel/cpu/sgx/Makefile              |   5 +
 arch/x86/kernel/cpu/sgx/arch.h                | 338 ++++++++
 arch/x86/kernel/cpu/sgx/driver.c              | 194 +++++
 arch/x86/kernel/cpu/sgx/driver.h              |  29 +
 arch/x86/kernel/cpu/sgx/encl.c                | 782 ++++++++++++++++++
 arch/x86/kernel/cpu/sgx/encl.h                | 107 +++
 arch/x86/kernel/cpu/sgx/encls.h               | 231 ++++++
 arch/x86/kernel/cpu/sgx/ioctl.c               | 716 ++++++++++++++++
 arch/x86/kernel/cpu/sgx/main.c                | 728 ++++++++++++++++
 arch/x86/kernel/cpu/sgx/sgx.h                 |  77 ++
 arch/x86/kernel/traps.c                       |  10 +
 arch/x86/mm/fault.c                           |  45 +-
 include/linux/mm.h                            |   3 +
 mm/mprotect.c                                 |   5 +-
 tools/testing/selftests/Makefile              |   1 +
 tools/testing/selftests/sgx/.gitignore        |   2 +
 tools/testing/selftests/sgx/Makefile          |  53 ++
 tools/testing/selftests/sgx/call.S            |  44 +
 tools/testing/selftests/sgx/defines.h         |  21 +
 tools/testing/selftests/sgx/load.c            | 277 +++++++
 tools/testing/selftests/sgx/main.c            | 243 ++++++
 tools/testing/selftests/sgx/main.h            |  38 +
 tools/testing/selftests/sgx/sigstruct.c       | 391 +++++++++
 tools/testing/selftests/sgx/test_encl.c       |  20 +
 tools/testing/selftests/sgx/test_encl.lds     |  40 +
 .../selftests/sgx/test_encl_bootstrap.S       |  89 ++
 48 files changed, 5247 insertions(+), 20 deletions(-)
 create mode 100644 Documentation/x86/sgx.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.S
 create mode 100644 arch/x86/include/asm/enclu.h
 create mode 100644 arch/x86/include/uapi/asm/sgx.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.c
 create mode 100644 arch/x86/kernel/cpu/sgx/driver.h
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.c
 create mode 100644 arch/x86/kernel/cpu/sgx/encl.h
 create mode 100644 arch/x86/kernel/cpu/sgx/encls.h
 create mode 100644 arch/x86/kernel/cpu/sgx/ioctl.c
 create mode 100644 arch/x86/kernel/cpu/sgx/main.c
 create mode 100644 arch/x86/kernel/cpu/sgx/sgx.h
 create mode 100644 tools/testing/selftests/sgx/.gitignore
 create mode 100644 tools/testing/selftests/sgx/Makefile
 create mode 100644 tools/testing/selftests/sgx/call.S
 create mode 100644 tools/testing/selftests/sgx/defines.h
 create mode 100644 tools/testing/selftests/sgx/load.c
 create mode 100644 tools/testing/selftests/sgx/main.c
 create mode 100644 tools/testing/selftests/sgx/main.h
 create mode 100644 tools/testing/selftests/sgx/sigstruct.c
 create mode 100644 tools/testing/selftests/sgx/test_encl.c
 create mode 100644 tools/testing/selftests/sgx/test_encl.lds
 create mode 100644 tools/testing/selftests/sgx/test_encl_bootstrap.S

Comments

Jethro Beekman Nov. 8, 2020, 8:48 p.m. UTC | #1
On 2020-11-04 15:54, Jarkko Sakkinen wrote:
*snip*

> Jarkko Sakkinen (14):
>   x86/sgx: Add SGX architectural data structures
>   x86/sgx: Add wrappers for ENCLS functions
>   x86/cpu/intel: Add nosgx kernel parameter
>   x86/sgx: Add SGX page allocator functions
>   x86/sgx: Add SGX misc driver interface
>   x86/sgx: Add SGX_IOC_ENCLAVE_CREATE
>   x86/sgx: Add SGX_IOC_ENCLAVE_ADD_PAGES
>   x86/sgx: Add SGX_IOC_ENCLAVE_INIT
>   x86/sgx: Add SGX_IOC_ENCLAVE_PROVISION
>   selftests/x86: Add a selftest for SGX
>   x86/sgx: Add a page reclaimer
>   x86/sgx: Add ptrace() support for the SGX driver
>   docs: x86/sgx: Document SGX kernel architecture
>   x86/sgx: Update MAINTAINERS
> 
> Sean Christopherson (10):
>   x86/sgx: Initialize metadata for Enclave Page Cache (EPC) sections
>   x86/cpufeatures: x86/msr: Add Intel SGX hardware bits
>   x86/cpufeatures: x86/msr: Add Intel SGX Launch Control hardware bits
>   x86/mm: x86/sgx: Signal SIGSEGV with PF_SGX
>   x86/cpu/intel: Detect SGX support
>   mm: Add 'mprotect' hook to struct vm_operations_struct
>   x86/vdso: Add support for exception fixup in vDSO functions
>   x86/fault: Add helper function to sanitize error code
>   x86/traps: Attempt to fixup exceptions in vDSO before signaling
>   x86/vdso: Implement a vDSO for Intel SGX enclave call

I tested Jarkko's public git master branch at the time of writing (patch number, commit):

01 3dbc955 Acked-By: Jethro Beekman <jethro@fortanix.com>
02 0fb18ca Acked-By: Jethro Beekman <jethro@fortanix.com>
03 8f7ab60 Acked-By: Jethro Beekman <jethro@fortanix.com>
04 358d170 Acked-By: Jethro Beekman <jethro@fortanix.com>
05 0c64b4c Acked-By: Jethro Beekman <jethro@fortanix.com>
06 b0bacb5 Acked-By: Jethro Beekman <jethro@fortanix.com>
07 e131efe Acked-By: Jethro Beekman <jethro@fortanix.com>
08 5984a2c Acked-By: Jethro Beekman <jethro@fortanix.com>
09 93b27a8 Acked-By: Jethro Beekman <jethro@fortanix.com>
10 8ec6c36 Acked-By: Jethro Beekman <jethro@fortanix.com>
11 1e67355 Tested-By: Jethro Beekman <jethro@fortanix.com>
12 9f48d02 Tested-By: Jethro Beekman <jethro@fortanix.com>
13 53f7984 Tested-By: Jethro Beekman <jethro@fortanix.com>
14 5ab939b Tested-By: Jethro Beekman <jethro@fortanix.com>
15 6caa47ae Acked-By: Jethro Beekman <jethro@fortanix.com>
16 3106551 Acked-By: Jethro Beekman <jethro@fortanix.com>
17 7193709 Acked-By: Jethro Beekman <jethro@fortanix.com>
18 9c7d634 Acked-By: Jethro Beekman <jethro@fortanix.com>
19 cad6a3d Tested-By: Jethro Beekman <jethro@fortanix.com>
20 0dadc6b Acked-By: Jethro Beekman <jethro@fortanix.com>
21 e396b6f Acked-By: Jethro Beekman <jethro@fortanix.com>
22 bfcbc47 Tested-By: Jethro Beekman <jethro@fortanix.com>
23 7a0da40 Acked-By: Jethro Beekman <jethro@fortanix.com>
24 a644dc1 Acked-By: Jethro Beekman <jethro@fortanix.com>

--
Jethro Beekman | Fortanix
Jarkko Sakkinen Nov. 9, 2020, 7:59 p.m. UTC | #2
On Sun, Nov 08, 2020 at 11:56:30AM +0800, Hillf Danton wrote:
> On Wed,  4 Nov 2020 16:54:27 Jarkko Sakkinen wrote:
> [...]
> > +/**
> > + * sgx_alloc_epc_page() - Allocate an EPC page
> > + * @owner:	the owner of the EPC page
> > + * @reclaim:	reclaim pages if necessary
> > + *
> > + * Iterate through EPC sections and borrow a free EPC page to the caller. When a
> > + * page is no longer needed it must be released with sgx_free_epc_page(). If
> > + * @reclaim is set to true, directly reclaim pages when we are out of pages. No
> > + * mm's can be locked when @reclaim is set to true.
> > + *
> > + * Finally, wake up ksgxswapd when the number of pages goes below the watermark
> > + * before returning back to the caller.
> > + *
> > + * Return:
> > + *   an EPC page,
> > + *   -errno on error
> > + */
> > +struct sgx_epc_page *sgx_alloc_epc_page(void *owner, bool reclaim)
> > +{
> > +	struct sgx_epc_page *entry;
> 
> Nit: s/entry/epc_page/
> > +
> > +	for ( ; ; ) {
> > +		entry = __sgx_alloc_epc_page();
> > +		if (!IS_ERR(entry)) {
> > +			entry->owner = owner;
> > +			break;
> > +		}
> > +
> > +		if (list_empty(&sgx_active_page_list))
> > +			return ERR_PTR(-ENOMEM);
> > +
> > +		if (!reclaim) {
> > +			entry = ERR_PTR(-EBUSY);
> > +			break;
> > +		}
> > +
> > +		if (signal_pending(current)) {
> > +			entry = ERR_PTR(-ERESTARTSYS);
> > +			break;
> > +		}
> > +
> > +		sgx_reclaim_pages();
> i
> This is the direct reclaim mode with ksgxswapd that works in
> the background ignored in the entire for loop. But we can go
> with it in parallel, see below, if it tries as hard as it can
> to maitain the watermark in which allocators may have no
> interest.

I think this policy should be left at is and once the code in mainline
further refined. Consider it as a baseline/initial version for
reclaiming code.

> > +		schedule();
> 
> To cut allocator's latency use cond_resched();

Thanks, I'll change this.

> > +	}
> > +
> > +	if (sgx_should_reclaim(SGX_NR_LOW_PAGES))
> > +		wake_up(&ksgxswapd_waitq);
> 
> Nit: s/ksgxswapd/sgxd/ as it seems to have nothing to do with swap,
> given sgx itself is clear and good enough.

Yeah, it also handling kexec() situation, i.e. has multitude of
functions.

> > +
> > +	return entry;
> > +}
> 
> struct sgx_epc_page *sgx_alloc_epc_page(void *owner, bool reclaim)
> {
> 	struct sgx_epc_page *epc_page;
> 
> 	for (;;) {
> 		epc_page = __sgx_alloc_epc_page();
> 
> 		if (!IS_ERR(epc_page)) {
> 			epc_page->owner = owner;
> 			return epc_page;
> 		}
> 
> 		if (signal_pending(current))
> 			return ERR_PTR(-ERESTARTSYS);
> 
> 		if (list_empty(&sgx_active_page_list) || !reclaim)
> 			return ERR_PTR(-ENOMEM);
> 
> 		wake_up(&ksgxswapd_waitq);
> 		cond_resched();
> 	}
> 	return ERR_PTR(-ENOMEM);
> }

/Jarkko
Dr. Greg Nov. 21, 2020, 3:12 p.m. UTC | #3
On Wed, Nov 04, 2020 at 04:54:06PM +0200, Jarkko Sakkinen wrote:

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

> Important Kernel Touch Points
> =============================
>
> This implementation is picky and will decline to work on hardware which
> is locked to Intel's root of trust.

Given that this driver is no longer locked to the Intel trust root, by
virtue of being restricted to run only on platforms which support
Flexible Launch Control, there is no longer any legitimate technical
reason to not expose all of the functionality of the hardware.

The patch that I am including below implements signature based policy
controls for enclave initialization.  It does so in a manner that is
completely transparent to the default behavior of the driver, which is
to initialize any enclave passed to it with the exception of enclaves
that set the PROVISION_KEY attribute bit.

Secondary to the discussions that have been ongoing regarding the
restriction of mmap/mprotect, this patch has been extended to
implement signature based controls on dynamic enclaves.  The default
behavior of the driver under this patch is to reject mmap/mprotect on
initialized enclaves, unless the platform owner has elected to allow
the enclave signer the option to implement 'dynamic' enclaves,
ie. enclaves that are allowed to modify their page permissions after
initialization.

There have been a number of 'GOOGLE-ites' copied on all of these
discussions.  The notion of signature based policy controls should be
uncontroversial since it allows platform owners to implement a
'Zero-Trust' security model, a notion that has been widely advocated
by GOOGLE and others in the industry.

The strongest platform security guarantees for trusted execution
environments, that offer strong confidentiality guarantees on both
code and data, are ultimately only reputational.  This patch enables
SGX platform owners to avail themselves of that option while not
restricting, in any way, what platform owners can do with their
hardware.

This patch is also available from the following location, given the
vagaries of e-mail based patch transmission:

ftp://ftp.enjellic.com/pub/sgx/kernel/SFLC-v41.patch

Have a good remainder of the weekend.

Dr. Greg

---------------------------------------------------------------------------
Implement signature based policy controls.

This patch implements the ability for the platform owner to
implement signature based enclave control policies.  It does so
in a manner that is completely transparent to the normal behavior
of the driver, which is to initialize any enclave that is
presented to it with the exception of enclaves that have the
PROVISION_KEY attribute set.

If a launch enclave control policy is not implemented, any attempt
to pass a launch token into the driver will cause enclave
initialization to fail.

Signature based policy control is based on the identity modulus
signature of the enclave signer which is the SHA256 hash of the
modulus of the enclave signing key.

The following policy functionality is implemented.

1.) Control over which keys are allowed to sign enclaves.

2.) Control over which keys are allowed to implement launch
enclaves.

3.) Control over which keys are allowed to sign enclaves that
have access to the PROVISION_KEY attribute.

4.) Control over which enclaves are allowed to have their page
permissions modified after enclave initialization.

For each policy type a plurality of key signatures are
allowed.

Cryptographic initialization policy is accessed through the
following four pseudo-files that are implemented by this patch:

/sys/kernel/security/sgx/signing_keys

/sys/kernel/security/sgx/launch_keys

/sys/kernel/security/sgx/provisioning_keys

/sys/kernel/security/sgx/dynamic_keys

Policy keys are registered with the driver by writing the identity
modulus signature to these files in simple hexadecimal format, ie:

0000000000000000000000000000000000000000000000000000000000000000

The current list of policy keys can be displayed by reading the
contents of the pseudo-files.

In addition to a key signature, the following keywords are
accepted as valid entries for a policy file:

clear

lock

The 'clear' keyword causes all existing entries in a policy list
to be deleted.

The 'lock' keyword causes any further modifications or access to
a policy list to be denied.

All of the policy code is implemented in a single file, policy.c,
with minimal impact to the driver at large.  Since the calculation
of the identity modulus signature needed to program a launch control
register is effectively a policy decision, the code to compute the
signature was moved from the ioctl.c file to the policy.c file.

Tested-by: Dr. Greg <greg@enjellic.com>
Signed-off-by: Dr. Greg <greg@enjellic.com>
---
 arch/x86/Kconfig                 |   1 +
 arch/x86/include/uapi/asm/sgx.h  |   1 +
 arch/x86/kernel/cpu/sgx/Makefile |   3 +-
 arch/x86/kernel/cpu/sgx/driver.c |   8 +
 arch/x86/kernel/cpu/sgx/driver.h |   2 +
 arch/x86/kernel/cpu/sgx/encl.c   |  47 +--
 arch/x86/kernel/cpu/sgx/encl.h   |   3 +
 arch/x86/kernel/cpu/sgx/ioctl.c  | 129 +++----
 arch/x86/kernel/cpu/sgx/policy.c | 569 +++++++++++++++++++++++++++++++
 9 files changed, 664 insertions(+), 99 deletions(-)
 create mode 100644 arch/x86/kernel/cpu/sgx/policy.c

diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 618d1aabccb8..575936aa4d91 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -1937,6 +1937,7 @@ config X86_SGX
 	depends on CRYPTO_SHA256=y
 	select SRCU
 	select MMU_NOTIFIER
+	select SECURITYFS
 	help
 	  Intel(R) Software Guard eXtensions (SGX) is a set of CPU instructions
 	  that can be used by applications to set aside private regions of code
diff --git a/arch/x86/include/uapi/asm/sgx.h b/arch/x86/include/uapi/asm/sgx.h
index 791e45334a4a..48316ffe00b3 100644
--- a/arch/x86/include/uapi/asm/sgx.h
+++ b/arch/x86/include/uapi/asm/sgx.h
@@ -63,6 +63,7 @@ struct sgx_enclave_add_pages {
  */
 struct sgx_enclave_init {
 	__u64 sigstruct;
+	__u64 token;
 };
 
 /**
diff --git a/arch/x86/kernel/cpu/sgx/Makefile b/arch/x86/kernel/cpu/sgx/Makefile
index 91d3dc784a29..4576a491eb3f 100644
--- a/arch/x86/kernel/cpu/sgx/Makefile
+++ b/arch/x86/kernel/cpu/sgx/Makefile
@@ -2,4 +2,5 @@ obj-y += \
 	driver.o \
 	encl.o \
 	ioctl.o \
-	main.o
+	main.o \
+	policy.o
diff --git a/arch/x86/kernel/cpu/sgx/driver.c b/arch/x86/kernel/cpu/sgx/driver.c
index f2eac41bb4ff..35ff0ca362dd 100644
--- a/arch/x86/kernel/cpu/sgx/driver.c
+++ b/arch/x86/kernel/cpu/sgx/driver.c
@@ -190,5 +190,13 @@ int __init sgx_drv_init(void)
 		return ret;
 	}
 
+	ret = sgx_policy_fs_init();
+	if (ret) {
+		pr_err("SGX policy fs creation failed with %d.\n", ret);
+		misc_deregister(&sgx_dev_provision);
+		misc_deregister(&sgx_dev_enclave);
+		return ret;
+	}
+
 	return 0;
 }
diff --git a/arch/x86/kernel/cpu/sgx/driver.h b/arch/x86/kernel/cpu/sgx/driver.h
index 4eddb4d571ef..6c0fac29e6ff 100644
--- a/arch/x86/kernel/cpu/sgx/driver.h
+++ b/arch/x86/kernel/cpu/sgx/driver.h
@@ -26,4 +26,6 @@ long sgx_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
 
 int sgx_drv_init(void);
 
+int sgx_policy_fs_init(void);
+u64 *sgx_policy_get_signer(u64 *signature);
 #endif /* __ARCH_X86_SGX_DRIVER_H__ */
diff --git a/arch/x86/kernel/cpu/sgx/encl.c b/arch/x86/kernel/cpu/sgx/encl.c
index 5551c7d36483..2731edc296b8 100644
--- a/arch/x86/kernel/cpu/sgx/encl.c
+++ b/arch/x86/kernel/cpu/sgx/encl.c
@@ -212,27 +212,22 @@ static void sgx_vma_open(struct vm_area_struct *vma)
  * @end:		upper bound of the address range, exclusive
  * @vm_flags:		VMA flags
  *
- * Iterate through the enclave pages contained within [@start, @end) to verify
- * that the permissions requested by a subset of {VM_READ, VM_WRITE, VM_EXEC}
- * does not contain any permissions that are not contained in the build time
- * permissions of any of the enclave pages within the given address range.
+ * This function provides a method for determining whether or not mmap
+ * or mprotect can be invoked on the virtual memory address range of
+ * an enclave.  Page permission manipulations are only allowed on
+ * enclaves that have their dynamic flag set.
  *
- * An enclave creator must declare the strongest permissions that will be
- * needed for each enclave page  This ensures that mappings  have the identical
- * or weaker permissions that the earlier declared permissions.
+ * The function signature is left intact since future versions of the
+ * driver may implement verifications that the requested permission
+ * changes are consistent with the desire of the enclave author.
  *
  * Return: 0 on success, -EACCES otherwise
  */
 int sgx_encl_may_map(struct sgx_encl *encl, unsigned long start,
 		     unsigned long end, unsigned long vm_flags)
 {
-	unsigned long vm_prot_bits = vm_flags & (VM_READ | VM_WRITE | VM_EXEC);
-	struct sgx_encl_page *page;
-	unsigned long count = 0;
 	int ret = 0;
 
-	XA_STATE(xas, &encl->page_array, PFN_DOWN(start));
-
 	/*
 	 * Disallow READ_IMPLIES_EXEC tasks as their VMA permissions might
 	 * conflict with the enclave page permissions.
@@ -240,31 +235,9 @@ int sgx_encl_may_map(struct sgx_encl *encl, unsigned long start,
 	if (current->personality & READ_IMPLIES_EXEC)
 		return -EACCES;
 
-	mutex_lock(&encl->lock);
-	xas_lock(&xas);
-	xas_for_each(&xas, page, PFN_DOWN(end - 1)) {
-		if (!page)
-			break;
-
-		if (~page->vm_max_prot_bits & vm_prot_bits) {
-			ret = -EACCES;
-			break;
-		}
-
-		/* Reschedule on every XA_CHECK_SCHED iteration. */
-		if (!(++count % XA_CHECK_SCHED)) {
-			xas_pause(&xas);
-			xas_unlock(&xas);
-			mutex_unlock(&encl->lock);
-
-			cond_resched();
-
-			mutex_lock(&encl->lock);
-			xas_lock(&xas);
-		}
-	}
-	xas_unlock(&xas);
-	mutex_unlock(&encl->lock);
+	/* Disallow mapping on initialized enclave. */
+	if (test_bit(SGX_ENCL_INITIALIZED, &encl->flags) && !encl->dynamic)
+		ret = -EACCES;
 
 	return ret;
 }
diff --git a/arch/x86/kernel/cpu/sgx/encl.h b/arch/x86/kernel/cpu/sgx/encl.h
index 244e1d93fce2..cc4392929652 100644
--- a/arch/x86/kernel/cpu/sgx/encl.h
+++ b/arch/x86/kernel/cpu/sgx/encl.h
@@ -51,6 +51,7 @@ struct sgx_encl {
 	unsigned long base;
 	unsigned long size;
 	unsigned long flags;
+	unsigned int dynamic;
 	unsigned int page_cnt;
 	unsigned int secs_child_cnt;
 	struct mutex lock;
@@ -104,4 +105,6 @@ 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);
 
+int sgx_policy_get_params(struct sgx_encl *encl, void *modulus, u64 *signer,
+			  int *signcnt);
 #endif /* _X86_ENCL_H */
diff --git a/arch/x86/kernel/cpu/sgx/ioctl.c b/arch/x86/kernel/cpu/sgx/ioctl.c
index 6d37117ac8a0..4c92f4e1d507 100644
--- a/arch/x86/kernel/cpu/sgx/ioctl.c
+++ b/arch/x86/kernel/cpu/sgx/ioctl.c
@@ -466,70 +466,14 @@ static long sgx_ioc_enclave_add_pages(struct sgx_encl *encl, void __user *arg)
 	return ret;
 }
 
-static int __sgx_get_key_hash(struct crypto_shash *tfm, const void *modulus,
-			      void *hash)
+static int sgx_encl_try_init(struct sgx_encl *encl,
+			     struct sgx_sigstruct *sigstruct, void *token,
+			     u64 *signer)
 {
-	SHASH_DESC_ON_STACK(shash, tfm);
-
-	shash->tfm = tfm;
-
-	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,
-			 void *token)
-{
-	u64 mrsigner[4];
 	int i, j, k;
 	void *addr;
 	int ret;
 
-	/*
-	 * Deny initializing enclaves with attributes (namely provisioning)
-	 * that have not been explicitly allowed.
-	 */
-	if (encl->attributes & ~encl->attributes_mask)
-		return -EACCES;
-
-	/*
-	 * Attributes should not be enforced *only* against what's available on
-	 * platform (done in sgx_encl_create) but checked and enforced against
-	 * the mask for enforcement in sigstruct. For example an enclave could
-	 * opt to sign with AVX bit in xfrm, but still be loadable on a platform
-	 * without it if the sigstruct->body.attributes_mask does not turn that
-	 * bit on.
-	 */
-	if (sigstruct->body.attributes & sigstruct->body.attributes_mask &
-	    sgx_attributes_reserved_mask)
-		return -EINVAL;
-
-	if (sigstruct->body.miscselect & sigstruct->body.misc_mask &
-	    sgx_misc_reserved_mask)
-		return -EINVAL;
-
-	if (sigstruct->body.xfrm & sigstruct->body.xfrm_mask &
-	    sgx_xfrm_reserved_mask)
-		return -EINVAL;
-
-	ret = sgx_get_key_hash(sigstruct->modulus, mrsigner);
-	if (ret)
-		return ret;
-
 	mutex_lock(&encl->lock);
 
 	/*
@@ -545,7 +489,7 @@ static int sgx_encl_init(struct sgx_encl *encl, struct sgx_sigstruct *sigstruct,
 			preempt_disable();
 
 			for (k = 0; k < 4; k++)
-				wrmsrl(MSR_IA32_SGXLEPUBKEYHASH0 + k, mrsigner[k]);
+				wrmsrl(MSR_IA32_SGXLEPUBKEYHASH0 + k, signer[k]);
 
 			ret = __einit(sigstruct, token, addr);
 
@@ -585,6 +529,60 @@ static int sgx_encl_init(struct sgx_encl *encl, struct sgx_sigstruct *sigstruct,
 	return ret;
 }
 
+static int sgx_encl_init(struct sgx_encl *encl, struct sgx_sigstruct *sigstruct,
+			 void *token)
+{
+	u64 mrsigner[4];
+	u64 *signer;
+	int ret;
+	int signcnt = 1;
+
+	/* Configure the launch policy. */
+	ret = sgx_policy_get_params(encl, sigstruct->modulus, mrsigner,
+				    &signcnt);
+	if (ret)
+		return ret;
+
+	/*
+	 * Deny initializing enclaves with attributes (namely provisioning)
+	 * that have not been explicitly allowed.
+	 */
+	if (encl->attributes & ~encl->attributes_mask)
+		return -EACCES;
+
+	/*
+	 * Attributes should not be enforced *only* against what's available on
+	 * platform (done in sgx_encl_create) but checked and enforced against
+	 * the mask for enforcement in sigstruct. For example an enclave could
+	 * opt to sign with AVX bit in xfrm, but still be loadable on a platform
+	 * without it if the sigstruct->body.attributes_mask does not turn that
+	 * bit on.
+	 */
+	if (sigstruct->body.attributes & sigstruct->body.attributes_mask &
+	    sgx_attributes_reserved_mask)
+		return -EINVAL;
+
+	if (sigstruct->body.miscselect & sigstruct->body.misc_mask &
+	    sgx_misc_reserved_mask)
+		return -EINVAL;
+
+	if (sigstruct->body.xfrm & sigstruct->body.xfrm_mask &
+	    sgx_xfrm_reserved_mask)
+		return -EINVAL;
+
+	/* Try the available policies. */
+	signer = mrsigner;
+	while (signcnt--) {
+		ret = sgx_encl_try_init(encl, sigstruct, token, signer);
+		if (!ret)
+			return ret;
+		if (signcnt)
+			signer = sgx_policy_get_signer(signer);
+	}
+
+	return ret;
+}
+
 /**
  * sgx_ioc_enclave_init() - handler for %SGX_IOC_ENCLAVE_INIT
  * @encl:	an enclave pointer
@@ -621,7 +619,16 @@ static long sgx_ioc_enclave_init(struct sgx_encl *encl, void __user *arg)
 
 	sigstruct = kmap(initp_page);
 	token = (void *)((unsigned long)sigstruct + PAGE_SIZE / 2);
-	memset(token, 0, SGX_LAUNCH_TOKEN_SIZE);
+	if (!init_arg.token)
+		memset(token, 0, SGX_LAUNCH_TOKEN_SIZE);
+	else {
+		if (copy_from_user((uint8_t *) token,
+				   (void __user *) init_arg.token,
+				   SGX_LAUNCH_TOKEN_SIZE)) {
+			ret = -EFAULT;
+			goto out;
+		}
+	}
 
 	if (copy_from_user(sigstruct, (void __user *)init_arg.sigstruct,
 			   sizeof(*sigstruct))) {
diff --git a/arch/x86/kernel/cpu/sgx/policy.c b/arch/x86/kernel/cpu/sgx/policy.c
new file mode 100644
index 000000000000..e51440759192
--- /dev/null
+++ b/arch/x86/kernel/cpu/sgx/policy.c
@@ -0,0 +1,569 @@
+// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
+// Copyright(c) Enjellic Systems Development, 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"
+#include "encl.h"
+
+static struct dentry *sgx_fs;
+
+struct list_key {
+	struct list_head list;
+	u64 key[KEY_SIZE / 8];
+};
+
+struct list_key_iterator {
+	char *type;
+	atomic_t *opencount;
+	unsigned int *count;
+	struct mutex *lock;
+	struct list_head *list;
+	bool *lockfile;
+};
+
+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);
+
+static struct dentry *dynamic_keys;
+static atomic_t dynamic_keys_opencount = ATOMIC_INIT(1);
+static unsigned int dynamic_keys_count;
+static bool dynamic_keys_locked;
+static DEFINE_MUTEX(dynamic_key_list_mutex);
+static LIST_HEAD(dynamic_key_list);
+
+/**
+ * have_signer - Verify the 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;
+}
+
+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 void *key_start(struct seq_file *c, loff_t *pos)
+{
+	struct list_key_iterator *ki = (struct list_key_iterator *) c->private;
+
+	if (*pos >= *ki->count)
+		return NULL;
+
+	mutex_lock(ki->lock);
+	return seq_list_start(ki->list, *pos);
+}
+
+static void *key_next(struct seq_file *c, void *p, loff_t *pos)
+{
+	struct list_key_iterator *ki = (struct list_key_iterator *) c->private;
+
+	return seq_list_next(p, ki->list, pos);
+}
+
+static void key_stop(struct seq_file *c, void *p)
+{
+	struct list_key_iterator *ki = (struct list_key_iterator *) c->private;
+
+	mutex_unlock(ki->lock);
+}
+
+static int key_show(struct seq_file *c, void *key)
+{
+	struct list_key *kp;
+
+	kp = list_entry(key, struct list_key, list);
+	seq_printf(c, "%*phN\n", KEY_SIZE, kp->key);
+	return 0;
+}
+
+static const struct seq_operations keys_seqops = {
+	.start = key_start,
+	.next = key_next,
+	.stop = key_stop,
+	.show = key_show
+};
+
+static ssize_t write_keys(struct file *file, const char __user *buf,
+			  size_t datalen, loff_t *ppos)
+{
+	struct seq_file *s = file->private_data;
+	struct list_key_iterator *ki = (struct list_key_iterator *) s->private;
+	ssize_t retn;
+
+	if (*ppos != 0)
+		return -EINVAL;
+
+	retn = process_lock(buf, datalen, ki->lockfile);
+	if (retn != 0)
+		return retn;
+
+	retn = process_clear(buf, datalen, ki->type, ki->count, ki->lock,
+			     ki->list);
+	if (retn != 0)
+		return retn;
+
+	retn = process_write_key(buf, datalen, ki->count, ki->lock, ki->list);
+	return retn;
+}
+
+static int release_keys(struct inode *inode, struct file *file)
+{
+	struct seq_file *s = file->private_data;
+	struct list_key_iterator *ki = (struct list_key_iterator *) s->private;
+
+	atomic_set(ki->opencount, 1);
+	seq_release_private(inode, file);
+	return 0;
+}
+
+static int open_launch_keys(struct inode *inode, struct file *filp)
+{
+	struct list_key_iterator *ki;
+
+	if (launch_keys_locked)
+		return -EACCES;
+
+	if (!atomic_dec_and_test(&launch_keys_opencount))
+		return -EBUSY;
+
+	ki = __seq_open_private(filp, &keys_seqops, sizeof(*ki));
+	if (!ki)
+		return -ENOMEM;
+
+	ki->type = "launch control";
+	ki->opencount = &launch_keys_opencount;
+	ki->count = &launch_keys_count;
+	ki->lock = &launch_key_list_mutex;
+	ki->list = &launch_key_list;
+	ki->lockfile = &launch_keys_locked;
+
+	return 0;
+}
+
+static const struct file_operations launch_keys_ops = {
+	.open = open_launch_keys,
+	.write = write_keys,
+	.release = release_keys,
+	.read = seq_read,
+	.llseek = seq_lseek,
+};
+
+/* Provisioning control. */
+
+static int open_provision_keys(struct inode *inode, struct file *filp)
+{
+	struct list_key_iterator *ki;
+
+	if (provision_keys_locked)
+		return -EACCES;
+
+	if (!atomic_dec_and_test(&provision_keys_opencount))
+		return -EBUSY;
+
+	ki = __seq_open_private(filp, &keys_seqops, sizeof(*ki));
+	if (!ki)
+		return -ENOMEM;
+
+	ki->type = "provisioning control";
+	ki->opencount = &provision_keys_opencount;
+	ki->count = &provision_keys_count;
+	ki->lock = &provision_key_list_mutex;
+	ki->list = &provision_key_list;
+
+	return 0;
+}
+
+static const struct file_operations provision_keys_ops = {
+	.open = open_provision_keys,
+	.write = write_keys,
+	.release = release_keys,
+	.read = seq_read,
+	.llseek = seq_lseek,
+};
+
+/* Signing control. */
+
+static int open_signing_keys(struct inode *inode, struct file *filp)
+{
+	struct list_key_iterator *ki;
+
+	if (signing_keys_locked)
+		return -EACCES;
+
+	if (!atomic_dec_and_test(&signing_keys_opencount))
+		return -EBUSY;
+
+	ki = __seq_open_private(filp, &keys_seqops, sizeof(*ki));
+	if (!ki)
+		return -ENOMEM;
+
+	ki->type = "signing control";
+	ki->opencount = &signing_keys_opencount;
+	ki->count = &signing_keys_count;
+	ki->lock = &signing_key_list_mutex;
+	ki->list = &signing_key_list;
+
+	return 0;
+}
+
+static const struct file_operations signing_keys_ops = {
+	.open = open_signing_keys,
+	.write = write_keys,
+	.release = release_keys,
+	.read = seq_read,
+	.llseek = seq_lseek,
+};
+
+/* Dynamic memory control. */
+
+static int open_dynamic_keys(struct inode *inode, struct file *filp)
+{
+	struct list_key_iterator *ki;
+
+	if (dynamic_keys_locked)
+		return -EACCES;
+
+	if (!atomic_dec_and_test(&dynamic_keys_opencount))
+		return -EBUSY;
+
+	ki = __seq_open_private(filp, &keys_seqops, sizeof(*ki));
+	if (!ki)
+		return -ENOMEM;
+
+	ki->type = "dynamic control";
+	ki->opencount = &dynamic_keys_opencount;
+	ki->count = &dynamic_keys_count;
+	ki->lock = &dynamic_key_list_mutex;
+	ki->list = &dynamic_key_list;
+	ki->lockfile = &dynamic_keys_locked;
+
+	return 0;
+}
+
+static const struct file_operations dynamic_keys_ops = {
+	.open = open_dynamic_keys,
+	.write = write_keys,
+	.release = release_keys,
+	.read = seq_read,
+	.llseek = seq_lseek,
+};
+
+static int __sgx_get_key_hash(struct crypto_shash *tfm, const void *modulus,
+			      void *hash)
+{
+	SHASH_DESC_ON_STACK(shash, tfm);
+
+	shash->tfm = tfm;
+
+	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;
+}
+
+/**
+ * sgx_policy_get_params
+ *
+ * This function sets the cryptographically configured initialization
+ * policy parameters.  These include the identity modulus signature to
+ * be used as well as the configuration of the allowed enclave
+ * attributes.
+ *
+ * Return:
+ *   0 on success.
+ *   -errno otherwise
+ */
+
+int sgx_policy_get_params(struct sgx_encl *encl, void *modulus, u64 *signer,
+			  int *signcnt)
+{
+	int retn = -EINVAL;
+	uint8_t mrsigner[KEY_SIZE];
+	struct list_key *kp;
+
+	retn = sgx_get_key_hash(modulus, mrsigner);
+	if (retn)
+		goto no_signer;
+
+	if (provision_keys_count > 0 &&
+	    have_signer(&provision_key_list, &provision_key_list_mutex,
+			mrsigner))
+		encl->attributes_mask |= SGX_ATTR_PROVISIONKEY;
+
+	if (dynamic_keys_count > 0 &&
+	   have_signer(&dynamic_key_list, &dynamic_key_list_mutex, mrsigner))
+		encl->dynamic = 1;
+
+	if (signing_keys_count == 0 && launch_keys_count == 0)
+		goto have_signer;
+
+	if (signing_keys_count > 0 &&
+	    have_signer(&signing_key_list, &signing_key_list_mutex,
+			mrsigner))
+		goto have_signer;
+
+	if (launch_keys_count == 0)
+		goto no_signer;
+
+	if (encl->attributes & SGX_ATTR_EINITTOKENKEY) {
+		if (have_signer(&launch_key_list, &launch_key_list_mutex,
+				 mrsigner)) {
+			encl->attributes_mask |= SGX_ATTR_EINITTOKENKEY;
+			goto have_signer;
+		} else
+			goto no_signer;
+	}
+
+	*signcnt = launch_keys_count;
+	kp = list_first_entry(&launch_key_list, struct list_key, list);
+	memcpy(mrsigner, kp->key, KEY_SIZE);
+
+ have_signer:
+	memcpy(signer, mrsigner, KEY_SIZE);
+	pr_debug("%s: Using signer: %*phN\n", __func__, KEY_SIZE, signer);
+	return 0;
+ no_signer:
+	memset(signer, '\0', KEY_SIZE);
+	return retn;
+}
+
+/**
+ * sgx_policy_get_launch_signer - Iterate through list of enclave signers.
+ *
+ * @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  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.
+ */
+
+u64 *sgx_policy_get_signer(u64 *signer)
+{
+	bool seeking = false;
+	u64 *retn = NULL;
+	struct list_key *kp;
+
+	if (!signer) {
+		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, signer, 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, signer, KEY_SIZE) == 0)
+			seeking = true;
+	}
+
+ done:
+	mutex_unlock(&launch_key_list_mutex);
+	return retn;
+}
+
+int __init sgx_policy_fs_init(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", 0600, 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", 0600,
+						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", 0600, sgx_fs,
+					      NULL, &signing_keys_ops);
+	if (IS_ERR(signing_keys)) {
+		retn = PTR_ERR(signing_keys);
+		goto err;
+	}
+
+	dynamic_keys = securityfs_create_file("dynamic_keys", 0600, sgx_fs,
+					      NULL, &dynamic_keys_ops);
+	if (IS_ERR(dynamic_keys)) {
+		retn = PTR_ERR(dynamic_keys);
+		goto err;
+	}
+
+	return 0;
+
+ err:
+	return retn;
+}
Dave Hansen Nov. 21, 2020, 4:25 p.m. UTC | #4
On 11/21/20 7:12 AM, Dr. Greg wrote:
>> Important Kernel Touch Points
>> =============================
>>
>> This implementation is picky and will decline to work on hardware which
>> is locked to Intel's root of trust.
> Given that this driver is no longer locked to the Intel trust root, by
> virtue of being restricted to run only on platforms which support
> Flexible Launch Control, there is no longer any legitimate technical
> reason to not expose all of the functionality of the hardware.

I honestly can't understand what the point of this is, and I mean that
on multiple levels.

First of all, there's not a coherent description of the problem you're
solving with ~700 lines of code and the treatise you wrote here instead
of a changelog.

Second, is the point here to distract folks from testing the branch in
the tip tree?  Or, is it to show appreciation to maintainers by giving
them more of the thing they love: code to review?
Andy Lutomirski Nov. 21, 2020, 6:36 p.m. UTC | #5
Dr. Greg, I know you like sending these emails, but they're not really
helpful for Linux kernel development.  Please see below.

On Sat, Nov 21, 2020 at 7:13 AM Dr. Greg <greg@enjellic.com> wrote:
>
> On Wed, Nov 04, 2020 at 04:54:06PM +0200, Jarkko Sakkinen wrote:
>
> Good morning, I hope the weekend is going well for everyone.
>
> > Important Kernel Touch Points
> > =============================
> >
> > This implementation is picky and will decline to work on hardware which
> > is locked to Intel's root of trust.
>
> Given that this driver is no longer locked to the Intel trust root, by
> virtue of being restricted to run only on platforms which support
> Flexible Launch Control, there is no longer any legitimate technical
> reason to not expose all of the functionality of the hardware.

I read this three times, and I can't tell what functionality you're
referring to.

>
> The patch that I am including below implements signature based policy
> controls for enclave initialization.  It does so in a manner that is
> completely transparent to the default behavior of the driver, which is
> to initialize any enclave passed to it with the exception of enclaves
> that set the PROVISION_KEY attribute bit.

It's completely unreviewable.  It's an ABI patch, and it does not
document what it does, nor does it document why it does it.  It's just
a bunch of code.  NAK.

To be crystal clear, I will not review, and I will NAK outright, any
patches of this sort, until ALL of the following conditions are met:

a) Either a functioning SGX driver lands in a -rc kernel or there is
an excellent justification for why a change of this sort is needed
prior to a release.  Dr. Greg, you seem to be interested in SGX
actually landing upstream, but these patches are just causing delays.
Please stop.

b) The patch needs to explain what problem it solves and why it is a
good solution to that problem.

c) The patch needs to explain, either in a changelog or in a text file
in the patch, *exactly* what it does.  Imagine MSDN-like documentation
in the good old days.  The documentation needs to be sufficiently
clear that a userspace programmer could use your mechanism without
reference to your implementation and that a kernel programmer could,
in principle, re-implement your code from the description.

Unless all three of these are met, your patch is going nowhere, and I
think no one should waste their time trying to read it.

>
> Secondary to the discussions that have been ongoing regarding the
> restriction of mmap/mprotect, this patch has been extended to
> implement signature based controls on dynamic enclaves.  The default
> behavior of the driver under this patch is to reject mmap/mprotect on
> initialized enclaves, unless the platform owner has elected to allow
> the enclave signer the option to implement 'dynamic' enclaves,
> ie. enclaves that are allowed to modify their page permissions after
> initialization.

You have sent this change repeatedly, and now for some reason you're
sending it mixed in with unrelated changes.  Please stop.  At no point
have you explained why this approach is better than anything else.  It
has the obnoxious side effect that you can't usefully SCM_RIGHTS an
enclave to a different process with your patch applied, which is at
least a minor disadvantage.  You have not explained any advantage to
your patch at all.

Dr Greg, before you hit send on further emails about SGX, could you
kindly try to imagine you're a kernel maintainer, read your own email,
and consider whether how to make it add something useful to the
discussion?

Thanks,
Andy
Dr. Greg Nov. 24, 2020, 10:55 a.m. UTC | #6
On Sat, Nov 21, 2020 at 08:25:23AM -0800, Dave Hansen wrote:

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

> On 11/21/20 7:12 AM, Dr. Greg wrote:
> >> Important Kernel Touch Points
> >> =============================
> >>
> >> This implementation is picky and will decline to work on hardware which
> >> is locked to Intel's root of trust.

> > Given that this driver is no longer locked to the Intel trust root, by
> > virtue of being restricted to run only on platforms which support
> > Flexible Launch Control, there is no longer any legitimate technical
> > reason to not expose all of the functionality of the hardware.

> I honestly can't understand what the point of this is, and I mean
> that on multiple levels.

I'm sorry the issue is elusive to you but that doesn't mean it isn't
technically relevant or grounded.

It also doesn't mean this issue isn't relevant to the kernel community
at large.  I have been active in Linux since late 1991 and my
perception was that technical honesty was always the imperative, hence
my last e-mail on this subject.

> First of all, there's not a coherent description of the problem
> you're solving with ~700 lines of code and the treatise you wrote
> here instead of a changelog.

A number of points.

While I'm flattered, I cannot ethically accept the fact that the
e-mail I wrote amounted to a treatise.  To do so would do injustice to
the likes of Euclid[0], Descartes[1] and Newton[2] among notable
others.  From a literary metric perspective it wouldn't rise to the
level of a monograph let alone an essay on the subject.

With that behind us.

There was a full changelog with the patch, the e-mail essentially
wrapped the changelog and patch with a cover letter that was directed
at being responsive to the issue of including the SGX driver in the
kernel.

If you would have clicked on the link that I provided, which I will
replicate below:

ftp://ftp.enjellic.com/pub/sgx/kernel/SFLC-v41.patch

You will get a fully 'git am' compliant patch, including a changelog.

The changelog was written in a parlance consistent with someone who
would have a basic understanding of the technology under review.  If
this entire review and vetting process is being done absent that kind
of understanding, then the case can be made that the kernel
development process has larger issues on its hands.

Lets be honest though, that is not the case here, we have been talking
about this issue for over a year, everyone involved with this
technology knows what the problem is.

Since LKML is copied, the basic issue is as follows:

1.) SGX as a technology is designed to execute code and operate on
data in a manner that is confidential to inspection and impervious to
modification and control by the kernel.

2.) The mindset of the driver developers is that the kernel should be
the ultimate authority on what SGX is allowed to do.

The two world views are inherently and technically incompatible and
lead to a potential security dilemma for the kernel.  We simply
advocate for an additional level of cryptographic security that
supplements, not replaces, kernel controls to address this issue.

Issue #1 isn't theoretical.  The Linux Foundation feels there is
commercial value to this concept, as do the primary signatories
(Intel, GOOGLE, Microsoft, IBM/RedHat, Alibaba, ARM, Huawei) to the
Confidential Computing Consortium, all of which have a desire to
economically exploit the notion of a generic Trusted Execution
Environment such as SGX.

So this is either a legitimate technical issue that needs to be
addressed or these companies and their customers are on a fools
errand.

> Second, is the point here to distract folks from testing the branch
> in the tip tree?  Or, is it to show appreciation to maintainers by
> giving them more of the thing they love: code to review?

Overall, given the extremely small number of people that understand
this technology end to end, let alone who can effectively test it, our
involvement was driven by:

Quis custodiet ipsos custodes?

With respect to the maintainers, I'm sure it is a thankless job.

However, if you are getting paid to review and maintain kernel code
then one needs to review kernel code or find a different job if it is
too thankless.  I have plenty of thankless things to do in my job but
I do them since it is my job.

Our patch has two external functions of around 30 lines (~1 screen)
each that impact the driver.  The bulk of the 700 lines, all in one
file, is boilerplate code, largely replicated for each instance,
needed to read/write sysfs files and maintain four, nearly identical,
linked lists.  If this is an insurmountable review burden then the
kernel development process has larger problems on its hands.

Have a good day.

Dr. Greg

[0]: The Elements
[1]: Discourse on the Method
[2]: Opticks

As always,
Greg Wettstein, Ph.D, Worker          Autonomously self-defensive
Enjellic Systems Development, LLC     IOT platforms and edge devices.
4206 N. 19th Ave.
Fargo, ND  58102
PH: 701-281-1686                      EMAIL: greg@enjellic.com
------------------------------------------------------------------------------
"I can only provide the information, I can't make you hear it."
                                -- Shelley Bainter
Andy Lutomirski Nov. 24, 2020, 5:49 p.m. UTC | #7
On Tue, Nov 24, 2020 at 2:56 AM Dr. Greg <greg@enjellic.com> wrote:
>
> On Sat, Nov 21, 2020 at 08:25:23AM -0800, Dave Hansen wrote:
>

> You will get a fully 'git am' compliant patch, including a changelog.
>
> The changelog was written in a parlance consistent with someone who
> would have a basic understanding of the technology under review.  If
> this entire review and vetting process is being done absent that kind
> of understanding, then the case can be made that the kernel
> development process has larger issues on its hands.

No, it wasn't.

I have a fairly good understanding of SGX, and I told you quite
explicitly what was wrong with your changelog.  Understanding the
sentences you wrote and having the background is not at all the same
thing as extracting meaning from your writing.  Your patch conveyed no
information.  This email you just sent also conveys no information.



>
> Lets be honest though, that is not the case here, we have been talking
> about this issue for over a year, everyone involved with this
> technology knows what the problem is.
>
> Since LKML is copied, the basic issue is as follows:
>
> 1.) SGX as a technology is designed to execute code and operate on
> data in a manner that is confidential to inspection and impervious to
> modification and control by the kernel.
>
> 2.) The mindset of the driver developers is that the kernel should be
> the ultimate authority on what SGX is allowed to do.
>
> The two world views are inherently and technically incompatible and
> lead to a potential security dilemma for the kernel.  We simply
> advocate for an additional level of cryptographic security that
> supplements, not replaces, kernel controls to address this issue.

No, they are not.

The kernel can and will enforce policy on what SGX may do.  Your own
NAKked patch, in fact, does exactly this.  At the same time, SGX
provides security to the contents of enclaves.  These are not mutually
exclusive.


> Our patch has two external functions of around 30 lines (~1 screen)
> each that impact the driver.  The bulk of the 700 lines, all in one
> file, is boilerplate code, largely replicated for each instance,
> needed to read/write sysfs files and maintain four, nearly identical,
> linked lists.  If this is an insurmountable review burden then the
> kernel development process has larger problems on its hands.

Frankly, the largest problem in the kernel development process with
regards to SGX is the distraction created by your emails.  Please just
stop.

If you have something useful to say, distill it down to the smallest
amount of text that actually says what you're trying to say.  And
don't forget the part about "something useful to say".  If you do not
have something useful to say, please don't say it.
Dr. Greg Nov. 24, 2020, 6:40 p.m. UTC | #8
On Sat, Nov 21, 2020 at 10:36:58AM -0800, Andy Lutomirski wrote:

Good morning to everyone.

> Dr. Greg, I know you like sending these emails, but they're not
> really helpful for Linux kernel development.  Please see below.

I don't necessarily enjoy sending these e-mails and they take time
away from a major initiative that I'm taking on, which is why I wanted
to close all of this out.

Since we are establishing the last correspondence on these issues, I
just wanted to establish some final clarifications for everyone
reading along at home.

Andy, I've always publically recognized you as a gifted kernel
developer, but for the record, have you a-priori architected or
written either an SGX application stack or a trusted/untrusted runtime
stack that exceeded 65 KLOC in size?

I've done both, in the case of native SGX application stacks, multiple
times.  Including the first enclave<->enclave remote attestation and
communications framework that bypassed the need for an Attestation
Service Provider.

Intel SGX developer licensing requires that you provide application
recipients with a full and complete runtime along with the signed
application.  Our developer license allowed us to substitute our
runtime for Intel's.

I also spent 4+ years of back and forth with Washington, DC working to
establish the importance of this technology for the DOD, DHS and
various other groups that were interested in our national
cybersecurity posture.  Including demonstrations of the technology in
Faraday shielded rooms.

That doesn't make me an expert in kernel programming but it did make
me feel obligated to ask what I believe are legitimate technical
questions regarding the design and evolution of this driver.

> On Sat, Nov 21, 2020 at 7:13 AM Dr. Greg <greg@enjellic.com> wrote:
> >
> > On Wed, Nov 04, 2020 at 04:54:06PM +0200, Jarkko Sakkinen wrote:
> >
> > Good morning, I hope the weekend is going well for everyone.
> >
> > > Important Kernel Touch Points
> > > =============================
> > >
> > > This implementation is picky and will decline to work on hardware which
> > > is locked to Intel's root of trust.
> >
> > Given that this driver is no longer locked to the Intel trust root, by
> > virtue of being restricted to run only on platforms which support
> > Flexible Launch Control, there is no longer any legitimate technical
> > reason to not expose all of the functionality of the hardware.

> I read this three times, and I can't tell what functionality you're
> referring to.

Yes you do, as I mentioned to Dave in my last e-mail, we have been
disagreeing about this for a year.

You were at some kind of seminar where SGX was discussed.  Based on
that you developed a 'manifesto' regarding how Linux should implement
the technology.  That manifesto indicated there would be no place for
cryptographic policy control on enclaves.

A well taken and considered point on a locked launch control platform
but completely irrelevant for this driver, that only operates on
Flexible Launch Control platforms.  By demanding compliance with only
that vision you deny platform owners a final measure of defense
against anonymous code execution.

> > The patch that I am including below implements signature based policy
> > controls for enclave initialization.  It does so in a manner that is
> > completely transparent to the default behavior of the driver, which is
> > to initialize any enclave passed to it with the exception of enclaves
> > that set the PROVISION_KEY attribute bit.

> It's completely unreviewable.  It's an ABI patch, and it does not
> document what it does, nor does it document why it does it.  It's
> just a bunch of code.  NAK.

You can certainly NAK-away Andy[0]. I've had sufficent private
feedback from reasoned and informed individuals that I've made my
point that this isn't about technical considerations.

Here is the link, again, to the patch in 'git am' compliant format.

ftp://ftp.enjellic.com/pub/sgx/kernel/SFLC-v41.patch

I've been watching Linux patches go by for close to 30 years.  If this
is completely unreviewable garbage, legitimate concerns can be raised
about what is getting pushed into the kernel.

> To be crystal clear, I will not review, and I will NAK outright, any
> patches of this sort, until ALL of the following conditions are met:
> 
> a) Either a functioning SGX driver lands in a -rc kernel or there is
> an excellent justification for why a change of this sort is needed
> prior to a release.  Dr. Greg, you seem to be interested in SGX
> actually landing upstream, but these patches are just causing delays.
> Please stop.

For the record I am stopping, I've said everything that I can say and
the debate is not intellectually honest from a technical perspective,
continuing forward would be a waste of my time and that of others.

Everything is now publically documented for the decision makers.

As to delaying the driver. I was told a year ago that any
consideration of these security issues would hopelessly delay the
driver.  I was told six months ago, when I refreshed the patch against
the new driver design, that the release of the driver was imminent and
thus the issue couldn't be addressed.  Three months ago I was
admonished for my apparent attempt to delay the driver.

It is now a year later and we are patching grammar and noun
possessiveness issues in the driver, so I don't think it is
intellectually honest to suggest I've delayed the driver, more on that
below.

> b) The patch needs to explain what problem it solves and why it is a
> good solution to that problem.

For the official record let me see if I can frame why I think we have
not been intellectually honest with respect to this driver nor my
suggested delay of it.

1.) SGX/TEE's are designed to be secure to an adversarial operating
system or application space, ie. an IAGO threat model.  Major players
financing Linux development believe there is a commercial opportunity
available in this capability.

2.) One year ago you indicated that the then current driver
implementation was deficient, since it allowed executable code from
anonymous memory, ie. executable code that was not surveilled by the
LSM.

3.) At that time I pointed out that this makes little difference since
the technology was perfectly capable of dynamically loading any
executable code or data that it wanted to, using integrity and
confidentiality protections that would prevent any inspection or
control by the operating system, see point 1.

4.) This only leaves reputational or identity based security as a
final and ultimate check as to who can execute code on a platform.
Our patch provides that without requiring it.

You and Dave have both indicated, in response to my concerns, that
there is minimal threat to enclave based code.  If that is the case we
have needlessly delayed the driver for a year engineering a solution
to what is a non-existent threat.

> c) The patch needs to explain, either in a changelog or in a text
> file in the patch, *exactly* what it does.  Imagine MSDN-like
> documentation in the good old days.  The documentation needs to be
> sufficiently clear that a userspace programmer could use your
> mechanism without reference to your implementation and that a kernel
> programmer could, in principle, re-implement your code from the
> description.

I will let the patch speak for itself, if I honestly believed that
writing a monograph on the design would make any difference I would,
but I think we can all agree that is not the case.

For the record, this is infrastructure for a system administrator, a
userspace programmer would have no involvement in it whatsoever.

As I indicated in my mail to Dave, the changelog was designed for
someone who has a working knowledge of SGX and basic kernel
fundamentals such as linked lists and readable/writable /sysfs files.

> Unless all three of these are met, your patch is going nowhere, and
> I think no one should waste their time trying to read it.

It is fine if it doesn't go anywhere, I've made my point, my intention
in all of this was to provide what I believed to be an informed
viewpoint on relevant technical issues.

> > Secondary to the discussions that have been ongoing regarding the
> > restriction of mmap/mprotect, this patch has been extended to
> > implement signature based controls on dynamic enclaves.  The default
> > behavior of the driver under this patch is to reject mmap/mprotect on
> > initialized enclaves, unless the platform owner has elected to allow
> > the enclave signer the option to implement 'dynamic' enclaves,
> > ie. enclaves that are allowed to modify their page permissions after
> > initialization.

> You have sent this change repeatedly, and now for some reason you're
> sending it mixed in with unrelated changes.  Please stop.  At no
> point have you explained why this approach is better than anything
> else.

In the discussion surrounding the mmap/mprotect based introspection of
page permissions implemented by the SGX driver, you indicated that we
should 'pretend' that some potential security model could be built on
top of the EPCM page permission walking infrastructure.  I believe we
do significantly better than that.

There are currently no controls over dynamic enclave behavior.  Given
that our patch implements a generic policy control framework we could
implement this naturally and with little cost or complexity.

For the LKML record, absent our patch the driver has an open security
issue with respect to anonymous code execution that should be
addressed, if that issue is indeed of any concern.

In the vm_ops->mprotect thread, Haitao Huang elegantly described how
this can be achieved, even without EDMM instructions, in a manner that
would never allow the LSM to see WX permissions on a page.  In fact
the current page permission introspection infrastructure enables that
behavior.

> It has the obnoxious side effect that you can't usefully
> SCM_RIGHTS an enclave to a different process with your patch
> applied, which is at least a minor disadvantage.  You have not
> explained any advantage to your patch at all.

I guess I don't understand the SCM_RIGHTS issue.  The policy controls
are implemented after the ioctl resolves the enclave control structure
from the file descriptor and just prior to enclave initialization.  It
isn't clear how this would affect or inhibit a process that has
possession of the file descriptor.

The only thing that I can think of is that you disagree with the
optional capability of blocking the enclave from implementing
anonymously executable memory.  Absent that ability there is the
security issue that has now been extensively discussed.

The current EPCM page permission walking code only enforces the wishes
of the enclave signer not the platform owner.  As I've noted multiple
times, the SGX hardware itself is perfectly capable of enforcing those
wishes.  The security threat comes from the enclave conspiring with
the untrusted component of the application, the current code only
endorses what the enclave wants to do, not necessarily the wishes of
the platform owner.

Beyond that it is unclear where the issue of SCM_RIGHTS comes from.  I
know for certain our runtime doesn't use the concept nor does
Intel's.  The only reference that GOOGLE has is of you saying it would
be nice to have if the system administrator wanted to enforce
restrictions on what can be executed inside of an enclave and then
give the enclave to another process.

As has been discussed, this is largely irrelevant as the new process
owner of the enclave handle (fd) can choose to load whatever code they
are interested in without any inspection or controls.

In fact, this is an often stated desire of the SGX user community in
order to protect their algorithms in a cloud environment.

> Dr Greg, before you hit send on further emails about SGX, could you
> kindly try to imagine you're a kernel maintainer, read your own
> email, and consider whether how to make it add something useful to
> the discussion?

You can breath a sign of relief as I won't be hitting send anymore.

> Thanks,
> Andy

Have a good day.

Dr. Greg

[0]: If you have the facts on your side pound on the facts, if you have
the law on your side pound on the law, if you have neither pound
on the table.

As always,
Dr. Greg Wettstein, Ph.D, Worker      Autonomously self-defensive
Enjellic Systems Development, LLC     IOT platforms and edge devices.
4206 N. 19th Ave.
Fargo, ND  58102
PH: 701-281-1686                      EMAIL: greg@enjellic.com
------------------------------------------------------------------------------
"There is no safe haven from irresponsible leadership."
                                -- Lou Dobbs
Andy Lutomirski Nov. 24, 2020, 9:57 p.m. UTC | #9
On Tue, Nov 24, 2020 at 10:40 AM Dr. Greg <greg@enjellic.com> wrote:
>
> On Sat, Nov 21, 2020 at 10:36:58AM -0800, Andy Lutomirski wrote:
>

> Intel SGX developer licensing requires that you provide application
> recipients with a full and complete runtime along with the signed
> application.  Our developer license allowed us to substitute our
> runtime for Intel's.

Upstream Linux wants nothing to do with Intel's developer licensing.

> > > Given that this driver is no longer locked to the Intel trust root, by
> > > virtue of being restricted to run only on platforms which support
> > > Flexible Launch Control, there is no longer any legitimate technical
> > > reason to not expose all of the functionality of the hardware.
>
> > I read this three times, and I can't tell what functionality you're
> > referring to.
>
> Yes you do, as I mentioned to Dave in my last e-mail, we have been
> disagreeing about this for a year.

No, I don't.  It's entirely possible that I'm aware of the
functionality you're referring to, but that doesn't mean that your
description quoted above is sufficient for me to have the slightest
idea which functionality you mean right here.

>
> You were at some kind of seminar where SGX was discussed.  Based on
> that you developed a 'manifesto' regarding how Linux should implement
> the technology.  That manifesto indicated there would be no place for
> cryptographic policy control on enclaves.

That's not what I said.  Paraphrasing myself, I said that there is no
place for a driver in upstream Linux that allows only Intel-approved
code to run.  That is not at all the same thing as saying we won't
support cryptographic policy in a way that allows the platform owner
an appropriate degree of control.

Actually supporting launch control (the EINIT-enforced kind) in
upstream Linux will be tricky but is surely possible.  It would
probably help if Intel or firmware vendors had some clear
specification of exactly how they intend for platform owners to select
an SGXLEPUBKEYHASH value.  (A nice spec in which an authenticated UEFI
variable contained the desired SGXLEPUBKEYHASH and lock state might be
an excellent start.)  Supporting this in upstream Linux will also
require decoupling the user code that creates an enclave from the user
code that invokes the LE.  Jarkko already wrote some code for this,
and it could be revived.  If this ends up being inconsistent with
Intel's licensing requirements, then Intel can change their licensing
requirements or people can just ignore Intel and use a different
signing key.

Frankly, using Intel's signing key in SGXLEPUBKEYHASH offers a dubious
degree of protection in the first place -- it assumes that Intel will
never approve a malware enclave, and it also assumes that the lack of
functioning EINITTOKEN revocation won't break the whole scheme.

>
> A well taken and considered point on a locked launch control platform
> but completely irrelevant for this driver, that only operates on
> Flexible Launch Control platforms.  By demanding compliance with only
> that vision you deny platform owners a final measure of defense
> against anonymous code execution.

I am denying Intel the chance to impose their licensing requirements.
The fact that Intel chose to poison the well with their licensing
system and that, as a result, Linux won't support the Intel model of
launch control to protect platform owners is an unfortunate side
effect.

>
> > > The patch that I am including below implements signature based policy
> > > controls for enclave initialization.  It does so in a manner that is
> > > completely transparent to the default behavior of the driver, which is
> > > to initialize any enclave passed to it with the exception of enclaves
> > > that set the PROVISION_KEY attribute bit.
>
> > It's completely unreviewable.  It's an ABI patch, and it does not
> > document what it does, nor does it document why it does it.  It's
> > just a bunch of code.  NAK.
>
> You can certainly NAK-away Andy[0]. I've had sufficent private
> feedback from reasoned and informed individuals that I've made my
> point that this isn't about technical considerations.

Depends on what you mean by "technical".  In the submitting-patches
guide (https://www.kernel.org/doc/html/v5.9/process/submitting-patches.html),
you will find instructions to "describe your changes" and "separate
your changes".  If you can produce a reasonably, reviewable submission
of your code, I will review it.  But I am not going to dig through
your diff to try to find the hidden technical merit.

>
> Here is the link, again, to the patch in 'git am' compliant format.
>
> ftp://ftp.enjellic.com/pub/sgx/kernel/SFLC-v41.patch
>
> I've been watching Linux patches go by for close to 30 years.  If this
> is completely unreviewable garbage, legitimate concerns can be raised
> about what is getting pushed into the kernel.

The kernel review process is by no means perfect.  That does not mean
that you get to apply your unreviewable garbage just because other
people have pulled it off in the past.

> For the LKML record, absent our patch the driver has an open security
> issue with respect to anonymous code execution that should be
> addressed, if that issue is indeed of any concern.

What do you mean?


> The only thing that I can think of is that you disagree with the
> optional capability of blocking the enclave from implementing
> anonymously executable memory.  Absent that ability there is the
> security issue that has now been extensively discussed.

You keep sending a patch that blocks mmap and mprotect on an
initialized enclave.  As far as I can tell, you haven't explained how
it's any better than the code it replaces.  The code it replaces
enforces per-page maximum permissions, and all the infrastructure is
in place for the platform owner to be able to enforce their rules
without breaking ABI.

Your proposal appears to accomplish something a little bit like what
the code in -tip does, except without as much room for future
improvements.  Since you haven't tried to explain why you think it's
better, I can't really evaluate it.