Differences

This shows you the differences between two versions of the page.

Link to this comparison view

isc:labs:03 [2022/03/20 19:17]
florin.stancu install qemu for SGX on UPB openstack
isc:labs:03 [2024/03/18 09:07] (current)
alexandru.mircea98 [[30p] 3. Using OpenSSL]
Line 1: Line 1:
-TODO+/* ~~SHOWSOLUTION~~ */
  
-===== Trusted Execution (e.g., Intel SGX) ======+====== Lab 03  - Hardware Security ​======
  
-SGX is an Intel technology aiming secure code execution inside enclaves, available starting with Intel Skylake CPUs. An enclave is a protected region of memory that can only be accessed by the owning application (not even the kernel or other peripherals - e.g. DMA - is allowed to read it). It can provide remote attestation to services that require code to be executed on untrusted devices.+===== Objectives ===== 
 +  * Side Channel Attacks 
 +  * Hardware Security Basics 
 +  * OpenSSL / PKCS#11 & #15 tools 
 +  * HSMs: Java Card & Simulator
  
-SGX applications are divided into two logical components: trusted and untrusted. Intel advises that the trusted component (the enclave) should be as small as possible (small ​lesser chance of bugs), enforced by a hardware limit of 128 MB for the entire protected memory space.+===== Preparation =====
  
-The enclave code runs in user space, and thus can access ​the entire memory of the process within which it runsIn this way, data can be transmitted between the trusted and untrusted application regions, e.g. for passing function parameters and results. +You may use the UPB's [[https://​cloud.grid.pub.ro|OpenStack cloud to instantiate a Virtual Machine]] to be used for this lab! 
-An aspect worth mentioning is that, inside the enclave, one can not directly execute priviledeged operations (such as system calls). For this, one needs to execute an untrusted function.+[[:​isc:​info:​virtualmachine|Read these instructions if you wanna know how!]].
  
-For the interaction between those two components, the SDK exposes two important concepts:+===== Overview =====
  
-  * ECALL (Enclave Call) - entering the enclave and calling a function inside the enclave. +==== Basics ====
-  * OCALL (Outside Call) - calling an untrusted function from the enclave mode. It implies leaving the protected mode, executing the untrusted function and then reentering the enclave.+
  
-These functions represent the way the untrusted application part and the enclave interact. They are defined ​in an EDL file (Enclave Definition Language), in specific formatA simple EDL file looks like this:+For a long time, hardware had a central role in computer security. Take, for example, the CPU's protection rings model (on x86): they realize ​privilege separation between a hypervisor / Operating System kernel and the user applications and is enforced at hardware-level for efficiency.
  
