Friday, 24 May 2019

Locksmith Writeup - Security Fest CTF 2019

This challenge is related to the concept of Lockpicking. In this challenge, we need to connect to remote service running at:

Once we connect, we are provided with the following information:

We are presented with two arrays of 9 numbers.

Array 1: This is the initial state of the numbers on the lock. Right now, it is in locked state.
Array 2: This is the target state of the numbers on the lock. This indicates the unlocked state.

We can send the inputs in the range 1 to 9 to the remote service. Based on each input, a specific value is added to each dial of the lock as shown below:

We need to keep sending the inputs till the numbers in Array 1 are the same as the numbers in Array 2.

And to solve the challenge, we need to unlock the lock 100 times. In each round, we are presented with a new initial and target state of the lock.

I used z3 and pwntools to solve this challenge.

pwntools was used to handle the network communication between my machine and the server.
z3 was used to solve the equations generated based on the responses received from the server.

Since each number (in the range: 1 to 9), adds a specific value to each number of the Array. I used this information to find out how many times each number has to be sent to the remote service to get the desired result.

For example, let the initial state of the lock be:

initial = [x1, x2, x3, x4, x5, x6, x7, x8, x9]

After we send the input number 1, the modified state becomes:

modified = [y1, y2, y3, y4, y5, y6, y7, y8, y9]

So, the diff is:

diff = [y1 - x1, y2 - x2, y3 - x3, y4 - x4, y5 - x5, y6 - x6, y7 - x7, y8 - x8, y9 - x9]

Le us denote, y1 - x1 with a1 which indicates the difference between the number in position 1 of the current array and the previous array when the input number is 1. Similarly,

y2 - x2 =b1
y3 - x3 = c1
y9 - x9 = i1

diff array for input 1 = [a1, b1, c1, d1, e1, f1, g1, h1, i1]

Similarly for other input numbers, the diff arrays will be:

[a2, b2, c2, d2, e2, f2, g2, h2, i2]
[a9, b9, c9, d9, e9, f9, g9, h9, i9]

if our target value in the lock is X, then we need to solve the equations of the form:

a1 * a + a2 * b + a3 * c + a4 * d + a5 * e + a6 * f + a7 * g + a8 * h + a9 * i == X
i1 * a + i2 * b + i3 * c + i4 * d + i5 * e + i6 * f + i7 * g + i8 * h + i9 * i == X

So, we have a system of 9 linear equations each containing 9 unknown values. This can be solved using z3.

Here is my code for solving this challenge:

Once all the rounds are successfully solved, the server responds with the flag as shown below:

Flag: sctf{1_gUeS5_tH4T_is_whY_th3Y_c4lL_iT_a_m0Nte_caRlO_bAnk}


Tuesday, 16 April 2019

Last Minute Write Up - WPI CTF 2019

Last Minute was a reversing challenge in WPI CTF 2019. This challenge was very interesting because it uses frame buffers to draw the actual flag if the environment and initial conditions are correct.

The provided binary is an ELF 64-bit binary.

The main functions performed by the binary are:

1. Uses the current timestamp to calculate a seed which is used to seed the random number generator.

The seed is calculated and used to seed the random number generator as shown below:

t = time()
seed = t/0x3c

This means that the seed only changes every 60 seconds.

2. Opens the frame buffer device, /dev/fb0

3. Uses the ioctl, FBIOGET_VSCREENINFO (0x4600) to retrieve the fb_var_screeninfo structure. The bits_per_pixel field in this structure is set to 32.

4. Updates the structure using another ioctl, FBIOPUT_VSCREENINFO (0x4601).

5. Runs a loop which will update the accel_flags field in the vinfo structure.

6. Retrieves the vinfo structure.

7. Retrieves the finfo structure using the ioctl, FBIOGET_FSCREENINFO (0x4602).

This structure is defined as shown below:

struct fb_fix_screeninfo {
    char id[16];            /* identification string eg "TT Builtin" */
    unsigned long smem_start;    /* Start of frame buffer mem */
                    /* (physical address) */
    __u32 smem_len;            /* Length of frame buffer mem */
    __u32 type;            /* see FB_TYPE_*        */
    __u32 type_aux;            /* Interleave for interleaved Planes */
    __u32 visual;            /* see FB_VISUAL_*        */
    __u16 xpanstep;            /* zero if no hardware panning  */
    __u16 ypanstep;            /* zero if no hardware panning  */
    __u16 ywrapstep;        /* zero if no hardware ywrap    */
    __u32 line_length;        /* length of a line in bytes    */
    unsigned long mmio_start;    /* Start of Memory Mapped I/O   */
                    /* (physical address) */
    __u32 mmio_len;            /* Length of Memory Mapped I/O  */
    __u32 accel;            /* Indicate to driver which    */
                    /*  specific chip/card we have    */
    __u16 capabilities;        /* see FB_CAP_*            */
    __u16 reserved[2];        /* Reserved for future compatibility */

It fetches the line_length field of the finfo structure and prints it to stdout.

The line_length field needs to be equal to 0x1900 for it to continue the execution to display the flag as shown below:

if line_length <= 0x18ff:
    print "Ectomporh"
elif line_length != 0x1900:
    print "Endomorph"
    print "Mesomorph"

