\HeadingLevelB{SGX Enclave Measurement}
\label{sec:sgx_measurement}
\label{sec:sgx_mrenclave}

SGX implements a software attestation scheme that follows the general
principles outlined in \S~\ref{sec:generic_software_attestation}. For the
purposes of this section, the most relevant principle is that a remote party
authenticates an enclave based on its measurement, which is intended to
identify the software that is executing inside the enclave. The remote party
compares the enclave measurement reported by the trusted hardware with an
expected measurement, and only proceeds if the two values match.

% Enclave Measurement: SDM S 39.4.1

\S~\ref{sec:sgx_enclave_lifecycle} explains that an SGX enclave is built using
the \texttt{ECREATE}~(\S~\ref{sec:sgx_ecreate}),
\texttt{EADD}~(\S~\ref{sec:sgx_eadd}) and \texttt{EEXTEND} instructions.
After the enclave is initialized via
\texttt{EINIT}~(\S~\ref{sec:sgx_einit_overview}), the instructions mentioned
above cannot be used anymore. As the SGX measurement scheme follows the
principles outlined in \S~\ref{sec:generic_measurement}, the measurement of an
SGX enclave is obtained by computing a secure
hash~(\S~\ref{sec:integrity_crypto}) over the inputs to the \texttt{ECREATE},
\texttt{EADD} and \texttt{EEXTEND} instructions used to create the enclave and
load the initial code and data into its memory. \texttt{EINIT} finalizes the
hash that represents the enclave's measurement.

Along with the enclave's contents, the enclave author is expected to specify
the sequence of instructions that should be used in order to create an enclave
whose measurement will match the expected value used by the remote party in the
software attestation process. The \texttt{.so} and \texttt{.dll} dynamically
loaded library file formats, which are SGX's intended enclave delivery methods,
already include informal specifications for loading algorithms. We expect the
informal loading specifications to serve as the starting points for
specifications that prescribe the exact sequences of SGX instructions that
should be used to create enclaves from \texttt{.so} and \texttt{.dll} files.

As argued in \S~\ref{sec:generic_measurement}, an enclave's measurement is
computed using a secure hashing algorithm, so the system software can only
build an enclave that matches an expected measurement by following the exact
sequence of instructions specified by the enclave's author.

% SGX Enclave Control Structure (SECS): SDM S 38.7, S 38.7.1
% MRENCLAVE: SDM S 39.4.1.1

The SGX design uses the 256-bit SHA-2~\citep{fips2015shs} secure hash function
to compute its measurements. SHA-2 is a block hash
function~(\S~\ref{sec:integrity_crypto}) that operates on 64-byte blocks, uses
a 32-byte internal state, and produces a 32-byte output. Each enclave's
measurement is stored in the MRENCLAVE field of the enclave's SECS. The 32-byte
field stores the internal state and final output of the 256-bit SHA-2 secure
hash function.


\HeadingLevelC{Measuring \texttt{ECREATE}}
\label{sec:sgx_ecreate_mrenclave}

% ECREATE: SDM S 41.3

The \texttt{ECREATE} instruction, described in \S~\ref{sec:sgx_ecreate},
first initializes the MRENCLAVE field in the newly created SECS using the
256-bit SHA-2 initialization algorithm, and then extends the hash with
the 64-byte block depicted in Table~\ref{fig:ecreate_mrenclave}.

\begin{table}[hbt]
  \centering
  \caption{
    64-byte block extended into MRENCLAVE by \texttt{ECREATE}.
  }
  \label{fig:ecreate_mrenclave}
  \begin{tabularx}{\columnwidth}{| r | r | X |}
  \hline
  \textbf{Offset} & \textbf{Size} & \textbf{Description}\\
  \hline
  0 & 8 & ``ECREATE\textbackslash{}0'' \\
  \hline
  8 & 8 & SECS.SSAFRAMESIZE (\S~\ref{sec:sgx_ssa}) \\
  \hline
  16 & 8 & SECS.SIZE (\S~\ref{sec:sgx_elrange}) \\
  \hline
  32 & 8 & 32 zero (0) bytes \\
  \hline
  \end{tabularx}
\end{table}

