Search code examples
stack-overflowexploit

Why does fgets fail when I use 0 as FILE* to read from stdin in rop chain?


I am making a rop chain to call fgets with stdin as input to be able to make a basic stack overflow.

But my issue is that when I call fgets with 0 as the third argument (for stdin) fgets crash at

 <fgets+49>       mov    ecx, DWORD PTR [esi]

where esi is the third argument I control, why does it crash? With 0 it should not try to read the content of it and just read from stdin, no?

The useful part of my ropchain looks like :

fgets.plt
pop_pop_pop_ret
buffer
0x500
0

I have no idea why it doesn't work. The call made is something like :

_IO_fgets(buf=0xf7f77000, n=0x500, fp=0x0)

Solution

  • Because stdin is not a number. It's an object in libc.

    zeltrax@ubuntu:~$ readelf -s /lib/x86_64-linux-gnu/libc.so.6 | grep "stdin"
    377: 00000000001eb980   224 OBJECT  GLOBAL DEFAULT   31 _IO_2_1_stdin_@@GLIBC_2.2.5
    546: 00000000001ec790     8 OBJECT  GLOBAL DEFAULT   31 stdin@@GLIBC_2.2.5
    

    Check this example:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
            printf("stdin : %p\n", stdin);
            printf("printf: %p\n", printf);
            
            return 0;
    }
    

    Output:

    zeltrax@ubuntu:~$ gcc test.c
    zeltrax@ubuntu:~$ ./a.out
    stdin : 0x7fcec21dc980
    printf: 0x7fcec2055e10