Differences

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

Link to this comparison view

isc:labs:03 [2022/03/20 20:29]
florin.stancu minor basics correction
isc:labs:03 [2024/03/18 09:07] (current)
alexandru.mircea98 [[30p] 3. Using OpenSSL]
Line 4: Line 4:
  
 ===== Objectives ===== ===== Objectives =====
-  * Hardware Security Basics 
   * Side Channel Attacks   * Side Channel Attacks
-  * Intel SGX API +  * Hardware Security Basics 
 +  * OpenSSL / PKCS#11 & #15 tools 
 +  * HSMs: Java Card & Simulator 
 + 
 +===== Preparation ===== 
 + 
 +You may use the UPB's [[https://​cloud.grid.pub.ro|OpenStack cloud to instantiate a Virtual Machine]] to be used for this lab! 
 +[[:​isc:​info:​virtualmachine|Read these instructions if you wanna know how!]]. 
 + 
 +===== Overview =====
  
-===== Basics ​======+==== Basics ====
  
 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 a privilege separation between a hypervisor / Operating System kernel and the user applications and is enforced at hardware-level for efficiency. 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 a privilege separation between a hypervisor / Operating System kernel and the user applications and is enforced at hardware-level for efficiency.
  
-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 TrustZone, Intel SGX, memory encryption etc.).+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 TrustZone, Intel SGX, memory encryption etc.).
  
 On a different note, hardware is also susceptible to security bugs: side channel attacks, cryptographic vulnerabilities (e.g., cache or timing attacks or the much recent Spectre / Meltdown speculative execution bugs), hardcoded credentials or even manufacturer-introduced backdoors. On a different note, hardware is also susceptible to security bugs: side channel attacks, cryptographic vulnerabilities (e.g., cache or timing attacks or the much recent Spectre / Meltdown speculative execution bugs), hardcoded credentials or even manufacturer-introduced backdoors.
 These are very difficult (or even impossible) to fix without re-designing the chip and replacing the faulty products. These are very difficult (or even impossible) to fix without re-designing the chip and replacing the faulty products.
  
 +==== Side Channel Attacks ====
  
 +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.
  
-===== Side Channel Attacks ======+By analyzing these side effects, an attacker can gain information about the system'​s operations, such 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.
  
-TODO+==== Java Smart Cards ====
  
-===== Trusted Execution (e.g., Intel SGX) ======+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 informationJava Card technology is a subset of Java that has been designed specifically for smart card environments.
  
-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.+Java smart cards can be found in various forms, such as SIM cards in mobile phones, banking cards, ​e-passports, and employee ID cardsThey can be purchased from smart card manufacturers or vendors, or provided by organizations to their customers or employees.
  
-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.+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.
  
-The enclave code runs in user space, and thus can access the entire memory of the process within which it runs. In this way, data can be transmitted between the trusted and untrusted application regions, e.g. for passing function parameters and results. +===== Tasks =====
-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.+
  
-For the interaction between those two components, the SDK exposes two important concepts:+==== [40p] 1. Python timing side channel attack ====
  
-  * ECALL (Enclave Call) - entering ​the enclave and calling a function inside the enclave. +Download ​the {{isc:​labs:​lab03-sidechannel.zip|side channel demo}} archive here.
-  * OCALL (Outside Call) calling an untrusted function from the enclave modeIt 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 a specific format. A simple EDL file looks like this:+Implement ​the TODOs and crack the password via a timing attack ;)
  
 +<​note>​
 +Hint: you have LunarVim installed on the VM, use ''​lvim ${file}''​ to start it!
 +</​note>​
 +
 +<​solution -hidden>
 <​code>​ <​code>​