The enclave's measurement does not include the BASEADDR field. The omission is
intentional, as it allows the system software to load an enclave at any virtual
address inside a host process that satisfies the ELRANGE
restrictions~(\S~\ref{sec:sgx_elrange}), without changing the enclave's
measurement. This feature can be combined with a compiler that generates
position-independent enclave code to obtain relocatable enclaves.

The enclave's measurement includes the \texttt{SSAFRAMESIZE} field, which
guarantees that the SSAs~(\S~\ref{sec:sgx_ssa}) created by AEX and used by
\texttt{EENTER}~(\S~\ref{sec:sgx_eenter}) and
\texttt{ERESUME}~(\S~\ref{sec:sgx_eresume}) have the size that is expected by
the enclave's author. Leaving this field out of an enclave's measurement would
allow a malicious enclave loader to attempt to attack the enclave's security
checks by specifying a bigger SSAFRAMESIZE than the enclave's author intended,
which could cause the SSA contents written by an AEX to overwrite the enclave's
code or data.


\HeadingLevelC{Measuring Enclave Attributes}
\label{sec:sgx_ecreate_mrenclave_no_attributes}

The enclave's measurement does not include the enclave
attributes~(\S~\ref{sec:sgx_secs_attributes}), which are specified in the
ATTRIBUTES field in the SECS. Instead, it is included directly in the
information that is covered by the attestation signature, which will be
discussed in \S~\ref{sec:sgx_ereport}.

The SGX software attestation definitely needs to cover the enclave attributes.
For example, if XFRM~(\S~\ref{sec:sgx_secs_attributes}, \S~\ref{sec:sgx_ssa})
would not be covered, a malicious enclave loader could attempt to subvert an
enclave's security checks by setting XFRM to a value that enables architectural
extensions that change the semantics of instructions used by the enclave, but
still produces an \texttt{XSAVE} output that fits in SSAFRAMESIZE.

The special treatment applied to the ATTRIBUTES SECS field seems questionable
from a security standpoint, as it adds extra complexity to the software
attestation verifier, which translates into more opportunities for exploitable
bugs. This decision also adds complexity to the SGX software attestation
design, which is described in \S~\ref{sec:sgx_attestation}.

The most likely reason why the SGX design decided to go this route, despite the
concerns described above, is the wish to be able to use a single measurement to
represent an enclave that can take advantage of some architectural extensions,
but can also perform its task without them.

Consider, for example, an enclave that performs image processing using a
library such as OpenCV, which has routines optimized for SSE and AVX, but also
includes generic fallbacks for processors that do not have these features. The
enclave's author will likely wish to allow an enclave loader to set bits 1
(SSE) and 2 (AVX) to either true or false. If ATTRIBUTES (and, by extension,
XFRM) was a part of the enclave's measurement, the enclave author would have to
specify that the enclave has 4 valid measurements. In general, allowing $n$
architectural extensions to be used independently will result in $2^n$ valid
measurements.


\HeadingLevelC{Measuring \texttt{EADD}}
\label{sec:sgx_eadd_mrenclave}

% EADD and EEXTEND Interaction: SDM S 39.1.1
% EADD: SDM S 41.3

The \textit{EADD} instruction, described in \S~\ref{sec:sgx_eadd}, extends the
SHA-2 hash in MRENCLAVE with the 64-byte block shown in
Table~\ref{fig:eadd_mrenclave}.

\begin{table}[hbt]
  \centering
  \caption{
    64-byte block extended into MRENCLAVE by \texttt{EADD}. The ENCLAVEOFFSET
    is computed by subtracting the BASEADDR in the enclave's SECS from the
    LINADDR field in the PAGEINFO structure.
  }
  \label{fig:eadd_mrenclave}
  \begin{tabularx}{\columnwidth}{| r | r | X |}
  \hline
  \textbf{Offset} & \textbf{Size} & \textbf{Description}\\
  \hline
  0 & 8 &
  ``EADD\textbackslash{}0\textbackslash{}0\textbackslash{}0\textbackslash{}0'' \\
  \hline
  8 & 8 & ENCLAVEOFFSET \\
  \hline
  16 & 48 & SECINFO (first 48 bytes) \\
  \hline
  \end{tabularx}
\end{table}