-<​code>​ +Nowadays, the security requirements of certain applications has led to the implementation of additional access control or cryptographic functions directly into the hardware, e.g., AES-NI ​SHA SSE-based instructions,​ the Trusted Platform Module cryptoprocessor,​ Smart Cards or Trusted Execution Environments ​(ARM TrustZoneIntel SGX, memory encryption etc.).
-enclave { +
-    trusted { +
-        /* define ECALLs here*/ +
-        public int get_sum(int aint b)+
-    };+
  
-    untrusted { +On different notehardware ​is also susceptible ​to security bugs: side channel attackscryptographic vulnerabilities (e.g., cache or timing attacks or the much recent Spectre ​Meltdown speculative execution bugs), hardcoded credentials ​or even manufacturer-introduced backdoors
-        /* define OCALLs here. */ +These are very difficult ​(or even impossible) to fix without re-designing ​the chip and replacing the faulty products.
-        void ocall_print([in,​ string]const char* str); +
-    }; +
-}; +
-</​code>​ +
-ECALL and OCALL functions parameters that are pointers should be decorated with either ​pointer direction attribute inout or a user_check attribute explicitly. +
-  * [in] – the parameter ​is passed from the calling procedure ​to the called procedure. For an ECALL the in parameter is passed from the application to the enclavefor an OCALL the parameter is passed from the enclave to the application. +
-  * [out] – the parameter is returned from the called procedure to the calling procedureIn an ECALL function an out parameter is passed from the enclave to the application and an OCALL function passes it from the application to the enclave. +
-  * [user_check] - Pointer is not checked. Users must perform the check and/or copy+
-Observation: ​ Using direction attributes ​([in], [out]implies copying buffers from the application ​to enclave or the other way around, so usually these are followed by a size attributes that indicates how much data needs to be copied, e.g.: +
-<​code>​ +
-void foo([in, size=buf_len]const char* buf, size_t buf_len); +
-</​code>​+
  
-===== Preparation =====+==== Side Channel Attacks ​====
  
-==== Instance Creation ====+A side-channel attack is a type of cyber-attack that targets the unintended //side effects// of a software application / hardware component in a computer system, rather than attacking it directly. These side effects may include signals or data that are generated by the system'​s physical components, such as its power consumption,​ electromagnetic emissions, or even sound.
  
-Ideallyyou should solve this laboratory on [[https://​cloud.grid.pub.ro|openstack]]. As in the first week, create ​an **m1.small** instance from the **ISC 2020** image. If you are outside the campus local network, you will need to set up a 2-hop SSH connection via fep. If you have configured your **localhost**'​s ​keypair on openstack (not the one you generated on fep)you can connect ​directly ​this way: +By analyzing these side effects, an attacker can gain information about the system'​s ​operationssuch as encryption keys or other sensitive data, without ​directly ​accessing the system. Side-channel attacks ​can be executed remotely or locally ​and are often used to target cryptographic systems that use secret keys.
-<code bash> +
-$ ssh -J ${LDAP_ID}@fep.grid.pub.ro student@${VM_IP} +
-</​code>​ +
-NOTE: you can have more than one keypair configured (both for your localhost, ​and for fep). Select the one you want from the //Key Pair// tab during the instance creation.+
  
-**<color red>​Note:​ UPB's OpenStack servers currently have very old CPUs (Core 2 Duo!!!) lacking modern cryptographic instructions!</​color>​** +==== Java Smart Cards ====
-We will need to work around it by using qemu user-mode emulation (version >4 required, so we need to install it beforehand):​ <code bash> +
-wget http://​archive.ubuntu.com/​ubuntu/​pool/​universe/​q/​qemu/​qemu-user-static_4.2-3ubuntu6.21_amd64.deb +
-sudo dpkg -i qemu-user-static_4.2-3ubuntu6.21_amd64.deb +
-# test it? +
-qemu-x86_64-static --version +
-</​code>​+
  
 +Java smart cards are small electronic devices that have an embedded microprocessor and memory, which can be programmed with Java Card technology to perform secure transactions and store sensitive information. Java Card technology is a subset of Java that has been designed specifically for smart card environments.
  
-==== SGX SDK Usage and Skeleton ====+Java smart cards can be found in various forms, such as SIM cards in mobile phones, banking cards, e-passports, ​and employee ID cards. They can be purchased from smart card manufacturers or vendors, or provided by organizations to their customers or employees.
  
-You can find the skeleton here: {{:​isc:​labs:​isc-enclave-2020.zip|}}. The provided code archive contains TODOs that will guide you through solving ​the tasks. Over the course of the lab, make sure to consult the [[https://​download.01.org/​intel-sgx/​sgx-linux/​2.8/​docs/​Intel_SGX_Developer_Reference_Linux_2.8_Open_Source.pdf|documentation]].+To program and manage Java smart cards, specialized software development kits and tools are needed, such as Java Card Development Kit (JCDK), Global Platform Card Specification,​ and Smart Card Integrated Development Environment (IDE). Developers ​can use these tools to create and test Java Card applets ​that run on the smart cards and perform various secure operations.
  
-Since you'll be working inside a headless machine, you will need some vim skills to effortlessly edit the code; don't worry! [[https://​vim.rtorr.com/​|there are plenty of docs on the Internet]] ;)+===== Tasks =====
  
-Normally, to benefit from //most// SGX security features, you need two things: +==== [40p] 1Python timing side channel attack ====
-  - **SGX driver & BIOS support**: needed to lock memory and limit access to Enclaves. +
-  - **SGX SDK (Software Development Kit)**: implements most Enclave interactions,​ generates required code from EDL files, signs resulting objects, etc.+
  
-SGX projects can be compiled in both **hardware** and **simulation** mode. Since we will be working in simulation mode, we won't require ​the SGX driver, the BIOS support, or even the [[https://www.felixcloutier.com/​x86/​enclu|ENCLU]] instructions that implement the SGX functionality. The SDK is already installed on your VM.+Download ​the {{isc:labs:​lab03-sidechannel.zip|side channel demo}} archive here.
  
-In order to be able to use the SDK, you need to import/​update some environment variables:​ +Implement ​the TODOs and crack the password via a timing attack ;)
-<code bash> +
-# do this in every shell you open (maybe add it to .bashrc) +
-source /​opt/​intel/​sgxsdk/​environment +
-</​code>​+
  
-Use the following Makefile targets for compiling / cleaning the workspace:​ +<note
-<code bash+Hint: you have LunarVim installed on the VM, use ''​lvim ​${file}''​ to start it! 
-make SGX_MODE=SIM +</note>
-$ make clean +
-</code>+
  
-==== Working Locally ====+<​solution -hidden>​ 
 +<​code>​ 
 +TODO(1): 
 +CHARACTERS ​ascii_letters + digits + '​{}'​
  
-<note important>​ +TODO(2): 
-Due to the huge setup time, this is not recommended to do during the on-premise activity. +CHECK_PASS_LEN_VULN = check_password1 
-</​note>​+CHECK_PASS_CHARS_VULN = check_password2
  
-If you encounter problems creating an //​openstack//​ instance, you may be able to solve the lab locally. You will have to install the SGX SDK from [[https://​github.com/​intel/​linux-sgx|here]]. The code for this laboratory will be compiled ​in **simulation** mode, so you won't need hardware support. Here are the steps for Ubuntu 18.04. Make the necessary modifications based on the SDK repo's README.md if you are using something else:+TODO(3): 
 +for length ​in range(20)
  
-<note warning>​ +TODO(4): 
-The SDK build process for **Ubuntu 16** is broken. +if CHECK_PASS_LEN_VULN(np): 
-This is 100% the fault of the Intel developers working on the SDK. +    ​return np 
-Unless you want to try and update your //glibc// from 2.23 to 2.27, work in a docker container ​([[https://​www.digitalocean.com/​community/​tutorials/​how-to-install-and-use-docker-on-ubuntu-16-04|how to install]]): + 
-<code bash> +TODO(5): 
-# use sudo if you are not in the docker group +duration = timed_check_pass(CHECK_PASS_CHARS_VULN,​ pad(np, length))
-$ docker run -ti --entrypoint bash ubuntu:20.04+
 </​code>​ </​code>​
-</note>+</solution>
  
 +==== [30p] 2. Using OpenSSL ====
  
-<code bash> +You are tasked with encrypting a large file using RSA. 
-# IMPORTANT: find out what distro you are using +For this, you will need to use both symmetric and asymmetric crypto, and all of this can be done using one swiss-army-knife-like tool ''​openssl''​! ​
-#            especially if you are working on WSL +
-#            ​use this information where appropriate in the build process +
-$ cat /etc/lsb-release +
-    DISTRIB_ID=Ubuntu +
-    DISTRIB_RELEASE=18.04 +
-    DISTRIB_CODENAME=bionic +
-    DISTRIB_DESCRIPTION="​Ubuntu 18.04.5 LTS"+
  
-# install deps for Ubuntu 18 +  * For starters, we need a file to encrypt; let's make a backup of ''/​etc/'':​ <​code>​ 
-sudo apt update ​-y && sudo apt install ​-y          \ +sudo tar czf etc-backup-2023.tar.gz ​-C /etc . 
-  build-essential ocaml ocamlbuild automake autoconf \ +</​code>​
-  ​libtool wget python libssl-dev git cmake perl      \ +
-  libssl-dev libcurl4-openssl-dev protobuf-compiler ​ \ +
-  libprotobuf-dev debhelper cmake reprepro unzip+
  
-install deps for Ubuntu ​20 +  * We will use a symmetric cipher to encrypt the file using an ephemeral (random) key (which we will then encrypt using RSA): <​code>​ 
-$ sudo apt update -y && sudo apt install -y              \ +generate the random passphrase 
-  ​build-essential ocaml ocamlbuild automake autoconf ​    \ +dd if=/​dev/​urandom of=.mysecretpass bs=20 count=1 
-  libtool wget python-is-python3 libssl-dev git cmake    \ +</​code>​ 
-  ​perl libssl-dev libcurl4-openssl-dev protobuf-compiler \ +  ​* Encrypt the file using ''​openssl enc -aes-256-cbc -e''​ and the password generated earlier from file; 
-  ​libprotobuf-dev debhelper cmake reprepro unzip+  ​* **Hint**: ''​openssl enc %%--%%help''​ (you can specify password from file using ''​-pass file:<​path-to-passphrase-file>''​). 
 +<note info> 
 +Almost all ''​openssl''​ operations take their options using a single dash (''​-''​);​ all subcommand may take input from a file specified by ''​-in <​file-path>''​ and may output their results to a file specified by ''​-out <file-path>''​! 
 +</​note>​ 
 +<​note>​ 
 +OpenSSL'​s symmetric encryption can use PBKDF2 to derive a key from an arbitrary password (salted, by default). 
 +It also chooses a secure IV for the first block automatically,​ so we don't have to do anything else (but we could: using the ''​-K''​ and ''​-iv''​ arguments). 
 +</​note>​
  
 +  * Generate a RSA key pair: <​code>​
 +openssl genrsa -out <specify your filename>​
 +</​code>​
 +  * Export the public key to a separate file (**hint:** use ''​openssl rsa -pubout''​ -- ofc, ''​%%--%%help''​ to see the syntax!);
 +  * Encrypt the AES passphrase file (then delete the original!): <​code>​
 +openssl pkeyutl -in <​path-to-passphrase-file>​ -out backup-secret.enc -pubin -inkey <​your-public-key>​ -encrypt
 +rm -f <​path-to-passphrase-file>​
 +</​code>​
 +  * __**some time later...**__
 +  * Oh noes, our system crashed and we lost all configuration! Fortunately,​ we have the encrypted backup file! First, you need to decrypt the AES passphrase using your private RSA key! Use ''​openssl pkeyutl''​ with ''​-decrypt''​ (note: ''​-inkey''​ must point to your private key generated above!)!
 +  * Once you obtain the AES passphrase, decrypt the backup file and test it: <​code>​
 +openssl enc -aes-256-cbc -d -pbkdf2 -in etc-backup-encrypted.bin -pass file:<​decrypted-passfile>​ -out backup-decrypted.tar.gz
 +# test whether the resulting .tar.gz archive is valid?
 +file backup-decrypted.tar.gz
 +</​code>​
  
-clone repo and init submodules +<​solution -hidden><​code>​ 
-$ git clone https://github.com/​intel/​linux-sgx.git +generate the random passphrase 
-$ cd linux-sgx +dd if=/dev/urandom of=.mysecretpass bs=20 count=1 
-$ make preparation ​-j $(nproc)+# use openssl enc: 
 +openssl enc -aes-256-cbc -e -pass file:​.mysecretpass -pbkdf2 -in etc-backup-2023.tar.gz -out etc-backup-encrypted.bin 
 +# generate RSA key pair 
 +openssl genrsa ​-out key.pem 
 +openssl rsa -in key.pem -pubout -out key.pub 
 +# encrypt the AES password file: 
 +openssl pkeyutl -in .mysecretpass -out backup-secret.enc -pubin -inkey key.pub -encrypt 
 +# decrypt the AES password file 
 +openssl pkeyutl -in backup-secret.enc -out .decrypted-passfile -inkey key.pem -decrypt 
 +# decrypt the archive 
 +openssl enc -aes-256-cbc -d -pbkdf2 -in etc-backup-encrypted.bin -pass file:​.decrypted-passfile -out backup-decrypted.tar.gz 
 +# test whether the resulting .tar.gz archive is valid? 
 +file backup-decrypted.tar.gz 
 +</​code></​solution>​
  
-# make sure to use the provided mitigation binaries or the +==== [30p] 3Java Card Simulator ====
-# next step will fail; change "​ubuntu18.04"​ to your distro +
-$ export PATH="​$(realpath external/​toolset/​ubuntu18.04):​${PATH}"​ +
-$ which as ld ld.gold objdump +
-    ${HOME}/​linux-sgx/​external/​toolset/​ubuntu18.04/​as +
-    ${HOME}/​linux-sgx/​external/​toolset/​ubuntu18.04/​ld +
-    ${HOME}/​linux-sgx/​external/​toolset/​ubuntu18.04/​ld.gold +
-    ${HOME}/​linux-sgx/​external/​toolset/​ubuntu18.04/​objdump+
  
-# compile SDK with default settings; create installer +{{ :​isc:​labs:​lab03.png?​direct&​600 |}}
-$ make sdk_install_pkg -j $(nproc)+
  
-# create installation path and install ​SDK +In order to simulate a Java Card, we must install ​all required Java components (Oracle JavaCard SDKs, jCardSim, IsoApplet, VSmartCard).
-$ mkdir /​opt/​intel +
-$ cd linux/​installer/​bin +
-./​build-installpkg.sh sdk +
-$ ./​sgx_linux_x64_sdk_2.13.100.4.bin +
-    Do you want to install in current directory? [yes/no] : no +
-    Please input the directory which you want to install in : /opt/intel+
  
-# import env variables specific ​to the installed SDK +**Note**: you don't need to do this on the ISC VM 2023, it's already been setup!
-$ source /​opt/​intel/​sgxsdk/​environment+
  
-# test that everything is working +<​spoiler>​ 
-$ cd ../../../SampleCode/SampleEnclave +  * Download the [[https://​github.com/​martinpaljak/​oracle_javacard_sdks|Oracle JavaCard SDKs]]: 
-make SGX_MODE=SIM +<code bash> 
-./app +git clone https://​github.com/martinpaljak/​oracle_javacard_sdks.git "​$HOME/​oracle_javacard_sdks"​ 
-    ​Checksum(0x0x7fffffffd5f0100= 0xfffd4143 +export JC_HOME="​$HOME/​oracle_javacard_sdks/​jc222_kit"​ 
-    Info: executing thread synchronizationplease wait...   +export JC_CLASSIC_HOME="​$HOME/​oracle_javacard_sdks/​jc305u3_kit"​ 
-    InfoSampleEnclave successfully returned+</​code>​ 
-    ​Enter ​character before exit ...+  * Since we don't have a physical smart card, we need a simulator: download & install [[https://​github.com/arekinath/​jcardsim|JCardSim]]:​ 
 +<code bash> 
 +git clone https://​github.com/​arekinath/​jcardsim.git "$HOME/jcardsim"​ 
 +cd "$HOME/jcardsim";​ mvn initialize && mvn clean install 
 +</​code>​ 
 +  * We now need an applet to install on our (emulated) Smart Card. [[https://​github.com/​philipWendland/​IsoApplet|IsoApplet]] is an open source applet implementing Public Key cryptography operations (with OpenSC integration):​ 
 +<code bash> 
 +git clone -b main-javacard-v2.2.2 https://​github.com/​philipWendland/​IsoApplet.git "$HOME/​IsoApplet"​ 
 +cd "$HOME/IsoApplet"​ 
 +# install dependencies ​(fortunatelythis project uses git submodules
 +git submodule init && git submodule update 
 +# unfortunatelyjCardSim cannot simulate CAPs (compiled applet firmwares)... 
 +# so we directly compile the Java files (make sure to have the card simulator'​s SDK in Java Path): 
 +javac -classpath "​$HOME/​jcardsim/​target/​jcardsim-3.0.5-SNAPSHOT.jar"​ "​$HOME/​IsoApplet/​src/​xyz/​wendland/​javacard/​pki/​isoapplet/"​*.java 
 +</​code>​ 
 +  * Finally, note that we need Card Reader to interface with the smart cardsSo, with our simulated card, we will have to use a virtual card reader software (''​vpcd''​ from [[https://​frankmorgner.github.io/​vsmartcard/​virtualsmartcard/​README.html|vsmartcard]]):​ 
 +<code bash> 
 +git clone https://​github.com/​frankmorgner/​vsmartcard.git "​$HOME/​vsmartcard"​ 
 +cd "​$HOME/​vsmartcard/​virtualsmartcard"​ 
 +autoreconf -vis && ./configure && sudo make install 
 +# Restart PCSC daemon to load our new vcard driver 
 +sudo systemctl restart pcscd 
 +cd ~  # go back to home
 </​code>​ </​code>​
  
-If you installed the latest SDK yourselvesuse the updated skeleton from {{:isc:​labs:​isc-enclave-2020-revision.zip|here}}.+Finallywe must create a configuration file for ''​jcardsim'''​:
  
-If you want to check whether you do have hardware support, there are two easy ways: 
-  - Check if bit 2 is set in the EBX register as returned by the EAX=7,ECX=0 [[https://​en.wikipedia.org/​wiki/​CPUID#​EAX=7,​_ECX=0:​_Extended_Features|CPUID]] leaf instruction. You can use the tool with the same name: [[https://​linux.die.net/​man/​1/​cpuid|cpuid]]. 
-  - Compile and run //​test-sgx.c//​ from this [[https://​github.com/​ayeks/​SGX-hardware|repo]]. Note that this user also maintains a list of hardware that supports Intel SGX (if you may ever need it). 
- 
-===== Tasks ==== 
- 
-==== [20p] 1. Implement an ECALL function that generates a random number (unsigned int) inside the enclave, between 3 and 42. ==== 
-The function should have the **prototype**: ​ 
 <​code>​ <​code>​
-unsigned int generate_random_number(void)+$ cat $HOME/​jcardsim.cfg ​ # <-- yes, create this file ! 
 +com.licel.jcardsim.card.applet.0.AID=F276A288BCFBA69D34F31001 
 +com.licel.jcardsim.card.applet.0.Class=xyz.wendland.javacard.pki.isoapplet.IsoApplet 
 +com.licel.jcardsim.card.ATR=3B80800101 
 +com.licel.jcardsim.vsmartcard.host=localhost 
 +com.licel.jcardsim.vsmartcard.port=35963
 </​code>​ </​code>​
 +</​spoiler>​
 +<​html><​br></​html>​
  
-**Steps** +**[Re]Start ​the PCSC service:** 
-  - Add the function prototype to **Enclave/​Enclave.edl** +<​code ​bash
-  - Implement the function in **Enclave/​Enclave.cpp**. The function must make use of the **sgx_read_rand** function in the Intel SGX SDK. <​code>​sgx_status_t sgx_read_rand(unsigned char *rand, size_t length_in_bytes);</​code>​ Where: +the VM does not automatically start thisso do it manually 
-      * rand - pointer to the memory area where the random bytes will be generated +sudo systemctl restart pcscd
-      * length_in_bytes - number of bytes to generate +
-      * **sgx_trts.h** must be included +
-  - Call the function in **App/​App.cpp**. First parameter of the function must be **global_eid**. The result is returned in the **second parameter**. The following parameters (if any) represent the arguments of the function defined in **Enclave/​Enclave.cpp** +
- +
-  * **Hint**: See the already implemented get_sum ECALL. +
- +
-==== [20p] 2. System calls can not be called directly from an enclave. ==== +
-  * Implement 2 OCALLSone for reading from a file, the other for writing to a file. +
-  * The functions should have the prototypes: <​code>​ +
-void ocall_write_file(const char* filename, const char* buf, size_t buf_len); +
-void ocall_read_file(const char* filename, char* buf, size_t buf_len);+
 </​code>​ </​code>​
-  * The functions must be implemented in **App/​App.cpp** and their prototypes must be added to **Enclave/​Enclave.edl**. The parameters which are pointers must be decorated as described in the beginning of the lab (similar to **ocall_print**). Please note that **filename** is a string, but **buf** might contain non-ASCII characters, so **buf_len** must be used to describe its size. 
-  * **Obs**: The methods are also responsible for opening/​closing the corresponding file descriptors. 
-  * **Hint**: [[https://​www.geeksforgeeks.org/​input-output-system-calls-c-create-open-close-read-write/​|I/​O system calls]] Don't forget to include **unistd.h** and **fcntl.h** 
  
-==== [20p] 3. Implement a function, inside the enclave, that does the following operations: ==== +**Start the simulator:**
-  ​Seals the string “SGX_RULLZ” using **sgx_seal_data**. <​code>​sgx_status_t sgx_seal_data( +
-    const uint32_t additional_MACtext_length, ​ ---> no additional MAC, this parameter should be 0 +
-    const uint8_t * p_additional_MACtext, ​     ---> no additional MAC, this parameter should be NULL +
-    const uint32_t text2encrypt_length, ​       ---> length of the text to be encrypted +
-    const uint8_t ​p_text2encrypt, ​           ---> the text to be encrypted (make sure the type of this parameter is uint8_t- you can use casts) +
-    const uint32_t sealed_data_size, ​          ​--->​ length of the output (encrypted text), must be computed using sgx_calc_sealed_data_size (see below) +
-    sgx_sealed_data_t * p_sealed_data ​         ---> output of the function; you must dynamically allocate this prior to this function call +
-);</​code>​. Use **sgx_calc_sealed_data_size** to calculate the number of bytes to allocate for the **sgx_sealed_data_t** structure and to use for the **sealed_data_size** parameter. <​code>​uint32_t sgx_calc_sealed_data_size( +
-    const uint32_t add_mac_txt_size, ​          ​--->​ no additional MAC, this parameter should be 0 +
-    const uint32_t txt_encrypt_size ​           ---> length of the text to be encrypted +
-);</​code>​ +
-  * Writes the sealed data into a file (filename is given by the macro SECRET_ENCLAVE) +
-  * [[https://​software.intel.com/​en-us/​blogs/​2016/​05/​04/​introduction-to-intel-sgx-sealing|More on SGX sealing]].+
  
-  * The function prototype should be: <​code>​ +<​code ​bash
-void seal_secret(void);​+java -classpath "​$HOME/​jcardsim/​target/​jcardsim-3.0.5-SNAPSHOT.jar:​$HOME/​IsoApplet/​src"​ com.licel.jcardsim.remote.VSmartCard "​$HOME/​jcardsim.cfg"​
 </​code>​ </​code>​
-  * Inspect ​the file contents. Can you guess the secret?+<note hint> 
 +Hint: use separate terminals or ''​tmux'',​ since the command is blocking and prints lots of debugging info, so it will not be a good idea to run it in background with ''&''​ and reuse that terminal! 
 +</​note>​
  
-  * **Obs**: Uncomment the function call from main and don't forget about **Enclave/​Enclave.edl**+**Loading the Smart Card applet:**
  
-==== [20p] 4. Similar to the sealing function, implement a function, inside the enclave, that unseals the enclave secret. ==== +<​note>​ 
-  * Reads the content of SECRET_ENCLAVE file (it contains sealed data) +The APDU [[https://en.wikipedia.org/wiki/Smart_card_application_protocol_data_unit|Smart Card Application Protocol Data Unit]] is a communication protocol used for interfacing with smart cardsstandardized in ISO/IEC 7816-4.
-  * Uses **sgx_get_encrypt_txt_len()** (see [[https://01.org/sites/default/​files/​documentation/​intel_sgx_sdk_developer_reference_for_linux_os_pdf.pdf|documentation]]) to determine the buffer size for the decrypted data and allocate said buffer. +
-  * Unseals the data using **sgx_unseal_data** <​code>​sgx_status_t sgx_unseal_data( +
-    const sgx_sealed_data_t * p_sealed_data, ---> encrypted data (read from the file); you must cast the buffer read from the file to sgx_sealed_data_t * +
-    uint8_t * p_additional_MACtext, ​         ---> no additional MAC, this parameter should be NULL +
-    uint32_t * p_additional_MACtext_length, ​ ---> no additional MAC, this parameter should be 0 +
-    uint8_t * p_decrypted_text, ​             ---> buffer where the decrypted data will be written; you can allocate it +
-                                                  statically, just make sure you provide a large enough buffer +
-    uint32_t * p_decrypted_text_length ​      ​--->​ this parameter is both input and output; +
-                                                  as input, it represents the length of p_decrypted_text;​ +
-                                                  as output, represents the number of bytes that were decrypted +
-);</​code>​ +
-  * Prints the unsealed string.+
  
-  * The function prototype should be<​code>​ +We use an [[https://​jcardsim.org/​docs/​quick-start-guide-using-in-cli-mode|initial APDU script]] to install & execute the IsoApplet into the emulated smart card. 
-void unseal_secret(void);​ +</note>
-</code> +
-  * **Obs**: Uncomment the function call from main and don't forget about **Enclave/​Enclave.edl**+
  
 +<code bash>
 +# install IsoApplet usign a APDU script
 +opensc-tool --card-driver default --send-apdu 80b800001a0cf276a288bcfba69d34f310010cf276a288bcfba69d34f3100100
 +opensc-tool -n
  
-==== [10p] 5. Modify the seal_secret ECALL such that it seals random generated stringinstead of “SGX_RULLZ”====+# create PKCS#15 structure on our smart card (also set PIN and a PUKfor security purposes) 
 +pkcs15-init --create-pkcs15 --so-pin 123456 --so-puk 0123456789abcdef 
 +# generate an RSA key pair to use for signing (note: auth-id is a PIN slot) 
 +pkcs15-init --generate-key rsa/​2048 ​ --id 1 --key-usage decrypt,​sign --label MyRSAKey --auth-id FF --pin 123456 
 +# download the generated public key to your machine 
 +pkcs15-tool --read-public-key "​1"​ --output "​smartcard-pubkey.pem"
  
-  * Use **sgx_read_rand** for generating the string.+echo "Sunt de acord să cedez toată averea mea asistenților de ISCAdevăraaat\!"​ > textToSign.txt 
 +openssl dgst -engine pkcs11 -sign "​pkcs11:​object=MyRSAKey;​type=private;​pin-value=123456"​ -keyform ENGINE -sha256 -out textSignature.sig textToSign.txt
  
-<​solution ​-hidden>+# now everyone can check whether the document is correctly signed using the public key: 
 +openssl dgst -sha256 -verify smartcard-pubkey.pem -keyform PEM -signature textSignature.sig textToSign.txt 
 +# modificați fișierul textToSign.txt și re-verificați semnătura digitală... ce se întâmplă?​ 
 +</code>
  
-Tasks archive: https://drive.google.com/open?​id=0BypiZKffc_dBVEVGaC1jcllJaFE+<note important>​ 
 +Unfortunately,​ jCardSim is unstable and will crash after some short timeout (approx. several minutes), so make sure you run these commands with little pause between them (make a script). 
 +If it crashed, you must restart both the ''​pcscd''​ service and the simulator<​code>​ 
 +killall java 
 +sudo systemctl restart pcscd 
 +java -classpath "$HOME/jcardsim/target/​jcardsim-3.0.5-SNAPSHOT.jar:​$HOME/​IsoApplet/​src" ​com.licel.jcardsim.remote.VSmartCard "​$HOME/​jcardsim.cfg"​ 
 +</​code>​ 
 +</note>
  
-Solutions archivehttps://​drive.google.com/open?​id=0BypiZKffc_dBdXR2UWItQ2pyd1k+Finally, here's one last challengeuse ''​openssl''​ to encrypt ​decrypt a file using this key!
  
 +<​solution -hidden>
 +<code bash>
 +openssl pkeyutl -encrypt -in textToSign.txt -pubin -inkey smartcard-pubkey.pem -out encrypted.enc
 +openssl pkeyutl -decrypt -in encrypted.enc -engine pkcs11 -keyform ENGINE -inkey "​pkcs11:​object=MyRSAKey;​type=private;​pin-value=123456"​ -out decrypted.txt
 +</​code>​
 </​solution>​ </​solution>​
  
-<​hidden>​ +Bonus: [[https://access.redhat.com/articles/​1523343|You can configure OpenSSH ​to use private ​key stored inside ​smart card for authentication]]!
- +
-Ex. scoase: +
- +
-===== Trusted Platform Module ====== +
- +
-==== Description ==== +
- +
-The Trusted Platform Module (TPM) is a standard for secure cryptoprocessors maintained +
-by the Trusted Computing Group (TCG) consortium that provides hardware-based cryptographic +
-functions for secure key generation, integrity (remote attestation) and data protection +
-(sealing). +
- +
-Note that, by itself, the TPM is inert. It needs to receive commands from another party +
-(e.g. firmware, CPU) for it to be useful. +
- +
-For example, it can be coupled with Intel Trusted Execution Technology (TXT) to provide +
-trusted boot ([[https://www.quora.com/What-is-the-difference-between-Secure-Boot-and-Trusted-Platform-Module-given-that-both-involves-Trusted-Hardware|not to be confused with secure boot]], which is weaker). +
- +
-As soon as a "chain of trust" is established,​ the TPM may be used to permanently seal +
-(i.e. encrypt) sensitive data like disk encryption keys such that, if the software / hardware +
-integrity is compromised,​ it won't be able to access it. +
- +
-This is realized by using the TPM's PCRs (Platform Configuration Registers): registers that are +
-reset on system'​s startup that store hashes of system'​s code and configuration at different +
-points of execution. They can only be extended, never modified, thus, if the software is somehow +
-altered, the PCRs will result with an invalid hash and the integrity checks will fail. +
- +
-The TPM can also be used for storing encrypted data, sealed with secret ​key+
-together with the current PCRs values. +
-For decryption, the PCRs are compared with the sealed ones. If not the same, the cryptoprocessor +
-will refuse decryption, so the data remains safe until the unaltered state of the system is +
-restored. +
- +
-==== Tasks ==== +
- +
-There is [[https://​github.com/​PeterHuewe/​tpm-emulator|TPM Emulator]] project available,​ +
-though we weren'​t able to make it work :D +
- +
-So rejoyce! No tasks to be done for this lab! +
-But, if you are interested, you can check out the +
-[[https://​www.cylab.cmu.edu/​tiw/​slides/​challener-handout.pdf|API documentation]] and even +
-test some samples if you have a TPM enabled laptop! +
- +
-</​hidden>​+
  
-==== [10p] 6. Feedback ====+==== 3. Feedback ====
  
 Please take a minute to fill in the [[https://​forms.gle/​5Lu1mFa63zptk2ox9|feedback form]] for this lab. Please take a minute to fill in the [[https://​forms.gle/​5Lu1mFa63zptk2ox9|feedback form]] for this lab.
  
  
isc/labs/03.1647796648.txt.gz · Last modified: 2022/03/20 19:17 by florin.stancu
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0