Differences

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

Link to this comparison view

isc:labs:03 [2022/03/20 19:19]
florin.stancu add qemu usage note
isc:labs:03 [2025/01/23 12:36] (current)
radu.mantu [03. [15p] Password Hashing]
Line 1: Line 1:
-/* ~~SHOWSOLUTION~~ */ +===== Lab 03 - Authentication in Linux =====
- +
-====== Lab 03  Hardware Security ======+
  
 ===== Objectives ===== ===== Objectives =====
-  * Hardware Security Basics 
-  * Side Channel Attacks 
-  * Intel SGX API  
  
-===== Basics ======+  * Hashing 
 +  * Linux PAM 
 +  * Multi-Factor Authentication
  
-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.+===== Preparation =====
  
-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.).+You may use the UPB's [[https://​cloud.grid.pub.ro|OpenStack]] cloud to instantiate a Virtual Machine. 
 +Read these [[:​isc:​info:​virtualmachine|instructions]] if you wanna know how!
  
-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. +===== Overview =====
-These are very difficult (or even impossible) to fix without re-designing replacing the entire .+
  
 +Hashing is the process of converting data — text, numbers, files, or anything, really — into a fixed-length string of letters and numbers. Data is converted into these fixed-length strings, or hash values, by using a special algorithm called a hash function.
  
-===== Side Channel Attacks ======+Linux Pluggable Authentication Modules (PAM) is a suite of libraries that allow a Linux system administrator to configure methods to authenticate users.
  
-TODO+"​pam_exec"​ is a PAM module that can be used to run an external command.
  
-===== Trusted Execution ​(e.g., Intel SGX) ======+Multi-factor authentication ​(MFA) is a multi-step account login process that requires users to enter more information than just a passwordFor examplealong with the password, users might be asked to enter a code sent to their email, answer a secret question, or scan a fingerprint. A second form of authentication can help prevent unauthorized account access if a system password has been compromised.
  
-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.+===== Tasks =====
  
-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.+In the current security lab, we'll explore ​the fundamentals ​of Linux authentication.
  
-The enclave code runs in user space, and thus can access ​the entire memory of the process within which it runsIn this waydata can be transmitted between the trusted ​and untrusted application regions, e.g. for passing function parameters and results. +We'll start by examining how the OS performs hashingFirstwe'll crack it and then we'll replicate it using Python.
-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:+Thenwe'll utilize ​the "​pam_exec"​ module to set up a custom Python script for user authentication. By exploiting a weak password vulnerability,​ we will be able to perform a successful login.
  
-  * ECALL (Enclave Call) entering the enclave and calling a function inside the enclave. +Finally, we'll enhance security measures by implementing Multi-Factor Authentication ​(MFAwith Google Authenticator.
-  * 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 interactThey are defined in an EDL file (Enclave Definition Language), in a specific format. A simple EDL file looks like this:+==== 01[5p] Setup ====
  
-<​code>​ +We use Docker:
-enclave { +
-    trusted { +
-        /* define ECALLs here. */ +
-        public int get_sum(int a, int b); +
-    };+
  
-    untrusted { +<​code ​bash
-        /* define OCALLs here. */ + 
-        void ocall_print([in,​ string]const char* str); +docker pull ghcr.io/cs-pub-ro/isc-auth-pam:latest 
-    }; +mkdir ~/auth-lab 
-}; +docker run --rm --name auth-lab -v $(pwd)/​auth-lab/:/​home/​hacker/​auth-lab -it ghcr.io/​cs-pub-ro/​isc-auth-pam
-</code> +
-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 procedureFor 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. +
-  * [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. +
-  * [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>​ </​code>​
  
-===== Preparation =====+<​note>​ 
 +The ''​~/​auth-lab''​ folder is used as persistent volume so you won't lose + sync your work inside the container! 
 +</​note>​
  
-==== Instance Creation ====+Download the {{:​isc:​labs:​lab03-pam.zip|lab archive}} inside the ''​~/​auth-lab''​ directory and unzip it.
  
-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 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: +Analyse the users and groups ​on the systemWhat user are we interested in? 
-<code bash> + 
-$ ssh -J ${LDAP_ID}@fep.grid.pub.ro student@${VM_IP} +<solution -hidden
-</code> +<​code>​ 
-NOTE: you can have more than one keypair configured (both for your localhostand for fep). Select the one you want from the //Key Pair// tab during the instance creation.+ 
 +User "​dani.mocanu"​member of group "​top_10_manelisti"​.
  
-**<color red>​Note:​ UPB's OpenStack servers currently have very old CPUs (Core 2 Duo!!!) lacking modern cryptographic instructions!</​color>​** 
-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>​ </​code>​
 +</​solution>​
  
-<note important>​ 
-Don't forget to prefix SGX executables with ''​qemu-x86_64-static''​ when running them! 
-</​note>​ 
  
 +==== 02. [15p] Password Cracking ====
  
-==== SGX SDK Usage and Skeleton ====+Use John the Ripper to crack our user's password. You need to run it as super user on the file that contains the passwords.
  
-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]].+We want to use the default mode "​wordlist"​ with the default location ''​/usr/share/john/password.lst''​.
  
