RSA low randomness key cracker.
Resumen: Bloque de criptografΓa
Este proyecto introduce conceptos especΓficos sobre la fortaleza del algoritmo RSA y sus vulnerabilidades potenciales. Si bien el algoritmo es considerado suficientemente fuerte para la potencia computacional de los dispositivos actuales, ciertas formas de utilizarlo pueden llevar a graves problemas de seguridad.
Para este proyecto, debes usar C como lenguaje. La lista de funciones pemitidas es la
siguiente:
β’ Todas las funciones de <math.h>
β’ Todas las funciones de <string.h>
β’ La librerΓa openssl
β’ Todo lo puesto en cabecera del ejercicio.
La seguridad en la criptografΓa asimΓ©trica usando claves RSA se basa en la premisa de que es muy difΓcil computacionalmente factorizar los dos factores primos de un nΓΊmero.
βMultiplicar dos nΓΊmeros primos p y q para obtener nβ es una operaciΓ³n sencilla y su complejidad no aumenta drΓ‘sticamente cuando los nΓΊmeros crecen:
[1736640013 Β· 1230300287 = 2136588706409583731]
En cambio, la operaciΓ³n inversa, βdado un nΓΊmero n obtener sus dos factores pri- mosβ, es una operaciΓ³n que se vuelve computacionalmente inviable cuando los nΓΊmeros involucrados son lo suficientemente grandes.
Para generar la pareja de claves, el algoritmo RSA crea una clave pΓΊblica y privada usando este concepto. Simplificando la generaciΓ³n de las claves, los nΓΊmeros primos elegidos aleatoriamente p y q se multiplican para crear el mΓ³dulo n que se usarΓ‘ tanto en la clave privada como en la pΓΊblica. Este mΓ³dulo n es pΓΊblico pero los factores primos p y q no.
[? Β· ? = 2136588706409583731]
Si tenemos dos certificados generados en un sistema cuyo generador de nΓΊmeros alea- torios estaba configurado al mΓnimo y por tanto en el que la entropΓa era mΓnima. . .
Esto puede haber dado pie a repeticiones de nΓΊmeros primos durante distintas generaciones, se podrΓa haber dado el caso en el que dos mΓ³dulos compartan el mismo nΓΊmero p o q.
[n1 = p1 Β· q1] [n2 = p1 Β· q2]
Nombre de funciΓ³n | corsair |
Archivos a entregar | *.c, *.h |
Funciones autorizadas | printf, snprintf, write, read, open, close, malloc, free |
DescripciΓ³n | Bloque de criptografΓa: cifrados vulnerables |
Con esta informaciΓ³n, crearΓ‘s una herramienta que:
β’ Lea la clave pΓΊblica de estos certificados y obtenga el mΓ³dulo y exponente. Calcular el resto de los datos necesarios.
β’ Construya la clave privada a partir de dos primos y su producto, y de ahΓ saque la clave simΓ©trica cifrada con Γ©l.
β’ Β‘Descifre el mensaje!
La evaluaciΓ³n de los bonus se harΓ‘ SI Y SOLO SI la parte obligatoria es PERFECTA. De lo contrario, los bonus serΓ‘n totalmente IGNORADOS.
Puedes mejorar tu proyecto con las siguientes caracterΓsticas:
β’ DocumentaciΓ³n detallada y clara de todos los fundamentos teΓ³ricos detrΓ‘s del pro- yecto
β’ ImplementaciΓ³n propia de una librerΓa o conjunto de funciones en C para operar con enteros de gran tamaΓ±o.
β’ Todo lo que se te ocurra... podrΓ‘s justificarlo todo durante la evaluaciΓ³n.
- Features:
wrongUserInputBool = 0
helpBool = 1
pFuncBool = 0
pPath =
fFuncBool = 0
pemFileOne4Func =
pemFileTwo4Func =
binFileOne4fFunc =
binFileTwo4fFunc =
cFuncBool = 0
BN_One_cFunc =
BN_Two_cFunc =
xFuncBool = 0
number_xFunc = 0
gFuncBool = 0
number_gFunc = 0
dFUncBool = 0
dPrivateKeyFile =
dBinFile =
eFuncBool = 0
eEncryptPublicKey =
eEncryptTextFile =
outputPathBool = 0
OutputPath =
DEBUG - pwd = /home/spider/Documents/Portfolio/PortfolioFiles/CyberSecurity42/Modules/PortfolioProjects/corsair
corsair is a program used to crack RSA passwords and work with RSA keys.
The capabilities of this program are the following:
-h --> Prints the Program help.
-p (path) --> The main function. Reads all .pem files in the -p path and tries to crack the private password with other .pem files in the folder. If the provate key is cracked it decodes the .bin file
with equal name as the private key '.pem' file1
Example of files in the folder
1.pem
2.pem
1.bin
2.bin
If the key of '1.pem' and '2.pem' was cracked, the program decrypts the files 2.bin and 2.bin.
It also generates a .pem file for each public key cracked with the respective private key.
This file will be named after the file containing the public key, the key type, the program name and the version of the program used.
As example if 1.pem and 2.pem files containing a public key where cracked, two files will be created containing the private key.
Those files will be named for corsair version 0.001:
1_privateKey_Corsair_0-001.pem
2_privateKey_Corsair_0-001.pem
The function also saves the decoded message in .txt files, which will be named as:
1_decryptedMessage_Corsair_0-001.txt
2_decryptedMessage_Corsair_0-001.txt
-f (file1.pem file2.pem file1.bin file2.bin) --> The flag -f does the same as the flag -p but for 4 specific files. It does not read recursively a path looking for files to crack.
This flag allows working with files which are not named for the use of the function used for -p
It creates the same files as the function used with the -p flag (if key was cracked)
-g (N) --> Generate N 'YES Random' public keys, private keys and encrypted messages in order to check the functionability of the -d path function.
- FOR VERSION 0.002
-C ('BIGNUM IN ASCII' 'BIGNUM IN ASCII')-C ('BIGNUM IN ASCII' 'BIGNUM IN ASCII') --> The flag C calculate the RSA keys for the two BIGNUMs give in ASCII format and generates 2 key .pem files. One for the public key
and other for the private key.
Remember that the numbers need to:
1. Be integers (No Float are allowed)
2. Be Primes
3. Not be the same number
-o (outputPath) --> Specifies the ouput path where the output files will be stored. If not output path is specified the relative path './CorsairOutputV0-001/' will be used
[WARNING] The program creates the path if it does NOT exist, but does NOT check for file 'collision'. Therefore some files in the ouput folder could be deleted.
-h --> Show the help of the program into terminal.
-x (N) --> Generate N 'NOT Random' public keys, private keys and encrypted messages in order to check the functionability of the -p path function. (USED FOR DEBUGGING and TESTING)
-d (private_key_file.pem encrypted_file.bin) --> Tries to decrypt the ecrypted_file.bin using the private key contained into the private_key_file.pem.
If succes shows the decrypted message into terminal.
If fails shows error into terminal.
-e (public_key_file.pem input_text_file.txt) --> if the length of the text of the input_text_file is lower or equal than the maximum encryption lenght,
this function encrypts the text and save it into the file given with the -o flag.
ToDo for Version 0.002
- Input Read Arguments Function With Parameters stored into Struct and check consistency of gieven parameters
- Help Print Function
- Create Output Folder if needed
- -p Function
- Clean
- Create .pem files and save into output with name public key files
- Create .txt files and save into output path with decrypted message
- Free all variables
- -f Function
- SAME as -p but for 4 files
- -C function
- -x function using the same function as -C
- .g function using the same function as -C
- -d function
ToDo for Version 0.002
- H (HASH) --> Specifies the HASH to be used for all functions
- F (file.pem) --> Cracks the public key stored into file.pem
- Clean Code
- Assure all Variables are freedn
- All functions with 'no deprecated' open ssl functions
- The list of files used for the project is the following:
FILE | Function |
---|---|
README.md (this file) | Readme file with some information about this project. |
corsair.c | Corsair program written in C |
corsair | Compiled Corsair Program |
corsairTest.sh | Bash Script used to test the several Corsair functionalities |
testLeaks.sh | Bash Script used to test leaks for all the Corsair functionalities |
testLeaksOld.sh | Old Bash Script used to test leaks for all the Corsair functionalities without the capability of changing de output directory |
testX.sh | Bash Script to test recall capability of corsair program |
Sources/ | Folder with several files used in order to test the functions of the program. |
The program can be build with the gcc for two main goals:
- Distribution: Use the program normally.
- Debugging: Test, debug and improve the code.
- Compile standard:
gcc corsair.c -o corsair -lm -lssl -lcrypto -w
OR
gcc corsair.c -o ../binaries/corsair -lm -lssl -lcrypto -w
- Compile Debugging:
gcc -o corsair -std=c11 -Wall -ggdb3 corsair.c -lssl -lcrypto -w
gcc -o corsair -std=c11 -Wall -ggdb3 corsair.c -lssl -lcrypto -w -lm
#OR
gcc -o ../binaries/corsair -std=c11 -Wall -ggdb3 corsair.c -lssl -lcrypto -w
gcc -o ../binaries/corsair -std=c11 -Wall -ggdb3 corsair.c -lssl -lcrypto -w -lm
- Compile the program with -dgb flag
gcc -o corsair -std=c11 -Wall -ggdb3 corsair.c -lssl -lcrypto -w -lm
- Run the compiled program using the utily valgrind:
dirValRes="valgrindRes20/"
dirValResOut="./""$dirValRes"
mkdir $dirValRes
valgrind --log-file="$dirValRes"Xout01.file --leak-check=yes --tool=memcheck ./corsair -x 4 -o "$dirValResOut"valXOut01/
[!] - Some leak tests are in the file: ./tests/testsLeaks.sh
# Test the path option:
./corsair -p ../examples/challenge_corsair/
- More test in the bash script "corsairTest.sh" in the main project folder.
./corsair -h
./corsair -g 1 -o ./keys/
./corsair -f ../examples/challenge_corsair/29.pem ../examples/challenge_corsair/82.pem ../examples/challenge_corsair/29.bin ../examples/challenge_corsair/82.bin -o ./outNow3/
./corsair -p ../examples/challenge_corsair/ -o ./OutputPath13/
- Installation:
apt install gcc
- Installation:
apt isntall gdb
- Installation:
apt install libssl-dev openssl
- Instructions in order to install other versions:
1. Install open ssl 3 or superior in debian:
nano /etc/apt/sources.list
ADD
deb http://deb.debian.org/debian testing bullseye main
deb-src http://deb.debian.org/debian testing bullseye main
deb http://deb.debian.org/debian testing bullseye-security main
deb-src http://deb.debian.org/debian testing bullseye-security main
run
apt install openssl
openssl version
apt install libssl-dev
apt install openssl
apt install libssl-dev
apt install gcc gdb valgrind
apt install openssl libssl-dev gcc gdb
- Installation:
apt install valgrind
- In order to debug the C program Corsair:
1. Compile program:
gcc -o corsair -std=c11 -Wall -ggdb3 corsair.c -lssl -lcrypto -w -lm
2. Run Program using gdb
gdb ./corsair
3. run Command + arguments:
run -x 10 -o ./ouputX/
4. If fault occurs use "where" command to see traceback.
where
openssl rsa -check -in privateKey.pem
openssl rsa -pubin -in 1699361481_1_publicKey.pem
openssl rsa -in alice_private.pem -pubout > alice_public.pem
openssl rsautl -encrypt -inkey bob_public.pem -pubin -in top_secret.txt -out top_secret.enc
openssl rsautl -decrypt -inkey privateKey.pem -in message.bin > message.txt
cat $(openssl rsautl -decrypt -inkey privateKey.pem -in message.bin)
cat $(openssl pkeyutl -decrypt -inkey 1699361826-privateKey.pem -in 1699361826-publicKey.bin)
- In order to correct corsair: #Source:
valgrind --log-file=output10.file --leak-check=yes --tool=memcheck ./corsair -h
valgrind --log-file=output20.file --leak-check=yes --tool=memcheck ./corsair -g 1 -o ./keys/
valgrind --log-file=output30.file --leak-check=yes --tool=memcheck ./corsair -f ./Sources/challenge_corsair/29.pem ./Sources/challenge_corsair/82.pem ./Sources/challenge_corsair/29.bin ./Sources/challenge_corsair/82.bin -o ./outNow3/
./corsair -f ./Sources/challenge_corsair/97.pem ./Sources/challenge_corsair/60.pem ./Sources/challenge_corsm ./97.bin ./Sources/challenge_c.bin r/60.bin -o ./outNow3/
valgrind --log-file=output40.file --leak-check=yes --tool=memcheck ./corsair -p ./Sources/challenge_corsair/ -o ./OutputPath13/
valgrind --log-file=output41.file --leak-check=yes --track-origins=yes --tool=memcheck ./corsair -p ./Sources/challenge_corsair/ -o ./OutputPath13/
valgrind --log-file=output41.file --leak-check=full --track-origins=yes --tool=memcheck ./corsair -p ./Sources/challenge_corsair/ -o ./OutputPath13/
- ERROR MESSSAGE VALGRIND EXAMPLE
==43284== Memcheck, a memory error detector
==43284== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==43284== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==43284== Command: ./a.out
==43284== Parent PID: 39695
==43284==
==43284== Invalid write of size 4
==43284== at 0x4004B6: f (in /tmp/a.out)
==43284== by 0x4004C6: main (in /tmp/a.out)
==43284== Address 0x4c1c068 is 0 bytes after a block of size 40 alloc'd
==43284== at 0x4A05E1C: malloc (vg_replace_malloc.c:195)
==43284== by 0x4004A9: f (in /tmp/a.out)
==43284== by 0x4004C6: main (in /tmp/a.out)
==43284==
==43284==
==43284== HEAP SUMMARY:
==43284== in use at exit: 40 bytes in 1 blocks
==43284== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==43284==
==43284== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==43284== at 0x4A05E1C: malloc (vg_replace_malloc.c:195)
==43284== by 0x4004A9: f (in /tmp/a.out)
==43284== by 0x4004C6: main (in /tmp/a.out)
==43284==
==43284== LEAK SUMMARY:
==43284== definitely lost: 40 bytes in 1 blocks
==43284== indirectly lost: 0 bytes in 0 blocks
==43284== possibly lost: 0 bytes in 0 blocks
==43284== still reachable: 0 bytes in 0 blocks
==43284== suppressed: 0 bytes in 0 blocks
==43284==
==43284== For counts of detected and suppressed errors, rerun with: -v
==43284== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 4 from 4)
In some future version... RSA theroy will be here...
- OpenSSL 3.0 Official Documentation
- GCC Official Documentation
- GDB Official Documentation
- Valgrind Official Documentation
- RFC 8017 - RSA Cryptography Specifications Version
- Backup Program and Files
- Clean Program
- Improve console output file Function (Make it beauty)
- Names Variables Program Improve