-enclave { +TODO(1): 
-    trusted { +CHARACTERS = ascii_letters + digits + '{}'
-        /* define ECALLs here. */ +
-        public int get_sum(int a, int b); +
-    };+
  
-    untrusted { +TODO(2): 
-        /* define OCALLs here. */ +CHECK_PASS_LEN_VULN = check_password1 
-        void ocall_print([in, string]const char* str); +CHECK_PASS_CHARS_VULN = check_password2 
-    }; + 
-}; +TODO(3): 
-</​code>​ +for length in range(20) 
-ECALL and OCALL functions parameters that are pointers should be decorated with either a pointer direction attribute in, out 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 enclave, ​for an OCALL the parameter is passed from the enclave to the application. +TODO(4): 
-  * [out] – the parameter is returned from the called procedure to the calling procedure. In 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. +if CHECK_PASS_LEN_VULN(np): 
-  * [user_check] - Pointer is not checked. Users must perform the check and/or copy. +    ​return np 
-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>​ +TODO(5): 
-void foo([in, size=buf_len]const char* bufsize_t buf_len);+duration ​timed_check_pass(CHECK_PASS_CHARS_VULNpad(np, length))
 </​code>​ </​code>​
 +</​solution>​
  
-===== Preparation =====+==== [30p] 2. Using OpenSSL ​====
  
-==== Instance Creation ====+You are tasked with encrypting a large file using RSA. 
 +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''​! ​
  
-Ideally, you 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 networkyou will need to set up 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: +  ​For starterswe need a file to encrypt; let's make backup of ''/​etc/'​': <​code>​ 
-<​code ​bash+sudo tar czf etc-backup-2023.tar.gz -C /etc .
-$ ssh -J ${LDAP_ID}@fep.grid.pub.ro student@${VM_IP}+
 </​code>​ </​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>​** +  ​* We will use a symmetric cipher ​to encrypt the file using an ephemeral ​(random) key (which ​we will then encrypt using RSA): <​code>​ 
-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+# generate the random passphrase 
-wget http://archive.ubuntu.com/​ubuntu/​pool/​universe/​q/​qemu/​qemu-user-static_4.2-3ubuntu6.21_amd64.deb +dd if=/dev/urandom of=.mysecretpass bs=20 count=1
-sudo dpkg -i qemu-user-static_4.2-3ubuntu6.21_amd64.deb +
-# test it? +
-qemu-x86_64-static --version+
 </​code>​ </​code>​
- +  * Encrypt the file using ''​openssl enc -aes-256-cbc -e''​ and the password generated earlier from file; 
-<​note ​important+  * **Hint**: ''​openssl enc %%--%%help''​ (you can specify password from file using ''​-pass file:<​path-to-passphrase-file>''​). 
-Don't forget ​to prefix SGX executables with ''​qemu-x86_64-static'' ​when running them!+<​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>​ </​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>​
  
-==== SGX SDK Usage and Skeleton ====+<​solution -hidden><​code>​ 
 +# generate the random passphrase 
 +dd if=/​dev/​urandom of=.mysecretpass bs=20 count=
 +# 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>​
  
-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]].+==== [30p3Java Card Simulator ====
  
-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]] ;)+{{ :isc:​labs:​lab03.png?​direct&​600 ​|}}
  
-Normally, ​to benefit from //most// SGX security featuresyou need two things: +In order to simulate a Java Cardwe must install all required Java components ​(Oracle JavaCard SDKsjCardSimIsoAppletVSmartCard).
-  - **SGX driver & BIOS support**: needed to lock memory and limit access to Enclaves. +
-  - **SGX SDK (Software Development Kit)**: implements most Enclave interactionsgenerates required code from EDL filessigns resulting objectsetc.+
  
-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 driverthe 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.+**Note**: you don'​t ​need to do this on the ISC VM 2023it'​s ​already ​been setup!
  