The address included in the measurement is the address where the
\texttt{EADD}ed page is expected to be mapped in the enclave's virtual address
space. This ensures that the system software sets up the enclave's virtual
memory layout according to the enclave author's specifications. If a malicious
enclave loader attempts to set up the enclave's layout incorrectly, perhaps in
order to mount an active address translation
attack~(\S~\ref{sec:memory_mapping_attacks}), the loaded enclave's measurement
will differ from the measurement expected by the enclave's author.

The virtual address of the newly created page is measured relative to the
start of the enclave's ELRANGE. In other words, the value included in the
measurement is LINADDR - BASEADDR. This makes the enclave's measurement
invariant to BASEADDR changes, which is desirable for relocatable enclaves.
Measuring the relative addresses still preserves all information about the
memory layout inside ELRANGE, and therefore has no negative security impact.

\texttt{EADD} also measures the first 48 bytes of the SECINFO
structure~(\S~\ref{sec:sgx_eadd}) provided to \texttt{EADD}, which contain the
page type (PT) and access permissions (R, W, X) field values used to initialize
the page's EPCM entry. By the same argument as above, including these values in
the measurement guarantees that the memory layout built by the system software
loading the enclave matches the specifications of the enclave author.

The EPCM field values mentioned above take up less than one byte in the SECINFO
structure, and the rest of the bytes are reserved and expected to be
initialized to zero. This leaves plenty of expansion room for future SGX
features.

The most notable omission from Table~\ref{fig:eadd_mrenclave} is the data used
to initialize the newly created EPC page. Therefore, the measurement data
contributed by \texttt{EADD} guarantees that the enclave's memory layout
will have pages allocated with prescribed access permissions at the desired
virtual addresses. However, the measurements don't cover the code or data
loaded in these pages.

For example, \texttt{EADD}'s measurement data guarantees that an enclave's
memory layout consists of three executable pages followed by five writable data
pages, but it does not guarantee that any of the code pages contains the
code supplied by the enclave's author.


\HeadingLevelC{Measuring \texttt{EEXTEND}}
\label{sec:sgx_eextend}

% EEXTEND: SDM S 41.3

The \texttt{EEXTEND} instruction exists solely for the reason of measuring data
loaded inside the enclave's EPC pages. The instruction reads in a virtual
address, and extends the enclave's measurement hash with the five 64-byte
blocks in Table~\ref{fig:eextend_mrenclave}, which effectively guarantee the
contents of a 256-byte chunk of data in the enclave's memory.

\begin{table}[hbt]
  \centering
  \caption{
    64-byte blocks extended into MRENCLAVE by \texttt{EEXTEND}. The
    ENCLAVEOFFSET is computed by subtracting the BASEADDR in the enclave's SECS
    from the LINADDR field in the PAGEINFO structure.
  }
  \label{fig:eextend_mrenclave}
  \begin{tabularx}{\columnwidth}{| r | r | X |}
  \hline
  \textbf{Offset} & \textbf{Size} & \textbf{Description}\\
  \hline
  0 & 8 &``EEXTEND\textbackslash{}0'' \\
  \hline
  8 & 8 & ENCLAVEOFFSET \\
  \hline
  16 & 48 & 48 zero (0) bytes \\
  \hline
  \hline
  64 & 64 & bytes 0 - 64 in the chunk \\
  \hline
  \hline
  128 & 64 & bytes 64 - 128 in the chunk \\
  \hline
  \hline
  192 & 64 & bytes 128 - 192 in the chunk \\
  \hline
  \hline
  256 & 64 & bytes 192 - 256 in the chunk \\
  \hline
  \end{tabularx}
\end{table}

Before examining the details of \texttt{EEXTEND}, we note that SGX's security
guarantees only hold when the contents of the enclave's key pages is measured.
For example, \texttt{EENTER}~(\S~\ref{sec:sgx_eenter}) is only guaranteed to
perform controlled jumps inside an enclave's code if the contents of all
Thread Control Structure~(TCS,~\S~\ref{sec:sgx_tcs}) pages are measured.
Otherwise, a malicious enclave loader can change the OENTRY
field~(\S~\ref{sec:sgx_tcs}, \S~\ref{sec:sgx_eenter}) in a TCS while building
the enclave, and then a malicious OS can use the TCS to perform an arbitrary
jump inside enclave code. By the same argument, the entire body of the enclave's code should
be measured by \texttt{EEXTEND}. Any code fragment that is not measured can be
replaced by a malicious enclave loader.

