Differences

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

Link to this comparison view

isc:labs:03 [2021/03/23 14:28]
ionut_mugurel.anghel [6. [10p] Feedback]
isc:labs:03 [2024/03/18 09:07] (current)
alexandru.mircea98 [[30p] 3. Using OpenSSL]
Line 1: Line 1:
-====== Lab 03 - Cryptography ​======+/* ~~SHOWSOLUTION~~ */ 
 + 
 +====== Lab 03  Hardware Security ​======
  
 ===== Objectives ===== ===== Objectives =====
-  * Basic Cryptography +  * Side Channel Attacks 
-  * Block Cipher Modes +  * Hardware Security Basics 
-  * RSA+  * OpenSSL / PKCS#11 & #15 tools 
 +  * HSMs: Java Card & Simulator
  
-===== Resources ​=====+===== Preparation ​=====
  
-  *[[https://en.wikipedia.org/​wiki/​Block_cipher_mode_of_operation|Block Cipher Mode of Operation]] +You may use the UPB'​s ​[[https://cloud.grid.pub.ro|OpenStack cloud to instantiate a Virtual Machine]] to be used for this lab! 
-  *[[http://​www.di-mgt.com.au/​crt.html|Chinese remainder theorem - Broadcast attack]] +[[:isc:​info:​virtualmachine|Read these instructions if you wanna know how!]].
-  *[[https://​en.wikipedia.org/​wiki/​Fermat%27s_factorization_method|Fermat factorisation]] +
-  *[[http://​factordb.com/|Factor DB]]+
  
 ===== Overview ===== ===== Overview =====
  
-==== Symmetric Key Encryption ​====+==== Basics ​====
  
-Symmetric-key encryption is based on either stream ciphers or block ciphers.+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.
  
-  * **Stream ciphers** consume ​the message one bit at a time +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 instructionsthe Trusted Platform Module cryptoprocessor,​ Smart Cards or Trusted Execution Environments ​(ARM TrustZoneIntel SGXmemory encryption etc.).
-    * //​Examples//: ​the legendary one-time pad (though unfeasible for most applications);​ RC4 (deprecated);​ most block ciphers can be turned ​into stream ciphers using special modes of operation (read on). +
-  * **Block ciphers** operate on fixed-length blocks +
-    * //​Examples//:​ **Data Encryption Standard** (DES) deprecated**AES (Advanced Encryption Standard)** - designed to be efficient in both hardware and softwareand supports a block length of 128 bits and key lengths of 128192, and 256 bits.+
  
-**Block ciphers** have one or more block size(s) butduring transformation,​ the block size is always fixed. +On a different notehardware ​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. 
-Block cipher modes operate on whole blocks and require that the last part of the data be padded ​to a full block if it is smaller than the current block sizeThere arehowevermodes that do not require padding because they effectively use a block cipher as a stream cipher; such ciphers ​are capable of encrypting arbitrarily long sequences of bytes or bits.+These are very difficult (or even impossible) to fix without re-designing the chip and replacing the faulty products.
  
-Most block cipher modes require a unique binary sequence, often called an initialization vector (IV), for each encryption operation. The IV has to be non-repeating and, for some modes, random as well. The initialization vector is used to ensure distinct ciphertexts are produced even when the same plaintext is encrypted multiple times independently with the same key. +==== Side Channel Attacks ====
-  +
-The simplest of the encryption modes is the ECB (Electronic Codebook) mode. The message is divided into blocks, and each block is encrypted separately (with the same key and no IV). The disadvantage of this method is that identical plaintext blocks are encrypted into identical ciphertext blocks, so statistical analysis can reveal the protected message:+
  
-{{https://upload.wikimedia.org/wikipedia/commons/thumb/​d/​d6/​ECB_encryption.svg/​800px-ECB_encryption.svg.png}}+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 directlyThese 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.
  
-In CBC (Cipher Block Chaining) modeeach block of plaintext is XORed with the previous ciphertext block before being encrypted. This wayeach ciphertext block depends on all plaintext blocks processed up to that point. To make each message uniquea random initialization vector must be used in for first block.+By analyzing these side effectsan attacker can gain information about the system'​s operationssuch as encryption keys or other sensitive datawithout 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.
  
-{{https://​upload.wikimedia.org/​wikipedia/​commons/​thumb/​8/​80/​CBC_encryption.svg/​800px-CBC_encryption.svg.png}}+==== Java Smart Cards ====
  
-There is also a CTR (Counter) mode that specifically turns the block algorithm into a stream cipher: a keystream is generated by encrypting a random IV (i.e. nonce) with the key for the first block and, for successive fragments, the IV is incremented (any deterministic function ​can be used) and encrypted with the same keyThe plaintext ​is XOR-ed with the keystream (basic stream cipher operation) thus the ciphertext is obtained.+Java smart cards are small electronic devices ​that have an embedded microprocessor ​and memorywhich 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.
  
-{{https://​upload.wikimedia.org/​wikipedia/​commons/​thumb/​4/​4d/​CTR_encryption_2.svg/​800px-CTR_encryption_2.svg.png}}+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.
  
-==== Asymmetric EncryptionRSA ====+To program and manage Java smart cardsspecialized 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.
  
-Public-key cryptography uses two separate keys, one for encryption (the public key) and one for decryption (the private key). +===== Tasks =====
-Anyone with the public key can compute an encrypted message that only the owner of the private key can read.+
  
-**RSA** was the first algorithm that demonstrated this conceptIts security assumptions are based on complexity theory: computing the product of two prime numbers is easy (polynomial time), but there is no efficient algorithm for factoring them back (so far, all factorization methods are in the non-polynomial class). +==== [40p] 1Python timing side channel attack ====
-  +
-The keys for the RSA algorithm are generated the following way:+
  
-  - Choose two different large random prime numbers //**p**// and //**q**// +Download ​the {{isc:labs:lab03-sidechannel.zip|side channel demo}} archive here.
-  - Calculate //**n = pq**// +
-    * //**n**// is the modulus for the public key and the private keys +
-  - Calculate the totient//**phi (n)=(p-1)(q-1)**//. +
-  - Choose an integer //**e**// such that 1 < //**e**// < //​**phi(n)**//,​ and //**e**// is coprime to //**phi(n) **//  +
-    * //**e**// is released as the public key exponent +
-  - Compute //**d**// to satisfy the congruence relation //**d*e ≡ 1 (mod(phi(n))) **// +
-    * //**d**// is kept as the private key exponent+
  
-The public key is made of the modulus //​**n**// ​and the public (or encryptionexponent //**e**//.+Implement ​the TODOs and crack the password via a timing attack ;)
  
-The private key is made of the modulus ​//**n**// and the private (or decryption) exponent //**d**// which must be kept secret.+<​note>​ 
 +Hint: you have LunarVim installed on the VM, use ''​lvim ${file}''​ to start it! 
 +</note>
  
-Encrypting a message: //**c = m ^ e (mod n)**// +<​solution -hidden>
- +
-Decrypting a message: //**m = c ^ d (mod n)**// +
- +
-Example:+
 <​code>​ <​code>​
-p = 29, q = 31 +TODO(1): 
-n = p * q = 29 * 31 = 899 +CHARACTERS ​ascii_letters + digits + '{}'
-phi = (p -1) * (q – 1) = (29 – 1) * (31 – 1) = 840 +
-11 +
-d * e ≡ 1 mod phi => (d * 11) / phi will give us a remainder of one. +
-(611 * 11) = 6721 and 6721 / 840 = 8 with remainder 1 => d = 611 +
-C = M ^ e mod n +
-C = 119 ^ 11 mod 899 = 595 +
-M = C ^ d mod n +
-M = 595 ^ 611 mod 899 = 119 +
-</​code>​ +
-<note warning>​In this case "​^"​ means exponentiation (raise to power), **not XOR**</​note>​ +
- +
-==== Recording ==== +
- +
-Please record your screen using [[https://​www.mankier.com/​1/​asciinema|asciinema]] while working. +
-<​code>​ +
-# install asciinema +
-$ sudo apt update -y && sudo apt install -y asciinema +
- +
-# start recording +
-# NOTE: use --append if you pause your work and resume it later +
-#       it helps us if you upload a single .cast +
-$ asciinema rec [--append] lab03_${LDAP_ID}.cast+
  
-# IMPORTANTbefore you start, echo your name in the terminal +TODO(2)
-$ echo "​Andrei Popescu"​+CHECK_PASS_LEN_VULN = check_password1 
 +CHECK_PASS_CHARS_VULN = check_password2
  
-# work...+TODO(3): 
 +for length in range(20)
  
-# stop recording +TODO(4): 
-$ exit+if CHECK_PASS_LEN_VULN(np):​ 
 +    return np
  
-# upload recording +TODO(5): 
-$ ASCIINEMA_API_URL=https://​asciinema.cs.pub.ro asciinema upload lab03_${LDAP_ID}.cast+duration ​timed_check_pass(CHECK_PASS_CHARS_VULN,​ pad(np, length))
 </​code>​ </​code>​
 +</​solution>​
  
-When you finish your work, submit the details on the [[ https://​forms.office.com/​r/​GZzRJVqQuy |form]]. Double check the [[ https://​ctipub-my.sharepoint.com/:​x:/​g/​personal/​mihai_chiroiu_upb_ro/​Ee4pZApRKA5Iq9JgR2r652QB0FVL4J9EFtTBtva3jX-1Lw?​e=ylQ7lu | form responses]] so there aren't any surprises.+==== [30p2Using OpenSSL ====
  
-===== Exercises =====+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''​! ​
  
-=== 0. [5p]  AES ECB (Warmup) === +  * For starters, we need a file to encrypt; let's make a backup of ''​/etc/'':​ <​code>​ 
- +sudo tar czf etc-backup-2023.tar.gz -C /etc .
- It is recommended NOT to encrypt ​more than one block with AES in ECB mode, but in order to understand why, an image with the following header was encrypted. The encrypted photo cand be found [[https://drive.google.com/open?​id=0B_sFoQMHYxA4TUFNY1JkQzZsdFU|here]]Is it possible to figure out what the initial image was? +
- +
-<​code>​ +
-42 4D 66 CA D7 00 00 00 00 00 36 00 00 00 28 00 00 00 D0 07 00 00 35 09 00 00 01 00 18 00 00 00 00 00 30 CA D7 00 74 12 00 00 74 12 00 00 00 00 00 00 00 00 00 00+
 </​code>​ </​code>​
  
-  * **Hint:** The image seems corrupted. Why? The header is encrypted, of course! Fix this and you can see how an encrypted image looks like! +  * We will use a symmetric cipher to encrypt ​the file using an ephemeral (random) key (which we will then encrypt using RSA): <​code>​ 
-  * You can use your favorite hex editor for modifying ​the binary ​file (bless. Try [[http://​www.devdungeon.com/​content/​working-binary-data-python|Python]] or [[http://​stackoverflow.com/​questions/​4411014/​how-to-get-only-the-first-ten-bytes-of-a-binary-file|Basic shell scripting]] if you don't have any! +# generate ​the random passphrase 
-  * You can use bless editor ​<code>​sudo apt-get install bless</code> +dd if=/​dev/​urandom of=.mysecretpass bs=20 count=1
- +
-<​solution -hidden>​ +
-<​code>​ +
-TODO: make the URL curl-able +
- +
-vim -b img.bmp +
-:%!xxd +
-[EDIT] +
-:%!xxd -r +
-:sav img2.bmp +
 </​code>​ </​code>​
-</​solution>​ +  * Encrypt the file using ''​openssl enc -aes-256-cbc -e''​ and the password generated earlier ​from file; 
- +  * **Hint**: ''​openssl enc %%--%%help''​ (you can specify password ​from file using ''​-pass file:<​path-to-passphrase-file>''​). 
-=== 1. [20p] AES === +<note info> 
- ​[[https://​drive.google.com/​open?​id=0B_sFoQMHYxA4NzVCMEFUM3JxMXc| This file]] was encrypted ​using the following code. Can you decrypt it? +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>''​! 
-<​code>​ +</​note>​ 
- +<​note>​ 
-from Crypto.Cipher import AES +OpenSSL'​s symmetric encryption can use PBKDF2 to derive a key from an arbitrary password ​(salted, by default). 
-from Crypto import Random +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>​
-BLOCK_SIZE = 32 +
-PADDING = '#' +
-iv = "​\x00"​ * 16 +
- +
-def encrypt(key,​ iv, data): +
-    aes = AES.new(key,​ AES.MODE_CBC,​ iv) +
-    data = aes.encrypt(data) +
-    ​return data +
- +
-def pad(s)+
-    return s + (BLOCK_SIZE ​len(s) % BLOCK_SIZE) * PADDING ​ +
- +
- +
-key = Random.new().read(BLOCK_SIZE) +
- +
-with open('plain.jpg''rb') as f: +
-    data = f.read() +
- +
-enc = encrypt(key, ​iv, pad(data)) +
- +
-f_out = open("​secret.enc", ​'wb') +
-f_out.write(key) +
-f_out.write(enc) +
-f_out.close()+
  
 +  * 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>​ </​code>​
  
-<​solution -hidden>​ +<​solution -hidden><​code> 
-<​code>​+# generate the random passphrase 
 +dd if=/​dev/​urandom of=.mysecretpass bs=20 count=1 
 +# 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>
  
-from Crypto.Cipher import AES +==== [30p] 3Java Card Simulator ====
-from Crypto import Random+
  
-BLOCK_SIZE = 32 +{{ :​isc:​labs:​lab03.png?​direct&​600 |}}
-PADDING = '#'​ +
-iv = "​\x00"​ * 16+
  
-def decrypt(keyivdata): +In order to simulate a Java Card, we must install all required Java components ​(Oracle JavaCard SDKsjCardSimIsoAppletVSmartCard).
-    aes = AES.new(keyAES.MODE_CBC,​ iv) +
-    data = aes.decrypt(data) +
-    return data+
  
-with open('​secret.enc', 'rb') as f: +**Note**: you don't need to do this on the ISC VM 2023it's already been setup!
-    data = f.read() +
- +
-extr_key = data[:32] +
-extr_data = data[32:] +
-f_dec = open("​decr.jpg",​ '​wb'​) +
-f_dec.write(decrypt(extr_key,​ iv, extr_data).rstrip(PADDING)) +
-f_dec.close()+
  
 +<​spoiler>​
 +  * Download the [[https://​github.com/​martinpaljak/​oracle_javacard_sdks|Oracle JavaCard SDKs]]:
 +<code bash>
 +git clone https://​github.com/​martinpaljak/​oracle_javacard_sdks.git "​$HOME/​oracle_javacard_sdks"​
 +export JC_HOME="​$HOME/​oracle_javacard_sdks/​jc222_kit"​
 +export JC_CLASSIC_HOME="​$HOME/​oracle_javacard_sdks/​jc305u3_kit"​
 </​code>​ </​code>​
-</​solution>​ +  * Since we don't have a physical smart cardwe need a simulatordownload & install ​[[https://github.com/​arekinath/​jcardsim|JCardSim]]: 
- +<code bash> 
- +git clone https://github.com/arekinath/jcardsim.git "$HOME/jcardsim"​ 
-=== 2. [20p] RSA - Known factorisation === +cd "​$HOME/​jcardsim";​ mvn initialize && mvn clean install
- +
-In order to decrypt the ciphertextyou need to factorize n into p and q, compute phi and find d.  +
- +
-  c = 28822365203577929536184039125870638440692316100772583657817939349051546473185 +
-  n = 70736025239265239976315088690174594021646654881626421461009089480870633400973 +
-  e = 3 +
- +
-  * **Hint:** Check out [[http://factordb.com|FactorDB]]! +
-  * Use Python to do the math: try the [[https://gmpy2.readthedocs.io/en/latest/overview.html|gmpy2]] module: +
-    <​code>​ +
-sudo apt-get ​install ​python3-gmpy2 ​ # or python-gmpy2,​ depending on your Python version+
 </​code>​ </​code>​
-  * **Note**: the result is a decimal number, you need to convert it to an ASCII text using the snippet below+  * 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>​ +<​code ​bash
-print(hex(message)[2:].decode("hex"))  ​python 2 +git clone -b main-javacard-v2.2.https://github.com/​philipWendland/​IsoApplet.git ​"$HOME/​IsoApplet" 
-print(bytearray.fromhex(hex(message)[2:]) # ​python 3+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>​ 
 +  * 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> 
 +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>​
  
-Useful gmpy2 functions:  +Finally, we must create a configuration file for ''​jcardsim''​':
-  * ''​invert(x, m)'' ​- returns y such that x * y == 1 modulo m, or 0 if no such y exists.+
  
-<​solution -hidden> 
 <​code>​ <​code>​
-#!/usr/bin/env python +$ cat $HOME/​jcardsim.cfg  ​<-- yes, create this file ! 
-import gmpy2+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> 
 +</spoiler> 
 +<​html><​br></​html>​
  
-c = 48150432592505707552503950434421170873397025541574547497460326222962564730297 +**[Re]Start the PCSC service:** 
-n = 70736025239265239976315088690174594021646654881626421461009089480870633400973 +<code bash> 
-e = 3 +# the VM does not automatically start this, so do it manually 
-p = 296805874594538235115008173244022912163 +sudo systemctl restart pcscd 
-q = 238324208831434331628131715304428889871+</​code>​
  
-phi = (p-1)*(q-1) +**Start the simulator:**
-d = gmpy2.invert(e,​ phi)  +
- +
-pt = pow(c, d, n) +
-print( "​plaintext" + hex(pt)[2:​].decode("​hex"​))+
  
 +<code bash>
 +java -classpath "​$HOME/​jcardsim/​target/​jcardsim-3.0.5-SNAPSHOT.jar:​$HOME/​IsoApplet/​src"​ com.licel.jcardsim.remote.VSmartCard "​$HOME/​jcardsim.cfg"​
 </​code>​ </​code>​
-</solution+<note hint
-<note warning>​Please download [[https://​drive.google.com/​file/​d/​1suqUuzJbz10Ane7icWWftILnatQ2d4Ww/​view?​fbclid=IwAR3bQ4dqqU8iHk_L9yNYdzDH1qSwlf10SoWxQWWNWFlzSNwwyBDM5-4AXd8 | Task Archive]] for the following tasks. ​</​note>​ +Hintuse 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! 
-==== 03 [15p] Is this even OTP? ==== +</​note>​
-  * Someone applied [[https://​en.wikipedia.org/​wiki/​One-time_pad|one time pad]] on a text. +
-  * However, he failed to understand that you should not use the same byte for the entire key. +
-    * **Hint:** bruteforce+
  
-==== 04 [20p] Many Time Pad ==== +**Loading ​the Smart Card applet:**
-  ​This time, he did use a proper key. Unfortunately for him, he used it for multiple encryptions. +
-  ​Knowing that the key starts with "​ALEXCTF{",​ can you determine the rest? +
-    * **Hint:** take a close look at the folder for this task. +
-==== 05 [20p] We want Nudes instead of Nukes  ==== +
-  * Donald has gone completely crazy. To prevent world chaos, you kidnapped him. Right before the kidnapping he tried to send one encrypted message to his wife Melania. Luckily you intercepted the message. Donald admits that he used AES256-CBC encryption - a block cipher operating with a block length of 16 bytes. +
-  * The IV that he used is "​7ec00bc6fd663984c1b6c6fd95ceeef1"​ (hex encoded). After torturing him by stealing his hairpiece, he tells you the plain text of the message is: "​FIRE_NUKES_MELA!"​. +
-  * As a passionate hacker you of course try to take advantage of this message. To get the flag alter the IV such that Melania will read: "​SEND_NUDES_MELA!"​. +
-    * **Hint 1:** The encrypted message and the key are not relevant. You will not break AES today. Look at the IV and the plaintext. +
-    * **Hint 2:** How does [[https://​en.wikipedia.org/​wiki/​Block_cipher_mode_of_operation#​Cipher_Block_Chaining_(CBC)|CBC]] work exactly? Take a look at the decryption process and remember that the message is only one block in length. +
-    * **Hint 3:** Run the given oracle with the altered IV (hex encoded) to check that the message was modified correctly.+
  
-==== 6. [10pFeedback ====+<​note>​ 
 +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 cards, standardized in ISO/IEC 7816-4.
  
-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.+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. 
 +</​note>​
  
 +<code bash>
 +# install IsoApplet usign a APDU script
 +opensc-tool --card-driver default --send-apdu 80b800001a0cf276a288bcfba69d34f310010cf276a288bcfba69d34f3100100
 +opensc-tool -n
  
 +# create PKCS#15 structure on our smart card (also set a PIN and a PUK, for 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"​
  
 +echo "Sunt de acord să cedez toată averea mea asistenților de ISC. Adevăraaat\!"​ > textToSign.txt
 +openssl dgst -engine pkcs11 -sign "​pkcs11:​object=MyRSAKey;​type=private;​pin-value=123456"​ -keyform ENGINE -sha256 -out textSignature.sig textToSign.txt
  
-<​hidden>​ +# now everyone can check whether the document is correctly signed using the public key: 
-old feedback form [[https://forms.gle/​5Lu1mFa63zptk2ox9|feedback form]] +openssl dgst -sha256 -verify smartcard-pubkey.pem -keyform PEM -signature textSignature.sig textToSign.txt 
-O sa las vechiile exercitii aici momentan (Mugur) +# modificați fișierul textToSign.txt și re-verificați semnătura digitală... ce se întâmplă?​ 
-=== 4[20p] RSA Fermat Factorization ===+</​code>​
  
-Implement ​and try out [[https://​en.wikipedia.org/​wiki/​Fermat%27s_factorization_method|Fermat'​s Factorization Algorithm]]! +<note important>​ 
-Then try to break this RSA key: +Unfortunately,​ jCardSim is unstable ​and will crash after some short timeout (approxseveral 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>​ 
-<​code>​ +killall java 
-c = 654564125967811572957608485461509223541781197895608920296825435452302563551217882689453762450350456257099687251554693360645992257362168460115089842875072530869254099617858153458510730488327127628978127748004507636893613507344065845140647694349616219705757465949239924311260160127009283418952554522720051840260714703523494071411559772701875928237248989122625648657235677768486515417771976078417365256201505968603934443986411140514722785883888625061210731765750448 +sudo systemctl restart pcscd 
-n = 1209143407476550975641959824312993703149920344437422193042293131572745298662696284279928622412441255652391493241414170537319784298367821654726781089600780498369402167443363862621886943970468819656731959468058528787895569936536904387979815183897568006750131879851263753496120098205966442010445601534305483783759226510120860633770814540166419495817666312474484061885435295870436055727722073738662516644186716532891328742452198364825809508602208516407566578212780807 +java -classpath "​$HOME/​jcardsim/​target/​jcardsim-3.0.5-SNAPSHOT.jar:​$HOME/​IsoApplet/​src"​ com.licel.jcardsim.remote.VSmartCard "​$HOME/​jcardsim.cfg"​
-e = 65537+
 </​code>​ </​code>​
 +</​note>​
  
-Useful gmpy2 functions: +Finally, here's one last challengeuse ''​openssl''​ to encrypt ​decrypt ​file using this key!
-  * //​is_square(x)//​ returns True if x is perfect square, False otherwise. +
-  * //​isqrt(x)//​ returns the integer square root of an integer x. x must be >= 0.+
  
 <​solution -hidden> <​solution -hidden>
-<​code>​ +<​code ​bash
-#​!/​usr/​bin/​env python +openssl pkeyutl -encrypt -in textToSign.txt -pubin -inkey smartcard-pubkey.pem -out encrypted.enc 
-import gmpy2 +openssl pkeyutl ​-decrypt -in encrypted.enc -engine pkcs11 -keyform ENGINE -inkey "​pkcs11:​object=MyRSAKey;​type=private;pin-value=123456" ​-out decrypted.txt
-from math import ceil +
-from decimal import Decimal +
- +
-def fermat(n):​ +
- a = gmpy2.isqrt(n) + 1 +
- b2 = a * a +
- +
- while not gmpy2.is_square(b2):​ +
-     a = a + 1 +
-     b2 = a * a +
- +
- b = gmpy2.isqrt(b2) +
- return (a+b, a-b) +
- +
-654564125967811572957608485461509223541781197895608920296825435452302563551217882689453762450350456257099687251554693360645992257362168460115089842875072530869254099617858153458510730488327127628978127748004507636893613507344065845140647694349616219705757465949239924311260160127009283418952554522720051840260714703523494071411559772701875928237248989122625648657235677768486515417771976078417365256201505968603934443986411140514722785883888625061210731765750448 +
-1209143407476550975641959824312993703149920344437422193042293131572745298662696284279928622412441255652391493241414170537319784298367821654726781089600780498369402167443363862621886943970468819656731959468058528787895569936536904387979815183897568006750131879851263753496120098205966442010445601534305483783759226510120860633770814540166419495817666312474484061885435295870436055727722073738662516644186716532891328742452198364825809508602208516407566578212780807 +
-e = 65537 +
- +
-p, q = fermat(n) +
- +
-phi = (p-1)*(q-1) +
-gmpy2.invert(e,​ phi)  +
- +
-pt = pow(c, d, n) +
-print( ​"plaintext: " + hex(pt)[2:].decode("​hex"​))+
 </​code>​ </​code>​
 </​solution>​ </​solution>​
  
-=== 5. [20pRSA - Broadcast Attack ===+Bonus: ​[[https://​access.redhat.com/​articles/​1523343|You can configure OpenSSH to use a private key stored inside a smart card for authentication]]!
  
-Beware! If you use a small exponent and you encrypt the same message using three different keys, the message can be recovered!+==== 3. Feedback ====
  
-<​code>​ +Please take a minute to fill in the [[https://forms.gle/5Lu1mFa63zptk2ox9|feedback form]] for this lab.
-  n1 = 0xa8688af04ce3d0b93d04219391054740f10272ab96706cb98f852d8123e93853dfa4c4cf1fbb61cd632a2dad437e25003d545cded563e20581b6738a8080ac23 +
-  n2 = 0x70b2de4871351f2736f6f98eaed99ae6a68dd02954c536ebefdd553e7c7cf3003991bad6081061d04a6513e3d0db8be164f8e2e8e51deb1469832600957b7fe9 +
-  n3 = 0x586b8bccfa79b1a4e1332bccb897df08ad8e1867cee01ba003c74d861fd84ffe3cef3b652d45282bc18a6a11ca001f06500b78763932ae8044dfc21b6288fc91 +
-  c1 = 0x352cf1b545414223ce9ef6897258be836a282b5bf5d9050a7329bc0cabf8c700fbe2f4fef2a2d936eb08961406b1a2d6f288d18892e851ebe5afddb48723e89d +
-  c2 = 0x1701b013a055ae8843ccfabceb1b29f79e676e2add6ca8256d893c754c1269820024ccd897d56f16d51f71023294d6d0ec30aaf1f9b07739bb9dfb7e3cb5ddb +
-  c3 = 0x46f96866b9751c6492fe72f0169421e906915aab1065bc89d1712b086392f31585f4b409f645f968c918a1b16863bfadf95298f932ed30e52089a536146aae82 +
-  e = 3   +
-</​code>​ +
- +
-  * Example [[http://​www.di-mgt.com.au/​crt.html|Broadcast attack]] +
-  * Check out [[https://​en.wikipedia.org/​wiki/​Chinese_remainder_theorem|Chinese Remainder Theorem]] ;) +
-  * **Hint:** Use the [[https://en.wikipedia.org/wiki/​Chinese_remainder_theorem#​Existence_.28direct_construction.29|proof by direct construction]] +
- +
-Useful gmpy2 functions:​ +
-  * //​iroot(x,​n)//​ returns a 2-element tuple (y, b) such that y is the integer n-th root of x and b is True if the root is exactx must be >= 0 and n must be > 0 +
- +
-<​solution -hidden>​ +
-<​code>​ +
-#​!/​usr/​bin/​python +
-import gmpy2 +
- +
-n1 = 0xa8688af04ce3d0b93d04219391054740f10272ab96706cb98f852d8123e93853dfa4c4cf1fbb61cd632a2dad437e25003d545cded563e20581b6738a8080ac23 +
-n2 = 0x70b2de4871351f2736f6f98eaed99ae6a68dd02954c536ebefdd553e7c7cf3003991bad6081061d04a6513e3d0db8be164f8e2e8e51deb1469832600957b7fe9 +
-n3 = 0x586b8bccfa79b1a4e1332bccb897df08ad8e1867cee01ba003c74d861fd84ffe3cef3b652d45282bc18a6a11ca001f06500b78763932ae8044dfc21b6288fc91 +
-c1 = 0x352cf1b545414223ce9ef6897258be836a282b5bf5d9050a7329bc0cabf8c700fbe2f4fef2a2d936eb08961406b1a2d6f288d18892e851ebe5afddb48723e89d +
-c2 = 0x1701b013a055ae8843ccfabceb1b29f79e676e2add6ca8256d893c754c1269820024ccd897d56f16d51f71023294d6d0ec30aaf1f9b07739bb9dfb7e3cb5ddb +
-c3 = 0x46f96866b9751c6492fe72f0169421e906915aab1065bc89d1712b086392f31585f4b409f645f968c918a1b16863bfadf95298f932ed30e52089a536146aae82 +
-e = 3 +
- +
-N = n1*n2*n3 +
-N1 = n2*n3 +
-N2 = n1*n3 +
-N3 = n1*n2 +
-d1 = gmpy2.invert(N1,​ n1) +
-d2 = gmpy2.invert(N2,​ n2) +
-d3 = gmpy2.invert(N3,​ n3) +
-res = c1*N1*d1 + c2*N2*d2 + c3*N3*d3 +
-s = int(res % N) +
-pt, perf = gmpy2.iroot(s,​ e) +
-print( "​plaintext:​ " + hex(pt)[2:​].decode("​hex"​)) +
-</​code>​ +
-</​solution>​ +
-</​hidden>​+
  
  
isc/labs/03.1616502504.txt.gz · Last modified: 2021/03/23 14:28 by ionut_mugurel.anghel
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