# Table of Contents - [Speculative Execution Side Channels | SGX 101](#speculative-execution-side-channels-sgx-101) - [Enclave | SGX 101](#enclave-sgx-101) - [Memory Corruption | SGX 101](#memory-corruption-sgx-101) - [SGX Security | SGX 101](#sgx-security-sgx-101) - [SGX Bootstrap | SGX 101](#sgx-bootstrap-sgx-101) - [Technion'18 Summer School Program | SGX 101](#technion-18-summer-school-program-sgx-101) - [Overview | SGX 101](#overview-sgx-101) - [CCS'17 Tutorial | SGX 101](#ccs-17-tutorial-sgx-101) - [Row Hammer Attacks | SGX 101](#row-hammer-attacks-sgx-101) - [Communication between Architectural and Application Enclaves | SGX 101](#communication-between-architectural-and-application-enclaves-sgx-101) - [Page-table-based Attacks | SGX 101](#page-table-based-attacks-sgx-101) - [Real-world Example | SGX 101](#real-world-example-sgx-101) - [Cache Attacks | SGX 101](#cache-attacks-sgx-101) - [SSLab | SGX 101](#sslab-sgx-101) - [Branch Shadowing | SGX 101](#branch-shadowing-sgx-101) - [Inter-process Local Attestation | SGX 101](#inter-process-local-attestation-sgx-101) - [About Us | SGX 101](#about-us-sgx-101) - [Uninitialized Memory | SGX 101](#uninitialized-memory-sgx-101) - [Other Resources | SGX 101](#other-resources-sgx-101) - [Attestation | SGX 101](#attestation-sgx-101) - [Sealing | SGX 101](#sealing-sgx-101) - [Home | SGX 101](#home-sgx-101) --- # Speculative Execution Side Channels | SGX 101 [PreviousRow Hammer Attacks](/sgx101/sgx-security/row-hammer-attack) [NextOther Resources](/sgx101/resources) Last updated 5 years ago Was this helpful? ### [](#introduction) Introduction One class of side channels that draws significant attention is speculative execution side channels. Based on such side channels, communities have proposed several attack variants including ones (e.g., foreshadow) against SGX. The attack allows an attacker to extract the data from an enclave. In response to the attack, Intel have released microcode updates. [foreshadow](https://foreshadowattack.eu/) --- # Enclave | SGX 101 [PreviousOverview](/sgx101/sgx-bootstrap/overview) [NextCommunication between Architectural and Application Enclaves](/sgx101/sgx-bootstrap/enclave/interaction-between-pse-and-application-enclaves) Last updated 5 years ago Was this helpful? [](#physical-memory-organization) Physical Memory Organization ------------------------------------------------------------------- The enclave’s code and data is stored in Processor Reserved Memory (PRM), which is a subset of DRAM that cannot be directly accessed by other software, including system software and System Management Module code (Ring 2). Direct Memory Access targeting the PRM is also rejected by the CPU in order to protect enclave from other peripherals. ### [](#enclave-page-cache-epc) Enclave Page Cache (EPC) The contents of enclaves and the associated data structures are stored in the Enclave Page Cache (EPC), which is a subset of the PRM. The SGX design supports having multiple enclaves on a system at the same time, which is a necessity in multi-process environments. This is achieved by having the EPC split into 4 KB pages that can be assigned to different enclaves. The EPC uses the same page size as the architecture’s address translation feature. The EPC is managed by the same system software that manages the rest of the computer’s physical memory. The system software, which can be a hypervisor or an OS kernel, uses SGX instructions to allocate unused pages to enclaves, and to free previously allocated EPC pages. Non-enclave software cannot directly access the EPC, as it is contained in the PRM. ### [](#enclave-page-cache-map-epcm) Enclave Page Cache Map (EPCM) The SGX design expects the system software to allocate the EPC pages to enclaves. However, as the system software is not trusted, SGX processors check the correctness of the system software’s allocation decisions, and refuse to perform any action that would compromise SGX’s security guarantees. For example, if the system software attempts to allocate the same EPC page to two enclaves, the SGX instruction used to perform the allocation will fail. In order to perform its security checks, SGX records some information about the system software’s allocation decisions for each EPC page in the Enclave Page Cache Map (EPCM). The EPCM is an array with one entry per EPC page, so computing the address of a page’s EPCM entry only requires a bitwise shift operation and an addition. (Like the page table in a regular OS) Above are the fields in an EPCM entry that track the ownership of pages. The SGX instructions that allocate an EPC page set the `VALID` bit of the corresponding EPCM entry to `1`, and refuse to operate on EPC pages whose `VALID` bit is already set. The instruction used to allocate an EPC page also determines the page’s intended usage, which is recorded in the page type (`PT`) field of the corresponding EPCM entry. The pages that store an enclave’s code and data are considered to have a regular type (`PT_REG`). The pages dedicated to the storage of SGX’s supporting data structures are tagged with special types. For example, the PT\_SECS type identifies pages that hold SGX Enclave Control Structures. A page’s EPCM entry also identifies the enclave that owns the EPC page. This information is used by the mechanisms that enforce SGX’s isolation guarantees to prevent an enclave from accessing another enclave’s private information. As the EPCM identifies a single owning enclave for each EPC page, it is impossible for enclaves to communicate via shared memory using EPC pages. ### [](#sgx-enclave-control-structure-secs) SGX Enclave Control Structure (SECS) SGX stores per-enclave metadata in a SGX Enclave Control Structure (SECS) associated with each enclave. Each SECS is stored in a dedicated EPC page with the page type `PT_SECS`. These pages are not intended to be mapped into any enclave’s address space, and are exclusively used by the CPU’s SGX implementation. An enclave’s identity is almost synonymous to its SECS. The first step in bringing an enclave to life allocates an EPC page to serve as the enclave’s SECS, and the last step in destroying an enclave deallocates the page holding its SECS. The EPCM entry field identifying the enclave that owns an EPC page points to the enclave’s SECS. The system software uses the virtual address of an enclave’s SECS to identify the enclave when invoking SGX instructions. All SGX instructions take virtual addresses as their inputs. Given that SGX instructions use SECS addresses to identify enclaves, the system software must create entries in its page tables pointing to the SECS of the enclaves it manages. However, the system software cannot access any SECS page, as these pages are stored in the PRM. SECS pages are not intended to be mapped inside their enclaves’ virtual address spaces, and SGX-enabled processors explicitly prevent enclave code from accessing SECS pages. [](#memory-layout-of-enclave-virtual-memory) Memory Layout of Enclave (Virtual Memory) ------------------------------------------------------------------------------------------- SGX was designed to minimize the effort required to convert application code to take advantage of enclaves. Therefore, it adopts similar memory address translation mechanism as the system software such as operating system or hypervisor. ### [](#enclave-linear-address-range-elrange) Enclave Linear Address Range (ELRANGE) _("Linear" roughly means "virtual" in regular memory layout)_ Each enclave designates an area in its virtual address space, called the enclave linear address range (ELRANGE), which is used to map the code and the sensitive data stored in the enclave’s EPC pages. The virtual address space outside ELRANGE is mapped to access non-EPC memory via the same virtual addresses as the enclave’s host process. The SGX design guarantees that the enclave’s memory accesses inside ELRANGE obey the virtual memory abstraction, while memory accesses outside ELRANGE receive no guarantees (because system software cannot be trusted). Therefore, enclaves must store all their code and private data inside ELRANGE, and must consider the memory outside ELRANGE to be an untrusted interface to the outside world. ELRANGE is specified using a base (the `BASEADDR` field) and a size (the `SIZE`) in the enclave’s SECS. ELRANGE must meet the same constraints as a variable memory type range and as the PRM range, namely the size must be a power of 2, and the base must be aligned to the size. These restrictions are in place so that the SGX implementation can inexpensively check whether an address belongs to an enclave’s ELRANGE quickly, in either hardware or software. ### [](#sgx-enclave-attributes) SGX Enclave Attributes The execution environment of an enclave is heavily influenced by the value of the `ATTRIBUTES` field in the enclave’s SECS. The most important attribute, from a security perspective, is the DEBUG flag. When this flag is set, it enables the use of SGX’s debugging features for this enclave. These debugging features include the ability to read and modify most of the enclave’s memory. Therefore, DEBUG should only be set in a development environment, as it causes the enclave to lose all the SGX security guarantees. SGX guarantees that enclave code will always run with the XCR0 register set to the value indicated by extended features request mask (XFRM). Enclave authors are expected to use XFRM to specify the set of architectural extensions enabled by the compiler used to produce the enclave’s code. The MODE64BIT flag is set to true for enclaves that use the 64-bit Intel architecture. The INIT flag is always false when the enclave’s SECS is created. The flag is set to true at a certain point in the enclave lifecycle. ### [](#address-translation-for-sgx-enclaves) Address Translation for SGX Enclaves Under SGX, the operating system and hypervisor are still in full control of the page tables and Extended Page Tables, and each enclave’s code uses the same address translation process and page tables as its host application. This minimizes the amount of changes required to add SGX support to existing system software. At the same time, having the page tables managed by untrusted system software opens SGX up to the address translation attacks. SGX’s active memory mapping attacks defense mechanisms revolve around ensuring that each EPC page can only be mapped at a specific virtual address. When an EPC page is allocated, its intended virtual address is recorded in the EPCM entry for the page, in the `ADDRESS` field. When an address translation result is the physical address of an EPC page, the CPU ensures that the virtual address given to the address translation process matches the expected virtual address recorded in the page’s EPCM entry. SGX also protects against some passive memory mapping attacks and fault injection attacks by ensuring that the access permissions of each EPC page always match the enclave author’s intentions. The access permissions for each EPC page are specified when the page is allocated, and recorded in the readable (`R`), writable (`W`), and executable (`X`) fields in the page’s EPCM entry. An enclave author must include memory layout information ("page table") along with the enclave, in such a way that the system software loading the enclave will know the expected virtual memory address and access permissions for each enclave page. In return, the SGX design guarantees to the enclave authors that the system software, which manages the page tables and Extended Page Table, will not be able to set up an enclave’s virtual address space in a manner that is inconsistent with the author’s expectations. Finally, a SGX-enabled CPU will ensure that the virtual memory inside ELRANGE is mapped to EPC pages. This prevents the system software from carrying out an address translation attack where it maps the enclave’s entire virtual address space to DRAM pages outside the PRM, which do not trigger any of the checks above, and can be directly accessed by the system software. [](#thread-control-structure-tcs) Thread Control Structure (TCS) --------------------------------------------------------------------- The SGX design fully supports multi-core processors. It is possible for multiple logical processors to concurrently execute the same enclave’s code at the same time, via different threads. The SGX implementation uses a Thread Control Structure (TCS) for each logical processor that executes an enclave’s code. Each TCS is stored in a dedicated EPC page whose EPCM entry type is PT\_TCS. Some of the first few fields are considered to belong to the architectural part of the structure, and therefore are guaranteed to have the same semantics on all the processors that support SGX. The rest of the TCS is not documented. The contents of an EPC page that holds a TCS cannot be directly accessed, even by the code of the enclave that owns the TCS. This restriction is similar to the restriction on accessing EPC pages holding SECS instances. However, the architectural fields in a TCS can be read by enclave debugging instructions. The architectural fields in the TCS lay out the context switches performed by a logical processor when it transitions between executing non-enclave and enclave code. ### [](#state-save-area-ssa) State Save Area (SSA) When the processor encounters a hardware exception, such as an interrupt, while executing the code inside an enclave, it performs a privilege level switch and invokes a hardware exception handler provided by the system software. Before executing the exception handler, however, the processor needs a secure area to store the enclave code execution context, so that the information in the execution context is not revealed to the untrusted system software. In the SGX design, the area used to store an enclave thread’s execution context while a hardware exception is handled is called a State Save Area (SSA). Each TCS references a contiguous sequence of SSAs. The offset of the SSA array (OSSA) field specifies the location of the first SSA in the enclave’s virtual address space. The number of SSAs (NSSA) field indicates the number of available SSAs. Each SSA starts at the beginning of an EPC page, and uses up the number of EPC pages that is specified in the SSAFRAMESIZE field of the enclave’s SECS. These alignment and size restrictions most likely simplify the SGX implementation by reducing the number of special cases that it needs to handle. An enclave thread’s execution context consists of the general-purpose registers (GPRs) and the result of the XSAVE instruction. Therefore, the size of the execution context depends on the requested-feature bitmap (RFBM) used by to XSAVE. All the code in an enclave uses the same RFBM, which is declared in the XFRM enclave attribute. The number of EPC pages reserved for each SSA, specified in SSAFRAMESIZE, must be large enough to fit the XSAVE output for the feature bitmap specified by XFRM. SSAs are stored in regular EPC pages, whose EPCM page type is PT\_REG. Therefore, the SSA contents is accessible to enclave software. This opens up possibilities for an enclave exception handler that is invoked by the host application after a hardware exception occurs, and acts upon the information in a SSA. [](#enclave-lifecycle) Enclave Lifecycle --------------------------------------------- To initialize an enclave, four of the new CPU instructions provided by SGX architecture are used, each will be provided with a wrapper available for developers’ usage (will be explained in sample code): ### [](#ecreate) ECREATE An enclave is born when the system software issues the ECREATE instruction, which turns a free EPC page into the SECS for the new enclave. `ECREATE` copies an SECS structure outside the EPC into an SECS page inside the EPC. The internal structure of SECS is not accessible to software. Software sets the following fields in the source structure: `SECS:BASEADDR`, `SECS:SIZE`, and `ATTRIBUTES`. `ECREATE` validates the information used to initialize the SECS, and results in a page fault or general protection fault if the information is not valid. `ECREATE` will also fault if SECS target page is in use; already valid; outside the EPC; addresses are not aligned; unused `PAGEINFO` fields are not zero. ### [](#eadd) EADD The system software can use `EADD` instructions to load the initial code and data into the enclave. `EADD` is used to create both TCS pages and regular pages. This function copies a source page from non-enclave memory into the EPC, associates the EPC page with an SECS page residing in the EPC, and stores the linear address and security attributes in EPCM. EADD reads its input data from a Page Information (`PAGEINFO`) structure. #### [](#the-pageinfo-structure-contains) The PAGEINFO structure contains: * The virtual address of the EPC page (`LINADDR`) * The virtual address of the non-EPC page whose contents will be copied into the newly allocated EPC page (`SRCPGE`) * A virtual address that resolves to the SECS of the enclave that will own the page (`SECS`). * The virtual address, pointing to a Security Information (`SECINFO`) structure, which contains the newly allocated EPC page’s access permissions (`R, W, X`) and its EPCM page type (`RT_REG` or `PT_TCS`). * EADD validates its inputs, and modifies the newly allocated EPC page and its EPCM entry. EADD ensures that the EPC page is not allocated to another enclave, the page’s virtual address falls within the enclave’s ELRANGE and all the reserved fields in `SECINFO` are set to zero. ### [](#eextend) EEXTEND While loading an enclave, the system software will also use the `EEXTEND` instruction, which updates the enclave’s measurement used in the software attestation process. It updates the MRENCLAVE measurement register of an SECS with the measurement of an EXTEND string composed of `EEXTEND || ENCLAVEOFFSET || PADDING || 256 bytes of the enclave page`. RCX register contains the effective address of the 256 byte region of an EPC page to be measured. ### [](#einit) EINIT This function is the final instruction executed in the enclave build process. After `EINIT`, the `MRENCLAVE` measurement is complete, and the enclave is ready to start user code execution using `EENTER` instruction. When `EINIT` completes successfully, it sets the enclave’s `INIT` attribute to true. This opens the way for ring 3 application software to execute the enclave’s code, using the SGX instructions. On the other hand, once `INIT` is set to true, `EADD` cannot be invoked on that enclave anymore, so the system software must load all the pages that make up the enclave’s initial state before executing the `EINIT` instruction. #### [](#before-jumping-into-design-decisions-there-are-several-terms-need-to-be-clarified-first) Before jumping into design decisions, there are several terms need to be clarified first: * ECALL: “Enclave Call”, a call made into an interface function within the enclave * OCALL: “Out Call”, a call made from within the enclave to the outside application * Trusted: Refers to any code or construct that runs inside an enclave in a “trusted” environment. * Trusted Thread Context: The context for a thread running inside the enclave. This is composed of: * Thread Control Structure (TCS) * Thread Data/Thread Local Storage: data within the enclave and specific to the thread * State Save Area(SSA): a data buffer which holds register state when an enclave must exit due to an interrupt or exception * Stack: a stack located within the enclave * Untrusted: Refers to any code or construct that runs in the applications “untrusted” environment (outside of the enclave). #### [](#this-is-the-general-approach-well-follow-for-designing-an-application-for-intel-sgx) This is the general approach we’ll follow for designing an application for Intel SGX: 1. Identify the application’s secrets. 2. Identify the providers and consumers of those secrets. 3. Determine the enclave boundary. 4. Tailor the application components for the enclave. The first step in designing enclave is to identify the assets it needs to protect, the data structures where the assets are contained, and the set of code that operates on those data structures and then place them into a separate trusted library. It is a required step because enclave code is loaded in a special way such that once the enclave has been initialized, privileged code and the rest of the untrusted application cannot directly read data that resides in the protected environment, or change the behavior of the code within the enclave without detection. After defining the trusted (enclave) and untrusted (application) components of an Intel SGX enabled application, we should carefully define the interface between untrusted application and enclave. An enclave must expose an API for untrusted code to call in (ECALLs) and express what functions provided by the untrusted code are needed (OCALLs). Both ECALLs and OCALLs are defined by developers using **Enclave Definition Language** (EDL), and they together consist the enclave boundary. ### [](#the-enclave-definition-language) The Enclave Definition Language Before moving to the actual enclave code sample, we’ll take a few moments to discuss the Enclave Definition Language (EDL) syntax. An enclave’s bridge functions, both its ECALLs and OCALLs, are prototyped in its EDL file and its general structure is as follows: Copy enclave { // Include files // Import other edl files // Data structure declarations to be used as parameters of the function prototypes in edl trusted { // Include file if any. It will be inserted in the trusted header file (enclave_t.h) // Trusted function prototypes (ECALLs) }; untrusted { // Include file if any. It will be inserted in the untrusted header file (enclave_u.h) // Untrusted function prototypes (OCALLs) }; }; **ECALLs** are prototyped in the trusted section, and **OCALLs** are prototyped in the untrusted section. When the project is built, the Edger8r tool that is included with the Intel SGX SDK parses the EDL file and generates a series of proxy functions. These proxy functions are essentially wrappers around the real functions that are prototyped in the EDL. Each ECALL and OCALL gets a pair of proxy functions: a trusted half and an untrusted half. The trusted functions go into `EnclaveProject_t.h` and `EnclaveProjct_t.c` and are included in the auto-generated Files folder of your enclave project. The untrusted proxies go into `EnclaveProject_u.h` and `EnclaveProject_u.c` and are placed in the auto-generated Files folder of the project that will be interfacing with your enclave. Your program does not call the ECALL and OCALL functions directly; it calls the proxy functions. When you make an ECALL, you call the untrusted proxy function for the ECALL, which in turn calls the trusted proxy function inside the enclave. That proxy then calls the “real” ECALL and the return value propagates back to the untrusted function. This sequence is shown in the figure above. When you make an OCALL, the sequence is reversed: you call the trusted proxy function for the OCALL, which calls an untrusted proxy function outside the enclave that, in turn, invokes the “real” OCALL. More details will be explained in the example code. [](#enclave-example) Enclave Example ----------------------------------------- Now let's start with an enclave Hello world coding example. The `App.h` head file defines the application we are going to create. Here, enclave initialization token is define as the `enclave.token` file and the signed enclave shared object after compilation will be `enclave.signed.so` (line 52, 53). A global `sgx_enclave_id_t` is also declared to uniquely identify the enclave (line 55). Now let's move to `App.cpp`. As it is in the untrusted application, we must include `sgx_urts.h`, the SGX untrusted runtime system, for SGX to work correctly with the application. We also include `Enclave_u.h`, which will include all of the ECALL proxies generated from the EDL file after compilation. Line 48-150 just summarize all the possible error code caused by enclave operation. The critical function here is `initialize_enclave(void)` at line 157. It first retrieves the launch token from previous transactions if available. If not, just use an empty buffer to record it. Then it calls `sgx_create_enclave()` function provided by urts library to officially initialize the enclave instance. The `sgx_create_enclave()` will performs an implicit ECALL. The implicit ECALL initiates enclave runtime initialization flow described in the Enclave Lifecycle tutorial. The actual enclave instance shared object will be saved as `enclave.signed.so`, which is signed by the CPU as indicated by the filename. And the enclave id will be saved in `global_eid` for future access. We can ignore the `ocall_print_string()` function as it was in the original sample code. In the main body of the application, we first initialize the enclave by calling `initialize_enclave()`. Then call our printf\_helloworld() function, which will be discussed later. Finally, we destroy the enclave instance by calling `sgx_destroy_enclave()` provided by urts library. It will perform the implicit ECALL that performs instructions that destroy the targeted enclave. Since our purpose of this example application is to print something from the enclave instead from the untrusted application directly, the enclave part should only contain the function that performs this task. The enclave header file declares the \`printf\_helloworld()\` function, which will be responsible for our purpose. This function call will be protected by the enclave so outside world won't know the secret being processed. But for demonstration purposes, we will just print out the secret from the enclave to the screen by calling this function. We define the `printf_helloworld()` function as a part of the enclave protected code path, which just prints out `Hello World` to the console. In reality, the secret string should be passed into the enclave from outside world, and will be protected by the enclave. Now since the untrusted application cannot access the enclave content directly, in order for the untrusted function to call enclave functions, we have to rely on the assistance of proxy functions, which will be generated by the Edger8r tool from EDL file after compilation. #### [](#the-proxy-functions-are-responsible-for) The proxy functions are responsible for: * Marshaling data into and out of the enclave * Placing the return value of the real ECALL or OCALL in an address referenced by a pointer parameter * Returning the success or failure of the ECALL or OCALL itself as an `sgx_status_t` value Note that this means each ECALL or OCALL has potentially two return values. There’s the success of the ECALL or OCALL itself, meaning, were we able to successfully enter or exit the enclave, and then the return value of the function being called in the ECALL or OCALL. Additional arguments will added to the parameter list for each proxy function and the proxy functions now return a type of `sgx_status_t` instead of the original return types. The first additional parameter is the enclave identifier, eid. The second argument to the proxy function is a pointer to an address that will store the return value from the original enclave function if it has a return value. Since our `printf_helloworld()` function does not have a return value, the proxy function generated for it will look like We can verify that after compiling the whole project. Therefore, in order to let the `Edger8r` generate the corresponding proxy functions, we put our function `printf_helloworld()` in the trusted section of `Enclave.edl`. By now, the whole hello world application has acquired all the required parts and should be ready to go. Then execute the application by typing `./app`. `Hello World` should be printed to the console. And the message is coming form within the enclave to the outside world! We can verify the proxy function generated in `Enclave_u.c` has the signature mentioned above (line 21). Congratulations you have created your first enclave application! [](#references) References: -------------------------------- Code is available under HelloEnclave . It is a simplified version of SampleEnclave example at Linux SGX SDK. Compile the project by typing `make` inside project directory. It should output something like this: [here](https://github.com/sangfansh/SGX101_sample_code.git) [https://eprint.iacr.org/2016/086.pdf](https://eprint.iacr.org/2016/086.pdf) [https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures](https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures) [https://eprint.iacr.org/2016/086.pdf](https://eprint.iacr.org/2016/086.pdf) [https://download.01.org/intel-sgx/linux-2.2/docs/Intel\_SGX\_Developer\_Reference\_Linux\_2.2\_Open\_Source.pdf](https://download.01.org/intel-sgx/linux-2.2/docs/Intel_SGX_Developer_Reference_Linux_2.2_Open_Source.pdf) [https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures](https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures) [https://insujang.github.io/2017-04-05/intel-sgx-instructions-in-enclave-initialization/](https://insujang.github.io/2017-04-05/intel-sgx-instructions-in-enclave-initialization/) [https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures](https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures) [https://software.intel.com/en-us/articles/software-guard-extensions-tutorial-series-part-3](https://software.intel.com/en-us/articles/software-guard-extensions-tutorial-series-part-3) [https://software.intel.com/en-us/articles/intel-software-guard-extensions-tutorial-part-7-refining-the-enclave](https://software.intel.com/en-us/articles/intel-software-guard-extensions-tutorial-part-7-refining-the-enclave) PRM EPCM ELRANGE Enclave Attrbites EPCM Entry SSA lifecycle ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTjk83gXaS9yEV61%252Fenclave1.png%3Falt%3Dmedia%26token%3D3883e8e8-571c-40a5-8e4a-21832e8b0fab&width=768&dpr=4&quality=100&sign=1e03232c&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTjli7ouFVJYH-51%252Fenclave2.png%3Falt%3Dmedia%26token%3D67adf79d-ab86-4315-9906-41fdb2db1d6d&width=768&dpr=4&quality=100&sign=377fd9b6&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTjnTkxqpXi6Iebm%252Fenclave4.png%3Falt%3Dmedia%26token%3D11d48cab-4000-4135-9cbc-b0308866df08&width=768&dpr=4&quality=100&sign=d19768ef&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTjmp1uVWifE157_%252Fenclave3.png%3Falt%3Dmedia%26token%3D6f874702-1682-4afa-a9b8-edc2dba7eb2b&width=768&dpr=4&quality=100&sign=141faaf9&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTjoG4_EwuWo6o_f%252Fenclave5.png%3Falt%3Dmedia%26token%3Dbdfcce07-a229-4f86-bb75-a29b5b516150&width=768&dpr=4&quality=100&sign=9c874cb0&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTjtkkM2XghT30Cc%252Fenclave6.png%3Falt%3Dmedia%26token%3Daf0ca206-958f-4af2-91f2-f67343fda553&width=768&dpr=4&quality=100&sign=6eafc356&sv=2) ![Enclave Example](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTk3obZ-CAucdkpw%252Fenclave_example.png%3Falt%3Dmedia%26token%3D120815b8-563b-4d63-bfad-d1489b7a3707&width=300&dpr=4&quality=100&sign=bede9de9&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBTjw1oiBc_2y0RB2%252Flifecycle.png%3Falt%3Dmedia%26token%3D5b677d8d-7c50-4dc5-9d84-9fa23b718ebd&width=768&dpr=4&quality=100&sign=af96c23c&sv=2) --- # Memory Corruption | SGX 101 [PreviousSGX Security](/sgx101/sgx-security) [NextUninitialized Memory](/sgx101/sgx-security/uninitialized-memory) Last updated 5 years ago Was this helpful? ### [](#introduction) Introduction An SGX program may still suffer from traditional software attacks if the program binary contains vulnerabilities. One type of vulnerabilities is memory corruption that enables control-flow hijacking attacks such as return-oriented programming (ROP) and return-to-libc attacks. This section demonstrates an ROP attack against an enclave and our mitigation (i.e., fine-grained ASLR) against the attack. ### [](#dark-rop) Dark ROP This video shows how the Dark ROP attack detects `memcpy()` and copy the entire memory contents of an enclave to the outside. ### [](#sgx-shield) SGX-Shield This video demonstrates the effectiveness of fine-grained ASLR support of SGX-Shield. --- # SGX Security | SGX 101 [PreviousTechnion'18 Summer School Program](/sgx101/sgx-bootstrap/technion18-summer-school-program) [NextMemory Corruption](/sgx101/sgx-security/memory-corruption) Last updated 5 years ago Was this helpful? Although Intel SGX technology claims to deliver various security promises, which we have gone through in previous sections, it is still vulnerable to certain types of attacks. Recent academic researches have discovered several such vulnerabilities and prove that Intel SGX is **not as secure as we thought**. In this section, explains known security concerns, including cache/branch side-channel attacks and memory safety issues, and corresponding defenses with various working demos. [](#sgx-security-issues-presented-by-taesoo-kim) SGX Security Issues (presented by Taesoo Kim) --------------------------------------------------------------------------------------------------- Slides are available here: [Prof. Taesoo Kim](https://taesoo.kim/) [8MB\ \ security-issues.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVcxBf2zBzuBoSYEE%2Fsecurity-issues.pdf?alt=media&token=1697a6a7-2479-41b5-bc10-aaccd97ac4db) Slides here --- # SGX Bootstrap | SGX 101 [PreviousSSLab](/sgx101/sslab) [NextOverview](/sgx101/sgx-bootstrap/overview) Last updated 5 years ago Was this helpful? [](#contents) Contents --------------------------- ### [](#id-1.-overview) 1. ### [](#id-2.-enclave) 2. ### [](#id-3.-attestation) 3. ### [](#id-4.-sealing) 4. ### [](#id-5.-real-world-example) 5. ### [](#id-6.-security-issues) 6. [](#bonus) Bonus --------------------- * A very good three-day security seminar from . * A must-read overall review of Intel SGX from CCS'17: [Overview](/sgx101/sgx-bootstrap/overview) [Enclave](/sgx101/sgx-bootstrap/enclave) [Attestation](/sgx101/sgx-bootstrap/attestation) [Sealing](/sgx101/sgx-bootstrap/sealing) [Real-world Example](/sgx101/sgx-bootstrap/real-world-example) [Security Issues](/sgx101/sgx-security) [Technion'18 summer school program](/sgx101/sgx-bootstrap/technion18-summer-school-program) [CCS17 Tutorial](/sgx101/sgx-bootstrap/ccs17-tutorial) --- # Technion'18 Summer School Program | SGX 101 [PreviousCCS'17 Tutorial](/sgx101/sgx-bootstrap/ccs17-tutorial) [NextSGX Security](/sgx101/sgx-security) Last updated 5 years ago Was this helpful? During the 7th Summer School on Cyber and Computer Security held by **Technion Insrael Institute of Technology** and **Hiroshi Fujiwara Cyber Security Research Center**, several talks were given on trusted execution and hardware side channels. Talks on day 1 focused mostly on Intel SGX technology. Those from day 2 were more on security issues on trusted execution. On day 3, more side channel related topics were discussed. This page includes selected talks with slides. Original website can be found . Unfortunately, videos of those talks are not available online. [](#day-1) Day 1 --------------------- ### [](#software-guard-extension-from-dream-to-reality) Software Guard Extension – from dream to reality #### [](#speaker-ittai-anati) Speaker: Ittai Anati #### [](#abstract) Abstract: > In 2015, Intel launched its 6th generation Core, codenamed Skylake, that implements a new ISA for security – Intel® SGX. We’ll start with the fundamentals of SGX1, and gradually dive deeper into more advanced topics of SGX. 1. SGX1 fundamentals 2. Advanced SGX1 topics and SGX2 3. Flexible launch control, VMM Oversubscription, key separation and sharing 4. Provisioning, attestation and recovery ### [](#attacks-and-defenses-for-intel-sgx) Attacks and Defenses for Intel SGX #### [](#speaker-taesoo-kim) Speaker: Taesoo Kim #### [](#abstract-1) Abstract: > The Intel Software Guard Extensions (SGX)---a gamechanging feature introduced in the recent Intel Skylake CPU---is a new technology likely to make secure and trustworthy computing in a hostile environment practical. At a high level, SGX consists of a set of new instructions that can be used to create secure regions (i.e., enclaves) to defeat attacks that aim to steal or tamper with the data within an enclave. Without a doubt, we expect that SGX will allow developers to protect sensitive code and data from unauthorized access or modification by software running at higher privilege levels such as an OS or a hypervisor. > > However, SGX is merely a set of instructions; it lacks support from the OS and libraries. These deficiencies allow programmers to easily introduce naive yet preventable bugs that often lead to critical security holes in an enclave program. Further, designing a correct and secure SGX infrastructure is also far from straightforward; enclave programs rely on the support of an underlying OS, but their security models exclude the OS from the TCB. This unconventional dependency makes various attack vectors, which are often considered impractical in a traditional setting, immediate and practical, especially in a cloud environment. > > In this tutorial, I will first provide a security-focused introduction to Intel SGX, including its internal mechanisms to implement the security features. Then, I will explain known security concerns, including recent research outputs from the community: e.g., memory safety issues, cache/branch side-channel attacks, and rowhammer attacks. I will not just only demonstrate these attacks but also guide you to the proper defense mechanisms. [](#day-2) Day 2 --------------------- ### [](#application-oriented-security-secrets-management-and-sidechannel-protection-for-tees) Application-oriented Security: Secrets Management and SideChannel Protection for TEEs #### [](#speaker-christof-fetzer) Speaker: Christof Fetzer #### [](#abstract-2) Abstract: > This tutorial will first introduce the problems one faces when trying to run unmodified applications inside of TEEs. Alternative solutions are presented but the focus will be on the use of cross-compilers and runtime support to execute applications inside of TEEs. We will introduce some example applications running inside of SGX using the SCONE platform. > > Second, we will motivate the need for integrating secrets management and remote attestation. We will motivate the problem of remote attestation and configuration management and show how to solve this. We show how that helps with transparent protection of files and secrets. > > We show how attestation can help to protect against some side-channel attacks. The main focus will, however, on a novel approach to protect against L1/L2-based side channels attacks. ### [](#the-house-is-built-on-sand-exploiting-hardware-glitches-and-side-channels-in-perfect-software) The house is built on sand: exploiting hardware glitches and side channels in perfect software #### [](#speaker-herbert-bos) Speaker: Herbert Bos #### [](#abstract-3) Abstract: > For years, we have tried to address security problems by fixing software bugs and misconfigurations. For critical systems we may even choose to formally verify software to guarantee the absence of bugs. However, the question is whether getting rid of bugs in the software is sufficient. In this talk, I will discuss vulnerabilities in hardware that allow attackers to compromise systems even in the absence of software bugs. In particular, these vulnerabilities offer attackers the read and write primitives needed to leak and modify sensitive information. For the write primitive, we will look at the evolution of the Rowhammer vulnerability in DRAM chips that has matured from a mere curiosity to a serious attack vector across all sorts of systems in just a few years. For read primitives, we will discuss several advanced side channel vulnerabilities, such as found in memory deduplication and Translation Lookaside Buffers. [](#day-3) Day 3 --------------------- ### [](#from-black-to-white-box-attacks-on-secure-systems-or-why-do-your-light-bulbs-need-a-firmware-update) From black to white (box) attacks on secure systems - Or why do your light bulbs need a firmware update #### [](#speaker-eyal-ronen) Speaker: Eyal Ronen #### [](#abstract-4) Abstract: > I will go over the process of RE and attacking the Philips Hue. It is partially based on the IoT Goes Nuclear paper (iotworm.eyalro.net). But I will mostly describe the process of breaking the secure SoC, including what we tried and didn't work. ### [](#side-channel-attacks-on-human-secrets) Side-Channel Attacks on Human Secrets #### [](#speaker-yossi-oren) Speaker: Yossi Oren #### [](#abstract-5) Abstract: > Side-channel analysis techniques have been traditionally applied toward the recovery of computer-related secrets such as cryptographic keys. Humans, however, also share secrets of their own with their computers – for example, their browsing habits, their political or religious beliefs, or sensitive information about their health. This secret information is increasingly vulnerable to emerging low-cost side-channel attacks that are highly scalable, employing malicious peripheral devices or turning components of a system against itself. There are countermeasures which can be applied to protect systems from the theft of human secrets via side channel attacks. These countermeasures, however, have different designs, and exact different costs, than those designed to protect against the theft of cryptographic secrets. ### [](#what-if-your-phones-battery-could-talk-inference-attacks-using-malicious-battery) What if your phone’s battery could talk? Inference attacks using malicious battery #### [](#speaker-mark-silberstein) Speaker: Mark Silberstein #### [](#abstract-6) Abstract: > Mobile devices are equipped with increasingly smart batteries designed to provide responsiveness and extended lifetime. However, such smart batteries may present a threat to users’ privacy. We demonstrate that the phone’s power trace sampled from the battery at 1KHz holds enough information to recover a variety of sensitive information. We show techniques to infer typed characters to reduce the password search space; to accurately recover browsing history in an open-world setup; to reliably detect incoming calls and the photo shots including their lighting conditions. Combined with a novel exfiltration covert channel that allows communication from the battery directly to a remote server without installing software on the phone, these attacks turn the malicious battery into a stealthy surveillance device. We deconstruct the attack by analyzing its robustness to sampling rate and execution conditions, and identify the sources of the information leakage to find the best way to defend against the attacks. We discover that an attacker can distinguish the browsed website by observing the GPU or DRAM power traces alone. However, the CPU and other power-hungry peripherals such as a touch screen are often the primary sources of fine-grain information leakage. We highlight the challenge to defend against the attacks by designing and evaluating several possible mitigation mechanisms. In summary, our work shows the feasibility of the malicious battery and motivates further research into system and application-level defenses to fully mitigate this emerging threat. > > Based on the joint work with Pavel Lifshits and Mohit Tiwari presented at the Symposium on Privacy Enhancement Technologies (2018) [here](http://cyber.technion.ac.il/2018-summer-school-on-cyber-computer-security/2018-summer-school-program/) [2MB\ \ ittai.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVjpj50N1qgAEplQJ%2Fittai.pdf?alt=media&token=ccf7dca6-2b5c-4cd6-81c9-8dded111f1dc) Slides here [7MB\ \ taesoo.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVnqc0yiEhmeE-Bbe%2Ftaesoo.pdf?alt=media&token=b70fbc0c-d842-4e81-830d-dd6c5e3faf03) Slides here [11MB\ \ christof.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVfU8vK6vfYZmv-om%2Fchristof.pdf?alt=media&token=d9050046-7e78-4cf1-80c2-a4e3f3f55e05) Slides here [23MB\ \ herbert.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVhwo0FB9zuXp2wcI%2Fherbert.pdf?alt=media&token=38dbab94-c919-44a0-babb-453569009062) Slides here [9MB\ \ eyal.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVghC15DQbULQLpKd%2Feyal.pdf?alt=media&token=35b1bf33-fa20-48c8-bad6-df69cf4ff16c) Slides here [6MB\ \ yossi.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVpHF19odhfLZZ8YT%2Fyossi.pdf?alt=media&token=3298662d-35e9-44c5-ab78-267b971ef6db) Slides here [5MB\ \ mark.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVl0ueKOsBIc_oCGc%2Fmark.pdf?alt=media&token=8e5f3887-8ef1-4035-bd4d-afd353dc2686) Slides here --- # Overview | SGX 101 [](#background) Background ------------------------------- Modern software applications tend to frequently process user private information such as usernames, passwords, credit records, encryption keys and health records. In most cases, **only designated recipients should be allowed to access this secret data**. The operating system’s duty is to enforce security policies in order to eliminate unintentional leakage of those secrets to other users and applications. For example, the operating system can prevent unauthorized users or applications from accessing other users’ files or other applications’ memory space. The operating system can also restrict unprivileged users from accessing privileged regions such as the OS kernel. At the same time, applications also apply extra protection mechanisms such as data encryption to protect themselves from malicious parties even if the operating system itself is compromised. However, there still persists a significant vulnerability in most of the computer systems. Even though there are numerous protection mechanisms one can apply to enhance security, there is virtually **no strategy to defense a malicious party with administrative privileges**. Such parties have unrestricted access to all system resources and all the running applications. Sophisticated malicious software can bypass protection schemes by extracting encryption keys or even the secret data itself direct from the memory. In order to defense such attacks and offer users higher level of protection of their secret data, Intel designed SGX (Software Guard Extension). In short, Intel SGX offers **an extra set of CPU instructions to create enclaves**, areas that are protected by hardware and ensure confidentiality and integrity even in front of privileged operating systems. [](#introduction) Introduction ----------------------------------- Intel SGX (Software Guard Extension) is a new instruction set in Skylake Intel CPUs since autumn 2015. It provides a reverse sandbox that protects enclaves from: * OS or hypervisor * BIOS, firmware, drivers * System management module (Ring 2) * Intel management engine (ME) * Any remote attack In short, SGX architecture is a hardware-enforced security mechanism that requires **Trusted Computing Base (TCB), Hardware Secrets, Remote Attestation, Sealed Storage and Memory Encryption**. Here, **TCB** will be the CPU’s package boundary and software components related to SGX. **Hardware Secrets** will be two 128-bit keys at production: Root Provisioning Key and Root Seal Key. Notice that RPK is known to Intel and RSK is not, therefore most of the derived keys are based on RSK. We will discuss this later in the tutorial. **Remote Attestation** is enforced for the client to prove to the service provider that an enclave is running a given software, inside a given CPU, with a given security level, for a given Individual Software Vender (ISV). This is required before the service provider decides to provide requested secrets. **Sealed Storage** is required to save secret data to untrusted media. Data and code inside enclaves are not secrets. They are just logics that are required to process the secret and most of them are open sourced or can be reverse engineered. Therefore, secrets are provisioned later by the service provider and should be stored out of the enclave through sealing mechanism when necessary (e.g. for future usage). ### [](#in-summary-intel-sgx-offers-the-following-protections-from-known-hardware-and-software-attacks) In summary, Intel SGX offers the following protections from known hardware and software attacks: * Enclave memory cannot be read or written from outside the enclave regardless of the current privilege level and CPU mode. * Production enclaves cannot be debugged by software or hardware debuggers. * The enclave environment cannot be entered through classic function calls, jumps, register manipulation, or stack manipulation. The only way to call an enclave function is through a new instruction that performs several protection checks. * Enclave memory is encrypted using industry-standard encryption algorithms with replay protection. Tapping the memory or connecting the DRAM modules to another system will yield only encrypted data. * The memory encryption key randomly changes every power cycle. The key is stored within the CPU and is not accessible. * Data isolated within enclaves can only be accessed by code that shares the enclave. As a result, the attack surface can be largely reduced after applying Intel SGX: ### [](#however-there-are-still-several-security-limitation-faced-by-intel-sgx) However, there are still several security limitation faced by Intel SGX: * Cache timing attacks * Physical attacks. E.g. laser fault injection attacks * Microcode malicious patching * Untrusted I/O * Human element. E.g. trusted development environment * CPU bugs and bugs in dependencies. Note that SGX trusted enclaves and microcode can be patched. However, memory encryption crypto cannot be patched since it is fused to hardware. Nevertheless, those security concerns are out of the tutorial's scope. Now let's get started with SGX! [](#get-started) Get Started --------------------------------- Let’s get started by prepare the environment for Intel SGX. Please follow the instructions to get Intel SGX SDK and PSW ready. The **Intel SGX Platform Service (PSW)** is required to run SGX enclaves. It contains drivers, services and Intel privileged enclaves for launch policy enforcement, EPID and remote attestation service and provisioning service. The **Intel SGX SDK** is required to develop SGX enclaves and applications. It contains Intel custom libc and cryptographic libraries, each with 2 versions (debug & release). It also has tools such as `sgx_edger8r` to generate glue code (we will discuss this in the enclave tutorial) and `sgx_sign` to sign enclaves with development key. After all the required libraries are installed, we can start developing applications with SGX in mind! [](#application-design) Application Design ----------------------------------------------- In order to create an application with SGX enabled, we need to establish enclaves, attestation and sealing. ### [](#enclave) Enclave: Application design with Intel SGX requires that the application be divided into two components: * Trusted component: This is the enclave. The code that resides in the trusted code is the code that accesses an application’s secrets. An application can have more than one trusted component/enclave. * Untrusted component: This is the rest of the application and any of its modules. It is important to note that, from the standpoint of an enclave, the OS and the VMM are considered untrusted components. The trusted component should be as small as possible to save more protected memory and reduce attack surface. Meanwhile, enclaves should also have minimal trusted-untrusted component interaction. ### [](#attestation) Attestation: In the Intel SGX architecture, attestation refers to the process of demonstrating that a specific enclave was established on a platform. There are two attestation mechanisms: Local attestation occurs when two enclaves on the same platform authenticate to each other. Remote attestation occurs when an enclave gains the trust of a remote provider. ### [](#sealing) Sealing: Sealing is the process of encrypting data so that it can be written to untrusted memory or storage without revealing its contents. The data can be read back in by the enclave at a later date and unsealed (decrypted). The encryption keys are derived internally on demand and are not exposed to the enclave. #### [](#there-are-two-methods-of-sealing-data) There are two methods of sealing data: * Enclave Identity: This method produces a key that is unique to this exact enclave. * Sealing Identity: This method produces a key that is based on the identity of the enclave’s Sealing Authority. Multiple enclaves from the same signing authority can derive the same key. Now that we have a better understanding of the main structure of an SGX application, we will proceed our tutorial to provide separate detailed explanations of each of the three main components. Each individual discussion of the component will also be followed by an existing code example to help understand implementation details. At the end of the tutorial, we will develop an SGX-enabled application (a password manager). And after that, you should be well equipped with all the necessary knowledge to develop your own SGX-enabled applications! Now let's jump into the heart of SGX, Enclave. [](#references) References: -------------------------------- [PreviousSGX Bootstrap](/sgx101/sgx-bootstrap) [NextEnclave](/sgx101/sgx-bootstrap/enclave) Last updated 2 years ago Was this helpful? Before installing Intel SGX SDK, we have to first purchase an SGX-enabled Skylake CPU. Then SGX option has to be enabled in system BIOS. Finally, the Intel SGX SDK and Platform Software need to be downloaded. This tutorial will be focusing on Intel SGX on Linux using Ubuntu 16.04. SDK is available . [here](https://github.com/intel/linux-sgx) [https://www.blackhat.com/docs/us-16/materials/us-16-Aumasson-SGX-Secure-Enclaves-In-Practice-Security-And-Crypto-Review.pdf](https://www.blackhat.com/docs/us-16/materials/us-16-Aumasson-SGX-Secure-Enclaves-In-Practice-Security-And-Crypto-Review.pdf) [http://www.cs.tau.ac.il/~tromer/istvr1516-files/lecture10-trusted-platform-sgx.pdf](http://www.cs.tau.ac.il/~tromer/istvr1516-files/lecture10-trusted-platform-sgx.pdf) [https://software.intel.com/en-us/articles/intel-software-guard-extensions-tutorial-part-1-foundation](https://software.intel.com/en-us/articles/intel-software-guard-extensions-tutorial-part-1-foundation) [https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures](https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures) [https://download.01.org/intel-sgx/linux-2.2/docs/Intel\_SGX\_Developer\_Guide.pdf](https://download.01.org/intel-sgx/linux-2.2/docs/Intel_SGX_Developer_Guide.pdf) Attack Surface ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmAvzcCRy2rBmqD4JI%252Foverview.png%3Falt%3Dmedia%26token%3D8cc6b471-89cf-475c-9e65-c0a1f26571b8&width=768&dpr=4&quality=100&sign=865e7970&sv=2) --- # CCS'17 Tutorial | SGX 101 [PreviousReal-world Example](/sgx101/sgx-bootstrap/real-world-example) [NextTechnion'18 Summer School Program](/sgx101/sgx-bootstrap/technion18-summer-school-program) Last updated 5 years ago Was this helpful? During CCS 2017, **Taesoo Kim** (Georgia Tech), **Zhiqiang Lin** (UT Dallas) and **Chia-Che Tsai** (Stony Brook University / UC Berkeley) together gave an overall tutorial on Intel SGX technology. The tutorial's contents are well organized and presented by SGX experts in the academia. We believe that this tutorial serves as a perfect entry point to understand the background of SGX technology. This tutorial consists of three parts, including: 1. SGX 101: introduction, performance, and applications 2. SGX shielding framework and development tools 3. SGX Security Issues **Presentation slides and demo videos are available** **.** In this tutorial, **Zhiqiang Lin** first introduced the basic concepts of Intel SGX, its development workflows, potential applications and performance characteristics. Then, **Chia-Che Tsai** introduced various ways to quickly start writing SGX applications, specifically by utilizing library OSes or thin shielding layers; he explained the pros and cons of each approach in terms of security and usability. Last but not least, **Taesoo Kim** explained known security concerns, including cache/branch side-channel attacks and memory safety issues, and corresponding defenses with various working demos. ### [](#sgx-101-introduction-performance-and-applications-zhiqiang-lin) **SGX 101: introduction, performance, and applications (Zhiqiang Lin)** ### [](#sgx-shielding-framework-and-development-tools-chia-che-tsai) **SGX shielding framework and development tools (Chia-Che Tsai)** ### [](#sgx-security-issues-taesoo-kim) **SGX Security Issues (Taesoo Kim)** [](#demo-videos) Demo Videos --------------------------------- ### [](#id-02-demo-libos) 02-demo-libos: #### [](#eleos_memcached_native_sgx) ELEOS\_memcached\_native\_sgx #### [](#eleos_memcached_rpc) ELEOS\_memcached\_rpc #### [](#eleos_memcached_suvm) ELEOS\_memcached\_suvm #### [](#graphene_container_demo) Graphene\_Container\_DEMO #### [](#graphene_edmm_demo) Graphene\_EDMM\_DEMO #### [](#graphene_gcc_demo) Graphene\_GCC\_DEMO #### [](#scone_demo_helloworld) SCONE\_DEMO\_helloworld ### [](#id-03-demo-security) 03-demo-security: #### [](#branch-shadowing) branch-shadowing #### [](#darkrop) darkrop #### [](#sgx-pagetable-attack) sgx-pagetable-attack #### [](#sgx-shield) sgx-shield #### [](#sgxbleed) sgxbleed #### [](#sgxbomb) sgxbomb #### [](#tsgx) tsgx [**here**](https://github.com/sslab-gatech/sgx-tutorial-ccs17) --- # Row Hammer Attacks | SGX 101 [PreviousBranch Shadowing](/sgx101/sgx-security/branch-shadowing) [NextSpeculative Execution Side Channels](/sgx101/sgx-security/speculative-side-channels) Last updated 5 years ago Was this helpful? ### [](#introduction) Introduction Traditional row hammer attacks are also effective on SGX. This section shows an attacker against an enclave that triggers the violation of SGX memory integrity checks and locks down the machine. ### [](#sgx-bomb) SGX-Bomb This video shows how the SGX-Bomb attack locks down a victim machine. ### [](#undefined) --- # Communication between Architectural and Application Enclaves | SGX 101 [](#what-are-architectural-enclaves) What are architectural enclaves? -------------------------------------------------------------------------- In order to allow a secured SGX environment to execute, several Architectural Enclaves (AE) are involved. #### [](#launch-enclave-le) Launch Enclave (LE) Launch Enclave is responsible for assigning `EINITTOKEN` to other enclaves wishing to launch on the platform. It verifies whether the requesting enclave is valid or not by examining the enclave's signature and identity, and generates the `EINITTOKEN` from **Launch Key**, which is only available to Launch Enclave. #### [](#provisioning-enclave-pve) Provisioning Enclave (PvE) The Provisioning Enclave is responsible for retrieving the **Attestation Key** from **Intel Provisioning Service** using the certificate provided by Provisioning Certificate Enclave. #### [](#provisioning-certificate-enclave-pce) Provisioning Certificate Enclave (PcE) Provisioning Certificate Enclave is responsible for signing the processor certificate, which is requested by the provisioning enclave. It signs the certificate using the **Provisioning Key**, which is only available to Provisioning Certificate Enclave. #### [](#quoting-enclave-qe) Quoting Enclave (QE) Quoting Enclave is responsible for providing trust in the enclave identity and its execution environment during remote attestation process. It uses the **Attestation Key** offered by Provisioning Enclave and turns a `REPORT` (locally verifiable) into a `QUOTE` (remotely verifiable). #### [](#platform-service-enclaves-pse) Platform Service Enclaves (PSE) Platform Service Enclaves are responsible for offering other enclaves various trusted services, such as monotonic counters and trusted time, using **Management Engine** (ME). [](#how-do-application-enclaves-communicate-with-architectural-enclaves-to-utilize-sgx-services) How do Application Enclaves communicate with Architectural Enclaves to utilize SGX services? -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Simply put, it is through **Intel SGX AESM**, the Application Enclave Service Manager. In more details, AESM is the system services management agent for SGX enabled applications. Those services include various components of the SGX system, such as launch approval, remote attestation quote signing, etc. They are implemented as Intel provided enclaves, i.e. **Architectural Enclaves** (above mentioned), and access to those enclaves is provided by AESM. `aesmd` provides an untrusted API to communicate with Architectural Enclaves using a domain socket, whose path is hard-coded at `/var/run/aesmd/aesm.socket`. All the messages transmitted between Architectural and Application Enclaves will go through AESM via this socket, and processed accordingly. [](#can-you-provide-an-example) Can you provide an example? ---------------------------------------------------------------- The simplest example will be an SGX Hello World application, as any communication between Architectural and Applications Enclaves requires AESM support, including enclave launch approval. Compile the application with `make`. Trace the execution of the SGX application by command `strace ./app`. From the trace we can see that a connection to `/var/run/aesmd/aesm.socket` is made and a file descriptor is established (`fd == 9` on my execution). Then the interaction between Architecture and Application Enclaves can be examined by looking at the data exchanged through AESM via the domain socket. [](#references) References ------------------------------- [PreviousEnclave](/sgx101/sgx-bootstrap/enclave) [NextAttestation](/sgx101/sgx-bootstrap/attestation) Last updated 5 years ago Was this helpful? AESM is a part of SGX Platform Software, which is included in SGX SDK. Logic related to Architectural Enclaves is under code path , which includes directories of different Architectural Enclaves. contains the AESM management agent, which provides the abstraction to access Architectural Enclaves. AESM runs as a daemon process `aesmd` when the system starts. Let's use the same application for demonstration. [`linux-sgx/psw/ae/`](https://github.com/intel/linux-sgx/tree/master/psw/ae) [`linux-sgx/psw/ae/aesm_service/`](https://github.com/intel/linux-sgx/tree/master/psw/ae/aesm_service) [HelloEnclave](https://github.com/sangfansh/SGX101_sample_code) [https://news.ycombinator.com/item?id=17470715](https://news.ycombinator.com/item?id=17470715) [https://blog.quarkslab.com/overview-of-intel-sgx-part-2-sgx-externals.html](https://blog.quarkslab.com/overview-of-intel-sgx-part-2-sgx-externals.html) [https://davejingtian.org/2017/11/10/some-notes-on-the-monotonic-counter-in-intel-sgx-and-me/](https://davejingtian.org/2017/11/10/some-notes-on-the-monotonic-counter-in-intel-sgx-and-me/) [https://arxiv.org/pdf/1805.05847.pdf](https://arxiv.org/pdf/1805.05847.pdf) Position of AESM ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LiynuicXEm0Oerp3RAd%252F-Liyo5Yuh1Rl920RoRKJ%252FHelloEnclave.png%3Falt%3Dmedia%26token%3Ddf9db65e-943d-4858-9b2e-61f30506d7e2&width=768&dpr=4&quality=100&sign=816b6beb&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LiynuicXEm0Oerp3RAd%252F-LiyoGfrzoJ67zSL7kk-%252Faesm.png%3Falt%3Dmedia%26token%3D0b228f74-2fad-45cc-9743-753caa0a6a96&width=768&dpr=4&quality=100&sign=adfc8264&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LiyooRMS_r00iNgB05h%252F-LiyotNZSrBQx45n9V2I%252Faesm_position.png%3Falt%3Dmedia%26token%3D1192128f-b95c-4650-a9cb-0da719709014&width=768&dpr=4&quality=100&sign=61cee10b&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LiynuicXEm0Oerp3RAd%252F-LiyoCg0n0eiNR91c8L0%252Faesm.socket.png%3Falt%3Dmedia%26token%3D578f652e-b5db-46e9-ba02-dabc7267c175&width=768&dpr=4&quality=100&sign=22d90093&sv=2) --- # Page-table-based Attacks | SGX 101 [PreviousUninitialized Memory](/sgx101/sgx-security/uninitialized-memory) [NextCache Attacks](/sgx101/sgx-security/cache-attack) Last updated 5 years ago Was this helpful? ### [](#introduction) Introduction In addition to traditional software attacks, another well-known attack vector against SGX is side channels. The threat model of SGX, which assumes that even privileged software (e.g., an OS and a hypervisor) is untrusted, enables broader and stronger classes of side channels. This section demonstrates one class of side-channel attacks (i.e., page-table-based attacks) that is unique to the SGX settings and our mitigation against the attacks. ### [](#sgx-page-table-based-attack) SGX page-table-based attack This video presents the page-table-based attack, which is also known as the controlled-channel attack. By manipulating the page table and hooking the page fault handler, the attacker is able to observe precise page access patterns. ### [](#t-sgx) T-SGX This video shows how T-SGX protect an SGX enclave from page-table-based attacks. ### [](#undefined) --- # Real-world Example | SGX 101 [PreviousSealing](/sgx101/sgx-bootstrap/sealing) [NextCCS'17 Tutorial](/sgx101/sgx-bootstrap/ccs17-tutorial) Last updated 5 years ago Was this helpful? Now let’s build a linux version of Password Manager application. Project code is available . Original unmodified version is available . The purpose of this application is to **create a password wallet that can safely store your passwords and display them when requested**. By implementing the wallet with SGX enclave protection, you are guaranteed to be able to securely create a wallet and manage the items inside it. The wallet will be sealed using SGX so that data are protected on disk and unsealed before any operation onto the wallet. Sealed wallet will be saved as filename “wallet.seal”. The application starts with `app/app.cpp`. First we start the application by creating an enclave for future secret operations. After successfully initializing the enclave, we will construct a console interface for users to interact with the application. Here we use `getopt()` to generate a console user interface with various options including: Copy h: help n: create new wallet p: master password c: change master password s: show wallet a: add item x: item’s title y: item’s username z: item’s password r: remove item And exception handling How to use the Command Line Interface: Copy Show help: sgx-wallet -h Show version: sgx-wallet -v Create a new wallet with master-password: sgx-wallet -n master-password Change current master-password to: sgx-wallet -p master-password -c new-master-password Add a new item to the wallet with title, username, and password: sgx-wallet -p master-password -a -x item_title -y item_username -z item_password Remove item at index from the wallet: sgx-wallet -p master-password -r item_index We set flags for each of the operations and perform actions according to the options given by the user. After each interaction with the user, the enclave will be destroyed and the application will safely exit. In this application, a password `Wallet` is just a container of password `Items`. Both `Item` and `Wallet` objects are defined inside `wallet.h`. An Item has a user defined name, a username field and the corresponding password. A Wallet also has a size to indicate the number of Items it has, and a `master_password` which is requested before modifying Wallet contents. Now let’s design the **trusted and untrusted boundary** of the application. In other words, we need to decide which functions will go to the trusted part (run inside enclave) and the untrusted part (run outside enclave). In order to keep the amount of operations inside the enclave **minimal**, we only put functions with sensitive operations inside enclave. In addition, functions that utilizes system calls that are not supported by SGX enclave, such as file IO, will have to be put in the untrusted part and accessed using `OCalls`. We conclude that any operation that is directly related to the wallet itself and the items inside should be put inside the enclave, including creating and showing the wallet, changing the wallet master password, and adding or removing password items. Other operations such as saving the sealed wallet to and loading the wallet form the disk require file IO, which is not supported by SGX enclave, should be put outside the enclave. Therefore, we will provide following functions to the user: Copy trusted { public int ecall_create_wallet(); public int ecall_show_wallet(); public int ecall_change_master_password(); public int ecall_add_item(); public int ecall_remove_item(); }; untrusted { int ocall_save_wallet(); int ocall_load_wallet();r int ocall_is_wallet(); }; The EDL file therefore looks like this: `int ecall_create_wallet(const char* master_password)`: This function will take a user input `master_password` and create an empty `Wallet` for the user if no Wallet has already existed. First it check the master password against the predefined password policy. Then it checks whether a Wallet already exists. If not, a new Wallet object will be initialized with size 0 and the master password provided. Then the wallet is sealed using SGX sealing function and saved to disk as `wallet.seal`. `int ecall_show_wallet(const char* master_password, wallet_t* wallet, size_t wallet_size)`: This function will load the wallet from `wallet.seal` if exists and unseal it inside the enclave. If the master password provided by the user matches the one in the wallet, the wallet will be returned to the untrusted application to display. `int ecall_change_master_password(const char* old_password, const char* new_password)`: This function will take in the old password of the wallet and a new password to update. The new password will first be validated against the password policy. Then the existing wallet will be loaded and unsealed inside the enclave. If the old password matches the one inside the wallet, the password field will be updated with the new password. Finally, the wallet will be sealed again and saved to the disk. `int ecall_add_item(const char* master_password, const item_t* item, const size_t item_size)`: This function will load and unseal the wallet inside the enclave first. Then if the master password matches the one inside the wallet, the new password item provided by the user will be added to the wallet. Finally, the wallet will be sealed again and saved to the disk. `int ecall_remove_item(const char* master_password, const int index)`: The function takes in the master password of the wallet and the index of the item to be deleted from the wallet. First it checks the index provided does not exceed the maximum number of items a wallet can contain. Then it loads and unseals the wallet inside the enclave. If the provided master password matches the one inside the wallet, the item at the given index is removed. Finally the wallet is sealed again and saved to the disk. `int ocall_save_wallet(const uint8_t* sealed_data, const size_t sealed_size)`: This function uses the standard file IO to save the sealed wallet to disk as `wallet.seal`. `int ocall_load_wallet(uint8_t* sealed_data, const size_t sealed_size)`: This function reads in the file `wallet.seal` into the application’s memory. `int ocall_is_wallet(void)`: This function verifies whether a wallet `wallet.seal` already exists on the disk. Other utility functions, such as displaying the wallet with format and providing explanations of the error code, are defined in `app/utils.cpp`. A `show_help` function is also defined here so that when user gives `-h` option in the console interface, a usage guide will be prompted. In order to build and run the password wallet, first `cd sgx-wallet`, then `make`. Type `./sgx-wallet -options` to run the application. Sample output looks like: [here](https://github.com/sangfansh/SGX101_sample_code) [here](https://github.com/asonnino/sgx-wallet) wallet ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmDIa4-4aTre3WdOWx%252Fwallet.png%3Falt%3Dmedia%26token%3De1127241-9202-4383-98bf-c041354f9c73&width=768&dpr=4&quality=100&sign=6582adf3&sv=2) --- # Cache Attacks | SGX 101 ### [](#introduction) Introduction One well-known class of side channels is cache attacks. By exploiting the timing difference between accessing cached and non-cached data, the attacks infer the particular the memory accesses of a victim process by manipulating CPU caches. Because an enclave shares the CPU caches with the rest of system, the enclave is vulnerable to cache attacks by design. Moreover, cache attacks launched by privileged software (under the SGX threat model) are much more powerful (e.g., more accurate) than launched by non-privileged software. [PreviousPage-table-based Attacks](/sgx101/sgx-security/page-table-based-attack) [NextBranch Shadowing](/sgx101/sgx-security/branch-shadowing) Last updated 5 years ago Was this helpful? --- # SSLab | SGX 101 [PreviousHome](/sgx101) [NextSGX Bootstrap](/sgx101/sgx-bootstrap) Last updated 5 years ago Was this helpful? SSLab represents the from Georgia Institute of Technology led by . We have been actively working on SGX related research. These research projects can be broadly classified into three different categories: System Design, Defense, and Attack. [](#system-design) System Design ------------------------------------- * : An open-source platform for SGX research that consists of a QEMU-based emulator and a software development kit (SDK) * S-NFV: A protection scheme for network function virtualization (NFV) applications that uses SGX to secure the applications' internal states * AirBox: A secure design of edge function platforms using SGX for ensuring code integrity and data confidentiality of an edge function * : A design of Tor that enhances the security and privacy of the protocol by utilizing SGX [](#defense) Defense ------------------------- * : A compiler-level approach that incorporates Intel TSX to prevent SGX enclaves from controlled-channel attacks * : A software-based design of SGX enclaves that enables fine-grained address space layout randomization (ASLR) [](#attack) Attack ----------------------- * Branch Shadowing: A novel side-channel attack against SGX exploiting branch history states preserved across an SGX mode switch and last branch record (LBR) * Dark ROP: A novel blind return-oriented programming (ROP) attack against SGX exploiting uninitialized registers across an enclave exit * SGX-Bomb: A rowhammer attack against SGX resulting in processor lockdown, i.e., a cold reboot is necessary to use the machine again * SGX-Bleed: A vulnerability that can leak uninitialized SGX memory through structure padding [](#publications) Publications ----------------------------------- Leaking Uninitialized Secure Enclave Memory via Structure Padding (Extended Abstract, arXiv.org) SGX-Bomb: Locking Down the Processor via Rowhammer Attack (SysTEX 2017) Inferring Fine-grained Control Flow Inside SGX Enclaves with Branch Shadowing (Security 2017) Hacking in Darkness: Return-oriented Programming against Secure Enclaves (Security 2017) Enhancing Security and Privacy of Tor's Ecosystem by using Trusted Execution Environments (NSDI 2017) SGX-Shield: Enabling Address Space Layout Randomization for SGX Programs (NDSS 2017) T-SGX: Eradicating Controlled-Channel Attacks Against Enclave Programs (NDSS 2017) Fast, Scalable and Secure Onloading of Edge Functions using AirBox (SEC 2016) S-NFV: Securing NFV states by using SGX (SDNNFVSEC 2016) OpenSGX: An Open Platform for SGX Research (NDSS 2016) [Systems Software & Security Lab](https://gts3.org/) [Prof. Taesoo Kim](https://taesoo.kim/) [OpenSGX](https://github.com/sslab-gatech/opensgx) [SGX-Tor](https://github.com/kaist-ina/SGX-Tor) [T-SGX](https://github.com/sslab-gatech/t-sgx) [SGX-Shield](https://github.com/jaebaek/SGX-Shield) [\[pdf\]](https://arxiv.org/abs/1710.09061) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2017/jang:sgx-bomb.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2017/lee:sgx-branch-shadow.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2017/lee:darkrop.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2017/kim:sgx-tor.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2017/seo:sgx-shield.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2017/shih:tsgx.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2016/bhardwaj:airbox.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2016/shih:snfv.pdf) [\[pdf\]](https://sslab.gtisc.gatech.edu/assets/papers/2016/jain:opensgx.pdf) --- # Branch Shadowing | SGX 101 [PreviousCache Attacks](/sgx101/sgx-security/cache-attack) [NextRow Hammer Attacks](/sgx101/sgx-security/row-hammer-attack) Last updated 5 years ago Was this helpful? ### [](#introduction) Introduction Another unique class of side-channel attacks in the SGX settings is branch-prediction-based attacks. By exploiting the branch predictor, the attacks infer the states (taken or non-taken) of branches executed by an enclave. This section demonstrates the attack. ### [](#branch-shadowing) Branch Shadowing This video shows how the branch shadowing attack can extract RSA private key bits * Target code: Sliding window exponentiation of **mbedTLS** * Attack code: We modified Linux SGX SDK to run our shadow code * Kernel log: Our attack code prints the output of LBR via `dmesg` ### [](#undefined) --- # Inter-process Local Attestation | SGX 101 [PreviousAttestation](/sgx101/sgx-bootstrap/attestation) [NextSealing](/sgx101/sgx-bootstrap/sealing) Last updated 5 years ago Was this helpful? [](#what-is-this) What is this? ------------------------------------ Intel has provided a nice example of how to perform SGX local attestation among enclaves running in the same process. However, it is not very clear how to perform local attestation among enclaves running in different processes but on the same platform. This example serves the purpose to explain that. [](#recall-local-attestation-flow) Recall Local Attestation Flow --------------------------------------------------------------------- Let's recall how local attestation is performed between two enclaves. Information is borrowed from Intel thread. This figure shows an example flow of how two enclaves on the same platform would authenticate each other. 1. Application A hosts enclave A and application B hosts enclave B. After the **untrusted** applications A and B have established **a communication path** between the two enclaves, enclave B sends its `MRENCLAVE` identity to enclave A. 2. Enclave A asks the hardware to produce a `EREPORT` structure destined for enclave B using the `MRENCLAVE` value it received from enclave B. Enclave A **transmits** its report to enclave B via the **untrusted** application. 3. Once it has received the `EREPORT` from enclave A, enclave B asks the hardware to verify the report to affirm that enclave A is on the same platform as enclave B. Enclave B can then reciprocate by creating its own `EREPORT` for enclave A, by using the `MRENCLAVE` value from the report it just received. Enclave B **transmits** its report to enclave A. 4. Enclave A then verifies the report to affirm that enclave B exists on the same platform as enclave A. [](#intra-process-local-attestation) Intra-process Local Attestation ------------------------------------------------------------------------- If two enclaves are within different application processes, they will not be able to access each other's attestation-handling APIs. Therefore, the **untrusted communication path** requires an extra layer of indirection, which can be IPC, TLS, etc. Extra data transmission logics will need to be added to the untrusted applications in order to pass necessary data structures for ECDH and attestation process. At the end of inter-process local attestation, we should reach the same points as intra-process local attestation, i.e. a shared EDCH secret generated from SGX keys for secured future communication between two enclaves, and mutual identity verification of each other. [](#reference-implementation) Reference Implementation ----------------------------------------------------------- In this example, the **untrusted communication path** between two enclaves from two application processes is established using IPC (shared memory). To run the example, compile both in two terminal sessions using `make`. Then run Enclave1 first using `./Enclave1/app` followed by Enclave2 by executing `./Enclave2/app` in two separate terminal sessions. We can examine the inter-process local attestation by monitoring the dynamic output, which looks like this eventually: ### [](#walk-through) Walk-through In the example, Enclave1 is the attestation **initiator** and Enclave2 is the attestation **responder**. Some potential confusions to clarify first: In both Enclave1 and Enclave2 directories, the original folders of three enclaves still exist. However, **only** _Enclave1_ (Enclave1/Enclave1 and Enclave2/Enclave1) is used in the two processes as the enclaves within. The high-level interaction between the enclaved from two processes are self-explanatory from the outputs (screenshots above). But I will provide a detailed walk-through of the function calls involved and hope it helps to understand the overall approach better. #### [](#id-1.-enclave1-initializes-an-edch-session-as-the-initiator) 1\. Enclave1 initializes an EDCH session as the initiator Enclave1 calls `sgx_dh_init_session(SGX_DH_SESSION_INITIATOR, &sgx_dh_session)` inside the enclave to initialize a new ECDH session as the initiator. Then Enclave enters `session_request_ocall()` to wait for Enclave2 to initialize and transmit the new **SessionID** and **message 1** via the **untrusted** shared memory. #### [](#id-2.-enclave2-initializes-an-edch-session-as-the-responder) 2\. Enclave2 initializes an EDCH session as the responder Enclave2 calls `sgx_dh_init_session(SGX_DH_SESSION_RESPONDER, &sgx_dh_session)` inside the enclave to initialize a new ECDH session as the responder. It then generates a new SessionID using `generate_session_id(&session_id)`. Enclave2 also creates message 1 using `sgx_dh_responder_gen_msg1((sgx_dh_msg1_t*)&dh_msg1, &sgx_dh_session)`. Message 1 contains the **report** of Enclave2 targeting Enclave1 to obtain `target_info`. Finally, Enclave2 calls `session_reques_ocall()`, in which it passes the SessionID and message 1 to untrusted shared memory for Enclave1 to process. Enclave2 waits for message 2 from Enclave1 to further proceed. #### [](#id-3.-enclave1-processes-message-1-from-enclave2) 3\. Enclave1 processes message 1 from Enclave2 Enclave1 process message 1 using `sgx_dh_initiator_proc_msg1(&dh_msg1, &dh_msg2, &sgx_dh_session)`. When message 1 is being processed, a shared ECDH key is computed and is embedded in message 2 for Enclave2. Message 2 also contains the report of Enclave1 targeting Enclave2 for verification. Message 2 is passed to shared memory inside `exchange_report_ocall()` and Enclave1 then waits for Enclave2 to process message 2 and generate message 3. #### [](#id-4.-enclave2-processes-message-2-from-enclave1) 4\. Enclave2 processes message 2 from Enclave1 Enclave2 retrieves message 2 from Enclave1 inside `exchange_report_ocall()`. It then processes message 2 to get the shared ECDH key and verifies report of Enclave1 by calling `sgx_dh_responder_proc_msg2(&dh_msg2, &dh_msg3, &sgx_dh_session, &dh_aek, &initiator_identity)`. Message 3 is generated as a result and is passed to shared memory by calling `exchange_report_ocall()` again. A report of Enclave2 targeting Enclave1 is embedded in message 2 for verification. #### [](#id-5.-enclave1-processes-message-3-from-enclave2) 5\. Enclave1 processes message 3 from Enclave2 Enclave1 retrieves message 3 inside `exchange_report_ocall()` from shared memory after waiting for Enclave2 to process. It then verifies the report of Enclave2 by calling `sgx_dh_initiator_proc_msg3(&dh_msg3, &sgx_dh_session, &dh_aek, &responder_identity)` and obtains the final shared ECDH key. #### [](#id-6.-end-of-local-attestation) 6\. End of local attestation At the end of exchanging and processing of the three messages above, the two enclaves from two processes have verified the trust of each other, and shared a secret ECDH key for future communication session. ### [](#todo) TODO 1. The example has only integrated shared memory for passing data (IPC). Messages are demultiplexed using `sleep()` (e.g. Enclave2 `sleep(5)` ) to wait for message 2 after sending message 1 to Enclave1. A better approach (e.g. message queue) needs to be integrated to synchronize messages. 2. Need to remove extra enclaves and cleanup legacy code not related to inter-process local attestation. **Note that** the **untrusted communication path** highlight above varies depending on whether the local attestation is intra-process or inter-process. In the provided by Intel SGX SDK, three enclaves are within the same application process, i.e. **intra-process**. Required data structures are being passed around by **ecalling into the destination enclave** with the destination enclave EnclaveID. Example code is available . The reference example is based on the from Intel SGX SDK, with an extra layer of IPC for passing required data structures using shared memory between two processes. [Local Attestation Sample Code](https://github.com/intel/linux-sgx/tree/master/SampleCode/LocalAttestation) [here](https://github.com/sangfansh/SGX101_sample_code/tree/master/ProcessLocalAttestation) [Local Attestation Sample Code](https://github.com/intel/linux-sgx/tree/master/SampleCode/LocalAttestation) [this](https://software.intel.com/en-us/node/702983) Enclave1 Enclave2 ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LhhJjEW6KpUr6O6ktt0%252Fuploads%252Fgit-blob-71376b4ab02d1a3201ca31ab922bf2570cbef7b3%252Flocal_attestation.png%3Falt%3Dmedia&width=768&dpr=4&quality=100&sign=b127573c&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LjIUJ0TXIAqcDZRrCqz%252F-LjIaKdCAuDASXMWA4tw%252Fenclave1.png%3Falt%3Dmedia%26token%3D70d4c0e6-663a-4e5d-9487-9746108bef21&width=768&dpr=4&quality=100&sign=97143d60&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LjIUJ0TXIAqcDZRrCqz%252F-LjIaPRkxkXIQTS0o39L%252Fenclave2.png%3Falt%3Dmedia%26token%3D7c2040c3-a902-4d4f-92b9-166b9e29ddfb&width=768&dpr=4&quality=100&sign=d971a4f&sv=2) --- # About Us | SGX 101 [PreviousOther Resources](/sgx101/resources) Last updated 5 years ago Was this helpful? [](#systems-software-and-security-lab) Systems Software & Security Lab --------------------------------------------------------------------------- We build practical systems with focuses on security, performance, robustness, or often just for fun. Our research projects have been published in top academic conferences, and have made great impacts on real programs, such as Firefox, Android, and the Linux kernel, that you might be using every day. If you are interested in hacking with us, please drop us an email via . [](#location) Location --------------------------- Klaus Advanced Computing Building, 266 Ferst Dr NW, Atlanta GA 30332-0765 [](#more) More ------------------- For more information, please visit . [sslab@cc.gatech.edu](mailto:sslab@cc.gatech.edu) [(map)](http://goo.gl/maps/1gbI8) [gts3.org](https://gts3.org/) --- # Uninitialized Memory | SGX 101 [PreviousMemory Corruption](/sgx101/sgx-security/memory-corruption) [NextPage-table-based Attacks](/sgx101/sgx-security/page-table-based-attack) Last updated 5 years ago Was this helpful? ### [](#introduction) Introduction Another type of vulnerabilities is uninitialized memory that may allow untrusted host (i.e., the OS) to infer the data inside an enclave. ### [](#sgx-bleed) SGX-Bleed This video shows how the SGX-Bleed problem leaks uninitialized SGX memory via structure padding. --- # Other Resources | SGX 101 [PreviousSpeculative Execution Side Channels](/sgx101/sgx-security/speculative-side-channels) [NextAbout Us](/sgx101/about-us) Last updated 5 years ago Was this helpful? [](#from-intel) From Intel ------------------------------- * . * is a comprehensive introduction of SGX presented by Dror Caspi from Intel in Israel Institute of Technology. * is a set of tutorial blogs provided by Intel, which is focused on developing SGX applications for Windows platform. * provides the overview of the instructions and data structures used in SGX. It's useful as a reference for technical terms. * explains the Remote Attestation code example provided by Intel. Note that the code example from SGX SDK does not include the actual provisioning process with Intel Attestation Service. * is the initial white paper for the attestation and sealing techniques now offered by SGX. * provides the reference on how to interact with Intel Attestation Service using RESTful API. * is the initial paper from Intel that proposes Enhanced Privacy ID, the anonymous attestation scheme that is adopted by Intel Attestation Service. * introcudes how to use remote attestation to achieve a TLS connection. * introduces the primitives associated with SGX sealing process. are also available from SGX developer guide. [](#from-others) From Others --------------------------------- * is a comprehensive introduction to the technology, including the architecture background and the implementation. A must-have. * is the dissertation for MS degree by Alon Jackson. It offers an extensive description of the SGX ecosystem and evaluations of SGX security guarentees. * is a review slides of the technology during BlackHat 2016. is the corresponding review paper. * is another good intruduction slides from Tel Aviv University. * is a blog that explores and explains the implementation details of SGX enclave initialization very well. * is a report from University of Tartu that gives a good high level explanation of attestation process. * is a blog that explains the details of SGX sealing process very well. [](#papers) Papers ----------------------- Below are the best places to keep track of SGX related research papers for general purposes: [](#useful) Useful ----------------------- Other useful recources: A well categorized SGX reading list. [SGX developer guide from Intel](https://software.intel.com/en-us/documentation/sgx-developer-guide) [This](http://tce.webee.eedev.technion.ac.il/wp-content/uploads/sites/8/2015/10/SGX-for-Technion-TCE.pdf) [Introducing the Intel® Software Guard Extensions Tutorial Series](https://software.intel.com/en-us/articles/introducing-the-intel-software-guard-extensions-tutorial-series) [This blog form Intel](https://software.intel.com/en-us/blogs/2016/06/10/overview-of-intel-software-guard-extensions-instructions-and-data-structures) [This blog from Intel](https://software.intel.com/en-us/articles/code-sample-intel-software-guard-extensions-remote-attestation-end-to-end-example) [Innovative Technology for CPU Based Attestation and Sealing](https://software.intel.com/en-us/articles/innovative-technology-for-cpu-based-attestation-and-sealing) [Attestation Service for Intel® Software Guard Extensions (Intel® SGX): API Documentation](https://software.intel.com/sites/default/files/managed/7e/3b/ias-api-spec.pdf) [Enhanced Privacy ID: A Direct Anonymous Attestation Scheme with Enhanced Revocation Capabilities](https://eprint.iacr.org/2007/194.pdf) [Integrating Remote Attestation with Transport Layer Security](https://arxiv.org/pdf/1801.05863.pdf) [This blog from Intel](https://eprint.iacr.org/2016/086.pdf) [More details](https://software.intel.com/en-us/node/702997) [Intel SGX Explained](https://eprint.iacr.org/2016/086.pdf) [Trust is in the Keys of the Beholder: Extending SGX Autonomy and Anonymity](https://www.idc.ac.il/en/schools/cs/research/Documents/jackson-msc-thesis.pdf) [SGX Secure Enclaves in Practice](https://www.blackhat.com/docs/us-16/materials/us-16-Aumasson-SGX-Secure-Enclaves-In-Practice-Security-And-Crypto-Review.pdf) [This](https://github.com/kudelskisecurity/sgxfun/blob/master/paper/sgxpaper.md) [Information Security – Theory vs. Reality](http://www.cs.tau.ac.il/~tromer/istvr1516-files/lecture10-trusted-platform-sgx.pdf) [Intel SGX Instructions in Enclave Initialization](https://insujang.github.io/2017-04-05/intel-sgx-instructions-in-enclave-initialization/) [SGX attestation process](https://courses.cs.ut.ee/MTAT.07.022/2017_spring/uploads/Main/hiie-report-s16-17.pdf) [Intel SGX Sealing](https://insujang.github.io/2017-10-09/intel-sgx-sealing/) [SGX Reading List](http://ina.kaist.ac.kr/~dongsuh/SGXReadingList.html) [An up-to-date list of system papers related to Intel SGX](https://github.com/vschiavoni/sgx-papers) [A list of hardwares that support Intel SGX](https://github.com/ayeks/SGX-hardware) [Command-line tools to analyze SGX related binaries](https://github.com/kudelskisecurity/sgxfun) --- # Attestation | SGX 101 [PreviousCommunication between Architectural and Application Enclaves](/sgx101/sgx-bootstrap/enclave/interaction-between-pse-and-application-enclaves) [NextInter-process Local Attestation](/sgx101/sgx-bootstrap/attestation/inter-process-local-attestation) Last updated 2 years ago Was this helpful? Sometimes enclaves need to collaborate with other enclaves on the same platform due to different reasons such as data exchange if the enclave is too small to hold all the information, or communication with Intel reserved enclaves to conduct specific Intel services. Therefore, the two exchanging enclaves have to prove to each other that they can be trusted. In other scenarios when an SGX enabled ISV client requests secrets from its ISV client, password management service for example, the client have to prove to the server that the client application is running on a trusted platform that can process the secrets securely. Both of those two conditions require a proof of secured execution environment, and Intel SGX refers to this proving process as attestation. There are two types of attestation with respect to the two above mentioned scenarios: **Local Attestation** and **Remote Attestation**. The successful result of local attestation provides an authenticated assertion between two enclaves running on the same platform that they can trust each other and exchange information safely, while remote attestation provides this kind of verification for the ISV client to the server so that ISV server can confidently provides the client with the secrets it requested. Before diving into the details of attestation, we need to clarify some required instructions and data. [](#device-root-keys) Device Root Keys ------------------------------------------- There are two device root keys that are fused to SGX CPU at production. ### [](#root-provisioning-key-rpk) Root Provisioning Key (RPK) This key is randomly generated on a dedicated Hardware Security Module (HSM) within a special purpose facility called Intel Key Generation Facility (iKGF) which is guaranteed to be a well-guarded offline production facility. Intel is also responsible for maintaining a database of all keys ever produced by the HSM. RPKs are delivered out to different factory facilities, named by Intel’s formal publications as the “high volume manufacturing system”, to be integrated into processors’ fuses. Intel stores all RPKs as they are the basis of how SGX processors demonstrate their genuineness through an online provisioning protocol. For this reason, the iKGF also forwards different derivations of each RPK to Intel’s online servers. ### [](#root-sealing-key-rsk) Root Sealing Key (RSK) This key is randomly generated automatically inside the CPU during production to be statistically different from part to part. Intel declares that it attempts to erase all production lines residues of this key so that each platform should assume that its RSK value is both unique and known only to itself. Most of the keys provided by enclave’s trusted interface base their derivation on platform’s RSK so that no other parties can known the keys. [](#enclave-measurement-aka-software-tcb) Enclave Measurement (aka Software TCB): -------------------------------------------------------------------------------------- #### [](#when-an-enclave-is-built-and-initialized-intel-sgx-will-generate-a-cryptographic-log-of-all-the-buil) When an enclave is built and initialized, Intel SGX will generate a cryptographic log of all the build activities, including: * Content: code, data, stack, heap * Location of each page within the enclave * Security flags being used The “Enclave Identity”, which is a 256-bit hash digest of the log, is stored as MRENCLAVE as the enclave’s software TCB. In order to verify the software TCB, one should first securely obtain the enclave’s software TCB, then securely obtain the expected enclave’s software TCB and compare those two values. [](#two-user-instructions) Two user instructions: ------------------------------------------------------ ### [](#report-contains-following-data) REPORT Contains following data: * Measurement of the code and data in the enclave. * A hash of the public key in the ISV certificate presented at enclave initialization time. * User data. * Other security related state information (not described here). * A signature block over the above data, which can be verified by the same platform that produced the report. ### [](#ereport) `EREPORT` This instruction generates a cryptographic structure, called REPORT, that binds `MRENCLAVE` to the target enclave’s REPORT KEY. ### [](#report-key) `REPORT KEY` Used by EREPORT to sign all reports generated on that specific platform and destined that for that enclave. ### [](#egetkey) `EGETKEY` Enclaves can use EGETKEY instruction to get derivatives of device keys. `EGETKEY` produces symmetric keys for different purposes depending on invoking enclave attributes and the requested key type. There are five different key types. Two are sealing and report keys available for all enclave. The rest are limited only to SGX architectural enclaves. `EGETKEY` uses Security Version Number (SVN) specified by the requesting enclave to define requested key characteristics. CPU SVN to reflect processor microcode version, or ISV SVN to reflect enclave software version. `EGETKEY` checks these values against those stored in `SIGSTRUCT` and only allows to obtain keys with SVN values lower or equal to those of the invoking enclave so that upgraded versions of the same software can retrieve keys created by former versions. ### [](#sigstruct) `SIGSTRUCT` Enclaves’ certificate is called `SIGSTRUCT` and is a mandatory supplement for launching any enclave. The `SIGSTRUCT` holds enclave’s `MRENCLAVE` together with other enclave attributes. `SIGSTRUCT`s are signed by the ISV with its private key, which was originally signed by an SGX launch authority. Intel is considered the primary enclave launch authority, however other entities can be trusted by the platform owner to authorize launching of enclaves. The respected launch authority is specified by its public key hash signed by Intel and stored on the platform. We start with clarifying the process of local attestation and then remote attestation. [](#local-attestation) Local Attestation --------------------------------------------- Before multiple enclaves collaborate with each other on the same platform, one enclave will have to authenticate the other locally using Intel SGX Report mechanism to verify that the counterpart is running on the same TCB platform by applying the `REPORT` based Diffie-Hellman Key Exchange. This procedure is referred as local attestation by Intel. The successful result of local attestation will offer a protected channel between two local enclaves with guarantee of confidentiality, integrity and replay protection. ### [](#local-attestation-abstract) Local Attestation Abstract: 1. There are two enclaves on the same platform, referred to as Enclave A and Enclave B. We assume they have established a communication path between each other, and the path doesn’t need to be trusted. W.l.o.g we assume B is asking A to prove it’s running on the same platform as B. 2. First, B retrieves its `MRENCLAVE` value and sends it to A via the untrusted channel. 3. A uses `EREPORT` instruction to produce a report for B using B’s `MRENCLAVE`. Then A sends this report back to B. A can also include Diffie-Hellman Key Exchange data in the `REPORT` as user data for trusted channel creation in the future. 4. After B receives the `REPORT` from A, B calls `EGETKEY` instruction to get `REPORT` KEY to verify the `REPORT`. If the `REPORT` can be verified with the REPORT KEY, then B assures that A is on the same platform as B because the REPORT KEY is specific to the platform. 5. Then B use the `MRENCLAVE` received from A’s `REPORT` to create another `REPORT` for A and sends the `REPORT` to A. 6. A then also can do the same as step 4 to verity B is on the same platform as A. 7. By utilizing the user data field of the `REPORT`, A and B can create a secure channel using Diffie-Hellman Key Exchange. Information exchange can be encrypted by the shared symmetric key. [](#remote-attestation-primitives) Remote Attestation Primitives --------------------------------------------------------------------- This section introduces the design details of the remote attestation service provided by Intel. ### [](#overall-view-of-intel-sgx-infrastructure-services) Overall View of Intel SGX Infrastructure Services ### [](#platform-provisioning) Platform Provisioning In order to transform a local REPORT into a remotely verifiable `QUOTE`, Quoting Enclave uses a platform unique asymmetric attestation key. The `QUOTE` can then be verified by a remote party using the corresponding public key. So how does QE obtain this attestation key in the first place? In this tutorial we explain the provisioning process in which an SGX platform receives its remote attestation key. Provisioning is the process by which an SGX device demonstrates to Intel its authenticity as well as its CPU SVN and other system components attributes, in order to receive an appropriate attestation key reflecting its SGX genuinely and TCB version. Normally, provisioning is done during platform initial setup phase, but re-provisioning can also be performed after purchase due to update to crucial system components such as firmware, BIOS or microcode due to vulnerabilities. In such cases, the attestation key may be replaced to reflect platform renewed TCB security level. Attestation key is the core asset in the SGX ecosystem. Relying parties trust valid attestation signatures as an Intel signed certificate that guarantees the platform’s authenticity. In order to facilitate SGX provisioning services, Intel operates a dedicated online provisioning infrastructure. SGX provisioning and remote attestation protocol follows a group signature scheme developed by Intel called Enhanced Privacy ID (EPID). To implement the EPID provisioning process Intel provides an architectural enclave called the Provisioning Enclave (PvE). ### [](#provisioning-enclave-pve) Provisioning Enclave (PvE) The PvE is responsible for conducting the provisioning process on the platform against Intel’s online provisioning servers. In this process PvE demonstrates that is has a key that Intel put in a real SGX processor and in return, is provisioned with a unique platform attestation for future remote attestations. Both sides implement the EPID scheme join protocol; the PvE functions as a new joining member and Intel as the group membership issuer that issues new group membership credentials. PvE proves its authenticity by using several SGX privileged key types which are accessible through EGETKEY instruction only by SGX architectural enclaves. Two of those keys are Provisioning Key (PK) and Provisioning Seal Key (PSK). The uniqueness of PvE and QE is based on their SIGSTRUCT certificates signed by Intel (MRSIGNER). Those enclaves are thus authorized to launch with privileged attributes in order to later obtain special keys by executing EGETKEY instruction. Two phases are involved in the derivation process of PK. First, bind Root Provisioning Key to HW TCB. TCB key occurs during processors boot time by looping over PRF with the current platform SVN patch level which reflects platform’s firmware components. Second, add SW properties to the resulting PK. It occurs when EGETKEY is called and uses the TCB key as basis for derivation. PvE’s software elements are reflected by EGETKEY input parameters. Root Signing Key and Owner Epoch value are ignored in this case to render the same platform-specific key regardless of its current owner. The resulting PK is then a unique key that reflects both HW and SW components of the SGX platform. This process also minimizes the exposure of Root Provisioning Key. ### [](#provisioning-protocol) Provisioning Protocol After getting the PK, the platform can start the provisioning process to get the attestation key. #### [](#id-1.-enclave-hello) 1\. Enclave Hello Once we have TCB specific PK, PvE generates two values to initiate the provisioning protocol. The first is a hash of the PK called Platform Provisioning ID (PPID). The second reflects the claimed TCB level based on current SVN. Both encrypted using IPS’s public key and sent to IPS. #### [](#id-2.-server-challenge) 2\. Server Challenge Intel uses PPID to determine whether the platform has been previously provisioned. If so, an encrypted version of a previously generated attestation key is added to the server’s challenge. If not, the server determines the EPID group for that platform, and adds the EPID group parameters together with a liveliness nonce and a pre-computed TCB challenge to the message sent back to the platform. Since all RPKs are stored by the offline Intel Key Generation Facility (iKGF), it can perform the same hardware and software TCB specific derivation process as performed by the PvE using EGETKEY (how to get SW attributes?) on every SGX device to produce its own provisioning key (how to know which SGX is which?). This PK is used to encrypt a random value to generate a platform specific TCB challenge. All pre-computed challenges are sent to Intel’s online servers to support the provisioning protocol. #### [](#id-3.-enclave-response) 3\. Enclave Response After PvE decrypts the TCB challenge with its PK, it uses it to generate a TCB proof by using the TCB challenge as a key to CMAC the nonce received from Intel. Next, PvE generates a random EPID membership key and hides it mathematically according to EPID protocol so that IPS cannot learn the membership key. To facilitate future attestation key retrieval service, the non-hidden membership key is encrypted by PvE using another special key, PSK. PSK derivation does not include the Owner Epoch and uses RSK as the root key for derivation. The PSK thus is not affected by the platform changing owners, and is exclusive to that specific platform. If the platform has been formerly provisioned and the ongoing protocol is an attestation key retrieval or TCB update, the platform has to prove that it has never been revoked in the past. This is achieved by using PSK to decrypt the backed up attestation key copies obtained from the server, and using them to sign a selected message chosen by Intel. Both the hidden and the encrypted EPID membership keys are sent, together with the TCB and non-revoked proofs. #### [](#id-4.-completion) 4\. Completion After receiving the response, IPS first validates the TCB proof using the value received from iKGF and continues the EPID Join protocol on success. The hidden membership key is processed to create a unique certificate signed with the EPID group issuer key and stored together with the encrypted membership key for future re-provisioning events. The final message completing the protocol is then sent by the server containing the signed certificate. Platform’s membership key together with the matching signed certificate form a unique EPID private key. Since the attestation key is constructed collaboratively by both parties, no one can forge a valid membership signature produced by the platform. #### [](#id-5.-final) 5\. Final PvE encrypts the attestation key with PSK and stores on the platform for future use. Since EPID groups are categorized according to TCB levels, EPID signature can thus be user to represent both platform’s SGX genuineness and its TCB level. [](#remote-attestation-process) Remote Attestation Process --------------------------------------------------------------- Generally speaking, the goal of Remote Attestation is for a Hardware entity or a combination of Hardware and Software to gain the trust of a remote service provider, such that the service provider can confidently provide the client with the secrets requested. With Intel SGX, Remote Attestation software includes the application’s enclave, and the Intel-provided Quoting Enclave (QE) and Provisioning Enclave (PvE). The attestation Hardware is the Intel SGX enabled CPU. Remote attestation provides verification for three things: the application’s identity, its intactness (that it has not been tampered with), and that it is running securely within an enclave on an Intel SGX enabled platform. ### [](#sigma-protocol) Sigma protocol Sigma is a protocol that includes a **Diffie-Hellman key exchange**, but also addresses the weaknesses of DH. The protocol Intel SGX uses differs from the regular Sigma protocol in that the Intel SGX platform uses Intel EPID to authenticate while the service provider uses Public Key Infrastructure (in regular Sigma, both parties use PKI). Finally, the Key Exchange libraries require the service provider to use an ECDSA, not an RSA, key pair in the authentication portion of the protocol and the libraries use ECDH for the actual key exchange. As a result of this exchange between the client and the service provider, a shared key between the enclave and the challenger is produced that can be used for encrypting secrets that are to be provisioned in the enclave. Once inside the enclave, these secrets could then be decrypted by the application. ### [](#diffie-hellman-key-exchange-dhke) Diffie-Hellman Key Exchange (DHKE) A method for exchanging keys over a public channel without leaking the actual key to other listeners. The cryptographic algorithm is explained here. ### [](#intel-enhanced-privacy-id-epid) Intel Enhanced Privacy ID (EPID) It is an extension to an existing Direct Anonymous Attestation (DAA) scheme with some additions, for example the use of SigRL (Signature Revocation List). EPID enables signing objects without leaving a trace that can be uniquely backtracked to the signer, making the signing process anonymous. This is done by dividing signers to groups (also known as EPID groups), based on their processor type. This way they create signatures with their own secret keys, but the signatures can be verified only with the public key of the group they belong to, making it possible to check that the signer belongs to the right group, but impossible to uniquely identify the signer. ### [](#revocation-lists) Revocation Lists SGX facilitates three types of Revocation Lists (RLs): Group-RL which holds all revoked EPID groups, Priv-RL listing all revoked private-keys of the same EPID group, and Sig-RL that lists tuples of a basename and its corresponding signature of all revoked members in the same EPID group. ### [](#trusted-computing-base-tcb) Trusted Computing Base (TCB) An entity responsible for protecting the secret provisioned to the enclave (both software and hardware). ### [](#quoting-enclave-qe) Quoting Enclave (QE) A special enclave on every SQX processor and is tasked entirely with handling the remote attestation. It receives REPORTs from other enclaves, verifies them and signs them with the attestation key before returning the result, also known as a QUOTE, to the application. ### [](#sgx-service-providers) SGX Service Providers Relying parties are referred to as service providers and do not have to hold SGX enabled hardware. Service providers are expected to register to the IAS and meet a set of Intel defined requirements in order to submit attestation evidence for IAS verification. This registration binds service providers’ Transport Layer Security (TLS) certificate to a unique Service Provider ID (SPID), and permits access to the IAS services. Some of these main IAS services are: verifying ISV enclave Quotes, requesting updated attestation revocation lists and retrieving the assertion information history associated with a Quote. ### [](#remote-attestation-modes) Remote Attestation Modes The QE supports two Quote signature modes with different link-ability properties, Fully-anonymous and Pseudonymous Quotes. The link-ability property of a Quote is determined by a basename parameter signed using platform’s unique attestation key. Using the same attestation key to sign the same basename parameter multiple times yields pseudonymous Quotes that are easily linkable. This mode is used by service providers to keep track of revisiting users and protect against sybil attacks, while preserving user’s privacy. When a pseudonymous Quote is used, the IAS first validates that the basename used is associated to that specific service provider. This role of the IAS enforces user’s pseudonymous separation between different service providers. In contrast, by signing multiple signatures on different basenames, it is computationally infeasible to determine whether the Quotes were produced using the same attestation key or not, thus preserving platform’s anonymity. Therefore random basenames are used by the QE to sign Fully-anonymous Quotes. ### [](#remote-attestation-abstract) Remote Attestation Abstract For remote attestation, both symmetric and asymmetric key systems are used. The symmetric key system is used in local attestation with only the quoting enclave and the EREPORT instruction having access to the authentication key. Asymmetric key system is used for creating an attestation that can be verified from other platforms. The attestation key itself is asymmetric (EPID keys). #### [](#there-are-mainly-three-platforms-involved-in-remote-attestation) There are mainly three platforms involved in Remote Attestation: * The service provider (challenger) * The application with its enclave and its QE * Intel Attestation Service (IAS) that verifies the enclave Stages ### [](#detailed-stages) Detailed Stages 1. At first, the ISV enclave sends out an initial request to the remote service provider, which includes the **EPID group** the platform claims to currently be a member of. 2. If the service provider wishes to serve members of the claimed group, it may proceed by requesting an updated **SigRL** from the IAS. 3. he service provider then constructs a **challenge message** that consists its SPID, a liveliness random nonce, the updated SigRL and an optional basename parameter (if a pseudonym signature is required). 4. If the enclave supports the requested signature mode, it invokes the `EREPORT` instruction to create a locally verifiable report addressed to platform’s QE. In order to establish an authenticated secure channel between the enclave and the service provider, a **freshly generated ephemeral public key** may be added to the report’s user data field. The report and SP’s challenge are sent to QE. 5. _(Local Attestation happens here)_ The QE calls `EGETKEY` to obtain the `REPORT KEY` and verifies the report. If successful, QE calls `EGETKEY` again to receive platform’s Provisioning Seal Key to decrypt platform’s remote attestation key (EPID private key). The attestation key is first used to produce an identity signature by either signing the challenged basename or a random value, according to the attestation mode requested. 6. The attestation key is then used to compute two signatures of knowledge over the platform’s identity signature `MRENCLAVE`. **The first** proves the identity signature was signed with a key certified by Intel. **The second** is a non-revoked proof that proves the key used for the identity signature does not create any of the identity signatures listed in the challenged SigRL. A final `QUOTE` is then generated and encrypted using IAS’s public key, which is hardcoded in QE, and the result is sent back to the attesting enclave. The `QUOTE` holds the identity of the attesting enclave, execution mode details (e.g. SVN level) and additional data. 7. The enclave then forwards the `QUOTE` to the **SP** for verification. 8. Since the `QUOTE` is encrypted, it is verifiable exclusively by Intel. Hence, the service provider simply forwards the `QUOTE` to the **IAS** for verification. 9. The **IAS** examines the `QUOTE` by first validating its EPID proofs against its identity signature. It then verifies the platform is not listed on the group **Priv-RL** by computing an identity signature on the `QUOTE` basename for each private key in the list, and verifying that none of them equals the QUOTE’s identity signature. This finalizes the validity check of the platform, and the IAS then creates a new attestation **verification report** as a response to the SP. The Attestation Verification Report includes the QUOTE structure generated by the platform for the attesting enclave. 10. A **positive** Attestation Verification Report confirms the enclave as running a particular piece of code on a genuine intel SGX processor. It is then the responsibility of the SP to validate the ISV enclave identity and serve an appropriate response back to the platform. [](#remote-attestation-example) Remote Attestation Example --------------------------------------------------------------- ### [](#before-running-the-code-some-settings-have-to-be-set-in-the-generalsettings.h-file) Before running the code, some settings have to be set in the GeneralSettings.h file: * The application port and IP * A server certificate and private key are required for the SSL communication between the SP and the Application (which can be self-signed) Copy openssl req -x509 -nodes -newkey rsa:4096 -keyout server.key -out server.crt -days 365 * The SPID provided by Intel when registering for the developer account * The certificate sent to Intel when registering for the developer account * IAS Rest API url (should stay the same) ### [](#to-be-able-to-run-the-above-code-some-external-libraries-are-needed) To be able to run the above code some external libraries are needed: * Google Protocol Buffers (should already be installed with the SGX SDK package) otherwise install Copy libprotobuf-dev libprotobuf-c0-dev protobuf-compiler **All other required libraries** can be installed with the following command: Copy sudo apt-get install libboost-thread-dev libboost-system-dev curl libcurl4-openssl-dev libssl-dev liblog4cpp5-dev libjsoncpp-dev After the installation of those dependencies, the code can be compiled with the following commands: Copy cd ServiceProvider make cd ../Application make SGX_MODE=HW SGX_PRERELEASE=1 First let’s examine the **Application**. The entry point of the Application is inside isv\_app.cpp (ISV stands for Individual Software Vendor). It starts by initiating the `MessageHandler` that handles the messages to be exchanged during remote attestation. ### [](#messagehandler-a-wrapper-of-all-of-the-networking-functionalities) MessageHandler (a wrapper of all of the networking functionalities): The MessageHandler has a protected enclave that handles all the secrets, as well as the generation and processing of cryptographic messages. We can see that MessageHandler has several message generation and handling functions. Specifically they are functions in forms of `generateMsgx()` and `handleMsgx()`. Google Protobuf is used by those functions to serialize the messages to be exchanged via network transportation. The MessageHandler also has a `NetworkManagerServer` object. The NetworkManagerServer object enables the Application to act as a server to initialize connection and binds itself to a client via SSL (implementation detail in server.h, using object `Server* server`). It also inherits `NetworkManager` class in order to serialize and send messages. `msg -> init():` When the `MessageHandler` msg is initialized using `init()`, the `NetworkManagerServer` object inside is also initialized. It causes the initialization of `Server` object, which sets up the SSL io\_service socket and the selected port. Then a function `incomingHandler()` is connected to the `NetworkManagerServer` as the `CallbackHandler`. This function is responsible for generating all the message replies according to the type of the message that it receives. As mentioned above, `incomingHandler(string, int)` handles all of the incoming messages and generates corresponding replies. Let’s briefly examine this handler (line 395 at `MessageHandler.cpp`). ### [](#there-are-four-cases) There are four cases: * RA\_VERIFICATION * RA\_MSG0 * RA\_MSG2 * RA\_ATT\_RESULT Each case is one type of the messages that are exchanged in time order during remote attestation. Upon here, the ISV application’s MessageHandler has finished initialization. `msg -> start()`: Function `start()` calls NetworkManager’s `startService()` function, which calls Server’s `start_accept()` to start SSL service. Upton here, the ISV has started running and is ready for any incoming traffic. ### [](#now-lets-examine-serviceproviders-structure-and-initialization-process) Now let’s examine `ServiceProvider`’s structure and initialization process. `isv_app.cpp` inside `ServiceProvider`: It’s the ServiceProvider Application itself. Similar to the client’s application, it has its own message handler `VerificationManager` since it acts as the verifier in the remote attestation process. Inside the VerificationManager, it has a `NetworkManagerClient` which also inherits `NetworkManager` and is responsible for the SSL connection as well as serializing and sending messages. In addition, it has a `WebService` object to performs the verification phase with **Intel Attestation Service (IAS)** using the `QUOTE` sent from the client enclave. In one word, a `ServiceProvider` also acts as a wrapper of all the IAS requests and message processing, as well as any encryption key derivation, using `WebService`. `vm -> init()`: First, dynamically allocate a new `ServiceProvider` to ensure freshness of secret. Then the function initializes `NetworkManagerClient` that will connect to the Server (the Application) using SSL. Finally, a `CallBackHandler` similar to the one of the Application is set up. The handler itself is the function `incomingHandler(string, int)` inside `VerificationManager` that will handle incoming messages coming from the Application during remote attestation (line 132 at `VerificationManager.cpp`). ### [](#there-are-also-four-cases-of-handling-messages) There are also four cases of handling messages: * RA\_MSG0 * RA\_MSG1 * RA\_MSG3 * RA\_APP\_ATT\_OK Notice that at the end of the handler, it initializes the message stream with a `RA_VERIFICATION` type string and the actual `REQUEST`. By doing so right after SSL handshake, the ServiceProvider can immediately start the RA process by forwarding the remote attestation request to the Application. `vm -> start()`: `NetworkManagerClient` starts the service by connecting the SSL client to server. Then the client starts the SSL handshake process with server. We can see that the `Client::handle_handshake()` function triggers the remote attestation by sending out the attestation request mentioned above if handshake is successful. Upon here, `ServiceProvider` and Application are connected and remote attestation process has started. Now let’s examine both `incomingHandler(string, int)` in `MessageHandler.cpp` and `VerificationManager.cpp` to reflect the remote attestation process between SP and ISV described in the tutorial. ### [](#summary-of-function-calls) Summary of function calls: (Please refer to `Messages.proto` for message structure details.) (Please refer to the two `incomingHandler`'s attached below for actual implementation.) [](#references) References: -------------------------------- Remote Attestation code example is available Original unmodified version is available IAS Service Guide is available The sample application has two parts: **ServiceProvider** and the **Application**. The Application needs to prove to the ServiceProvider that it is running on a claimed trusted SGX enclave so that the Service Provider can proceed to provision secret data. The messages exchanged during the remote attestation process are serialized using . [here](https://github.com/sangfansh) [here](https://github.com/svartkanin/linux-sgx-remoteattestation) [here](https://software.intel.com/sites/default/files/managed/7e/3b/ias-api-spec.pdf) [Google Protobuf](https://github.com/google/protobuf) [https://courses.cs.ut.ee/MTAT.07.022/2017\_spring/uploads/Main/hiie-report-s16-17.pdf](https://courses.cs.ut.ee/MTAT.07.022/2017_spring/uploads/Main/hiie-report-s16-17.pdf) [https://www.idc.ac.il/en/schools/cs/research/Documents/jackson-msc-thesis.pdf](https://www.idc.ac.il/en/schools/cs/research/Documents/jackson-msc-thesis.pdf) [https://software.intel.com/en-us/articles/innovative-technology-for-cpu-based-attestation-and-sealing](https://software.intel.com/en-us/articles/innovative-technology-for-cpu-based-attestation-and-sealing) [http://tce.webee.eedev.technion.ac.il/wp-content/uploads/sites/8/2015/10/SGX-for-Technion-TCE.pdf](http://tce.webee.eedev.technion.ac.il/wp-content/uploads/sites/8/2015/10/SGX-for-Technion-TCE.pdf) [https://www.idc.ac.il/en/schools/cs/research/Documents/jackson-msc-thesis.pdf](https://www.idc.ac.il/en/schools/cs/research/Documents/jackson-msc-thesis.pdf) [https://software.intel.com/en-us/node/702983](https://software.intel.com/en-us/node/702983) [https://software.intel.com/en-us/articles/code-sample-intel-software-guard-extensions-remote-attestation-end-to-end-example](https://software.intel.com/en-us/articles/code-sample-intel-software-guard-extensions-remote-attestation-end-to-end-example) [https://arxiv.org/pdf/1801.05863.pdf](https://arxiv.org/pdf/1801.05863.pdf) [https://software.intel.com/en-us/forums/intel-software-guard-extensions-intel-sgx/topic/747718](https://software.intel.com/en-us/forums/intel-software-guard-extensions-intel-sgx/topic/747718) [https://eprint.iacr.org/2007/194.pdf](https://eprint.iacr.org/2007/194.pdf) attestation local attestation IAS RA ra ra ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LhhJjEW6KpUr6O6ktt0%252Fuploads%252Fgit-blob-71376b4ab02d1a3201ca31ab922bf2570cbef7b3%252Flocal_attestation.png%3Falt%3Dmedia&width=768&dpr=4&quality=100&sign=b127573c&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBg0YelNwdGGRNbD2%252Fra_summary.png%3Falt%3Dmedia%26token%3Dec7ebf41-f8a0-4e0c-8822-ce761a23b675&width=768&dpr=4&quality=100&sign=3c236208&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBg0BUplAWA3gEds3%252Fra.png%3Falt%3Dmedia%26token%3Dc330a403-da51-403a-ba2b-b2b680bb8ee4&width=768&dpr=4&quality=100&sign=824d315c&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBg0AFJ1FD_gF08d_%252Fias.png%3Falt%3Dmedia%26token%3Dcac6f6a4-9712-4169-bf0c-b8b0ee6a0423&width=768&dpr=4&quality=100&sign=ba09cf9d&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBg0dSqkDLkKJZMTV%252Fra_flow.png%3Falt%3Dmedia%26token%3Dc9508a3b-ad85-4975-a9bd-a9b488e85d75&width=768&dpr=4&quality=100&sign=9a15469f&sv=2) ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmBg026nQwAfrSXYsn%252Fattestation.png%3Falt%3Dmedia%26token%3D1b506465-f13f-4176-9d73-6740a81261fe&width=768&dpr=4&quality=100&sign=4fc4118c&sv=2) --- # Sealing | SGX 101 When an enclave is instantiated it provides protection to the data by keeping it within the boundary of the enclave. **Enclave developers should identify enclave data and/or state that is considered secret and potentially needs to be preserved across the following events during which the enclave is destroyed:** * The application is done with the enclave and closes it. * The application itself is closed. * The platform is hibernated or shutdown. In general, the secrets provisioned to an enclave are lost when the enclave is closed. But if the secret data needs to be preserved during one of these events for future use within an enclave, then it must be stored outside the enclave boundary before closing the enclave. In order to protect and preserve the data, a mechanism is in place which allows enclave software to retrieve **a key unique to that enclave**. This key can only be generated by that enclave on that particular platform. Enclave software uses that key to encrypt data to the platform or to decrypt data already on the platform. SGX refer to these encrypt and decrypt operations as sealing and unsealing, respectively. There are two options when sealing data or future unsealing conditions (different policies to derive sealing keys from **Root Sealing Key**, which is only known by the enclave): ### [](#seal-to-current-enclave) Seal to Current Enclave: This method binds the measurement of the current enclave, `MRENCLAVE`, to the key used by the sealing operation, using `EGETKEY` instruction. Therefore, only an enclave with the same `MRENCLAVE` will be able to generate the key to unseal the data. If any attribute related to the enclave has changed, the `MRENCLAVE` will also change. As a result, the sealing key will also change and the sealed data cannot be decrypted. ### [](#seal-to-the-enclave-author) Seal to the Enclave Author: This method binds the identity of the enclave author, which is stored in the enclave’s `MRSIGNER` register at initialization time, to the sealing key derived from the Root Sealing Key using `EGETKEY` instruction. The Product ID of the enclave is also bound to the derived sealing key. Therefore, only an enclave with the same `MRSIGNER` measurement and the same **Product ID** can retrieve the sealing key and unseal the data. There are two benefits of this mechanism over sealing to the enclave identity. **First**, it allows an enclave to be upgraded by the enclave author without a complex upgrade process to unlock data sealed to the previous version of the enclave and reseal it to the new version. **Second**, it allows enclaves from the same author to share sealed data. [](#sealing-abstract) Sealing Abstract: -------------------------------------------- ISV enclaves are responsible for choosing and implementing the encryption scheme suitable for their needs when sealing their data. That is, SGX does not provide a complete sealing service, but rather a new security primitive (available exclusively for enclaves) based on `EGETKEY` features described. First, allocate memory within the enclave for encrypted data and the sealed data structure which contains both the data to encrypt and additional data, such as application version and enclave information, which participates in the MAC calculation. Then call the seal data API to perform the sealing operation, which will perform following steps: 1. Verify the input parameters. For example, make sure that the pointer to sealed data structure really points to the buffer inside the enclave. 2. Instantiate and populate a **key request structure** used in the `EGETKEY` operation to obtain a seal key: 3. Call `EREPORT` to obtain the ISV and TCB Security Version Numbers, which will be used in the key derivation 4. **Key Name:** Identifies the key required, which in this case is the seal key. 5. **Key Policy:** Use MRSIGNER to seal to the enclave’s author or MRENCLAVE to seal to the current enclave. Reserved bits must be cleared. 6. **Key ID:** Call RDRAND to obtain a random number for key wear-out protection. 7. **Attribute Mask:** Bitmask indicating which attributes the seal key should be bound to. 8. Call `EGETKEY` with the key request structure from the previous step to obtain the seal key. 9. Call the encryption algorithm to perform the seal operation with the seal key. It is recommended to utilize a function that performs `AES-GCM` encryption/decryption, such as the `Rijndael128GCM`, which is available in the Intel Integrated Performance Primitives Cryptography library. 10. **Delete** the seal key from memory to prevent accidental leaks. Finally, save the seal data structure (including the key request structure) to external memory for future use within an enclave. The key request structure will be used in future enclave instantiations to obtain the seal key required for the decryption process. [](#unsealing-abstract) Unsealing Abstract: ------------------------------------------------ First, allocate memory for the decrypted data. Then call the unseal API to perform the unsealing operation, which will perform following steps: 1. **Verify** input parameters. 2. **Retrieve** the key request structure stored together with the seal data structure. 3. Call **EGETKEY** with the **key request structure** to obtain the seal key. 4. Call the **decryption algorithm** to perform the unseal operation using the seal key. 5. **Delete** the seal key from memory to prevent accidental leaks. 6. **Confirm** that the hash generated by the decryption algorithm matches the one generated during encryption to ensure integrity. We use sample code example to explain implementation details. [](#sealing-example) Sealing Example ----------------------------------------- In `App.cpp`: The application first initializes the enclave in the main function. Then it makes an `ECall` into the enclave to generate a random number (a fake random number just for simplicity). In order to seal the number, the application first has to **allocate memory** for sealed data block (line 30 at App.cpp). Then it makes another `ECall` into the enclave to seal the random secret. The `seal()` function is an `ECall` wrapper function of the trusted SGX sealing api. It passes the required parameters into function `sgx_seal_data()` provided by SGX SDK (`Sealing.cpp`). If this ECall returns successfully, the random secret will be securely sealed in `(sgx_sealed_data_t*)sealed_data`. After the random secret is successfully sealed, the application makes another `ECall` `unseal()` to unseal the sealed\_data. Function `unseal()` is also a wrapper function of the trusted SGX sealing api `sgx_unseal_data()`. If this `ECall` returns successfully, the unsealed content of `sealed_data` will be stored into `int unsealed`. Finally the application verifies the result by printing out and comparing the unsealed secret with the original generated random number (line 50 at `App.cpp`). In order to compile and run this example, run `make` inside the example directory and type `./app` to run the application. It should produce some output like this: [](#references) References: -------------------------------- [PreviousInter-process Local Attestation](/sgx101/sgx-bootstrap/attestation/inter-process-local-attestation) [NextReal-world Example](/sgx101/sgx-bootstrap/real-world-example) Last updated 5 years ago Was this helpful? This sealing example is only for illustration purpose. It generates a random number inside the enclave and calls the sealing api to seal it. Then it unseals the sealed data structure to verify the number. Code is available . Original unmodified version is available . [here](https://github.com/sangfansh/SGX101_sample_code) [here](https://github.com/digawp/hello-enclave) [https://eprint.iacr.org/2016/086.pdf](https://eprint.iacr.org/2016/086.pdf) [https://www.idc.ac.il/en/schools/cs/research/Documents/jackson-msc-thesis.pdf](https://www.idc.ac.il/en/schools/cs/research/Documents/jackson-msc-thesis.pdf) [https://software.intel.com/en-us/articles/innovative-technology-for-cpu-based-attestation-and-sealing](https://software.intel.com/en-us/articles/innovative-technology-for-cpu-based-attestation-and-sealing) [https://software.intel.com/en-us/blogs/2016/05/04/introduction-to-intel-sgx-sealing](https://software.intel.com/en-us/blogs/2016/05/04/introduction-to-intel-sgx-sealing) [https://insujang.github.io/2017-10-09/intel-sgx-sealing/](https://insujang.github.io/2017-10-09/intel-sgx-sealing/) [https://software.intel.com/en-us/node/702997](https://software.intel.com/en-us/node/702997) sealing ![](https://sgx101.gitbook.io/~gitbook/image?url=https%3A%2F%2F4040253038-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LhhJjEW6KpUr6O6ktt0%252F-LhmAtCdHlavdXBn7_8v%252F-LhmD8LtFXuAwlNeUiHm%252Fsealing_example.png%3Falt%3Dmedia%26token%3Db4f7533f-96f7-4f80-a278-01fcf1d3515b&width=768&dpr=4&quality=100&sign=715ea77c&sv=2) --- # Home | SGX 101 [NextSSLab](/sgx101/sslab) Last updated 5 years ago Was this helpful? [](#sslab) -------------- SSLab represents the from Georgia Institute of Technology led by . We have been actively working on SGX related research. These research projects can be broadly classified into three different categories: System Design, Defense, and Attack. * Please take a look at our achievements on Attacks and Defenses for Intel SGX (download link blow). Demo videos can be viewed under . [](#sgx-bootstrap) ---------------------- This is the very place to learn building your first application with Intel SGX in mind. [](#sgx-security) --------------------- Intel SGX is not as secure as we thought. [](#other-resources) ------------------------ Here you can look up various resources related to Intel SGX for reference. [](#about-us) ----------------- [About Us](/sgx101/about-us) [SSLab](/sgx101/sslab) [Systems Software & Security Lab](https://gts3.org/) [Prof. Taesoo Kim](https://taesoo.kim/) [SGX Bootstrap/CCS17 Tutorial](/sgx101/sgx-bootstrap/ccs17-tutorial) [SGX Bootstrap](/sgx101/sgx-bootstrap) [SGX Security](/sgx101/sgx-security) [Other Resources](/sgx101/resources) [8MB\ \ security-issues.pdf\ \ pdf](https://4040253038-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LhhJjEW6KpUr6O6ktt0%2F-LhmVUdpaMOFgzXnVfN6%2F-LhmVcxBf2zBzuBoSYEE%2Fsecurity-issues.pdf?alt=media&token=1697a6a7-2479-41b5-bc10-aaccd97ac4db) Attacks and Defenses for Intel SGX ---