    // perform the computations to display the flag

So, what is the line_length field?

In frame buffers, the line_length field represents the number of bytes in each line of the display. It is related to the X resolution field in the vinfo structure as shown below:

line_length = vinfo.x_res * (bits_per_pixel)/8

In our case, line_length should be equal to 0x1900 and bits_per_pixel is 32.

so, vinfo.x_res = 0x1900/4 = 1600

We can check the current resolution of the frame buffer device, /dev/fb0 using the command:

cat /sys/class/graphics/fb0/virtual_size

This displays both the resolution fields in (x,y) format.

If the X and Y resolution fields of the virtual_size are not equal to 1600 and 900 respectively, then the flag will not be displayed on the screen.

We can set the frame buffer resolution using the command:

fbset -fb /dev/fb0 1600 900 1600 900 32

Using the above command we have set all the fields of the frame buffer which are required to display the flag.

Now, lets explore the generation of seed using time(). The seed is very important here because it determines the random numbers generated by rand(). And these random numbers are useful because they are used to calculate the offsets at which the pixels will be drawn on the frame buffer.

The data to to be drawn to the frame buffer is stored in the .data section in the array called baboof[] as shown below:

Based on the challenge description, we find the timestamp when the CTF ends and it is: 1555286400.

Since we know that the seed changes every 60 seconds, we can generate all the possible seeds for the last 1 hour of the CTF.

This gives us the values:

['0x5cb3bb70', '0x5cb3bbac', '0x5cb3bbe8', '0x5cb3bc24', '0x5cb3bc60', '0x5cb3bc9c', '0x5cb3bcd8', '0x5cb3bd14', '0x5cb3bd50', '0x5cb3bd8c', '0x5cb3bdc8', '0x5cb3be04', '0x5cb3be40', '0x5cb3be7c', '0x5cb3beb8', '0x5cb3bef4', '0x5cb3bf30', '0x5cb3bf6c', '0x5cb3bfa8', '0x5cb3bfe4', '0x5cb3c020', '0x5cb3c05c', '0x5cb3c098', '0x5cb3c0d4', '0x5cb3c110', '0x5cb3c14c', '0x5cb3c188', '0x5cb3c1c4', '0x5cb3c200', '0x5cb3c23c', '0x5cb3c278', '0x5cb3c2b4', '0x5cb3c2f0', '0x5cb3c32c', '0x5cb3c368', '0x5cb3c3a4', '0x5cb3c3e0', '0x5cb3c41c', '0x5cb3c458', '0x5cb3c494', '0x5cb3c4d0', '0x5cb3c50c', '0x5cb3c548', '0x5cb3c584', '0x5cb3c5c0', '0x5cb3c5fc', '0x5cb3c638', '0x5cb3c674', '0x5cb3c6b0', '0x5cb3c6ec', '0x5cb3c728', '0x5cb3c764', '0x5cb3c7a0', '0x5cb3c7dc', '0x5cb3c818', '0x5cb3c854', '0x5cb3c890', '0x5cb3c8cc', '0x5cb3c908', '0x5cb3c944', '0x5cb3c980']

Now, we need to bruteforce the above timestamps and check the frame display output.

Since the binary is dynamically linked, we can leverage the LD_PRELOAD environment variable so that time() function always returns a predefined value for the binary being executed.

This can be done by writing a short function such as:

int time()
    return 0x5cb3c944;

Then compile it as a shared library:

gcc -shared -fPIC hook_time.c -o

Now, we can run the binary as shown below and confirm that the timestamp returned by time() is indeed how we configured it:

sudo LD_PRELOAD=$PWD/ ltrace -o trace1.txt ./lm

This will run the binary using ltrace to log the API calls and LD_PRELOAD will be used to load our shared library,

As shown below, time() returns our configured timestamp:

Now, we can run the binary and it will display the flag as shown below:



Monday, 1 April 2019

CyberRumble Writeup - Sunshine CTF 2019

In this challenge, we are provided a 64-bit ELF binary that accepts different forms of inputs as shown below:

Input: tombstone_piledriver<file_name>

You can specify the filename in this command. The server will read and display its contents.

Issue: This input will print only the first word of the flag file.

Reason: The contents of the file are read using ___isoc99_fscanf() and format string %99s. So, the space character is the delimiter and anything after the space character is not read. As a result, we cannot use this input to get the flag.

Input: old_school <shellcode>

max_length(shellcode) = 0x64 - len("old_school ")

Issue: The shellcode cannot be executed directly.

Reason: It uses mmap() to map the memory region to which the shellcode will be copied using memcpy(). It then uses mprotect() to remove the execute protection from this memory region. As a result of this, even though we can send the shellcode we cannot execute it directly.

Input: last_ride <shell_command>

This input is interesting because it will be sent to the system() function for execution.

However, a bug is included in the binary which sends the ASCII string itself to the system() function instead of the pointer to ASCII string.

It does not fetch the pointer using mov instruction and instead uses lea instruction as shown below:

So, we cannot send the shell command directly for code execution.

However, we can pass a pointer in the last_ride command as a string so that system() executes the contents pointed to by that pointer.

The binary has ASLR enabled. How can we get the address of our string?

The binary provides us our shellcode address. This can be used to solve the challenge.

1. Send the shell command in the old_school command like: old_school <shell_command>
2. Binary gives us the address of the shellcode.
3. Use the above address and send that as a string in the last_read command.

It is important to note that the shellcode address contains null bytes due to the way mmap() maps a new memory region. Since we are sending the address of the shellcode as a string to the system() command, it must not contain null bytes.

To resolve this, we can add some padding before our shell command so that the address does not contain null bytes.

The exploit code is:

from pwn import *
import re
import time

p = remote("", 4300)

print p.recv()

payload = "old_school Ash"

print "Sending first stage payload: %s" %(payload)


output = p.recv()
m = re.findall(r'0x(.*)?\.', output)
addr = m[0]
addr = int(addr, 16) + 1

print "The shellcode address is: %x" %(addr)


payload = "last_ride " + p64(addr)

print "Sending second stage payload: %s" %(payload.encode("hex"))



The execution of the exploit is shown below:

Flag: sun{the chair and thumbtacks are ready, but the roof is a little loose}


Big Bad Writeup - Sunshine CTF 2019

In this challenge, we are provided a PNG image that displays a Binary Tree as shown below:

After analyzing the tree, it was concluded that the challenge is related to Huffman Encoding.

In Huffman Encoding, we can construct the value for each leaf node by traversing the tree from the root node till the leaf node using the following logic:

1. If a left branch is taken, then we consider the bit 0.
2. If a right branch is taken, then we consider the bit 1.

The left and right branches originating from the root node of the tree are marked as 0 and 1 respectively in the provided image which is also an indication that we have to use Huffman Encoding.

So, based on the above logic, we construct the Huffman Encoding table:

s = 000
u = 0010
_ = 0011
0 = 010
d = 0110
9 = 0111
5 = 1000
n = 10010
h = 10011
l = 10100
a = 10101
e = 10110
b = 10111
1 = 1100
{ = 11010
} = 11011
r = 11100
c = 11101
k = 11110
3 = 11111

In Huffman Encoding, if we have to decode the message, we need a binary stream. However, no binary stream was provided in the challenge description.

After further analysis, it was found using Steganography that the binary stream was encoded in the PNG image as a set of vertical black and white lines as shown below:

Each line has a width of 1 pixel, so we can extract the binary stream using the logic:

1. If the pixel value is 255, then we consider the bit to be 1.
2. If the pixel value is 1, then we consider the bit to be 0.

We can leverage the Python PIL library to accomplish this:

#! /usr/bin/python

from PIL import image
import sys

if len(sys.argv) != 2:
    print "usage: python <image_file>"
im =[1])