-In order to be able to use the SDK, you need to import/update some environment variables:+<​spoiler>​ 
 +  * Download ​the [[https://​github.com/​martinpaljak/​oracle_javacard_sdks|Oracle JavaCard SDKs]]:
 <code bash> <code bash>
-# do this in every shell you open (maybe add it to .bashrc) +git clone https://​github.com/​martinpaljak/​oracle_javacard_sdks.git "​$HOME/​oracle_javacard_sdks"​ 
-source ​/opt/intel/sgxsdk/environment+export JC_HOME="​$HOME/oracle_javacard_sdks/jc222_kit"​ 
 +export JC_CLASSIC_HOME="​$HOME/oracle_javacard_sdks/jc305u3_kit"​
 </​code>​ </​code>​
- +  * Since we don't have a physical smart card, we need a simulator: download & install [[https://​github.com/​arekinath/​jcardsim|JCardSim]]:
-Use the following Makefile targets for compiling ​cleaning the workspace:+
 <code bash> <code bash>
-make SGX_MODE=SIM +git clone https://​github.com/​arekinath/​jcardsim.git "$HOME/​jcardsim"​ 
-make clean+cd "$HOME/​jcardsim";​ mvn initialize && mvn clean install
 </​code>​ </​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):
-==== Working Locally ==== +
- +
-<note important>​ +
-Due to the huge setup time, this is not recommended to do during the on-premise activity. +
-</​note>​ +
- +
-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: +
- +
-<note warning>​ +
-The SDK build process for **Ubuntu 16** is broken. +
-This is 100% the fault of the Intel developers working on the SDK. +
-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> <code bash>
-use sudo if you are not in the docker group +git clone -b main-javacard-v2.2.2 https://​github.com/​philipWendland/​IsoApplet.git "​$HOME/​IsoApplet"​ 
-docker run -ti --entrypoint bash ubuntu:20.04+cd "​$HOME/​IsoApplet"​ 
 +install dependencies (fortunately,​ this project uses git submodules) 
 +git submodule init && git submodule update 
 +# unfortunately,​ jCardSim 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>​ </​code>​
-</note+  * Finally, ​note that we need a Card Reader to interface with the smart cards. So, 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> <code bash>
-# IMPORTANT: find out what distro you are using +git clone https://​github.com/​frankmorgner/vsmartcard.git "$HOME/vsmartcard
-#            especially if you are working on WSL +cd "$HOME/vsmartcard/virtualsmartcard"​ 
-#            use this information where appropriate in the build process +autoreconf ​-vis && ​./configure && sudo make install 
-$ cat /​etc/​lsb-release +Restart PCSC daemon ​to load our new vcard driver 
-    DISTRIB_ID=Ubuntu +sudo systemctl restart pcscd 
-    DISTRIB_RELEASE=18.04 +cd  # go back to home
-    DISTRIB_CODENAME=bionic +
-    DISTRIB_DESCRIPTION="​Ubuntu 18.04.5 LTS" +
- +
-# install deps for Ubuntu 18 +
-$ sudo apt update -y && sudo apt install -y          \ +
-  build-essential ocaml ocamlbuild automake autoconf \ +
-  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 +
-$ sudo apt update -y && sudo apt install -y              \ +
-  build-essential ocaml ocamlbuild automake autoconf ​    \ +
-  libtool wget python-is-python3 libssl-dev git cmake    \ +
-  perl libssl-dev libcurl4-openssl-dev protobuf-compiler \ +
-  libprotobuf-dev debhelper cmake reprepro unzip +
- +
- +
-# clone repo and init submodules +
-git clone https://​github.com/​intel/linux-sgx.git +
-$ cd linux-sgx +
-$ make preparation -j $(nproc) +
- +
-# make sure to use the provided mitigation binaries or the +
-# 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 +
-make sdk_install_pkg -j $(nproc) +
- +
-# create installation path and install ​SDK +
-$ 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 +
-$ source /​opt/​intel/​sgxsdk/​environment +
- +
-# test that everything is working +
-cd ../​../​../​SampleCode/​SampleEnclave +
-$ make SGX_MODE=SIM +
-$ ./app +
-    Checksum(0x0x7fffffffd5f0,​ 100) = 0xfffd4143 +
-    Info: executing thread synchronization,​ please wait... ​  +
-    Info: SampleEnclave successfully returned. +
-    Enter a character before exit ...+
 </​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 a private key stored inside a smart card for authentication]]!
  
-Exscoase:+==== 3Feedback ====
  
-===== Trusted Platform Module ======+Please take a minute to fill in the [[https://​forms.gle/​5Lu1mFa63zptk2ox9|feedback form]] for this lab.
  
-==== 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 a 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 a [[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 ==== 
- 
-Please take a minute to fill in the [[https://​forms.gle/​5Lu1mFa63zptk2ox9|feedback form]] for this lab. 
  
isc/labs/03.1647800963.txt.gz · Last modified: 2022/03/20 20:29 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