Given these pitfalls, it is surprising that the SGX design opted to decouple
the virtual address space layout measurements done by \texttt{EADD} from the
memory content measurements done by \texttt{EEXTEND}.

At a first pass, it appears that the decoupling only has one benefit, which is
the ability to load unmeasured user input into an enclave while it is being
built. However, this benefit only translates into a small performance
improvement, because enclaves can alternatively be designed to copy the user
input from untrusted DRAM after being initialized. At the same time, the
decoupling opens up the possibility of relying on an enclave that provides no
meaningful security guarantees, due to not measuring all important data via
\texttt{EEXTEND} calls.

However, the real reason behind the \texttt{EADD} / \texttt{EEXTEND} separation
is hinted at by the \texttt{EINIT} pseudo-code in the SDM, which states that
the instruction opens an interrupt~(\S~\ref{sec:interrupts}) window while it
performs a computationally intensive RSA signature check. If an interrupt
occurs during the check, \texttt{EINIT} fails with an error code, and the
interrupt is serviced. This very unusual approach for a processor instruction
suggests that the SGX implementation was constrained in respect to how much
latency its instructions were allowed to add to the interrupt handling process.

In light of the concerns above, it is reasonable to conclude that
\texttt{EEXTEND} was introduced because measuring an entire page using 256-bit
SHA-2 is quite time-consuming, and doing it in \texttt{EADD} would have caused
the instruction to exceed SGX's latency budget. The need to hit a certain
latency goal is a reasonable explanation for the seemingly arbitrary 256-byte
chunk size.

The \texttt{EADD} / \texttt{EEXTEND} separation will not cause security issues
if enclaves are authored using the same tools that build today's dynamically
loaded modules, which appears to be the workflow targeted by the SGX design.
In this workflow, the tools that build enclaves can easily identify the enclave
data that needs to be measured.

It is correct and meaningful, from a security perspective, to have the message
blocks provided by \texttt{EEXTEND} to the hash function include the address of
the 256-byte chunk, in addition to the contents of the data. If the address
were not included, a malicious enclave loader could mount the memory mapping
attack described in \S~\ref{sec:memory_mapping_attacks} and illustrated in
Figure~\ref{fig:active_mapping_attack}.

More specifically, the malicious loader would \texttt{EADD} the
\texttt{errorOut} page contents at the virtual address intended for
\texttt{disclose}, \texttt{EADD} the \texttt{disclose} page contents at the
virtual address intended for \texttt{errorOut}, and then \texttt{EEXTEND} the
pages in the wrong order. If \texttt{EEXTEND} would not include the address of
the data chunk that is measured, the steps above would yield the same
measurement as the correctly constructed enclave.

% SGX Enclave Control Structure (SECS): SDM S 38.7, S 38.7.1

The last aspect of \texttt{EEXTEND} worth analyzing is its support for
relocating enclaves. Similarly to \texttt{EADD}, the virtual address measured
by \texttt{EEXTEND} is relative to the enclave's BASEADDR. Furthermore, the
only SGX structure whose content is expected to be measured by \texttt{EEXTEND}
is the TCS. The SGX design has carefully used relative addresses for all
TCS fields that represent enclave addresses, which are OENTRY, OFSBASGX and
OGSBASGX.


\HeadingLevelC{Measuring \texttt{EINIT}}

% EINIT: SDM S 41.3

The \texttt{EINIT} instruction~(\S~\ref{sec:sgx_einit_overview}) concludes the
enclave building process. After \texttt{EINIT} is successfully invoked on an
enclave, the enclave's contents are ``sealed'', meaning that the system
software cannot use the \texttt{EADD} instruction to load code and data into
the enclave, and cannot use the \texttt{EEXTEND} instruction to update the
enclave's measurement.

\texttt{EINIT} uses the SHA-2 finalization
algorithm~(\S~\ref{sec:integrity_crypto}) on the MRENCLAVE field of the
enclave's SECS. After \texttt{EINIT}, the field no longer stores the
intermediate state of the SHA-2 algorithm, and instead stores the final output
of the secure hash function. This value remains constant after \texttt{EINIT}
completes, and is included in the attestation signature produced by the SGX
software attestation process.