stream = ""

for i in range(152):
    if im.getpixel((i, 0)) == 255:
        stream += str(1)
        stream += str(0)
print stream

We scan 152 pixels from the left side of the image because based on analysis of the image in Gimp, it was found that approximately 152 pixels need to be scanned to extract the complete binary stream.

we get the binary stream as:


We can apply the Huffman Encodings to above binary stream to get the flag as: sun{sh0ulda_u5ed_br1cks_10011305191101}


Saturday, 29 December 2018

Corebot writeup - 35C3 CTF

The binary given in this challenge is a 32-bit Windows Binary.

The main subroutine of the binary looks like shown below:

It stores the flag encrypted in the resource section in the resource called: "65".

Main functions performed by the binary are:

1. It retrieves the VolumeID with GetVolumeInformationA() API.
2. This is used to calculate a key of length 0x20 bytes.
3. The key is imported using CryptImportKey() and the entire key including the public key structure looks like shown below:

The public key structure looks like shown below:

typedef struct _PUBLICKEYSTRUC {
  BYTE   bType;
  BYTE   bVersion;
  WORD   reserved;
  ALG_ID aiKeyAlg;

Based on this, we can see:

bVersion = 0x02
aiKeyAlg = 0x6610 (AES)
length of the key = 0x20 bytes.

The actual 32 byte key is stored after this.

Decryption of the Flag:

1. Encrypted flag is loaded from the resource called "65".
2. The key imported above using CryptImportKey() will be used to decrypt the flag using CryptDecrypt()

013C1210  |. 813F 33354333  CMP DWORD PTR DS:[EDI],33433533
013C1216  |. 74 0B          JE SHORT corebot.013C1223

If the first DWORD of the decrypted flag is: 0x33433533, then we have found the correct flag.

To solve this challenge, we need to bruteforce the VolumeID. I wrote a few lines of assembly code to bruteforce the VolumeID from 0x0 to 0xffffffff as shown below:

xor eax, eax
inc eax
push eax
call main()

Inside the main() subroutine, we have to NOP out the call to GetVolumeInformationA() and ensure that eax is restored when we return back to above code to continue bruteforcing.

Using this method, we can find the flag as shown below:

Correct value of Volume ID is: 0x25C3
Flag is: 35C3_MalwareAuthorKryptoChef


PHP Writeup - 35C3 CTF

In this challenge, we are given a PHP file with contents as shown below:

Challenge is running at: nc 1

So, we need to craft an input and send it in order to retrieve the flag.


1. Our input will be unserialized.
2. There is a Class called "B" with a __destruct() method.
3. The __destruct() method will echo $flag.
4. $flag contains the contents of the file called flag.

We can send the serialized input as shown below to retrieve the flag:

Flag is: 35C3_php_is_fun_php_is_fun


Permute Writeup - 35C3 CTF

The binary given in this challenge is a 32-bit ELF file.

$ file program
program: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.32, dynamically linked, interpreter \004, stripped

When we execute the binary, it asks us for a flag byte as an input:

$ ./program
Usage: ./program <flag byte>

In the screenshot below, we can see the requirements for the input of the binary:

1. argc == 2
2. strlen(argv[1]) == 1

So, we need to send a single character as an input.

When we execute the binary with a single character input, we notice that the MD5 hash of the binary changes as shown below:

$ md5sum program
817daa25ea4048e31a9703f53ff7c15a  program

$ ./program 3

$ md5sum program
80021d00fc812bbd9ccd3c76bdf0fcd1  program

When we pass 3 as an input to the binary, it changed the original binary itself.

Now, let's analyze further.

1. The binary is using libcapstone library to modify the disassembly of the binary at runtime.
2. The changes are written to a tmp file and the original file is overwritten. This results in the change in MD5 hash.
3. Disassembly of the binary is modified in such a way that the original logic of the program does not change.

We can observe in the screenshots below the similarity as well as the difference in the disassemblies between the original binary and after the binary was passed an input of 3.

Original binary:

Modified Binary:

Now, let's check how the input byte is being processed by the binary.

1. The subroutine, sub_804A1EE returns the value in eax.
2. This value is used to perform an XOR with the input byte as shown below:

LOAD:08049FF9                 call    sub_804A1EE
LOAD:08049FFE                 add     esp, 10h
LOAD:0804A001                 mov     [ebp+var_A], al
LOAD:0804A004                 mov     eax, [ebp+arg_C]
LOAD:0804A007                 add     eax, 4
LOAD:0804A00A                 mov     eax, [eax]
LOAD:0804A00C                 movzx   edx, byte ptr [eax]
LOAD:0804A00F                 movzx   eax, [ebp+var_A]
LOAD:0804A013                 xor     eax, edx
LOAD:0804A015                 mov     [ebp+var_B], al

3. We observe that the result of this XOR operation is equal to 0 only when the correct flag byte is passed as an input.

So, to solve this challenge, we need to do the following:

1. Bruteforce the flag byte till we get the XOR result as 0.
2. Pass the correct flag byte to the binary so that it overwrites itself and we get a new binary.
3. Do step 1 with the new binary.

And we need to continue this process till the binary prints "WIN" which indicates that we have completed processing all the flag bytes.

The flag we get is: 35C3_tempuemr_temupre