1. Introduction

SGX1 shortcomings

  • enclave建立时必须分配其所需的所有内存,并且难以根据工作量自适应分配enclave,需要根据最坏情况的工作量来分配内存

  • enclave页的访问控制由EPCM来管理,当页被加入enclave时其权限就得写入EPCM中,并且不能再改变,这就意味着必须允许页上将来可能执行的任何操作,不能做到权限最小化

  • library OS,异常处理和代码延迟加载

2. SGX2 Considerations & Requirements

动态内存管理需要满足的条件

  • enclave需要自己掌控其内存和权限
  • enclave代码在enclave不知情的情况下被改变时,将不会被执行
  • 系统的资源管理器能够正常管理和分配资源
  • 需要同时有EPCM权限和系统权限才能更改内存权限

安全考量

  • enclave软件需要改变页的权限来进行访问控制
  • 权限更改时要保证旧的权限从TLB中移除
  • 如果enclave要将页还回系统,并且想要在以后使用相同的内存地址,则enclave需要知道页是什么时候被还回的

软件考量

  • enclave内部的内存管理机构需要能够重新分配内存资源

3. SGX2 Overview and Usage

SGX2新增的指令

image-20201125160452272

image-20201125160710352

Enclave内存分配

To implement dynamic memory allocation and commitment, the enclave runtime system and the operating system have to agree on a protocol that coordinates the operating system usage of EAUG and the enclave runtime system usage of EACCEPT.

Committed: Virtual Size减去为程序保留的内存(未分配)。怎么理解为程序保留的但未分配的内存?就是告诉系统我要一块内存,但暂时还用不上,不过分配的地址得给我,系统就给程序一个不用的地址,但不分配内存,等程序真的要使用时(读写),就从页面或物理内存中分配出来映射到那个地址上。

提交的内存: 系统从物理内存或者换页内存分配给进程的那一部分。这部分内存在虚拟内存的线性地址中是连续的,不过在物理内存或者换页内存中,不一定是连续的。提交但未使用的内存一般都在换页内存里面,只有去使用的时候,才会换到物理内存里面,这点要注意。

Enclave内存释放

SGX2 provides a more robust reclamation of committed memory. OS and enclave runtime system need to coordinate the execution of EMODT, ETRACK, and EREMOVE by the OS and execution of EACCEPT by the enclave runtime.

改变页的权限

分为扩大权限和缩减权限。

  • 扩大权限:

    1. The internal manager executes EMODPE to extend the page permissions in the EPCM.
    2. The internal manager requests the system manager to extend page permissions in the page tables.
  • 缩减权限:

    1. The internal manager requests that the system manager to restrict permissions on a page.

    2. The system manager executes EMODPR and updates page table permissions. After permissions have been updated, the system manager executes ETRACK on the SECS of the calling enclave and sends IPIs (处理器间中断:允许一个CPU向系统其他的CPU发送中断信号) to all processors that may be executing inside the enclave to flush TLB mappings.

    3. After all IPIs have been acknowledged, control is returned to the internal manager. The internal manager verifies that page permissions have been restricted and TLB mappings flushed by executing EACCEPT.

  • 权限的更改(同时包含扩大和缩减权限):先缩减后扩大 —— 避免产生不安全的中间临时情况

线程控制机构TCS分配

The software protocol is very similar to page restriction except that instead of executing EMODPR the OS executes EMODT.

动态加载模块

To support dynamic loading of modules, SGX2 provides EACCEPTCOPY which allows the internal manager to atomically initialize the contents and permission of a page.

Library OS支持

  • 提供异常处理
    • 由enclave产生的异常
    • 异常的类型
    • 错误情况的具体信息
  • SGX2还另外提供enclave运行时产生的enclave内部的异常