qiling icon indicating copy to clipboard operation
qiling copied to clipboard

Simple fuzzing example does not work

Open majodu opened this issue 5 years ago • 13 comments

This is a simple program that i was able to fuzz with afl++ and emulate with qiling but when I try to fuzz with it qiling i get zero crashes and it runs forever. What exactly am i doing wrong here. Where is the fuzzing input being sent if not to the programs stdin

  1 #include <stdio.h>
  2 #include <string.h>
  3 int main(int argc,char* argv[]) {
  4         printf("Hello, World!\n");
  5         char buffer1[20];
  6         fgets(buffer1,19,stdin);
  7         printf("You typed: %s\n",buffer1);
  8         if(strchr(buffer1,'h') != 0){
  9                 if(strchr(buffer1,'c') != 0){
 10                         char buffer2[10];
 11                         strcpy(buffer2,buffer1);
 12                         printf("you hacked with: %s\n",buffer2);
 13                 }
 14         }else{
 15                 printf("nope!\n");
 16         }
 17         return 0;
 18 }

Fuzzing input is fed through stdin My qiling script looks like this

import sys, os
from qiling import *
from qiling.const import QL_VERBOSE
import unicornafl

unicornafl.monkeypatch()

def my_syscall_sig_suspend(ql, write_fd, write_buf, write_count, *args, **kw):
    regreturn = 0

    ql.os.set_syscall_return(regreturn)

def print_asm(ql, address, size, md):
    buf = ql.mem.read(address, size)
    for i in md.disasm(buf, address):
        print(":: 0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))

def main(input_file, enable_trace=False):
    ql = Qiling(['./a.out'], 
            '/', 
            verbose=QL_VERBOSE.DEFAULT,
             console = True)
   # ql.stdout = sys.stdout
    def place_input_callback(uc, input, _, data):
        pass
         #print(input)
         #print(data)
         #ql.mem.write(target_address, input)
    def start_afl(_ql: Qiling):
        """
        Callback from inside
        """
        # We start our AFL forkserver or run once if AFL is not available.
        # This will only return after the fuzzing stopped.
        try:
            #print("Starting afl_fuzz().")
            if not _ql.uc.afl_fuzz(
                        input_file="aaa",
                        place_input_callback=place_input_callback,
                        exits=[ql.os.exit_point]):
                print("Ran once without AFL attached.")
                os._exit(0)  # that's a looot faster than tidying up.
        except unicornafl.UcAflError as ex:
            # This hook trigers more than once in this example.
            # If this is the exception cause, we don't care.
            # TODO: Chose a better hook position :)
            if ex != unicornafl.UC_AFL_RET_CALLED_TWICE:
                raise
            #,multithread=True)
    #ql.debugger = "qdb"
    md = ql.create_disassembler()
    #md.detail = True
    main_addr = ql.os.elf_entry
    ql.hook_address(callback=start_afl, address=main_addr)
    #ql.hook_code(print_asm,user_data=md)
    #ql.patch(0x00587a40,b'\x00\x00\x00\x00')
    #ql.set_syscall("rt_sigsuspend", my_syscall_sig_suspend)
    #ql.set_syscall("poll", my_syscall_sig_suspend)
    ql.run()

if __name__ == "__main__":
    if len(sys.argv) == 1:
        main("aaa")
    else:
        main(sys.argv[1])

the command executed is AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 ./AFLplusplus/afl-fuzz -U -i in/ -o out/ -- python3 emulate.py

majodu avatar May 25 '21 23:05 majodu

Check #803 should be that fix

xwings avatar May 26 '21 01:05 xwings

You have multiple problems here:

  1. You do not redirect stdin to a pseudo pipe, so it probably waits for an input
  2. The place_input_callback does literally nothing, all the code there is commented out
  3. Although it shouldn't prevent the fuzzing (only slow it down), set the start_afl hook to the address of main. The program entry point is not main: there are some preparations that take place before main and you can have AFL skip them and restart from main every time istead of re-doing all of that stuff again and again every fuzzing iteration.

I highly recommend to see how things are done in the Linux fuzzing example, which I've just fixed and cleaned a day or two ago.

elicn avatar May 26 '21 14:05 elicn

I implemented the pipe and now I am getting fuzzing input into the program. My problem now is choosing the proper hook addresses I hooked main and the call to __stack_chk_fail but for some reason the program is not crashing.

    def abort_func(x):
        print("STACK CHECK FAIL!!!!!")
        os.abort()
    # make process crash whenever __stack_chk_fail@plt is about to be called.
    # this way afl will count stack protection violations as crashes
    ql.hook_address(callback=abort_func, address=ba + 0x246e)

    # set a hook on main() to let unicorn fork and start instrumentation
    ql.hook_address(callback=start_afl, address=ba + 0x000022a0)

these values were found with rizin/radare2

Hello, World!(fd = 0x0, buf_ptr = 0x80000000dba0)
[=]	fstat(fd = 0x0, buf_ptr = 0x80000000dba0)= 0x1000)
[=]	read(fd = 0x0, buf = 0x5555557606b0, len = 0x1000)
[=]	write(fd = 0x1, buf = 0x5555557602a0, count = 0x1e)
You typed: hellocAAAAAAAAA�
[=]	write(fd = 0x1, buf = 0x5555557602a0, count = 0x6)
[=]e!   writev(fd = 0x2, vec = 0x80000000dc10, vien = 0x3)
*** buffer overflow detected ***: terminated
[=]	mmap(addr = 0x0, length = 0x1000, prot = 0x3, flags = 0x22, fd = 0xffffffff, pgoffset = 0x0)
[=]	rt_sigprocmask(sigprocmask_how = 0x1, sigprocmask_nset = 0x80000000dae0, sigprocmask_oset = 0x0, sigprocmask_sigsetsize = 0x8)
[=]	rt_sigprocmask(sigprocmask_how = 0x0, sigprocmask_nset = 0x80000000da40, sigprocmask_oset = 0x80000000d9c0, sigprocmask_sigsetsize = 0x8)
[=]	getpid()
[=]	gettid()
[!]	0x7fffb7e31167: syscall ql_syscall_tgkill number = 0xea(234) not implemented
[=]	rt_sigprocmask(sigprocmask_how = 0x2, sigprocmask_nset = 0x80000000d9c0, sigprocmask_oset = 0x0, sigprocmask_sigsetsize = 0x8)
[=]	rt_sigaction(sigaction_signum = 0x6, sigaction_act = 0x80000000d990, sigaction_oldact = 0x0)
[=]	rt_sigprocmask(sigprocmask_how = 0x0, sigprocmask_nset = 0x80000000da40, sigprocmask_oset = 0x80000000d9c0, sigprocmask_sigsetsize = 0x8)
[=]	getpid()
[=]	gettid()
[!]	0x7fffb7e31167: syscall ql_syscall_tgkill number = 0xea(234) not implemented
[=]	rt_sigprocmask(sigprocmask_how = 0x2, sigprocmask_nset = 0x80000000d9c0, sigprocmask_oset = 0x0, sigprocmask_sigsetsize = 0x8)
[=]	fstat(fd = 0x1, buf_ptr = 0x80000000dc00)
[=]	write(fd = 0x1, buf = 0x5555557602a0, count = 0xe)
Hello, World!

