### Install GDB 7.11.1 to /usr/bin/gdb Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Setup-gdb-7.11-on-Ubuntu-18.04-for-VSCode---sgx-gdb-remote-debugging Install the compiled GDB 7.11.1 to the default system path /usr/bin/gdb. ```bash sudo make install ``` -------------------------------- ### General Build Instructions Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_unwind/libunwind/README.md Standard commands to build and install the libunwind library. 'autogen.sh' is only needed when building from git. ```bash $ ./autogen.sh # Needed only for building from git. Depends on libtool. $ ./configure $ make $ make install prefix=PREFIX ``` -------------------------------- ### OpenBSD Copyright Policy - Berkeley Copyright Example Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/licenses/LICENSE-tlibc.txt An example of the Berkeley copyright notice, which imposes minimal requirements for redistribution and attribution. ```c * Copyright (c) 1982, 1986, 1990, 1991, 1993 *\tThe Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: ``` -------------------------------- ### Install LLVM 11 Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/samplecode/cov/Readme.md Installs LLVM version 11 using the official LLVM installation script. This is a prerequisite for using llvm-cov for code coverage. ```bash wget https://apt.llvm.org/llvm.sh chmod +x llvm.sh sudo ./llvm.sh 11 ``` -------------------------------- ### Running Docker with Hardware Support Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Environment-Setup This command starts a Docker container with hardware support enabled, mounting the SDK directory and exposing the necessary devices. It's suitable for environments with SGX hardware. ```bash $ docker run -ti --rm -v /path/to/sdk:/root/sgx \ --device /dev/isgx \ --device /dev/mei0 \ baiduxlab/sgx-rust ``` -------------------------------- ### Create Symbolic Links for Custom GDB Installation Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Setup-gdb-7.11-on-Ubuntu-18.04-for-VSCode---sgx-gdb-remote-debugging Create symbolic links to install GDB 7.11.1 in a custom location, such as /opt, and configure its Python components. ```bash sudo ln -sf /opt/gdb-7.11.1/gdb/gdb /usr/bin/gdb cd /usr/local/share # if gdb dir doesn't exist, create it : mkdir -p gdb cd gdb # if python dir doesn't exist, create it: mkdir -p python cd python sudo ln -s /opt/gdb-7.11.1/gdb/data-directory/python/gdb/ /usr/local/share/gdb/python/ ``` -------------------------------- ### Start Docker Container for SGX Debugging Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Debugging-a-local-Rust-SGX-enclave-in-docker-with-sgx-gdb Execute this command to launch a Docker container with the necessary SGX drivers and volume mounts. Ensure the host path `/home/ding/rust-sgx-sdk` is correctly set to your SDK location. ```bash $ docker run -ti \ --rm \ --privileged \ -v /home/ding/rust-sgx-sdk:/root/rust-sgx-sdk \ --device /dev/isgx \ baiduxlab/sgx-rust:1604 bash root@ef40bc98b273:~# ``` -------------------------------- ### Running Docker without Hardware Support (Simulation) Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Environment-Setup This command starts a Docker container for simulation mode, suitable for development on systems without direct SGX hardware support, like Windows or Macbooks. The SDK directory is mounted. ```bash $ docker run -ti --rm -v /path/to/sdk:/root/sgx baiduxlab/sgx-rust ``` -------------------------------- ### Starting AESM Service in Docker Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Environment-Setup This shows the output of starting the AESM service within a Docker container, indicating successful initialization and white list updates. ```bash root@913e6a00c8d8:~# aesm_service[18]: The server sock is 0x5636e90be960 aesm_service[18]: [ADMIN]White List update requested aesm_service[18]: [ADMIN]Platform Services initializing aesm_service[18]: [ADMIN]Platform Services initialization failed due to DAL error aesm_service[18]: [ADMIN]White list update request successful for Version: 49 root@913e6a00c8d8:~# ``` -------------------------------- ### Verify GDB Version Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Debugging-a-local-Rust-SGX-enclave-in-docker-with-sgx-gdb Check the installed GDB version to confirm it is 7.11.1, which is required for `sgx-gdb` compatibility. The output shows the version and copyright information. ```bash root@ef40bc98b273:~# gdb --version GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: . Find the GDB manual and other documentation resources online at: . For help, type "help". Type "apropos word" to search for commands related to "word". ``` -------------------------------- ### Adding Rust Components Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Environment-Setup Install additional Rust tools like 'rust-src' for xargo or 'rust-clippy' for linting using this command. ```bash $ rustup component add rust-src ``` -------------------------------- ### Install Python Development Headers Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Setup-gdb-7.11-on-Ubuntu-18.04-for-VSCode---sgx-gdb-remote-debugging Install the python3-dev package, which is required for configuring the GDB Python interpreter during the build process. ```bash sudo apt-get install python3-dev ``` -------------------------------- ### Switching Rust Toolchain Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Environment-Setup Use this command to switch to a specific Rust toolchain version, such as a nightly build. This will trigger a download and installation if the toolchain is not already present. ```bash $ rustup toolchain default nightly-2019-03-31 ``` -------------------------------- ### GDB Debugging Session Example Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Debugging-a-local-Rust-SGX-enclave-in-docker-with-sgx-gdb This snippet shows a typical interactive debugging session using gdb within an SGX enclave context. It demonstrates stepping through code and inspecting variable values. ```gdb (gdb) n 54 let str_slice = unsafe { slice::from_raw_parts(some_string, some_len) }; (gdb) 55 let _ = io::stdout().write(str_slice); (gdb) This is a normal world string passed into Enclave! 58 let rust_raw_string = "This is a in-Enclave "; (gdb) n 60 let word:[u8;4] = [82, 117, 115, 116]; (gdb) p rust_raw_string $1 = {data_ptr = 0x7ffff5847150 "This is a in-Enclave Invalid UTF-8\n", length = 21} ``` -------------------------------- ### Run Docker with Hardware Support and External AESM Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Environment-Setup This command forwards the ISGX device and the AESM domain socket from the host to a Docker container. Ensure step 3 (AESM setup on host) is completed and the socket exists. ```bash $ docker run --rm -ti \ --device /dev/isgx \ -v /path/to/rust-sgx-sdk:/root/sgx \ -v /var/run/aesmd:/var/run/aesmd \ baiduxlab/sgx-rust ``` -------------------------------- ### Start AESM Service Daemon Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Debugging-a-local-Rust-SGX-enclave-in-docker-with-sgx-gdb Launch the AESM service daemon within the Docker container. This service is required for SGX enclave operations. Ignore the 'DAL error' as it is expected. ```bash root@ef40bc98b273:~# /opt/intel/libsgx-enclave-common/aesm/aesm_service aesm_service[878]: The server sock is 0x55ed65a9a560 aesm_service[878]: [ADMIN]White List update requested aesm_service[878]: [ADMIN]Platform Services initializing aesm_service[878]: [ADMIN]Platform Services initialization failed due to DAL error aesm_service[878]: [ADMIN]White list update request successful for Version: 49 ``` -------------------------------- ### Build Sample Rust SGX Enclave in Simulation Mode Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Setup-gdb-7.11-on-Ubuntu-18.04-for-VSCode---sgx-gdb-remote-debugging Navigate to the sample code directory and build the enclave in simulation mode with debugging enabled. ```bash cd rust-sgx-sdk/samplecode/hello-rust-vscode-debug/ SGX_MODE=SW SGX_DEBUG=1 make cd bin sgx-gdb ./app ``` -------------------------------- ### Install GDB within Docker Container Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Debugging-a-local-Rust-SGX-enclave-in-docker-with-sgx-gdb Update package lists and install GDB version 7.11.1 inside the Docker container. This version is known to be compatible with `sgx-gdb`. ```bash root@ef40bc98b273:~# apt-get update && apt-get install -y gdb ``` -------------------------------- ### Build for PowerPC64 / Linux (with Altivec) Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_unwind/libunwind/README.md Configure command for building libunwind for PowerPC64 on Linux, enabling Altivec support. ```bash $ ./configure CFLAGS="-g -O2 -m64 -maltivec" CXXFLAGS="-g -O2 -m64 -maltivec" ``` -------------------------------- ### Building and Running in Simulation Mode Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Environment-Setup These commands demonstrate how to build and run an application in simulation mode within a Docker container. It involves navigating to the project directory, setting the SGX_MODE to SW, and then executing the application. ```bash $ cd /root/sgx/samplecode/hello-rust $ SGX_MODE=SW make $ cd bin $ ./app ``` -------------------------------- ### Basic HashMap Usage in Rust Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_tstd/hashbrown/README.md Demonstrates the basic instantiation and insertion of elements into a hashbrown HashMap. ```rust use hashbrown::HashMap; let mut map = HashMap::new(); map.insert(1, "one"); ``` -------------------------------- ### Vulnerable Data Structure Example Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Mitigation-of-Intel-SA-00219-in-Rust-SGX Illustrates a C struct where sensitive data might be vulnerable due to its placement within a cache line, adjacent to accessible data. ```c struct foo { uint64_t A; uint64_t secret; uint64_t B; } ``` -------------------------------- ### Build for PowerPC64 / Linux (64-bit) Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_unwind/libunwind/README.md Configure command for building libunwind for PowerPC64 on Linux, specifying 64-bit mode. ```bash $ ./configure CFLAGS="-g -O2 -m64" CXXFLAGS="-g -O2 -m64" ``` -------------------------------- ### Launching sgx-gdb for Enclave Debugging Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Debugging-a-local-Rust-SGX-enclave-in-docker-with-sgx-gdb This command initiates the sgx-gdb debugger to attach to the enclave application. It shows the initial GDB output, including symbol loading and warnings. ```bash root@ef40bc98b273:~/rust-sgx-sdk/samplecode/hello-rust/bin# sgx-gdb ./app GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: . Find the GDB manual and other documentation resources online at: . For help, type "help". Type "apropos word" to search for commands related to "word"... Source directories searched: /opt/sgxsdk/lib64/gdb-sgx-plugin:$cdir:$cwd Setting environment variable "LD_PRELOAD" to null value. Reading symbols from ./app...done. warning: Missing auto-load script at offset 0 in section .debug_gdb_scripts of file /root/rust-sgx-sdk/samplecode/hello-rust/bin/app. Use `info auto-load python-scripts [REGEXP]' to list them. (gdb) b say_something Breakpoint 1 at 0x11800: file app/Enclave_u.c, line 731. (gdb) r Starting program: /root/rust-sgx-sdk/samplecode/hello-rust/bin/app detect urts is loaded, initializing [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". [+] Home dir is /root [-] Open token file /root/enclave.token error! Will create one. add-symbol-file '/root/rust-sgx-sdk/samplecode/hello-rust/bin/enclave.signed.so' 0x7ffff5805340 -readnow -s .interp 0x7ffff5800270 -s .note.gnu.build-id 0x7ffff580028c -s .gnu.hash 0x7ffff58002b0 -s .dynsym 0x7ffff58002e0 -s .dynstr 0x7ffff5800388 -s .gnu.version 0x7ffff58003c2 -s .gnu.version_d 0x7ffff58003d0 -s .rela.dyn 0x7ffff5800408 -s .plt 0x7ffff5805310 -s .plt.got 0x7ffff5805320 -s .nipx 0x7ffff5845060 -s .rodata 0x7ffff58458a0 -s .eh_frame_hdr 0x7ffff584ace0 -s .eh_frame 0x7ffff584d4b0 -s .gcc_except_table 0x7ffff5857850 -s .tbss 0x7ffff5a597a0 -s .init_array 0x7ffff5a597a0 -s .fini_array 0x7ffff5a597a8 -s .data.rel.ro 0x7ffff5a59800 -s .dynamic 0x7ffff5a5b000 -s .got 0x7ffff5a5b190 -s .got.plt 0x7ffff5a5c000 -s .data 0x7ffff5a5c020 -s .nipd 0x7ffff5a5cd84 -s .niprod 0x7ffff5a5cdc0 -s .bss 0x7ffff5a5d600 [+] Saved updated launch token! [+] Init Enclave Successful 2! Breakpoint 1, say_something (eid=2, retval=0x7fffffffe288, some_string=0x5555557c0f00 "This is a normal world string passed into Enclave!\n", len=51) at app/Enclave_u.c:731 731 { ``` -------------------------------- ### Build with Intel Compiler (Version 8+) Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_unwind/libunwind/README.md Configure command for building libunwind using the Intel compiler (icc) on versions 8 and later. ```bash $ ./configure CC=icc CFLAGS="-g -O3 -ip" CXX=icc CCAS=gcc CCASFLAGS=-g \ LDFLAGS="-L$PWD/src/.libs" ``` -------------------------------- ### Compiling a Rust SGX Enclave Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Debugging-a-local-Rust-SGX-enclave-in-docker-with-sgx-gdb This command compiles a Rust SGX enclave sample. It shows the output of the make command, including linking the enclave and signing the binary. ```bash root@ef40bc98b273:~# cd rust-sgx-sdk/samplecode/hello-rust/ root@ef40bc98b273:~/rust-sgx-sdk/samplecode/hello-rust# make info: syncing channel updates for 'stable-2019-01-17-x86_64-unknown-linux-gnu' info: latest update on 2019-01-17, rust version 1.32.0 (9fda7c223 2019-01-16) info: downloading component 'rustc' ..........(suppressed output).......... LINK => enclave/enclave.so 0 0 0x40000 0x100000 1 1 0 0 0xFFFFFFFF tcs_num 1, tcs_max_num 1, tcs_min_pool 1 The required memory is 1798144B. Succeed. SIGN => bin/enclave.signed.so ``` -------------------------------- ### Tokio Runtime Builder Configuration for gRPC Server Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/samplecode/rpc/Readme.md Configure Tokio's runtime with a specific number of worker threads using `tokio::runtime::Builder`. This example sets 32 worker threads, resulting in 33 TCS threads (32 workers + 1 initializer). ```rust #[no_mangle] pub extern "C" fn run_server() -> SgxStatus { let result = tokio::runtime::Builder::new_multi_thread() .worker_threads(32) // TCS = 32 + 1 = 33. 1 reserved for initializer .enable_all() .build() .map(|rt| rt.block_on(main())); match result { Ok(Ok(_)) => SgxStatus::Success, Ok(Err(e)) => { println!("Failed to run server: {}", e); SgxStatus::Unexpected }, Err(e) => { println!("Failed to create tokio runtime in enclave: {}", e); SgxStatus::Unexpected } } } ``` -------------------------------- ### Generate Coverage Report (Standard Build) Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/samplecode/cov/Readme.md Builds the project with code coverage enabled and then generates an HTML report. The report can be viewed at html/index.html. ```bash $ COV=1 make run $ make gen_cov_report ``` -------------------------------- ### Configure GDB Build with Python Support Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Setup-gdb-7.11-on-Ubuntu-18.04-for-VSCode---sgx-gdb-remote-debugging Configure the GDB build process, specifying the path to the Python 3 interpreter using the --with-python option. ```bash cd gdb-7.11.1 ./configure --with-python=/usr/bin/python3 ``` -------------------------------- ### Build on HP-UX with GCC Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_unwind/libunwind/README.md Configure command for building libunwind on HP-UX using GCC. Unwinding of 32-bit binaries is not supported. ```bash $ ./configure CFLAGS="-g -O2 -mlp64" CXXFLAGS="-g -O2 -mlp64" ``` -------------------------------- ### Configure target_cpu for LLVM using .cargo/config Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Performance-Optimization-Tips Configure the target CPU for LLVM by creating or modifying the `.cargo/config` file. This setting applies to the project it is placed in. ```toml [build] rustflags = ["-C", "target-cpu=native"] ``` -------------------------------- ### Initial Custom Alignment with Single Secret Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Mitigation-of-Intel-SA-00219-in-Rust-SGX Demonstrates the initial usage of `sgx::custom_alignment` with a structure containing a single secret, showing its size and offset calculations. ```cpp struct foo { uint64_t secret1[5]; // offset = 0 }; typedef sgx::custom_alignmentsecret1)> AFOO; printf("=== Size of foo = %u ===\n", sizeof(foo)); // 40 printf("=== Size of bar = %u ===\n", sizeof(AFOO)); // 64 printf("=== offset of AROO.v = %u ===\n", __builtin_offsetof(AFOO, v)); // 8 printf("=== offset of secret1 = %u ===\n", __builtin_offsetof(AFOO, v.secret1)); // 8 ``` -------------------------------- ### FreeBSD Copyright Notice and Disclaimer Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/licenses/LICENSE-tlibc.txt Standard redistribution and use conditions for FreeBSD source and binary forms. Includes a disclaimer of warranties and limitation of liability. ```text Copyright 1992-2013 The FreeBSD Project. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. ``` -------------------------------- ### Set SGX SDK Environment Variables Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Setup-gdb-7.11-on-Ubuntu-18.04-for-VSCode---sgx-gdb-remote-debugging Source the SGX SDK environment script to set up necessary environment variables for compilation. ```bash source ${sgx-sdk-install-path}/environment ``` -------------------------------- ### Build GDB 7.11.1 Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Setup-gdb-7.11-on-Ubuntu-18.04-for-VSCode---sgx-gdb-remote-debugging Compile GDB version 7.11.1. This step may take approximately 3 minutes to complete. ```bash make ``` -------------------------------- ### NetBSD Foundation Copyright and Disclaimer Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/licenses/LICENSE-tlibc.txt Copyright notice and redistribution conditions for code contributed to The NetBSD Foundation. Includes a standard 'AS IS' warranty disclaimer and liability limitation. ```c /*- * Copyright (c) 2008 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ ``` -------------------------------- ### Tokio Main Annotation for gRPC Server Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/samplecode/rpc/Readme.md This sample demonstrates using the `tokio::main` annotation to run a gRPC server within an enclave. The number of TCS threads should be set to the logical core count plus one for the initializer thread. ```rust //#[tokio::main] async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); let greeter = MyGreeter::default(); println!("GreeterServer listening on {}", addr); Server::builder() .add_service(GreeterServer::new(greeter)) .serve(addr) .await?; Ok(()) } // Ecall function #[no_mangle] pub extern "C" fn run_server() -> SgxStatus { match main() { Ok(_) => SgxStatus::Success, Err(e) => { println!("Failed to run server: {}", e); SgxStatus::Unexpected } } } ``` -------------------------------- ### Check for Altivec Support Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_unwind/libunwind/README.md Command to check if the processor has Altivec support by examining /proc/cpuinfo. ```bash cat /proc/cpuinfo | grep altivec ``` -------------------------------- ### VSCode Native Debug Configuration for SGX Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Use-VSCode---rls---rust-analysis---sgx-gdb-for-graphic-developing-(not-in-docker) This `launch.json` configuration is used with the VSCode Native Debug plugin to set up a debugging session for an SGX application. It specifies the target executable, working directory, and detailed SSH connection parameters for the debugger to launch on the remote machine. ```json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Debug", "type": "gdb", "request": "launch", "target": "app", "cwd": "${workspaceRoot}/bin", "valuesFormatting": "parseText", "gdbpath": "sgx-gdb", "ssh": { "forwardX11": false, "host": "172.19.32.44", // your IP "cwd": "${workspaceRoot}/bin", // SSH private key on remote machine. Add the pub key to ~/.ssh/authorized_keys // This ssh configuration is established from host to host, because the current // vscode session is "within a ssh session established by vscode-ssh". // I think this might be a bug but can hardly be resolved. "keyfile": "/home/ding/.ssh/id_rsa", // private key "user": "ding", "bootstrap": "source /opt/sgxsdk/environment", "port": 22 } } ] } ``` -------------------------------- ### Fix for CVE-2020-5499: Using sync::Once for Enclave ID Initialization Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Everything-about-CVE---2020---5499 This diff shows the modification to `sgx_tstd/src/rt.rs` to address the enclave ID racing problem. The `t_global_init_ecall` function is now wrapped with `INIT.call_once(|| { ... });` to ensure that the enclave ID and path are initialized atomically, preventing data races. ```diff diff --git a/sgx_tstd/src/rt.rs b/sgx_tstd/src/rt.rs index fcfd0a42..3f738a53 100644 --- a/sgx_tstd/src/rt.rs +++ b/sgx_tstd/src/rt.rs @@ -36,6 +36,9 @@ use core::str; pub use crate::panicking::{begin_panic, begin_panic_fmt, update_panic_count}; pub use crate::sys_common::at_exit; use crate::sys_common::cleanup; +use crate::sync::Once; + +static INIT: Once = Once::new(); #[no_mangle] pub extern "C" fn t_global_exit_ecall() { @@ -43,13 +46,14 @@ pub extern "C" fn t_global_exit_ecall() { #[no_mangle] pub extern "C" fn t_global_init_ecall(id: u64, path: * const u8, len: usize) { - - enclave::set_enclave_id(id as sgx_enclave_id_t); - let s = unsafe { - let str_slice = slice::from_raw_parts(path, len); - str::from_utf8_unchecked(str_slice) - }; - enclave::set_enclave_path(s); + INIT.call_once(|| { + enclave::set_enclave_id(id as sgx_enclave_id_t); + let s = unsafe { + let str_slice = slice::from_raw_parts(path, len); + str::from_utf8_unchecked(str_slice) + }; + enclave::set_enclave_path(s); + }); } global_dtors_object! { ``` -------------------------------- ### Emit Assembly Code using .cargo/config Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Performance-Optimization-Tips Configure the build system to emit assembly code by creating or modifying the `.cargo/config` file. This setting applies to the project it is placed in. ```toml [build] rustflags = ["--emit", "asm"] ``` -------------------------------- ### Run Regression Tests Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/sgx_unwind/libunwind/README.md Command to execute the set of regression tests after building the library. ```bash $ make check ``` -------------------------------- ### Mitigation by Inserting Padding Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Mitigation-of-Intel-SA-00219-in-Rust-SGX Shows how inserting a padding field between consecutive secrets resolves the compilation issue with `sgx::custom_alignment`, allowing for successful alignment. ```cpp struct foo { uint64_t secret1[5]; // offset = 0 char dumb; // offset = 40 uint64_t secret2[3]; // offset = 48 }; typedef sgx::custom_alignmentsecret1), __builtin_offsetof(foo, secret2), sizeof(((foo*)0)->secret2) > AFOO; printf("=== Size of foo = %u ===\n", sizeof(foo)); // 72 printf("=== Size of bar = %u ===\n", sizeof(AFOO)); // 128 printf("=== offset of AROO.v = %u ===\n", __builtin_offsetof(AFOO, v)); // 24 printf("=== offset of AROO.v.secret1 = %u ===\n", __builtin_offsetof(AFOO, v.secret1)); // 24 printf("=== offset of AROO.v.secret2 = %u ===\n", __builtin_offsetof(AFOO, v.secret2)); // 72 ``` -------------------------------- ### Generate Coverage Report (Xargo Build) Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/samplecode/cov/Readme.md Builds the project with code coverage enabled using xargo and then generates an HTML report. This is suitable for projects that use xargo for cross-compilation or custom build environments. ```bash $ BUILD_STD=xargo COV=1 make run $ BUILD_STD=xargo make gen_cov_report ``` -------------------------------- ### Generate Coverage Report (Cargo-std-aware Build) Source: https://github.com/apache/teaclave-sgx-sdk/blob/main/samplecode/cov/Readme.md Builds the project with code coverage enabled using cargo-std-aware mode and then generates an HTML report. This is useful for projects that integrate with cargo's standard library awareness. ```bash $ BUILD_STD=cargo COV=1 make run $ BUILD_STD=cargo make gen_cov_report ``` -------------------------------- ### Enable Link Time Optimization (LTO) in Cargo.toml Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Performance-Optimization-Tips Enable link-time optimization for release builds to potentially boost CPU-intensive enclaves. This setting is added to the `Cargo.toml` file. ```toml [profile.release] lto = true ``` -------------------------------- ### On-Heap Initialization with AlignBox Source: https://github.com/apache/teaclave-sgx-sdk/wiki/Mitigation-of-Intel-SA-00219-in-Rust-SGX Use `AlignBox` for on-heap initialization of aligned structures, ensuring no bit copying from the stack. This is useful when dealing with sensitive data structures that require specific alignment. ```rust let heap_align_obj = AlignBox::::heap_init_with_req(|mut t| { t.key1 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]; t.pad1 = [0x00; 16]; t.key2 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]; t.pad2 = [0x00; 16]; t.key3 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]; t.pad3 = [0x00; 16]; t.key4 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]; }, 16, &str_slice); assert!(heap_align_obj.is_some()); ```