-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]] ​;)+If you are getting an error "No password hashes loaded (see FAQ)", you need to specify ​the format ​of the hash. It is named the same as the Linux password hashing function ​;)
  
-Normally, to benefit from //most// SGX security features, you need two things: +**References:** 
-  - **SGX driver & BIOS support**: needed to lock memory and limit access to Enclaves. +  * https://​www.openwall.com/​john/​doc/​OPTIONS.shtml
-  ​- **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.+<​solution -hidden>​ 
 +<​code>​
  
-In order to be able to use the SDK, you need to import/update some environment variables: +$ sudo john /etc/shadow --format=crypt 
-<code bash> +dani.mocanu:​snoopdog
-# 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: 
-<code bash> 
-$ make SGX_MODE=SIM 
-$ make clean 
 </​code>​ </​code>​
 +</​solution>​
  
-==== Working Locally ​====+==== 03. [15p] Password Hashing ​====
  
-<note important>​ +Fill in the TODOs in ''​gen_hash.py'' ​to generate a new password hash. Using your super user privileges, manually overwrite ​the old password of our user.
-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:+Test if you were successful by trying ​to log in (''​su''​) using the new password.
  
 <note warning> <note warning>
-The SDK build process for **Ubuntu 16** is broken. +**crypt** was deprecated in PEP 594See [[https://docs.python.org/3/library/crypt.html|this]] for alternatives. **legacycrypt** works.</​note>​
-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> +
-# use sudo if you are not in the docker group +
-$ docker run -ti --entrypoint bash ubuntu:20.04 +
-</​code>​ +
-</​note>​+
  
 +<​solution -hidden>
 +<​code>​
  
-<code bash> +TODO(1)
-# IMPORTANTfind out what distro you are using +password ​'​parolanoua'​
-#            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 +TODO(2): 
-$ sudo apt update -y && sudo apt install -y          \ +salt = crypt.mksalt(crypt.METHOD_SHA512)
-  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 +TODO(3): 
-$ sudo apt update -y && sudo apt install -y              \ +hash = crypt.crypt(password,​ salt)
-  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+
  
 +</​code>​
 +</​solution>​
  
-# clone repo and init submodules +==== 04[5p] Account Locking ====
-$ 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 +As we want to use a Python script to log in to the user account we worked on so far, you need to delete and lock its password so that password-based authentication is disabled for this user account.
-# 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 +**Reference:​** 
-$ make sdk_install_pkg -j $(nproc)+  * https://​linux.die.net/​man/​1/​passwd
  
-# create installation path and install SDK +<​solution ​-hidden> 
-$ mkdir /​opt/​intel +<​code>​
-$ 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 +sudo passwd -dl dani.mocanu
-$ 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>​
 +</​solution>​
  
-If you installed the latest SDK yourselves, use the updated skeleton from {{:​isc:​labs:​isc-enclave-2020-revision.zip|here}}.+==== 05[10p] Linux PAM ====
  
-If you want to check whether you do have hardware support, there are two easy ways: +We wish to write our own authentication module ​in Python.
-  - 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 ==== +For this, we must modify the ''​common-auth''​ Linux PAM configuration file (look in ''/​etc/​pam.d''​) and add this as the **first** rule: <​code>​ 
- +auth sufficient pam_exec.so expose_authtok stdout quiet <​path-to-auth.py>​
-==== [20p] 1Implement an ECALL function that generates a random number (unsigned intinside the enclave, between 3 and 42. ==== +
-The function should have the **prototype**:  +
-<​code>​ +
-unsigned int generate_random_number(void)+
 </​code>​ </​code>​
  
-**Steps** +As we want to use the script to authenticate only our special userand because it will be called for all users, it should ​be //sufficient//​ to authenticate using it, but not //​required//​.
-  - Add the function prototype ​to **Enclave/​Enclave.edl** +
-  - 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 *randsize_t length_in_bytes);</​code>​ Where: +
-      * rand - pointer to the memory area where the random bytes will be generated +
-      * 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.+In order for authentication to be successfully performed using Python, we need 3 features, which can be achieved by passing the proper options to the ''​pam_exec.so''​ module: 
 +  ​perform reads in the Python script, 
 +  ​perform prints from the Python script, 
 +  * do not print anything else.
  
-==== [20p] 2. System calls can not be called directly from an enclave. ==== +<note tip
-  * Implement 2 OCALLS, one for reading from a file, the other for writing to a file. +If you need to debug your //auth.py// script, delete ​the ''​quiet''​ parameter from the PAM configNowyour stdout and stderr ​are no longer suppressed.
-  * 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> +
-  * 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 stringbut **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: ==== +----
-  * 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>​ +The PAM module may return different error codes depending on the nature of the error. Use the **errno** tool to check their meaning. 
-void seal_secret(void);​+ 
 +<​code ​bash
 +$ apt install errno 
 +$ errno 13 
 +    EACCES 13 Permission denied
 </​code>​ </​code>​
-  * Inspect the file contents. Can you guess the secret? 
  
-  * **Obs**: Uncomment the function call from main and don't forget about **Enclave/​Enclave.edl**+----
  
-==== [20p] 4. Similar to the sealing function, implement a function, inside the enclave, ​that unseals the enclave secret. ==== +Remember ​that ''​^?''​ sequences ​(where ''?''​ certain upper-case lettersrepresents a control characterIf you get an error that contains such a sequencetake look at the hexdump. 
-  * Reads the content of SECRET_ENCLAVE file (it contains sealed data) +</note>
-  * 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 ​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>​ +**References:** 
-void unseal_secret(void);​+  * https://​linux.die.net/​man/​5/​pam.d 
 +  * https://​man7.org/​linux/​man-pages/​man8/​pam_exec.8.html 
 + 
 +<​solution -hidden>​ 
 +<​code>​ 
 +$ cat /​etc/​pam.d/​common-auth 
 +... 
 +# here are the local modules 
 +auth sufficient pam_exec.so expose_authtok stdout quiet /​home/​hacker/​auth-lab/​auth.py 
 +...
 </​code>​ </​code>​
-  * **Obs**: Uncomment the function call from main and don't forget about **Enclave/Enclave.edl**+</solution>​
  
 +==== 06. [20p] Python Script ====
  
-==== [10p] 5Modify the seal_secret ECALL such that it seals a random generated string, instead of “SGX_RULLZ”====+Edit ''​auth.py''​ and fill in TODOs(6.*).
  
-  * Use **sgx_read_rand** for generating ​the string.+When you're done, [[http://​crackstation.net|crack ​the new password hash]] and try to log in ;)  
 + 
 +<note hint> 
 +Note that the password hash is hardcoded in Python (you will also find the algorithm by cracking it!) without any salt. 
 +Once you figure it out, use Python'​s ''​hashlib''​ to compute the input'​s ''​user_hash''​ and compare them! 
 +</​note>​
  
 <​solution -hidden> <​solution -hidden>
 +<​code>​
 +TODO(6.1):
 +if "​top_10_manelisti"​ not in user_groups:​
 +    return False
  
-Tasks archivehttps://​drive.google.com/​open?​id=0BypiZKffc_dBVEVGaC1jcllJaFE +TODO(6.2): 
- +hash_object = hashlib.sha256() 
-Solutions archive: https://​drive.google.com/open?id=0BypiZKffc_dBdXR2UWItQ2pyd1k+hash_object.update(user_password.encode("​utf-8"​)) 
 +user_hash ​hash_object.hexdigest()
  
 +13412ffd6149204f40e546ffa9fbd7124b410198a6ba3924f788622b929c8eb2 ---crackstation.net--->​ poochiedontsurf
 +</​code>​
 </​solution>​ </​solution>​
  
-<​hidden>​+==== 07. [30p] Multi-Factor Authentication ====
  
-Ex. scoase:+Finally, let's add two-factor authentication to our script!
  
-===== Trusted Platform Module ======+Edit ''​setup_mfa.py'',​ input a 32-byte secret and print its QR enrollment code to the console. 
 +After this, run the script and enroll the key inside a [[https://​www.rfc-editor.org/​rfc/​rfc6238|RFC 6238 (TOTP)]] compatible (e.g.: Google Authenticator,​ TOTP Authenticator,​ KeePassXC etc.).
  
-==== Description ====+Solve the remaining TODOs(7.*) in ''​auth.py''​ to integrate your MFA (note: the TOTP's secret key should be the same!).
  
-The Trusted Platform Module ​(TPMis a standard for secure cryptoprocessors maintained +<​note>​ 
-by the Trusted Computing Group (TCGconsortium that provides hardware-based cryptographic +**Hint / workaround:​** PAM only gives you one ''​input()''​ with the user-typed password ​(then closes stdin, any following reads will get EOF). 
-functions for secure key generationintegrity (remote attestation) ​and data protection +Soin order to read both a password ​and a numeric TOTP code, you must read them all at once (use whatever convention you desire, e.g.: password then 6-digit code either concatenated or split by space, then parse/​extract it in Python).
-(sealing).+
  
-Note that, by itself, the TPM is inertIt needs to receive commands from another party +Custom ''​.so''​ PAM plugins have no such limitations ​(but you must then write them in a system programming language). 
-(e.g. firmware, CPUfor it to be useful.+</​note>​
  
-For example, it can be coupled with Intel Trusted Execution Technology ​(TXT) to provide +<note important>​If you're getting an error (e.g., invalid padding) while scanning QR verifying ​the TOTPmake sure ''​TOTP_SECRET'' ​is 32 bytes in length!</​note>​
-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 +**References:​** 
-(i.eencrypt) sensitive data like disk encryption keys such that, if the software ​hardware +  * https://​pyauth.github.io/pyotp/#​module-pyotp 
-integrity is compromised,​ it won't be able to access it.+  * https://​pyqrcode.readthedocs.io
  
-This is realized by using the TPM's PCRs (Platform Configuration Registers): registers that are +<​solution -hidden> 
-reset on system'​s startup that store hashes of system'​s ​code and configuration at different +<code>
-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, +setup_mfa.py:
-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 ====+TODO(1): 
 +TOTP_SECRET ​"​NeverGonnaGiveYouUpNeverGonnaLet"​
  
-There is a [[https://github.com/​PeterHuewe/​tpm-emulator|TPM Emulator]] project available, +TODO(2): 
-though we weren'​t able to make it work :D+qr_code = pyqrcode.create(totp_auth) 
 +print(qr_code.terminal(quiet_zone=1))
  
-So rejoyce! No tasks to be done for this lab! +auth.py:
-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>+TODO(7.1):​ 
 +TOTP_SECRET = "​NeverGonnaGiveYouUpNeverGonnaLet"​ 
 + 
 +TODO(7.2):​ 
 +user_password = user_secret[:​-6] 
 +user_totp = user_secret[-6:​] 
 + 
 +TODO(7.3):​ 
 +totp = pyotp.TOTP(TOTP_SECRET) 
 +totp_correct = totp.verify(user_totp) 
 + 
 +</code> 
 +</​solution>
  
-==== [10p] 6. Feedback ====+====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://docs.google.com/​forms/​d/​e/​1FAIpQLSeMrKoWY6UKe1N_BASUARA-HixTuvSfrEnx_FKstT-RW464NQ/viewform ​|feedback form]] for this lab.
  
isc/labs/03.1647796784.txt.gz · Last modified: 2022/03/20 19:19 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