majodu avatar May 26 '21 18:05 majodu

Managed to get it working by hooking sym.imp.__memcpy_chk instead. I am wondering would more crashes be caught automatically if syscall ql_syscall_tgkill number = 0xea(234) was implemented?

majodu avatar May 26 '21 19:05 majodu

I am not sure what __memcpy_chk has to do with this.. are you sure you get "real" crashes? Anyway, I would recommend to extract the vulnerable code to a different function, and not having all of your code in main.

elicn avatar May 26 '21 19:05 elicn

Moving the logic to a separate function does not seem to change the result. The code should trigger a stack check fail right?

majodu avatar May 27 '21 18:05 majodu

The stack check failure is a lib function. You should hook the call and emulate a crash there. See the example code.

elicn avatar May 27 '21 18:05 elicn

Just to make sure I am doing this correctly, I am grabbing the offset from rizin/radare2

0x00002090    1 6            sym.imp.sigaction
0x000020a0    1 6            sym.imp.shmdt
0x000020c0    1 6            sym.imp.__stack_chk_fail
0x000020d0    1 6            sym.imp.mmap
0x000020e0    1 6            sym.imp.strchr
0x00002100    1 6            sym.imp.ioctl
0x00002110    1 6            sym.imp.close
ql.hook_address(callback=abort_func, address=ba + 0x000020c0)

Whenever I hook __stack_chk_fail, the abort_func is not called when a buffer overflow is reported by the program. Does this mean that __memcpy_chk does not call __stack_chk_fail? In that case using strcpy in my program is the issue.

Right now I am just aborting on ql_syscall_tgkill number = 0xea(234) which seems to happen every time the program should crash

majodu avatar May 27 '21 21:05 majodu

The purpose of __memcpy_chk is to prevent buffer overflows by checking the parameters before doing the actual copy. Hooking that function means you cause a crash every time it checks rather than fails. Look for the symbol __chk_fail which should be called on failures; if you see it - that's the one you need to hook.

If you can't see it, get rid of that check by compiling your source with either -D_FORTIFY_SOURCE=0 or -U_FORTIFY_SOURCE

elicn avatar May 28 '21 14:05 elicn

@majodu is this still an issue?

elicn avatar May 31 '21 10:05 elicn

So hooking __stack_chk_fail works if you compile with gcc and not afl-gcc-fast. I verified that the code compiled with both does call __stack_chk_fail with gdb but hooking it does not work when you compile with afl-gcc-fast for some reason.

I can close this issue if this is intended behavior.

majodu avatar Jun 04 '21 15:06 majodu

I don't think it should matter which compiler you use - as long as you hook the right location. Are you sure you are hooking the right call instruction? perhaps you picked a similar call on another code path..?

Try to execute both binaries normally with a malicious input that you know that would trigger the vulnerability, and use the enhanced tracing to see exactly which code is executing. That will tell you which call to hook.

Enable the enhanced tracing this way:

from qiling import Qiling
from qiling.const import QL_VERBOSE
from qiling.extensions import trace

ql = Qiling([r'path/to/binary'], r'path/to/rootfs', verbose=QL_VERBOSE.DEBUG)
trace.enable_full_trace(ql)
ql.run()

elicn avatar Jun 06 '21 18:06 elicn

It must be because I get different errors compiling with gcc vs afl-gcc-fast. In gcc I get

Hello, World!
hellocAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
You typed: hellocAAAAAAAAAAAA
you hacked with: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
*** stack smashing detected ***: terminated

In afl-gcc-fast I get

Hello, World!
hellocAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
You typed: hellocAAAAAAAAAAAA
*** buffer overflow detected ***: terminated

majodu avatar Jun 07 '21 17:06 majodu